Search Results

Search found 1503 results on 61 pages for 'timestamp'.

Page 28/61 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • Mysql InnoDB performance optimization and indexing

    - by Davide C
    Hello everybody, I have 2 databases and I need to link information between two big tables (more than 3M entries each, continuously growing). The 1st database has a table 'pages' that stores various information about web pages, and includes the URL of each one. The column 'URL' is a varchar(512) and has no index. The 2nd database has a table 'urlHops' defined as: CREATE TABLE urlHops ( dest varchar(512) NOT NULL, src varchar(512) DEFAULT NULL, timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY dest_key (dest), KEY src_key (src) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Now, I need basically to issue (efficiently) queries like this: select p.id,p.URL from db1.pages p, db2.urlHops u where u.src=p.URL and u.dest=? At first, I thought to add an index on pages(URL). But it's a very long column, and I already issue a lot of INSERTs and UPDATEs on the same table (way more than the number of SELECTs I would do using this index). Other possible solutions I thought are: -adding a column to pages, storing the md5 hash of the URL and indexing it; this way I could do queries using the md5 of the URL, with the advantage of an index on a smaller column. -adding another table that contains only page id and page URL, indexing both columns. But this is maybe a waste of space, having only the advantage of not slowing down the inserts and updates I execute on 'pages'. I don't want to slow down the inserts and updates, but at the same time I would be able to do the queries on the URL efficiently. Any advice? My primary concern is performance; if needed, wasting some disk space is not a problem. Thank you, regards Davide

    Read the article

  • Django generic relation field reports that all() is getting unexpected keyword argument when no args

    - by Joshua
    I have a model which can be attached to to other models. class Attachable(models.Model): content_type = models.ForeignKey(ContentType) object_pk = models.TextField() content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") class Meta: abstract = True class Flag(Attachable): user = models.ForeignKey(User) flag = models.SlugField() timestamp = models.DateTimeField() I'm creating a generic relationship to this model in another model. flags = generic.GenericRelation(Flag) I try to get objects from this generic relation like so: self.flags.all() This results in the following exception: >>> obj.flags.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all return self.get_query_set() File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set return superclass.get_query_set(self).filter(**query) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q can_reuse=used_aliases) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter negate=negate, process_extras=process_extras) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins "Choices are: %s" % (name, ", ".join(names))) FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user >>> obj.flags.all(object_pk=obj.pk) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: all() got an unexpected keyword argument 'object_pk' What have I done wrong?

    Read the article

  • Lost with hibernate - OneToMany resulting in the one being pulled back many times..

    - by Andy
    I have this DB design: CREATE TABLE report ( ID MEDIUMINT PRIMARY KEY NOT NULL AUTO_INCREMENT, user MEDIUMINT NOT NULL, created TIMESTAMP NOT NULL, state INT NOT NULL, FOREIGN KEY (user) REFERENCES user(ID) ON UPDATE CASCADE ON DELETE CASCADE ); CREATE TABLE reportProperties ( ID MEDIUMINT NOT NULL, k VARCHAR(128) NOT NULL, v TEXT NOT NULL, PRIMARY KEY( ID, k ), FOREIGN KEY (ID) REFERENCES report(ID) ON UPDATE CASCADE ON DELETE CASCADE ); and this Hibernate Markup: @Table(name="report") @Entity(name="ReportEntity") public class ReportEntity extends Report{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Integer ID; @Column(name="user") private Integer user; @Column(name="created") private Timestamp created; @Column(name="state") private Integer state = ReportState.RUNNING.getLevel(); @OneToMany(mappedBy="pk.ID", fetch=FetchType.EAGER) @JoinColumns( @JoinColumn(name="ID", referencedColumnName="ID") ) @MapKey(name="pk.key") private Map<String, ReportPropertyEntity> reportProperties = new HashMap<String, ReportPropertyEntity>(); } and @Table(name="reportProperties") @Entity(name="ReportPropertyEntity") public class ReportPropertyEntity extends ReportProperty{ @Embeddable public static class ReportPropertyEntityPk implements Serializable{ /** * long#serialVersionUID */ private static final long serialVersionUID = 2545373078182672152L; @Column(name="ID") protected int ID; @Column(name="k") protected String key; } @EmbeddedId protected ReportPropertyEntityPk pk = new ReportPropertyEntityPk(); @Column(name="v") protected String value; } And i have inserted on Report and 4 Properties for that report. Now when i execute this: this.findByCriteria( Order.asc("created"), Restrictions.eq("user", user.getObject(UserField.ID)) ) ); I get back the report 4 times, instead of just the once with a Map with the 4 properties in. I'm not great at Hibernate to be honest, prefer straight SQL but I must learn, but i can't see what it is that is wrong.....? Any suggestions?

    Read the article

  • @PrePersist with entity inheritance

    - by gerry
    I'm having some problems with inheritance and the @PrePersist annotation. My source code looks like the following: _the 'base' class with the annotated updateDates() method: @javax.persistence.Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Base implements Serializable{ ... @Id @GeneratedValue protected Long id; ... @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastModificationDate; ... public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } ... @PrePersist protected void updateDates() { if (creationDate == null) { creationDate = new Date(); } lastModificationDate = new Date(); } } _ now the 'Child' class that should inherit all methods "and annotations" from the base class: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Entity { ... // additional attributes @Column(nullable=false) protected String value; ... // additional getters, setters ... } If I store/persist instances of the Base class to the database, everything works fine. The dates are getting updated. But now, if I want to persist a child instance, the database throws the following exception: MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null So, in my opinion, this is caused because in Child the method "@PrePersist protected void updateDates()" is not called/invoked before persisting the instances to the database. What is wrong with my code?

    Read the article

  • Prevent two users from editing the same data

    - by Industrial
    Hi everyone, I have seen a feature in different web applications including Wordpress (not sure?) that warns a user if he/she opens an article/post/page/whatever from the database, while someone else is editing the same data simultaneously. I would like to implement the same feature in my own application and I have given this a bit of thought. Is the following example a good practice on how to do this? It goes a little something like this: 1) User A enters a the editing page for the mysterious article X. The database tableEvents is queried to make sure that no one else is editing the same page for the moment, which no one is by then. A token is then randomly being generated and is inserted into a database table called Events. 1) User B also want's to make updates to the article X. Now since our User A already is editing the article, the Events table is queried and looks like this: | timestamp | owner | Origin | token | ------------------------------------------------------------ | 1273226321 | User A | article-x | uniqueid## | 2) The timestamp is being checked. If it's valid and less than say 100 seconds old, a message appears and the user cannot make any changes to the requested article X: Warning: User A is currently working with this article. In the meantime, editing cannot be done. Please do something else with your life. 3) If User A decides to go on and save his changes, the token is posted along with all other data to update the database, and toggles a query to delete the row with token uniqueid##. If he decides to do something else instead of committing his changes, the article X will still be available for editing in 100 seconds for User B Let me know what you think about this approach! Wish everyone a great weekend!

    Read the article

  • Django unit testing: South-migrated DB works in MySQL, throws duplicate PK error in PostGreSQL. Am I

    - by unclaimedbaggage
    Hi folks, (Worth starting off with a disclaimer: I'm very new to PostGreSQL) I have a django site which involves a standard app/tests.py testing file. If I migrate the DB to MySQL (through South),, the tests all pass. However in PostGresQL, I'm getting the following error: IntegrityError: duplicate key value violates unique constraint "business_contact_pkey" Note this happens while unit testing only - the actual page runs fine in both MySQL & PostGresql. Really having a heckuva time figuring this one out. Anyone have ideas? Below are the Postgresql "\d business_contact" & offending tests.py method if they help. No changes made to either DB except the (same) South migrations Thanks first_name | character varying(200) | not null mobile_phone | character varying(100) | surname | character varying(200) | not null business_id | integer | not null created | timestamp with time zone | not null deleted | boolean | not null default false updated | timestamp with time zone | not null slug | character varying(150) | not null phone | character varying(100) | email | character varying(75) | id | integer | not null default nextval('business_contact_id_seq'::regclass) Indexes: "business_contact_pkey" PRIMARY KEY, btree (id) "business_contact_slug_key" UNIQUE, btree (slug) "business_contact_business_id" btree (business_id) Foreign-key constraints: "business_id_refs_id_772cc1b7b40f4b36" FOREIGN KEY (business_id) REFERENCES business(id) DEFERRABLE INITIALLY DEFERRED Referenced by: TABLE "business" CONSTRAINT "primary_contact_id_refs_id_dfaf59c4041c850" FOREIGN KEY (primary_contact_id) REFERENCES business_contact(id) DEFERRABLE INITIALLY DEFERRED TEST DEF: def test_add_business_contact(self): """ Add a business contact """ contact_slug = 'test-new-contact-added-new-adf' business_id = 1 business = Business.objects.get(id=business_id) postdata = { 'first_name': 'Test', 'surname': 'User', 'business': '1', 'slug': contact_slug, 'email': '[email protected]', 'phone': '12345678', 'mobile_phone': '9823452', 'business': 1, 'business_id': 1, } #Test to ensure contacts that should not exist are not returned contact_not_exists = Contact.objects.filter(slug=contact_slug) self.assertFalse(contact_not_exists) #Add the contact and ensure it is present in the DB afterwards """ contact_add_url = '%s%s/contact/add/' % (settings.BUSINESS_URL, business.slug) self.client.post(contact_add_url, postdata) added_contact = Contact.objects.filter(slug=contact_slug) print added_contact try: self.assertTrue(added_contact) except: formset = ContactForm(postdata) print formset.errors self.assertFalse(True, "Contact not found in the database - most likely, the post values in the test didn't validate against the form")

    Read the article

  • Problem using the prependTo() in jQuery

    - by raulriera
    Hi all, I am having a problem trying to use the prependTo() function in jQuery... for some reason I can't get this to work $(" <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> ").prependTo(".notes").fadeIn("slow"); Although when doing it like this, it works fine $.ajax({ url:'/chart-notes/show/<cfoutput>#chartnote.id#</cfoutput>', success: function(data) { $(data).prependTo(".notes").fadeIn("slow"); // Scroll to the top of the annotations $('html, body').animate({scrollTop: $(".notes").offset().top}, 1000); // Clear the form $('#chartnote-notes').val(""); } }); The "data" response from that success function is the same <div id="note178" class="note"> <div class="delete"><a href="/chart-notes/delete/178" onclick="$.ajax({ dataType: 'script', url: '/chart-notes/delete/178'}); return false;"><img src='/images/icons/delete.png'></a></div> <div class="timestamp">1 minute ago </div> <div class="content">ñasdas dasdasdasd conclusión</div> </div> As before

    Read the article

  • Disadvantages of MySQL Row Locking

    - by Nyxynyx
    I am using row locking (transactions) in MySQL for creating a job queue. Engine used is InnoDB. SQL Query START TRANSACTION; SELECT * FROM mytable WHERE status IS NULL ORDER BY timestamp DESC LIMIT 1 FOR UPDATE; UPDATE mytable SET status = 1; COMMIT; According to this webpage, The problem with SELECT FOR UPDATE is that it usually creates a single synchronization point for all of the worker processes, and you see a lot of processes waiting for the locks to be released with COMMIT. Question: Does this mean that when the first query is executed, which takes some time to finish the transaction before, when the second similar query occurs before the first transaction is committed, it will have to wait for it to finish before the query is executed? If this is true, then I do not understand why the row locking of a single row (which I assume) will affect the next transaction query that would not require reading that locked row? Additionally, can this problem be solved (and still achieve the effect row locking does for a job queue) by doing a UPDATE instead of the transaction? UPDATE mytable SET status = 1 WHERE status IS NULL ORDER BY timestamp DESC LIMIT 1

    Read the article

  • Mysql many to many problem (leaderborad/scoreboard)

    - by zoko2902
    Hi all! I'm working on a small project in regards of the upcoming World Cup. I'm building a roster/leaderboard/scoredboard based on groups with national teams. The idea is to have information on all upcoming matches within the group or in the knockout phase (scores, time of the match, match stats etc.). Currently I'm stuck with the DB in that I can't come up with a query that would return paired teams in a row. I have these 3 tables: CREATE TABLE IF NOT EXISTS `wc_team` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NULL , `description` VARCHAR(250) NULL , `flag` VARCHAR(45) NULL , `image` VARCHAR(45) NULL , `added` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id`) , CREATE TABLE IF NOT EXISTS `wc_match` ( `id` INT NOT NULL AUTO_INCREMENT , `score` VARCHAR(6) NULL , `date` DATE NULL , `time` VARCHAR(45) NULL , `added` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id`) , CREATE TABLE IF NOT EXISTS `wc_team_has_match` ( `wc_team_id` INT NOT NULL , `wc_match_id` INT NOT NULL , PRIMARY KEY (`wc_team_id`, `wc_match_id`) , I've simplified the tables so we don't go in the wrong direction. Now I've tried al kinds of joins and groupings I could think of, but I never seem to get. Example guery: SELECT t.wc_team_id,t.wc_match_id,c.id.c.name,d.id,d.name FROM wc_team_has_match AS t LEFT JOIN wc_match AS s ON t.wc_match_id = s.id LEFT JOIN wc_team AS c ON t.wc_team_id = c.id LEFT JOIN wc_team AS d ON t.wc_team_id = d.id Which returns: wc_team_id wc_match_id id name id name 16 5 16 Brazil 16 Brazil 18 5 18 Argentina 18 Argentina But what I really want is: wc_team_id wc_match_id id name id name 16 5 16 Brazil 18 Argentina Keep in mind that a group has more matches I want to see all those matches not only one. Any pointer or suggestion would be extremly appreciated since I'm stuck like a duck on this one :).

    Read the article

  • Going "behind Hibernate's back" to update foreign key values without an associated entity

    - by Alex Cruise
    Updated: I wound up "solving" the problem by doing the opposite! I now have the entity reference field set as read-only (insertable=false updatable=false), and the foreign key field read-write. This means I need to take special care when saving new entities, but on querying, the entity properties get resolved for me. I have a bidirectional one-to-many association in my domain model, where I'm using JPA annotations and Hibernate as the persistence provider. It's pretty much your bog-standard parent/child configuration, with one difference being that I want to expose the parent's foreign key as a separate property of the child alongside the reference to a parent instance, like so: @Entity public class Child { @Id @GeneratedValue Long id; @Column(name="parent_id", insertable=false, updatable=false) private Long parentId; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="parent_id") private Parent parent; private long timestamp; } @Entity public class Parent { @Id @GeneratedValue Long id; @OrderBy("timestamp") @OneToMany(mappedBy="parent", cascade=CascadeType.ALL, fetch=FetchType.LAZY) private List<Child> children; } This works just fine most of the time, but there are many (legacy) cases when I'd like to put an invalid value in the parent_id column without having to create a bogus Parent first. Unfortunately, Hibernate won't save values assigned to the parentId field due to insertable=false, updatable=false, which it requires when the same column is mapped to multiple properties. Is there any nice way to "go behind Hibernate's back" and sneak values into that field without having to drop down to JDBC or implement an interceptor? Thanks!

    Read the article

  • Object Oriented Programming Problem

    - by Danny Love
    I'm designing a little CMS using PHP whilst putting OOP into practice. I've hit a problem though. I have a page class, whos constructor accepts a UID and a slug. This is then used to set the properties (unless the page don't exist in which case it would fail). Anyway, I wanted to implement a function to create a page, and I thought ... what's the best way to do this without overloading the constructor. What would the correct way, or more conventional method, of doing this be? My code is below: <?php class Page { private $dbc; private $title; private $description; private $image; private $tags; private $owner; private $timestamp; private $views; public function __construct($uid, $slug) { } public function getTitle() { return $this->title; } public function getDescription() { if($this->description != NULL) { return $this->description; } else { return false; } } public function getImage() { if($this->image != NULL) { return $this->image; } else { return false; } } public function getTags() { if($this->tags != NULL) { return $this->tags; } else { return false; } } public function getOwner() { return $this->owner; } public function getTimestamp() { return $this->timestamp; } public function getViews() { return $this->views; } public function createPage() { // Stuck? } }

    Read the article

  • Relational MySQL - fetched properties?

    - by Kelso.b
    I'm currently using the following PHP code: // Get all subordinates $subords = array(); $supervisorID = $this->session->userdata('supervisor_id'); $result = $this->db->query(sprintf("SELECT * FROM users WHERE supervisor_id=%d AND id!=%d",$supervisorID, $supervisorID)); $user_list_query = 'user_id='.$supervisorID; foreach($result->result() as $user){ $user_list_query .= ' OR user_id='.$user->id; $subords[$user->id] = $user; } // Get Submissions $submissionsResult = $this->db->query(sprintf("SELECT * FROM submissions WHERE %s", $user_list_query)); $submissions = array(); foreach($submissionsResult->result() as $submission){ $entriesResult = $this->db->query(sprintf("SELECT * FROM submittedentries WHERE timestamp=%d", $submission->timestamp)); $entries = array(); foreach($entriesResult->result() as $entries) $entries[] = $entry; $submissions[] = array( 'user' => $subords[$submission->user_id], 'entries' => $entries ); $entriesResult->free_result(); } Basically I'm getting a list of users that are subordinates of a given supervisor_id (every user entry has a supervisor_id field), then grabbing entries belonging to any of those users. I can't help but think there is a more elegant way of doing this, like SELECT FROM tablename where user->supervisor_id=2222 Is there something like this with PHP/MySQL? Should probably learn relational databases properly sometime. :(

    Read the article

  • query structure - ignoring entries for the same event from multiple users?

    - by Andrew Heath
    One table in my MySQL database tracks game plays. It has the following structure: SCENARIO_VICTORIES [ID] [scenario_id] [game] [timestamp] [user_id] [winning_side] [play_date] ID is the autoincremented primary key. timestamp records the moment of submission for the record. winning_side has one of three possible values: 1, 2, or 0 (meaning a draw) One of the queries done on this table calculates the victory percentage for each scenario, when that scenario's page is viewed. The output is expressed as: Side 1 win % Side 2 win % Draw % and queried with: SELECT winning_side, COUNT(scenario_id) FROM scenario_victories WHERE scenario_id='$scenID' GROUP BY winning_side ORDER BY winning_side ASC and then processed into the percentages and such. Sorry for the long setup. My problem is this: several of my users play each other, and record their mutual results. So these battles are being doubly represented in the victory percentages and result counts. Though this happens infrequently, the userbase isn't large and the double entries do have a noticeable effect on the data. Given the table and query above - does anyone have any suggestions for how I can "collapse" records that have the same play_date & game & scenario_id & winning_side so that they're only counted once?

    Read the article

  • Use date operations on a computed field filter in a view

    - by stephenhay
    I'd like to expose a filter in Views based on a Computed Field. This field should utilize the date operation "less than". Apparently, a date type is not available to computed field (varchar is). However, using varchar results in views treating the field as a string rather than as a date, without the operation I'm looking for. So I tried using a timestamp instead of a date, which allowed me to use an integer data type. The exposed view gives me a "less than" operation, but as it's still not a date, the user must type in a timestamp. Not handy. So I'm thinking the best way to do this is to create a new (hidden) CCK field which is a date field, and set the value of this field to the value of the Computed Field. I can then use the new CCK field for my exposed filter. But I'm not getting anywhere with this, as I'm unsure how to set another CCK field with a Computed Field. To return the value to the computed field itself, I'm using the standard: $node_field[0]['value'] = $newestdate; I would like to set the value of the new CCK field to $newestdate as well. Can anyone help?

    Read the article

  • Non standard interaction among two tables to avoid very large merge

    - by riko
    Suppose I have two tables A and B. Table A has a multi-level index (a, b) and one column (ts). b determines univocally ts. A = pd.DataFrame( [('a', 'x', 4), ('a', 'y', 6), ('a', 'z', 5), ('b', 'x', 4), ('b', 'z', 5), ('c', 'y', 6)], columns=['a', 'b', 'ts']).set_index(['a', 'b']) AA = A.reset_index() Table B is another one-column (ts) table with non-unique index (a). The ts's are sorted "inside" each group, i.e., B.ix[x] is sorted for each x. Moreover, there is always a value in B.ix[x] that is greater than or equal to the values in A. B = pd.DataFrame( dict(a=list('aaaaabbcccccc'), ts=[1, 2, 4, 5, 7, 7, 8, 1, 2, 4, 5, 8, 9])).set_index('a') The semantics in this is that B contains observations of occurrences of an event of type indicated by the index. I would like to find from B the timestamp of the first occurrence of each event type after the timestamp specified in A for each value of b. In other words, I would like to get a table with the same shape of A, that instead of ts contains the "minimum value occurring after ts" as specified by table B. So, my goal would be: C: ('a', 'x') 4 ('a', 'y') 7 ('a', 'z') 5 ('b', 'x') 7 ('b', 'z') 7 ('c', 'y') 8 I have some working code, but is terribly slow. C = AA.apply(lambda row: ( row[0], row[1], B.ix[row[0]].irow(np.searchsorted(B.ts[row[0]], row[2]))), axis=1).set_index(['a', 'b']) Profiling shows the culprit is obviously B.ix[row[0]].irow(np.searchsorted(B.ts[row[0]], row[2]))). However, standard solutions using merge/join would take too much RAM in the long run. Consider that now I have 1000 a's, assume constant the average number of b's per a (probably 100-200), and consider that the number of observations per a is probably in the order of 300. In production I will have 1000 more a's. 1,000,000 x 200 x 300 = 60,000,000,000 rows may be a bit too much to keep in RAM, especially considering that the data I need is perfectly described by a C like the one I discussed above. How would I improve the performance?

    Read the article

  • Reading a C/C++ data structure in C# from a byte array

    - by Chris Miller
    What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12];} And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]public struct NewStuff{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking;} What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle;NewStuff MyStuff;int BufferSize = Marshal.SizeOf(typeof(NewStuff));byte[] buff = new byte[BufferSize];Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);handle = GCHandle.Alloc(buff, GCHandleType.Pinned);MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));handle.Free(); Is there better way to accomplish this?

    Read the article

  • Android: Resolution issue while saving image into gallery

    - by Luca D'Amico
    I've managed to programmatically take a photo from the camera, then display it on an imageview, and then after pressing a button, saving it on the Gallery. It works, but the problem is that the saved photo are low resolution.. WHY?! I took the photo with this code: Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); Then I save the photo on a var using : protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST) { thumbnail = (Bitmap) data.getExtras().get("data"); } } and then after displaying it on an imageview, I save it on the gallery with this function: public void SavePicToGallery(Bitmap picToSave, File savePath){ String JPEG_FILE_PREFIX= "PIC"; String JPEG_FILE_SUFFIX= ".JPG"; String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_"; File filePath = null; try { filePath = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, savePath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileOutputStream out = null; try { out = new FileOutputStream(filePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } picToSave.compress(CompressFormat.JPEG, 100, out); try { out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Add the pic to Android Gallery String mCurrentPhotoPath = filePath.getAbsolutePath(); MediaScannerConnection.scanFile(this, new String[] { mCurrentPhotoPath }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { } }); } I really can't figure out why it lose so much quality while saved.. Any help please ? Thanks..

    Read the article

  • Draw a comparison between an integer in a specific row and a count

    - by XCoderX
    This is a follow-up question to this one: Check for specific integer in a row WHERE user = $name I want a user to be able to comment on my site for exactly five times a day. After this five times, the user has to wait 24 hours. In order to accomplish that I raise a counter in my MYSQL database, right next to the user. So where the name of the user is, there is where the counter gets raised. When it reaches 5 it should stop counting and reset after 24 hours. In order to check the time I use a timestamp. I check if the timestamp is older than 24 hours. If that is the case, the counter gets reseted (-5) and the user can comment again. In order to do that, I use the following code, however it never stops at five, my guess is that my comparison is wrong somehow: $counter = "SELECT FROM table VALUES CommentCounterReset WHERE Name = '$name'"; if(!isset($_SESSION['ts'])); { $_SESSION['ts'] = time(); } if ($counter >= 5) { if (time() - $_SESSION['ts'] <= 60*60*24){ echo "You already wrote five comments."; } else { $sql = "UPDATE table SET CommentCounterReset = CommentCounterReset-5 WHERE Name = '$name'"; } } else { $sql = "UPDATE table SET CommentCounterReset = CommentCounterReset+1 WHERE Name = '$name'"; echo "Your comment has been added."; }

    Read the article

  • How to add a class to just upper element of trigger with Jquery?

    - by Ahmet Kemal
    Hello, I am working on a Jquery accordion stuff. I want to add a class to the div that contains the accordion trigger <a> tag. You can look at my code. I want to add "first" class name to just first "newsitems" class when clicked "Recession fashion in Japan Video" title. <!-- news items starts--> <div class="newsitems"> <h3 class="business"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Recession fashion in Japan Video</a> </h3> <p class="timestamp">0100hrs</p> </div> <!-- news items ends--> <!-- news items starts--> <div class="newsitems"> <h3 class="sports"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Murray survives five-set thriller at Wimbledon</a> </h3> <p class="timestamp">0100hrs</p> </div> <!-- news items ends-->

    Read the article

  • Static Logger in seperate thread?

    - by SirLenz0rlot
    Hi all, I've made my Logger, that logs a string, a static class with a static so I can call it from my entire project without having to make an instance of it. quite nice, but I want to make it run in a seperate thread, since accessing the file costs time is that possible somehow and what's the best way to do it? Its a bit of a short discription, but I hope the idea is clear. if not, please let me know. Thanks in advance! btw: any other improvements on my code are welcome as well, i have the feeling not everthing is as efficient as it can be: internal static class MainLogger { internal static void LogStringToFile(string logText) { DateTime timestamp = DateTime.Now; string str = timestamp.ToString("dd-MM-yy HH:mm:ss ", CultureInfo.InvariantCulture) + "\t" + logText + "\n"; const string filename = Constants.LOG_FILENAME; FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists) { if (fileInfo.Length > Constants.LOG_FILESIZE) { File.Create(filename).Dispose(); } } else { File.Create(filename).Dispose(); } int i = 0; while(true) { try { using (StreamWriter writer = File.AppendText(filename)) { writer.WriteLine(str); } break; } catch (IOException) { Thread.Sleep(10); i++; if (i >= 8) { throw new IOException("Log file \"" + Constants.LOG_FILENAME + "\" not accessible after 5 tries"); } } } } } enter code here

    Read the article

  • JNA Passing Structure By Reference Help

    - by tyeh26
    Hi all, I'm trying to use JNA to talk over a USB device plugged into the computer. Using Java and a .dll that was provided to me. I am having trouble with the Write function: C code: typedef struct { unsigned int id; unsigned int timestamp; unsigned char flags; unsigned char len; unsigned char data[16]; } CANMsg; CAN_STATUS canplus_Write( CANHANDLE handle, //long CANMsg *msg ); Java Equivalent: public class CANMsg extends Structure{ public int id = 0; public int timestamp = 0; public byte flags = 0; public byte len = 8; public byte data[] = new byte[16]; } int canplus_Write(NativeLong handle, CANMsg msg); I have confirmed that I can open and close the device. The close requires the NativeLong handle, so i am assuming that the CANMsg msg is the issue here. I have also confirmed that the device works when tested with C only code. I have read the the JNA documentation thoroughly... I think. Any pointers. Thanks all.

    Read the article

  • How should approach allowing users to create notes with revisions?

    - by Magicked
    I'm working on a Rails project where I want to allow users to create individual notes, which are really just text fields at this time. With each note, the user can edit what they have previously written, but the old version is kept in a revision table. I'm trying to figure out the best way to approach this. My initial thoughts are to have the following relationships: class User < ActiveRecord::Base has_many :notes end class Note < ActiveRecord::Base has_many :note_revisions belongs_to :user end class NoteRevision < ActiveRecord::Base belongs_to :note_revision end The Note model will only contain a timestamp of when the note was first created. The NoteRevision model will contain the text, as well as a timestamp for each revision. This way, every time a new revision is made, a new entry is created into the NoteRevision table which is tracked through the Note table. Hopefully this makes sense! First, does this look like a good way to do this? If so, I'm having trouble figuring out how the controller and view will present this information in one form. Are there any good tutorials or has someone seen anything similar that can point me in the right direction? Thanks in advance!

    Read the article

  • Entering Content Into A MySQL Database Via A Form

    - by ThatMacLad
    I've been working on creating a form that submits content into my database but I decided that rather than using a drop down menu to select the date I'd rather use a textfield. I was wondering what changes I will need to make to my table creation file. <?php mysql_connect ('localhost', 'root', 'root') ; mysql_select_db ('tmlblog'); $sql = "CREATE TABLE php_blog ( id int(20) NOT NULL auto_increment, timestamp int(20) NOT NULL, title varchar(255) NOT NULL, entry longtext NOT NULL, PRIMARY KEY (id) )"; $result = mysql_query($sql) or print ("Can't create the table 'php_blog' in the database.<br />" . $sql . "<br />" . mysql_error()); mysql_close(); if ($result != false) { echo "Table 'php_blog' was successfully created."; } ?> It's the timestamp that I need to edit to enter in via a textfield. The Title and Entry are currently being entered via that method anyway.

    Read the article

  • Preserving timestamps on Clojure .clj files when building shaded jar via Maven Shade Plugin

    - by Dereference
    When using the maven-shade-plugin to package our jar artifact that contained a few Clojure libs and some Java. We were using AOT compilation for our Clojure code. When we loaded the jar, it was having very slow load times. AOT compilation is supposed to help this quite a bit, but that wasn't what we were seeing. We noticed in java jar -verbose output that there was a lot of JVM__DEFINE_CLASS calls happening when Clojure classes were being loaded. This didn't make sense, since more of our Clojure code was AOT compiled to .class files. Turns out the maven-shade-plugin creates all new files, with new timestamps in the final artifact Clojure uses the timestamp information on a .clj file vs. a .class file, to determine if the file needs to be recompiled. The maven-shade-plugin was causing the .clj file and it's associated .class file to have the same timestamp, so Clojure always chose to dynamically recompile the source. The only workaround that we have been able to figure out, at this point, is to write a script that would re-open the shaded jar and bump the .clj file timestamps back to some time in the past, so that they wouldn't be equal to the timestamps of their associated .class files. Does anyone know of a better approach?

    Read the article

  • How to convert a list object to bigdecimal in prepared statement?

    - by user1103504
    I am using prepared statement for bulk insertion of records. Iam iterating a list which contains values and their dataTypes differ. One of the data type is BigDecimal and when i try to set calling preparedstatement, it is throwing null pointer exception. My code int count = 1; for (int j = 0; j < list.size(); j++) { if(list.get(j) instanceof Timestamp) { ps.setTimestamp(count, (Timestamp) list.get(j)); } else if(list.get(j) instanceof java.lang.Character) { ps.setString(count, String.valueOf(list.get(j))); } else if(list.get(j) instanceof java.math.BigDecimal) { ps.setBigDecimal(count, (java.math.BigDecimal)list.get(j)); } else { ps.setObject(count, list.get(j)); } count++; } I tried 2 ways to convert, casting the object and tried to create a new object of type BigDecimal ps.setBigDecimal(count, new BigDecimal(list.get(j).toString)); both donot solve my problem. It is throwing null pointer exception. help is appreciated. Thanks

    Read the article

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >