dimanche 28 juin 2015

Executing non-database actions in a transaction in Slick 3

I'm having trouble understanding the new Slick DBIOAction API, which does not seem to have a lot of examples in the docs. I am using Slick 3.0.0, and I need to execute some DB actions and also some calculations with the data received from the database, but all of those actions have to be done inside a single transaction. I'm trying to do the following:

  1. Execute a query to database (the types table).
  2. Do some aggregations and filtering of the query results (this calculation can't be done on the database).
  3. Execute another query, based on the calculations from step 2 (the messages table — due to some limitations, this query has to be in raw SQL).
  4. Join data from step 2 and 3 in memory.

I want the queries from step 1 and 3 to be executed inside a transaction, as the data from their result sets has to be consistent.

I've tried to do this in a monadic join style. Here's an overly simplified version of my code, but I can't even get it to compile:

  val compositeAction = (for {
    rawTypes <- TableQuery[DBType].result
    (projectId, types) <- rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10)))
    counts <- DBIO.sequence(types.map(aType => sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int]))
  } yield (projectId, types.zip(counts))).transactionally

  1. The first row of for comprehension selects the data from the types table.
  2. The second row of for comprehension is supposed to do some grouping and slicing of the results, resulting in a Seq[(Option[String], Seq[String])]
  3. The third row of for comprehension has to execute a set of queries for every element from the previous step, in particular, it has to execute a single SQL query for each of the values inside Seq[String]. So in the third row I build a sequence of DBIOActions.
  4. The yield clause zips types from the second step and counts from the third step.

This construction, however, does not work and gives two compile time errors:

Error:(129, 16) type mismatch;
 found   : slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.DBType#TableElementType, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect]
    (which expands to)  slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.TypeModel, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect]
 required: scala.collection.GenTraversableOnce[?]
        counts <- DBIO.sequence(types.map(aType => sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int]))
               ^
Error:(128, 28) type mismatch;
 found   : Seq[Nothing]
 required: slick.dbio.DBIOAction[?,?,?]
        (projectId, types) <- rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10)))
                           ^

I've tried to wrap the second line in a DBIOAction by using DBIO.successful, which is supposed to lift a constant value into the DBIOAction monad:

(projectId, types) <- DBIO.successful(rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10))))

But in this code the types variable is inferred to be Any, and the code does not compile because of that.

Full Export in PHPMyAdmin Problems

So today i was switching to my new webserver and when i backed up my mysql databases a did a full export.... is there anyway to import my full.sql file and still have all the databases separate and not all in one database?

POSTGRES - Combine same columns with different text in one row

I have three tables that i want to combine. I have a table doctor, patient and operation. Doctor represents all cind of doctors. Patient represents a patient and operation holds primaryKeys from patient and doctor. How do i write a query which will show me chiefDoctor and assistantDocotor and Patient? What did i reach so far?

Show firstname and lastname from one either Chiefdoctor or Assistantdoctor. How do i write to show a table with both Chief and Assistant in it?

select a.vorname|| ' ' || a.nachname AS leitenderArzt, p.firstname || ' ' || p.lastname AS patient
from angestellter a inner join operation o on a.id = o.leitenderarzt
inner join patient p on o.patientident=p.ident

| id | firstname       | lastname      | patient      |
| 1  | ImA             | ChiefDoctor1  | p.firstname  |
| 3  | ImA             | ChiefDoctor3  | p.firstname  |

The underlying structure of my database with a representation.

CREATE TABLE doctor
(
  id serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,  
  CONSTRAINT angestellter_pkey PRIMARY KEY (id),
}

 Table doctor
 |id | firstname | lastname        |
 | 1 | ImA       | ChiefDoctor1    |
 | 2 | ImA       | AssistantDoctor |
 | 3 | ImA       | ChiefDoctor2    |

CREATE TABLE patient
(
  ident serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,
  CONSTRAINT patient_pkey PRIMARY KEY (ident),
}

Table patient
| ident | firstname | lastname |
| 1     | Operated  | ME       |

CREATE TABLE operation
(
  id serial NOT NULL,
  chiefDoctor integer NOT NULL,
  AssistantDoctor integer NOT NULL,
  patientident integer NOT NULL,
  CONSTRAINT operation_pkey PRIMARY KEY (id),
  CONSTRAINT fkoperation539608 FOREIGN KEY (patientident)
      REFERENCES patient (ident) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation745809 FOREIGN KEY (assistantDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation949671 FOREIGN KEY (chiefDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
}

Table operation
| id | doctorID | doctorID | patientID |
| 1  |    1     |    2     |     1     |

How do i write a query which will show show who operated a patient with full name? It should look like this.

| id | chiefdoctor       | assistantdoctor      | patient      |
|----| ImA + ChiefDoctor |ImA + AssistantDoctor | Operated + ME|

Android - In App Purchase to remove admob ad bar

I am developing an app for Google Play that will integrate an admob ad bar. I see many apps on the appstore offer in app purchases to remove ads and would like to do the same with my app.

Are there any tutorials or ways you can think of to achieve this by not using SavedPreferences or having to query with a database that I'd have to create.

I may sound lazy but I really want a solution that would query with a Google Play server rather than one I will have to create.

My reasoning is because a server I would create would take their device id and I want the in app purchase to carry across multiple devices under one Google Play account.

What are the benefits and disadvantages of various database models?

I have a general overview of several models, including relational, document-based, graph-based, object-based, key-value store, etc., but what are the advantages and disadvantages of each?

Mongoose update not working with embedded objects

I'm working in the MEAN stack, and I'm stuck on a Mongoose issue. Updates are working fine for individual documents(single key:value), but when I attempt to update a nested object with a new object, it's just deleting the original object and not inserting the new one.

Using an identical query directly in mongo, within the terminal, works perfectly. But from my Mongoose model, I get the above behavior.

My final desired query is more complicated and uses many variables, so I've simplified the code to the following to highlight the issue:

Setup.update({name: "main"}, {$set: {"schedule.sunday.eleven_pm": { associates: 111, supervisors: 111}}}, function(err){
            if(err){
                console.log(err);
            }
            else{
                console.log('successfully updated main schedule setup')
                Setup.find({}, function(err, setup){
                    if(err){
                        console.log(err);
                    }
                    else{
                        res.json(setup);
                    }
                })
            }
        });

Gives me this in my db:

"eleven_pm" : {

        }

But from terminal, the same query (cut and pasted from my mongoose query, just added 'db.setups' to beginning:

db.setups.update({name: "main"}, {$set: {"schedule.sunday.eleven_pm": { associates: 111, supervisors: 111}}})

Gives me this, the desired result:

    "eleven_pm" : {
            "associates" : 111,
            "supervisors" : 111
        }

I've tried writing this as a findOneAndUpdate(), but encountered the same behavior. Am I doing something unorthodox here?

Any help greatly appreciated.

Something wrong with my IF statement

I created a simple code for my web game, there are no errors but some part of the code does not work. Parts which do not work are last two if statements, it won't give users an Antimatter, but it prints out correct message. Why it won't update DB correctly ?

CODE:

    ///////////////////////////////BLACKBOX////////////////
function buyblackbox(){
global $USER, $PLANET, $LNG, $UNI, $CONF,$resource,$pricelist;
$blackbox = HTTP::_GP('blackbox', 0);
$price = 10000 * $blackbox;
$loli   = mt_rand(1,2);
if ($price < 0) {
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
}
if($USER['antimatter'] < $price){
$this->printMessage("You do not have enough antimatter", true, array('game.php?page=premium', 2));
die();
}
elseif($blackbox < 0){
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
die();
}else{
    $USER['antimatter'] -= $price;
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkbox` = '".$loli."', `antimatter` = `antimatter` - '".$price."' WHERE `id` = ".$USER['id'].";");

if($USER['darkbox'] == 1)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` - '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('vins nem sit has succesfully be bought', true, array('game.php?page=premium', 2));
}
if($USER['darkbox'] == 2)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('BlackBox has succesfully be bought', true, array('game.php?page=premium', 2));
}
}
die();
}
/////////////////////////////////END BLACKBOX///////////////////////

Syncing data changes between devices (offline and online)

I have to create an application that has functionality similar to the contacts app. You can add a contact on the client's iPhone and it should get uploaded onto the client's iPad. If the client updates the contact on their iPad, it should get updated on their iPhone.

Most of this is fairly straight forward. I am using Parse.com as my back end and saving contacts locally with Core Data. The only problem I'm encountering is managing contacts when the user is offline.

Let's say I have an iPhone and an iPad. Both of them have the same up-to-date version of the online database. My iPhone is offline.

At 10AM I update the phone number for a contact on my iPad online. At 11AM I update the email address for the same contact on my iPhone but I'm offline.

Later that day my iPhone gets online and checks the servers for changes. It sees that all of its changes are more recent (checking an updatedAt timestamp property) and doesn't download the new phone number for the contact. Instead, it updates the properties that have changed since the older 10AM update and overrides the new phone number along with the email address.

How am I supposed to manage the online/offline problems encountered such as the one above?

I was thinking to have an updatedLocally and updatedOnline property on every object. This way if the two don't match I can do a diff-check and use the most recent one for conflicts but this doesn't seem like the cleanest solution. Has anyone else encountered this problem? If so, how did you solve it?

MS Access automation filling out forms and database tables

I have MS Access database, I need to automate filling out forms OR database tables from text file. How can I do it ?

Sql Error when running queires file

I am trying to run CREATE TABLE persons (id int(4) NOT NULL auto_increment, name varchar(30) NOT NULL, favorite_color varchar(30) NOT NULL, weight int(5) NOT NULL, favorite_movie varchar(20), state varchar(20), PRIMARY KEY (id));

I am recieving syntax error near unexpected token `('

Any help appreciated what im doing wrong.

Understanding the use of Gedmatch

I have been involved with genealogy for some time now. It is only recently that I have made strides forward to find my family and that was because of the use of various websites in Germany. About a year ago I use the Ancestry DNA option to find out what my DNA would tell me.

The initial result I got back from Ancestry was impressive and I was excited to find that there were over 15,000 people whose names I was given who were related to me. However when I started to check these people none of them had my last name which is Beucke. About four months ago I received notice that Ancestry DNA had changed and now my list dropped to 7,700 people but still no one with my last name. I have met numerous people on genealogy websites and many have told me that I should use Gedmatch to help me find valid relatives. I was not sure how Gedmatch could help me and I am still not certain that I can get any help from this website.

I accessed the Tools for DNA & Genealogy Research page and then selected Analyze Your Data and DNA Raw Data with the option One-To-Many Matches. The results I received were hard to understand. I selected three people from the list and what I received was a list of chromosomes that no match was found for. Even the ones that I did find a match for I have no idea what this means to me or to my research. If someone can explain this to me I would appreciate it.

Regards,

Garry Beucke (garry_beucke@hotmail.com)

PHP writing wrong value into DB?

I created the following table inside a DB

$sql = "CREATE TABLE tac_flightsize
(
    id int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id),

    gameid int NOT NULL,
    shipid int,
    flightsize int
 )";

I check for a DB write like this:

if (!$ship->superheavy){
   debug::log("db flight: " + $ship->flightSize);
   self::$dbManager->submitFlightSize($id, $gamedata->id, $ship->id, $ship->flightSize);
}

The debug::log entry shows 12 as the $ship->flightSize so the value is correct.

Here is the actual submitFlightSize function:

public function submitFlightSize($shipid, $gameid, $flightSize){
        try{
            $sql = "INSERT INTO `B5CGM`.`tac_flightsize` VALUES(null, $gameid, $shipid, $flightSize)";
            $id = $this->insert($sql);
            Debug::log($sql);

        }catch(Exception $e) {
            $this->endTransaction(true);
            throw $e;
        }
}

The Debug:::log from this function shows the follow SQL entry

INSERT INTO `B5CGM`.`tac_flightsize` VALUES(null, 2535, 16238, 1) 

Now, the last parameter is 1, when it should be 12 and was a second ago according to the earlier debug.

Can anyone explain to me what i might be doing wrong ?

What is the performance difference in MySQL relational division (IN AND instead of IN OR) implementations?

Because MySQL does not have a built in relational division operator, programmers must implement their own. There are two leading examples of implementations which can be found in this answer here.

For posterity I'll list them below:

Using GROUP BY/HAVING


SELECT t.documentid
FROM TABLE t
WHERE t.termid IN (1,2,3)
GROUP BY t.documentid
HAVING COUNT(DISINCT t.termid) = 3

The caveat is that you have to use HAVING COUNT(DISTINCT because duplicates of termid being 2 for the same documentid would be a false positive. And the COUNT has to equal the number of termid values in the IN clause.

Using JOINs


SELECT t.documentid
FROM TABLE t
JOIN TABLE x ON x.termid = t.termid
              AND x.termid = 1
JOIN TABLE y ON y.termid = t.termid
              AND y.termid = 2
JOIN TABLE z ON z.termid = t.termid
              AND z.termid = 3

But this one can be a pain for handling criteria that changes a lot.

Of these two implementation techniques, which one would offer the best performance?

Avoid Duplicate values for INSERT in SQL

  <?php 
mysql_query("INSERT INTO `users_badges` (`user_id`, `badge_id`, `badge_slot`) VALUES ('$my_id', 'VIP', '1')");
?>

I have this code to insert something in the table but every time if you visit the home page the same user gets the item dubplicated. How can I fix this.

So basicilly I want IF already you have VIP,the code doesn't have a value to avoid duplicate.

Mysql sub-filtering

Let's say I have a table U of users and a table R which represents the relations (friendships) between the users. Users are able to create posts which are saved in another table P (with the user_id of the user who sent the post).

I want to retrieve all the posts made by friends of friends of friends.... of friends of a specific person. This means when e.g. I have the following setup:

users (U)
  id - name
  1 - Mark
  2 - Eve
  3 - Peter

relations (R)
  id_user1 - id_user2
  1 - 2
  2 - 3

posts (P)
  id - user_id - text
  1 - 1 - "Hello from Mark"
  2 - 2 - "Hello from Eve"
  3 - 3 - "Hello from Peter"

and I want to retrieve all messages made by Mark, i would simply select all posts with Mark's user_id. But its getting tricky when I want to retrieve all the posts made by Mark's friends. Mark has only one friend in this example, so it's kind of obvious that we would get Eve's and Mark's post here. But let's assume he has 500. I would first execute a SQL command to retrieve all his friends and then do something like

SELECT * from posts WHERE user_id in (2,4,5,6,7,8,9,10,11,12.....,1442);

Well that seems quite inefficient, but it gets even worse when I want to get the messages made by friends of his friends (or even more sub-friend layers n): I would make n requests (one for each layer) to retrieve the id's of his friend's friends like in the example above. Then, when I have the result of the Id's of his n-sub-friends, I would do the same as above. For example, when we want to retrieve all posts by Marks friend's friends, we would get all the posts because Mark's friend Eve has Peter as a friend.

When the user has only 10 friends and each friend also got 10 friends, I would get 10^n ids. When I want to create a network containing ALL the posts of "somehow connected" friends, it would take ages to only get the ID's of all the users. And I guess the filtering with " in (....) " would take even longer when I pass like 100'000 id's.

Is there an efficient way to solve this problem?

I thought about saving some redundant data like associating every single sub-friend with every user directly in another table, but I doubt that this will work well because this would become a really gigantic table..

Warning: mysqli_num_rows() using MySQL search MATCH AGAINST $keywords [duplicate]

I am testing to get results using a new to me way of searching MySQL using MATCH AGAINST

Here is the code:

<?php
$keyworkds = mysqli_real_escape_string($database,$_POST['keywords']);
$result=mysqli_query($database,"
SELECT * FROM products 
WHERE MATCH (product,manufacturer,model) 
AGAINST ('$keyworkds')");
if(mysqli_num_rows($result)>0){
while($display=mysqli_fetch_assoc($result)){?>

Product:
<?php echo $display['product'] ?>

Manufacturer:
<?php echo $display['manufacturer'] ?>

Model:
<?php echo $display['model'] ?>



<?php }?>   

<?php }else{?> 

there are no results

<?php }?>

The problem is that I get the follow error and I can not see where the problem is. Any idea?

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/local/public_html/

System says the error is on line 89 the funny thing is that line 89 is empty and around it are only divs

Change default database of Bonita 6.5

I am using bonita 6.5 and I would like to change the organizational database : users , roles , tasks , permissions...(not data) of bonita to my mysql database. I've followed the official documentation but then I realised that it's maybe for data and I wonder if that's true !

1) If it's for data then how can I change the oraginzational DB ?

2) Otherwise , how can bonita "know" that I have users ... in that DB ? what are the changes that I have to make ? Thanks.

How to make a Child table to access another table laravel

I am using Laravel 5.1.

I have Three Table.

  • Films
  • Videos
  • Video Category

User can create a film and add many videos, but every video should belong to any one category (example. Making Video, Trailer Video, Film Events).

Now i want to fetch all films,video and video category of each video by passing a Film ID.

Table structure

Films Table

filmID | filmName 
-----------------
   1   |  Film 1
   2   |  Film 2

Video Table

videoID | catID | videoURL
--------------------------
   1    |  cat1 |   URL 1
   2    |  cat2 |   URL 2

Video Category Table

  catID  | category
--------------------
   cat1  |  Trailer
   cat2  |  Making
   cat3  |  Events

I can get All the Videos by passing FilmID

{
  filmId: "filmName",
  filmName: "Film Name",
  coverPhoto: "image URL",
  created_at: "2015-06-28 06:35:26",
  updated_at: "2015-06-28 06:35:45",
  videos: [
      {
        id: 7,
        filmId: "filmID",
        videoCategory: "trailer",
        videoUrl: "h41Jb29P4",
        created_at: "2015-06-28 11:40:22",
        updated_at: "2015-06-28 11:40:22"
      }
  ]
}

But how to i get the Video Category along with this output. Something like this

{
      filmId: "filmName",
      filmName: "Film Name",
      coverPhoto: "image URL",
      created_at: "2015-06-28 06:35:26",
      updated_at: "2015-06-28 06:35:45",
      videos: [
          {
            id: 7,
            filmId: "filmID",
            videoCategory: "trailer",
            videoUrl: "h41Jb29P4",
            created_at: "2015-06-28 11:40:22",
            updated_at: "2015-06-28 11:40:22"
            videoCategory: [
                  {
                     videoCategoryId: "1",
                     videoCategoryName: "Trailer"
                  }
            ]
          }
      ]
    }

Is there any way to do without passing multiple queries and merge in PHP?

Please anyone Help me.

Best practice for monitoring db table updates

I have a question 1) I have one table which will contain some rows (inserted by some other process after completing some work) 2) I need to make a process which will pick those rows, do some logic and then update an other system on REST.

Please suggest what is the best practice, Daemon or MQ? message queue? or any other best practice used for this thing.

How to record datareader results at Session?

How to record datareader results at Session? I read database then value that I read want to assigne at Session Thank you in advance for your advise

dr = islem.KayitGetir_DataReader("SELECT * FROM products P INNER JOIN products_description PD ON P.products_id = PD.products_id WHERE P.products_id='" + Session[i].ToString() + "'");

if (dr.Read())
{
    cartProductImage.ImageUrl = dr["products_thumbnails_images"].ToString();
    lblCartProductName.Text   = dr["pro_description_name"].ToString();
    lblCartProductPrice.Text  = dr["products_price"].ToString();
    dr.Close();

    Session["ProImg"]      = cartProductImage;
    Session["ProImgName"]  = lblCartProductName;
    Session["ProImgPrice"] = lblCartProductPrice;
}

How can I integrate data and program into single executable file?

Recently I created a project that manages details of students living in hostel and stores all the details regarding the fees paid by them.

I'm using Netbeans IDE to provide required GUI and ORACLE10g for the database support.
I want to know how can make these two components into one single executable file.
For example right now, when I export my program from one system to another I have to create (only one time though) DATABASE from scratch in new system and then I have to repeat all the queries to have same data as original system.
Are there any other way to accomplish above task automatically (i.e. from a executable file)?
I'm using Windows7.

Explaining how to use an OrientDB Schema

After a schema is generated or saved using the following basic code taken from the OrientDB docs, how can it be enforced? Where does the schema actually get saved to? It's pretty unclear in the docs how to actually use the schemas.

OSchema schema = database.getMetadata().getSchema();

What can we now do with this OSchema object?

Best way to optimize MySQL operations after a table grows

Background info: we run a an e-commerce website and are trying to figure out what is the best way to deal with "historical" data for tables that are used very frequently and are bound too contain a lot of records (ie. orders, customers, etc).

I am particularly looking at 2 specific scenarios:

  • DB migrations
  • SELECTs

DB migrations

In the case of DB migrations, we are starting to see that we sometimes need to run some ALTER TABLE which are locking the whole table and, if the table has so many records, this can take a while. Of course, all operations on the table are on hold until the migration is done, which means that our checkout might be down just because we are changing a VARCHAR(15) to VARCHAR(256).

From MySQL 5.6, a lot of operations are done "INPLACE" which means (from what I understood) that they wont be creating a full-table lock: that's ok-ish but still not perfect -- what if we need to change the type of a column (cannot be executed INPLACE) and we really do not want to be in maintenance mode for minutes?

My super-ghetto idea was to simply replicate the table (copy it over), then execute the migration on the copied table, stop writing to the original table (ie. lock it), copy the data that wasnt synced to the copied one and swap them. I think the percona tool for zero-downtime migrations does something similar so maybe that's the "best" approach?

Opinions?

SELECTs

For SELECTs, since most of the old data is accessed very rarely, I thought of range-partitioning it by date (say pre-2015 / post-2015 for example) and then change most of our queries to fetch stuff WHERE YEAR(created_at) >= 2015.

If the user wants his full historical data then we'd dynamically remove that condition. This somehow ensures that data is well-partitioned.

Any other idea? Do you think partitioning might be worth it?

mySQL innerjoin with where condition does not work

i'm trying to get a result of an mysql query for the last hours but did not get it. i hope you can help me. i have 2 sql tables. 1st is called 'drives' and is quite big with more than 200000 rows and 30 colums and a structure like: plate | time from | time to ab222 | 2015.05.12 08:00 | 2015.05.13 11:37 cv481 | 2015.05.14 12:08 | 2015.05.14 14:11

the second is called 'fuel' and is much shorter with about 5000 rows but also 22 colums. the structure of that is like: plate | time | amount | price ab222 | 2015.05.13 09:22 | 2.3 | 32.22 cv481 | 2015.05.14 13:59 | 12.2 | 17.7

what I'm going to do is to show for each row in 'fuel' table the right 'drive'. that means the time of the 'fuel' table has to be between the 'from time' and the 'to time' of the 'drives' table and the plate must be the same. the result should show the columns of both tables (so about 52 colums and 5000 rows because for each row in 'fuel' table must be one fitting drive in 'drive' table).

I'm not used to work with mysql so I googled a lot and tryed a lot. the following i made seems to be close to what I need:

INNER JOIN fuel.* ON
drives.plate = fuel.plate
WHERE fuel.time Between
drives.timefrom AND
drives.timeto

but it didnt work.

How is android.database different from android.database.sqlite?

I am trying to develop this android application whose database is not stored in the device but on a server. To use sqlite database I need to use android.database.sqlite; and I haven't made much use of android.database package. I went through the documentation site but it did not state clearly if it's possible can store my sqlite database file on server and invoke methods to access it from there. What should I do?

Selecting the right combination to fill DropDown list in asp

I'm working on an admission from . I was struck in simple problem. I've fourDropDown lists.three to Select the Major subjects and one to show the list whom Candidate can apply. I want to restrict the user to apply for the specific subject on the basis of selected subject. I only want to show the only the specific subject in fourth dropDown list. Suppose if user Select Physics , Computer and Statistics . He is should not able to apply for the Computer Sci ,Bio, Mathematics etc. How can I restrict the candidates to apply on the basis of selected subjects

Grocery CRUD Store longitude latitude to database

Hey I've this example code :

  <div id="map_canvas" style="width:50%; height:50%"></div>

  <div id="latlong">
  <p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>
</div>

</body>
</html>

<cfoutput>
<script type="text/javascript" src="http://ift.tt/1IllNtl"></script>
</cfoutput>

<script type="text/javascript">
//<![CDATA[

// global "map" variable
var map = null;
var marker = null;

// popup window for pin, if in use
var infowindow = new google.maps.InfoWindow({ 
    size: new google.maps.Size(150,50)
    });

// A function to create the marker and set up the event window function 
function createMarker(latlng, name, html) {

var contentString = html;

var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    zIndex: Math.round(latlng.lat()*-100000)<<5
    });

google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString); 
    infowindow.open(map,marker);
    });

google.maps.event.trigger(marker, 'click');    
return marker;

}

function initialize() {

// the location of the initial pin
var myLatlng = new google.maps.LatLng(33.926315,-118.312805);

// create the map
var myOptions = {
    zoom: 19,
    center: myLatlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

// establish the initial marker/pin
var image = '/images/googlepins/pin2.png';  
marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  icon: image,
  title:"Property Location"
});

// establish the initial div form fields
formlat = document.getElementById("latbox").value = myLatlng.lat();
formlng = document.getElementById("lngbox").value = myLatlng.lng();

// close popup window
google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
    });

// removing old markers/pins
google.maps.event.addListener(map, 'click', function(event) {
    //call function to create marker
     if (marker) {
        marker.setMap(null);
        marker = null;
     }

    // Information for popup window if you so chose to have one
    /*
     marker = createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng);
    */

    var image = '/images/googlepins/pin2.png';
    var myLatLng = event.latLng ;
    /*  
    var marker = new google.maps.Marker({
        by removing the 'var' subsquent pin placement removes the old pin icon
    */
    marker = new google.maps.Marker({   
        position: myLatLng,
        map: map,
        icon: image,
        title:"Property Location"
    });

    // populate the form fields with lat & lng 
    formlat = document.getElementById("latbox").value = event.latLng.lat();
    formlng = document.getElementById("lngbox").value = event.latLng.lng();

});

}
//]]>

Which I want to do is show maps in latitude and longitude field in grocery CRUD, and automatically fill both fields when I click the map like above html, then store the values to my database. How to do this ?

I tried callback_field function hidden field, but the values always zer0.

Any help would be appreciated. Thanks.

android database overwrite data on exist data

i have a database which have insert,delete,update function database work fine now i add some value to database . i add value in my splash activity like this

    foodDbHelper = new FoodDbHelper(context);
        sqLiteDatabase = foodDbHelper.getWritableDatabase();

        foodDbHelper.addInformations
                ("Paratha", "1 piece", 260, "8.99 g", "5.16 g", "2.18 g", "38.94 g");
        foodDbHelper.addInformations
                ("Chapatti", "1 Piece", 68, "0.62 g", "2.34 g", "0.26 g", "13 g");
        foodDbHelper.addInformations
                ("Alu Paratha", "1 Piece", 329, "6.16 g", "9.08 g", "3.9 g", "38.1 g");
        foodDbHelper.addInformations
                ("Vegetable Biryani", "1 Cup", 170, "0 g", "4 g", "8 g", "36 g");
        foodDbHelper.addInformations
                ("Chicken Biryani", "1 Tray", 480, "15 g", "34 g", "0 g", "51 g");

 foodDbHelper.close();

it store data in database when app run.but problem is that when every time i run app the data store every time and overwrite the exxisting data . when i update are delete value from database and again run the app value again store in database i want when i delete or update any value .and start again app it does not store the deleted value to database.

MySQL server and iOS

I run a site write now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Grails Relation m:n:n

We work with an existing mysql database under grails which contains a m:n relation. No problem here. But now we are in the situation that i have to add a second n relation entry, which links to the same table and has to be associated to the first n entry.

If it were for the database, I would simply create a table which looks like:

field m_id -> links to m table
field n_id1 -> links to n table
field n_id2 -> links to n table

But how can this be represented in a grails domain class?

Possibly the answer can already be found somewhere, but the searches I did were not successful, maybe due to lack of search term creativity.

using a session to show text for a specific group

This is a part of my session script:

$group='admin';

session_start();
header('Content-type: text/html;charset=UTF-8');
if(!isset($_SESSION['username']) and isset($_COOKIE['username'], $_COOKIE['password']))
{
  $cnn = mysql_query('select password,id,group from users where username="'.mysql_real_escape_string($_COOKIE['username']).'"');
  $dn_cnn = mysql_fetch_array($cnn);
  if(sha1($dn_cnn['password'])==$_COOKIE['password'] and mysql_num_rows($cnn)>0)
  {
    $_SESSION['username'] = $_COOKIE['username'];
    $_SESSION['userid'] = $dn_cnn['id'];
    $_SESSION['group'] = $dn_cnn['group'];
  }
}
?>

I want to show "blablabla" but only if you are in a group:

<?php
if(isset($_SESSION['group']) and $_SESSION['group']==$group)
{
?>
blablabla
 <?php 
 }
 ?>

In my table is a column named as "group". The group of this session is named as "admin" (that's why: $group='admin';) but it doesn't show the "blablabla".

Does someone know what I'm doing wrong?

PHP Code Doesn't insert data into the database on the web (godaddy) but works fine in localhost

I have written code that inserts some text data and also an image file through a form. the form processor code does not have to only insert and upload data but also create thumbnail for the image.
Now everything for image upload and creating the thumbnail works fine BUT when it comes to database and inserting the data into the table it doesn't insert data. I checked my database connection it is working fine. I also checked the same code in my localhost computer it works fine there too.
Note: I don't get any errors but it doesn't insert data into the database. I use godaddy.
Any cooperation and help will be highly appreciated.
Since the complete code is too long, Here is the code portion that has to insert data into the database.

include 'dbcon.php';
    //error_reporting(E_ALL ^ E_NOTICE);
    if(isset($_POST['submit']))
    {

    $file = ($_FILES['file']['name']);
    $author = $_POST['author'];
    $album = $_POST['name'];
    $imgdetails = $_POST['imgdetails'];
    $details = $_POST['details'];
    $datetime=date("M d, Y"); //date time 
    $jalali_date = jdate("l d p Y",$timestamp);
    $query = "INSERT INTO `fslide` (`picture`,`author`,  `album`, `imgdetails`, `details`, `date`, `fdate`) 
                                       VALUES ('$file', '$author', '$album', '$imgdetails', '$details', '$datetime', '$jalali_date');";
    $sql = mysql_query ($query);

Designing a database for storing 500 million domain names with full text search

I'm about to build an application that stores up to 500 million records of domain names. I'll index the '.net' or '.com' part and strip the 'www' at the beginning. So I believe the table would look like this:

domain_id | domain_name  | domain_ext
----------+--------------+-----------
1         | dropbox      | 2
2         | digitalocean | 2

domain_ext = 2 means it's a '.com' domain.

The queries I'm about to perform::

  1. I need to be able to insert new domains easily.
  2. I also need to make sure I'm not inserting a duplication (each domain should have only 1 record), so I think to make domain_name+domain_ext as UNIQUE index (with MySQL - InnoDB).
  3. Query domains in batches. For example: SELECT * FROM tbl_domains LIMIT 300000, 600;

What do you think? will that table hold hundreds of millions of records? How about partitioning by first letter of the domain name, would that be good? Let me know your suggestions, I'm open minded.

What will be the primary key of following relation

What will be the primary key of following relation R(A,B,C,D,E,F) F={AB ->C,BC ->DE,CD ->F}

ASP.NET Query database column with array of accepted keys

I've reached a problem with query the database correctly. I can't find it answered anywhere else.

My datamaodel contains three tables one with the Image data and another with tags. The third table joins the two tables creting a many to many relationship:

[Image] - 1 --- * ->[ImageTagJoin] <- * --- 1 - [Tag]

From a user input of a set of tags I want to get every image contaning all of the tags. The following code works for one tag

 viewModel.Tags = db.Tags.Where(
                            s =>
                                s.Name == searchString)
                         .Include(i => i.Images.Select( ii => ii.Image));
 viewModel.Images = t.Images.Select(x => x.Image);

The only solution I have is if, input is tag1, tag2, tag3, the controller iterated over each tag.

  1. Get set of images with the tag tag1
  2. From that set of images of tag1 get the subset of images with tag2
  3. From that set get the subset of images with tag3

Now I have a set of images with the tags tag1, tag2 and tag3. Though that this solution works but not as elegant because it requires to search the database once for every tag and every image row gets looked up for every tag in the input.

Conclusion: How can I query a many-to-many relationship between images and tags, where I select all images that have the subset of n tags given from the user.

Thanks.

CakePHP order in find() not displaying correctly

I'm trying to display data ordered by episode number, they range from 1 to 153. However, instead of displaying 1, 2, 3 ,4...100, etc, it's displaying 1, 10, 100,102, 11,...137... Does anyone have an idea why this is happening?

Databases for back end of websites

Which database system would be good to use for the back end of a website which would later handle large amounts of data? I was thinking of using SQL but considering that my project might expand over time I was thinking of going with hadoop. Will this be feasible?

How to create a database for page About us [on hold]

Help, I need to design a database for a site about us so http://ift.tt/1fXAVlJ

samedi 27 juin 2015

Web service in Rails to handle two databases

I asked in a question LINK how it was the best way to manage two databases MySQL for a Rails Web App. I searched "web services" in internet and i found a lot of things. My questions are:

1) I have to program an app in Rails, is it usefull to create the web service for this app in Rails too?

2) I have to use two databases , in my Web service how can i have to manage this?

for example, i need the list of the users of the DB1, so i write:

http://localhost:3000/users/

but how do i have to program the web service to be able to separate the two databases? I mean , if i need the users od the DB2 i would use an url like the before one:

http://localhost:3000/users/     (but for DB2)

3) I know that in a web service we should create the WSDL file. But is really necessary in my case? i will not publish the web service so , i think is not necessary to create the WSDL. is it?

Sorry for the newbie questions but it's my first time in web service programming.

How to Design Optimised Database Structure

I was working on eCommerce site and i am unable to optimize my database.Problem is:Suppose i have 10 venders with same products but with different product price. I want to design the database structure,but unable to get the optimised database structure.Further the venders can increase.If anyone with good database knowledge please help me to solve this problem.Thanks in advance.

How to model assets and a map with a composite key using Tuple and Generic

I have Versioned Maps objects that are represented/identified by 4 datatypes (or dimensions) like a guid, car, location, time, for e.g.
Tuple<GUID/Int64, AssetType, TimeT (can be.. DateTime/DateRange), LocationT (i.e. lat-long or SqlSpatial/SqlGeo)

MyCompositeType<MyKeyInt64,Tuple<T1,T2,T3,T4>> 

This forms the composite key, but when one of the types inside the TupleKey Changes the EF and SQL primary breaks. Can you tell me how to model/declare this key and not break EF or the DB - so that I can change the types in my key, please sprinkle some wisdom, if I should get rid MyKeyInt64 and just work off the Tuple?

For e.g. <Int64,<Tuple<GUID, Car, DateRange, SpatialType>> If I pass in a different key type to the same CompositeType<Int64, Tuple<Int64, Truck, DateTime, SpatialType>

Background:
The combination of the data represents a key / unique version of a map that forms a record. I'm cross walking between Asset/objects/list<> and the maps and need two-way access, i.e.

  • a) i.e. given a map version/key (represented by the combination of the above)-- getback/access the corresponding -- objectsList<>, location and time
  • or b) given the objectType, or time, get the corresponding maps

Since, most of the operations performed leverage the data in these 4 types in some combination of all or some of types. Hence I'm making a composite key

Question: How do I model this correctly as a composite key, where I can fit various Object/AssetTypes into the Composite type for EF compatibility and cross-walking between the Assetobjects and Maps, given, a time range, or asset type or map?

create two connections MySQL on Rails project

I am creating a CRM(Customer relationship management) in Rails. I have to use two databases(MySQL).I have a doubt in the correct use of these databases.

I mean, i read on internet that is possible to open two connections in a Rails project, but is this the right way to hit the problem? is really good to open two connection in a project?

is it used?if not, what is the solution in the state of art(maybe the simpler to manage queries) for my problem?

Alternative for mydac and unidac

I just want to ask if there are other ways to connect my mobile app in a remote MySQL database other than UniDac or myDac which is free.

Im using delphi xe8 for development.

I already research a lot about these, and I also tried a lot of options like firedac or dbexpress, still not getting any solutions. i tried mydac and it works, the problem is for now, i cant pay for the license so im looking for an alternative to mydac or unidac.

most research results points me to firedac, dbexpress or devart's liteDAC which is also licensed. what I did is this, i bought a host in a cloud server provider which I can create a remote database on it. so I created a database in there, which I will use it for my mobile app. i cant use firedac, it says i needed to get libmysqlclient.so or libmysqld.so and put it on a the path where the exe is, i just wonder, what could be the exe that xe8 points here?

i cant even use dbexpress also. when I open my app, It just give me a blackscreen, and dont even show the form. I tried to wait for a minute or two, hoping that it was just trying to connect to the database, still in the same black screen. i put the configuration process of the dbexpress to the form's show event.

thanks a lot for any help.

Android app development with remote database

I am new to android development. I would like to create an app that would store data in a remote database and i should be able to retrieve it. Which would the appropriate server and database for this application?

Inserting a time into mysql database in java

I'm wanting to insert a time which is taken from a textbox to the mysql database TIME column. I suppose I need to convert String to TIME like converting String to Date in mysql using "STR_TO_DATE" in the query. I looked for answers but I didn't get the answer I required. If anyone could suggest me a method for that would be really helpful.

Laravel Queue, Beanstalkd vs Database, what are the differences?

Is there much difference between using Beanstalkd and a database driver for queues?

What would some pros and cons be? The database queue seems to easier to setup and run, what should I know about using it?

Theres no real explanations in the docs about it.

Which database to choose between MS SQLSERVER or PostgreSQl

I am developing re-engineering a system so that all my existing desktop system can be hosted in a single server & single database (a sort of SAAS model).

While combining all the database the new database will be 500+GB. More, the expected concurrent users will be 5000+ users.

I am confused on which databased to choose between SQLSERVER & PROGRESQL.

Thanks Shakti

Are 'rajivratn'@'%' and rajivratn@localhost refer to same user in MySQL?

I want load data into a table (dataset) of a database. I am using the standard command

 LOAD DATA INFILE '/home/rajivratn/single_output.tsv' IGNORE INTO TABLE dataset ...

I am getting the following permission error:

ERROR 1045 (28000): Access denied for user 'rajivratn'@'localhost' (using password: YES)

Most of the post suggested that this problem is due to FILE privilege on MySQL and can be fixed by the following GRANT command:

GRANT FILE ON *.* to 'rajivratn'@'%';

I have checked the permission and found the following:

mysql> show grants for 'rajivratn'@'%'
    -> ;
+--------------------------------------+
| Grants for rajivratn@%               |
+--------------------------------------+
| GRANT FILE ON *.* TO 'rajivratn'@'%' |
+--------------------------------------+
1 row in set (0.00 sec)

mysql> show grants;
+------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for rajivratn@localhost                                                                                                                 |
+------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'rajivratn'@'localhost' IDENTIFIED BY PASSWORD 'somepassword'                               |
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON `yahoo`.* TO 'rajivratn'@'localhost' |
+------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

However, I am still getting the ERROR 1045 (28000): Access denied for user 'rajivratn'@'localhost' (using password: YES)

Moreover, Why I can not see the FILE permission in Grants for rajivratn@localhost and why it is different from the grants of 'rajivratn'@'%'

Any suggestions to fix this issue?

Thanks

Error in connecting Local Database (.sdf)

//SqlCeConnection con = new SqlCeConnection( "Data Source="
  + System.IO.Path.Combine( Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location ), "DBThree.sdf" ) );

//SqlCeConnection con = new SqlCeConnection( @"Data Source=|DataDirectory|\DBThree.sdf" );

//SqlCeConnection con = new SqlCeConnection( ConfigurationManager.ConnectionStrings["DBThreeConnectionString"].ConnectionString );

SqlCeConnection con = new SqlCeConnection( @"Data Source=""C:\Users\Visual Studio 2012\Projects\ForTesting2\ForTesting2\DBThree.sdf""" ); 
con.Open();
string comnd = "SELECT COUNT (*) FROM Mytable";
SqlCeCommand com1 = new SqlCeCommand( comnd, con );

string test1 = com1.ExecuteScalar().ToString() ;
label1.Text = "AAA\t" + test1;
con.Close();

I am getting the following error:

System.Data.SqlServerCe.SqlCeException (0x80004005): There was an error parsing the query. [ Token line number = 1,Token line offset = 23,Token in error = Mytable ]

I also tried the connection strings which are commented in above code. The connection string in App.config looks like

<connectionStrings>
    <add name="DBThreeConnectionString"
        connectionString="Data Source=|DataDirectory|\DBThree.sdf"
        providerName="Microsoft.SqlServerCe.Client.4.0" />
</connectionStrings>

Error comparing values in "if" construct

I am doing a face recognition project, and I want to compare the x.label returned value with the ID saved to database. I always get an error in if condition comparing the ID with the x.label

  public int Predict(Image<Gray, Byte> testImage)
        {

            Emgu.CV.FaceRecognizer.PredictionResult x;
            if (testImage != null)
            {
                x= fr.Predict(testImage);
                pictureBox1.Image = testImage.ToBitmap();
                //MessageBox.Show(x.Label.ToString()+" "+x.Distance.ToString());

                OleDbCommand D1 = new OleDbCommand("Select [ID] FROM [connect]", DBConnection);
                OleDbDataReader reader = D1.ExecuteReader();
                while (reader.Read())
                {

                   if (Convert.ToInt32(reader["ID"]) == x.Label)
                   {

                       OleDbCommand insert1 = new OleDbCommand("UPDATE OutputReport SET [Attendance]='yes' WHERE [StudentID]='109';", DBConnection);
                       insert1.ExecuteNonQuery();
                        MessageBox.Show(" its working");
                    }
               }
                RefreshDBConnection();


                if (x.Distance < 69)
                    return x.Label;
                else
                    MessageBox.Show("Error!!, The detected Face is neither recognised nor enrolled");
                return -1;
            }

            else

            {

                return -1;
            }

        }