问:
Best practices and data types for relative short strings in MySQL?
In most projects I've worked on, stuff like usernames are stored as the default VARCHAR(45). I've been under the mistaken impression that the (45) was just a display limit, but the docs indicate that it's the maximum number of characters you want to store.

This seems kind of annoying to me. Does this mean that you have to guess at the high end and implement some kind of check to warn your user every time a value for that field is provided? Do most devs simply declare something like VARCHAR(10000)?

Another field I have is for a short summary. This answer gives some examples of when to use VARCHAR (username) vs TEXT (messages). The field I'm looking at could have strings in the 300-2000 character range by my best guess. Is this still suitable for VARCHAR? What's the best way to protect or warn if it tries to store something too large?

答:
Varchar datatype is suitable for holding text in the 300-2000 character range, since it can hold up to 65,535 bytes of data (remember, if you use multi-byte character set, such as utf8, then the actual byte length is more than the character length).

What you need to consider is the overall record size limit of MySQL (65,535 bytes, which is shared among all columns) when you choose between varchar and any text fields:

The entire byte length of a varchar field counts towards the record size limit

For text fields only a table engine dependent part is stored within the record, which counts toward the overall record limit. The rest is stored somewhere else (again, it is table engine dependent).

So, if you need to store several 2k character long fields in  record, then you may hit the max record size limit and be forced to use text. Otherwise, you can use varchar.

And what's the best way to protect or warn if it tries to store something too large? Well, if you prevent users from entering more characters than allowed is a good start. Check out what SO does when you type a comment, it is quite a good example of restricting the length of text that can be typed. But it all depends on your exact application and audience.


来源: stackexchange

问:
add data attributes to <options> rendered by django form library
I have django choice field

The HTML rendered by django looks like this:

```<code><select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take">Take</option>
 <option value="query-action-forward">Forward</option>
</select>
</code>```

Before executing the action which was choosen by the user, a confirmation should happen. But not all actions need a confirmation. In this example "delete" needs, but "take" does not need a confirmation.

I would like to add html data attributes the options

The result should look like this:

```<code><select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take"   data-need-confirm="False">Take</option>
 <option value="query-action-delete" data-need-confirm="True">Delete</option>
</select>
</code>```

Up to now I found no way to inject the data "need confirmation" into individual choices.

... or am I on the wrong track here?

This question is only about "how to get the data into the html". The evaluation of the data (confirmation popup) is not part of this question.

答:
The template renderer definitely contains the functionality to add the data, the question is where you get it from.

```<code><select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 {% for action in actions %}
  <option value="{{action.value}}"   data-need-confirm="{{action.isConfirm}}">{{action.name}}</option>
 {% endfor %}
</select>
</code>```

Would this be something you want to add to a model? Probably not. But you can add it as a hard coded dictionary too.

ContentLicense: CC BY-SA 3.0

Body:
I have django choice field

The HTML rendered by django looks like this:

<select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take">Take</option>
 <option value="query-action-forward">Forward</option>
</select>

Before executing the action which was choosen by the user, a confirmation should happen. But not all actions need a confirmation. In this example "delete" needs, but "take" does not need a confirmation.

I would like to add html data attributes the options

The result should look like this:

<select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take"   data-need-confirm="False">Take</option>
 <option value="query-action-delete" data-need-confirm="True">Delete</option>
</select>

Up to now I found no way to inject the data "need confirmation" into individual choices.

... or am I on the wrong track here?

This question is only about "how to get the data into the html". The evaluation of the data (confirmation popup) is not part of this question.

Body:
The template renderer definitely contains the functionality to add the data, the question is where you get it from.

<select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 {% for action in actions %}
  <option value="{{action.value}}"   data-need-confirm="{{action.isConfirm}}">{{action.name}}</option>
 {% endfor %}
</select>

Would this be something you want to add to a model? Probably not. But you can add it as a hard coded dictionary too.


问:
update table column using two subset query
I am using one query where i have to update one column for that i have two subset of query which is below:

select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author' from (
select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='en-US') a
INNER JOIN
(select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='de-DE') b
ON a.documentnodeid =b.documentnodeid```

using this query i have value like below:

Now i have to update target author with source author.

答:
Use a common table expression</p>

```<code>;WITH cteUpdate
AS(
    select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author'
    FROM
    (
            SELECT d.documentnodeid,AuthorId from wv_blogdata
            INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
            WHERE DocumentCulture ='en-US'
    ) a
    INNER JOIN
    (       SELECT d.documentnodeid,AuthorId from wv_blogdata
            INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
            WHERE DocumentCulture ='de-DE'
    ) b
    ON a.documentnodeid =b.documentnodeid
)
UPDATE
    cteUpdate
SET
    cteUpdate.Target_Author = cteUpdate.Source_Author
</code>```

Body:
I am using one query where i have to update one column for that i have two subset of query which is below:

select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author' from (
select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='en-US') a
INNER JOIN
(select d.documentnodeid,AuthorId from wv_blogdata
inner join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
Where DocumentCulture ='de-DE') b
ON a.documentnodeid =b.documentnodeid

using this query i have value like below:

Now i have to update target author with source author.

Body:
Use a common table expression

;WITH cteUpdate
AS(
    select a.AuthorId as 'Source_Author',b.AuthorId as 'Target_Author'
    FROM
    (
            SELECT d.documentnodeid,AuthorId from wv_blogdata
            INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
            WHERE DocumentCulture ='en-US'
    ) a
    INNER JOIN
    (       SELECT d.documentnodeid,AuthorId from wv_blogdata
            INNER join CMS_Document d on wv_blogdata.BlogDataID = d.DocumentForeignKeyValue
            WHERE DocumentCulture ='de-DE'
    ) b
    ON a.documentnodeid =b.documentnodeid
)
UPDATE
    cteUpdate
SET
    cteUpdate.Target_Author = cteUpdate.Source_Author


问:
Send email with profile picture PHP mail function
I would like to show a profile picture in my users inbox when they receive an email sent from my website with PHP.

In this image the first email is from my website and the second one is what I want.

And here is my PHP mail function:

```<code>            $emailTo=$_POST['emialNewPass'];
            $emailSubject="Recovery";
            $emailLoctuz="noreply@loctuz.com";
            $message="msg";

            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                            // En-têtes additionnels
            $headers .= 'To: '.$emailTo."\r\n";
            $headers .= 'From: Loctuz Security <'. $emailLoctuz . '>' ."\r\n";

            if(@mail($emailTo,$emailSubject,$message, $headers))
            {
                ?><script>window.location = "?sent";</script><?php
            }
</code>```

答:
I don't believe that there is a way to add an avatar image to a MIME email

As far as Gmail goes.  If you add an image to your Gmail profile, it will automatically be shown when another Gmail user gets an email from you, looks you up in their address book, or chats with you.

Assuming its not gmail then its read from the users address book or contacts.  Neither of which you have access to edit.

ContentLicense: CC BY-SA 4.0

Body:
I would like to show a profile picture in my users inbox when they receive an email sent from my website with PHP.

In this image the first email is from my website and the second one is what I want.

And here is my PHP mail function:

            $emailTo=$_POST['emialNewPass'];
            $emailSubject="Recovery";
            $emailLoctuz="noreply@loctuz.com";
            $message="msg";

            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                            // En-têtes additionnels
            $headers .= 'To: '.$emailTo."\r\n";
            $headers .= 'From: Loctuz Security <'. $emailLoctuz . '>' ."\r\n";

            if(@mail($emailTo,$emailSubject,$message, $headers))
            {
                ?><?php
            }


问:
Unity Android Game Redirecting to setting/wifi screen automatically
I am working on mobile game project Android and IOS.

I used 3 plugins in my game (OneSignal, Google Play Game Services and OpenIAB).

I make the build in my android device (LG Nexus 5x) and everything is working fine, I tested on some Hawaii devices and its pretty good.

But when I tried this on Samsung S4 weird thing started happening, when I play game with my wifi on everything run smoothly, but when i turned off the wifi game automatically redirect me to the settings screen of android device.

I was searching the issue when the other colleague came to me with another Samsung S4 device in which if wifi is off the game redirect user to the wifi enabling screen in settings BUT if you leave the wifi off and came back to game it automatically turn on the wifi and connect to it.

I was searching alot with issues in plugins and in my game but everything is fine and didn't fine any other related issue.

Please Help to cure this weirdness.

答: This sometimes occurs when at the time of building the game, you must have set the base version in which the game runs as something which is more advanced than  the s4 mobile. Also there is an alternative option wich can llow you to play the game without net connection. you may check out that and rebuild it. hope this works!</p>


问:
What is the best way to deal with JSON object?
I have a big string that represents JSON feed. My app downloads this feed from remote web service.

Questions:

1) Once I download JSON feed, where should I store it? Right now I am storing it in app Preferences and it works fine. I am just interested if there is any reason not to do that, or if there are better/faster options, like Internal Storage or something else?

2) When I am about to show data from this feed in my activity, I do something like this:

```<code>JSONObject jsonObj = new JSONObject(json_string);
JSONArray jsonArr = jsonObj.getJSONArray("root");
for (int m = 0; m < jsonArr.length(); m++) {
    ....
}
</code>```

The problem is, the first line that parses JSON feed is sort of expensive. At my current size feed (that might grow in the future) it takes maybe half a second to complete, not much, but still a problem. For example, I click button to call activity (to show data) and this 1/2 sec pause is noticeable and not good.

To avoid this pause, I should probably parse JSON immediately after feed is downloaded. Then question is, where should I keep parsed JSON object?

i) I can't save JSON object to preferences since only primitive data can be stored there.

ii) Should I do parsing every time my app starts, and make my parsed JSON objects (I have more of them) global (on application level) so I can access them from all of my activities?

iii) Or, I believe my 3rd option would be to declare JSON objests static so they can be easy accessed from other activities?

What is the best way to do this?

THX.

答:
It sounds like you should be using the SQLite database to store the values you pull out from the JSON.  This should help you get started: http://developer.android.com/guide/topics/data/data-storage.html#db

All of your activities within your application can then query the database for the data.  If you are using a ListView to view the information, you would be able to use a CursorAdapter to easily populate the list.

You could even create a Content Provider to share this information with other applications

ContentLicense: CC BY-SA 2.5

Body:
I have a big string that represents JSON feed. My app downloads this feed from remote web service.

Questions:

1) Once I download JSON feed, where should I store it? Right now I am storing it in app Preferences and it works fine. I am just interested if there is any reason not to do that, or if there are better/faster options, like Internal Storage or something else?

2) When I am about to show data from this feed in my activity, I do something like this:

JSONObject jsonObj = new JSONObject(json_string);
JSONArray jsonArr = jsonObj.getJSONArray("root");
for (int m = 0; m < jsonArr.length(); m++) {
    ....
}

The problem is, the first line that parses JSON feed is sort of expensive. At my current size feed (that might grow in the future) it takes maybe half a second to complete, not much, but still a problem. For example, I click button to call activity (to show data) and this 1/2 sec pause is noticeable and not good.

To avoid this pause, I should probably parse JSON immediately after feed is downloaded. Then question is, where should I keep parsed JSON object?

i) I can't save JSON object to preferences since only primitive data can be stored there.

ii) Should I do parsing every time my app starts, and make my parsed JSON objects (I have more of them) global (on application level) so I can access them from all of my activities?

iii) Or, I believe my 3rd option would be to declare JSON objests static so they can be easy accessed from other activities?

What is the best way to do this?

THX.


问:
Is it possible to inherit css class?
I have two css classes:

```<code>magrin{
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}
</code>```

Is it possible to make #MainContent class inherit magrin class?

答:
No.

CSS inheritance is from parent element to child element, not from one ruleset to another.

You can write your styles using a grouping selector, apply multiple classes to a single element, or use a preprocessing tool such as SASS or LESS.

In this case, a grouping selector (,) would probably be the best fit:

```<code>#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}

#MainContent, magrin{
    margin-top:35px;
    background-color:red;
}
</code>```

Title: Is it possible to inherit css class?

Body:
I have two css classes:

magrin{
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}

Is it possible to make #MainContent class inherit magrin class?

Body:
No.

CSS inheritance is from parent element to child element, not from one ruleset to another.

You can write your styles using a grouping selector, apply multiple classes to a single element, or use a preprocessing tool such as SASS or LESS.

In this case, a grouping selector (,) would probably be the best fit:

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}

#MainContent, magrin{
    margin-top:35px;
    background-color:red;
}


问:
How to give value to previously defined string inside onClick block in android studio
So i have 2 activities that link to each other through an intent, but i need the second page to know what was clicked in the previous page. Heres what i mean.

```<code>public class featuredvendors extends AppCompatActivity {

public String nextpageref;
</code>```

The string i would like to edit is declared above.

```<code>t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);

            startActivity(t2);
        }
    });
</code>```

So essentially, i want to change the value of nextpageref based on what was clicked on. However it seems that i cant change the value inside an onClick block. Is there anyway i can pass the value "post1" to a string, but ONLY when this particular button is clicked? I need it this way because the next page 'featureddetails' needs to know this String value in order to pull the correct information from the DB.

答:
In the onClick block add this

```<code>t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);
t2.putString("key", nextpageref);
            startActivity(t2);
        }
    });
</code>```

In the next activity get value from this piece of code in onCreate's method

```<code>Intent i= getIntent();
String value = i.getStringExtra("key");
Log.e("value", value);
</code>```

Body:
So i have 2 activities that link to each other through an intent, but i need the second page to know what was clicked in the previous page. Heres what i mean.

public class featuredvendors extends AppCompatActivity {

public String nextpageref;

The string i would like to edit is declared above.

t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);

            startActivity(t2);
        }
    });

So essentially, i want to change the value of nextpageref based on what was clicked on. However it seems that i cant change the value inside an onClick block. Is there anyway i can pass the value "post1" to a string, but ONLY when this particular button is clicked? I need it this way because the next page 'featureddetails' needs to know this String value in order to pull the correct information from the DB.

Body:
In the onClick block add this

t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);
t2.putString("key", nextpageref);
            startActivity(t2);
        }
    });

In the next activity get value from this piece of code in onCreate's method

Intent i= getIntent();
String value = i.getStringExtra("key");
Log.e("value", value);


问:
Is there any way to protect your binary code (shared library) from illegal use?
I develop some codes and pack them into several shared libraries (*.so in Android OS). I would share them to some vendors but I want these libraries can be used only on one or more Android devices.
I tried to get the device unique id and check is the id legal or not, but it seems there is no any id that represents a unique device and can not be changed even the device is re-flashed. I know there is a CPUID under x86 windows system, but not similar thing under arm-based Android device. Also, for the sake of linux security mechanism, I can't get anything like MAC for flash id either from user space without root.

Any ways to achieve that ? Look forward to your advice. Thanks.

答:
Even if you try to do that, someone can just decompile your library and revert these countermeasures. There is no way you can avoid that.

If this is not a concern to you, you can get the IMEI of the device. The downside is that there might not be one (most likely the case if it is a tablet without 3G). Here is how: How to get the device's IMEI/ESN programmatically in android?

If you want to get the MAC address you can try this (still, not guaranteed that it will work, plus it is easy to spoof): Getting MAC address in Android 6.0

This is also an interesting read, however most of these methods are likely to not uniquely identify a device once it has been reset: https://developer.android.com/training/articles/user-data-ids.html


问:
AVMutableVideoCompositionInstruction background Color using UIImage?
```<code>I want to change the background color for AVMutableVideoCompositionInstruction which is working fine.But in when I am using UIImage for Color Pattern its not Working ??? Please Help...here is code Image Using.also I am giving is BackgroundColor White but its not Showing it White.
</code>```

<p>here is my code I am using: </p>

```<code>AVMutableVideoCompositionInstruction *MainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    MainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
    MainInstruction.layerInstructions = layerInstructionsArr;
    UIColor  *bgBlurrcolor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"aa.png"]];
    MainInstruction.backgroundColor = bgBlurrcolor.CGColor;
</code>```

答:
Check these links

Only solid BGRA colors are supported; patterns and other supported colors are ignored. If the rendered pixel buffer does not have alpha, the alpha value of the background color is ignored.
If the background color is NULL, the video compositor uses a default background color of opaque black.

https://developer.apple.com/reference/avfoundation/avvideocompositioninstruction?language=objc

https://developer.apple.com/reference/avfoundation/avvideocompositioninstruction/1389384-backgroundcolor?language=objc

Body:
I want to change the background color for AVMutableVideoCompositionInstruction which is working fine.But in when I am using UIImage for Color Pattern its not Working ??? Please Help...here is code Image Using.also I am giving is BackgroundColor White but its not Showing it White.

here is my code I am using:

AVMutableVideoCompositionInstruction *MainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    MainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
    MainInstruction.layerInstructions = layerInstructionsArr;
    UIColor  *bgBlurrcolor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"aa.png"]];
    MainInstruction.backgroundColor = bgBlurrcolor.CGColor;


问:
PrimeNg AutoComplete Multiple - Preselect value

In the PrimeNg AutoComplete Multiple mode, is there a way to display preselect values? I have tried to add

 but nothing happened.

答:
Alright so I found a solution for that. Do it with a formControl.

In the html do this

, and in the component do this public myValue= new FormControl([]); and this.myValue.setValue(initialValues);

Body:
Alright so I found a solution for that. Do it with a formControl.

In the html do this <p-autoComplete [formControl]="myValue" ></p-autoComplete>, and in the component do this public myValue= new FormControl([]); and this.myValue.setValue(initialValues);


问:
SQL query get last value
I want to get the last time (by date) that appears a (Empleado) where the value "Entrar" is 1
enter image description here

```<code>SELECT '20498090R'
FROM fichajes
WHERE fecha IN (SELECT MAX(fecha) FROM fichajes)
  AND entrada = '1'
</code>```

But this give me the las register where entrada= '1' and I just want to return information if the last entry is 1, not the las entry where entrada ='1'

In this case my last register entrada = "0" so i need no information
What is wrong?

答:
The  following code is for if you want the most recent value of Fecha for a specific employee (in this case "20498090R") if that employee has an entrada value of 1.

```<code>SELECT maxFecha
FROM
(
    SELECT MAX( fecha ) AS maxFecha,
           entrada AS entrada
    FROM fichajes
    WHERE empleado = '20498090R'
) withEntrada
WHERE entrada = 1;
</code>```

The following code is for if you want the most recent value of Fecha for each employee with a value of entrada equalling 1.

```<code>SELECT empleado,
       maxFecha
FROM
(
    SELECT empleado AS empleado,
           MAX( fecha ) AS maxFecha,
           entrada AS entrada
    FROM fichajes
    GROUP BY empleado
) withEntrada
WHERE entrada = 1;
</code>```

If you have any questions or comments, then please feel free to post a Comment accordingly.

Title: SQL query get last value

Body:
I want to get the last time (by date) that appears a (Empleado) where the value "Entrar" is 1
enter image description here

SELECT '20498090R'
FROM fichajes
WHERE fecha IN (SELECT MAX(fecha) FROM fichajes)
  AND entrada = '1'

But this give me the las register where entrada= '1' and I just want to return information if the last entry is 1, not the las entry where entrada ='1'

In this case my last register entrada = "0" so i need no information
What is wrong?

Body:
The  following code is for if you want the most recent value of Fecha for a specific employee (in this case "20498090R") if that employee has an entrada value of 1.

SELECT maxFecha
FROM
(
    SELECT MAX( fecha ) AS maxFecha,
           entrada AS entrada
    FROM fichajes
    WHERE empleado = '20498090R'
) withEntrada
WHERE entrada = 1;

The following code is for if you want the most recent value of Fecha for each employee with a value of entrada equalling 1.

SELECT empleado,
       maxFecha
FROM
(
    SELECT empleado AS empleado,
           MAX( fecha ) AS maxFecha,
           entrada AS entrada
    FROM fichajes
    GROUP BY empleado
) withEntrada
WHERE entrada = 1;

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
Lazarus: Can't find unit [unit] used by [program]
I'm trying to use an external library (wingraph) in a simple program. I have .o and .ppu files. I added the directory that contains them to the list of both "Other Unit Files" and "Include Files" paths under Project->Compiler Options. When building, I still get the error "Can't find unit wingraph used by [program]".

The library is Windows specific and I'm compiling on Windows, too.

What should I do to solve the problem?

Note that I don't have extensive knowledge about Pascal itself nor its tools. I'm just trying to quickly help someone start using the library.

答:
In future, if this happens make sure any Units used in main units are tagged in the 'uses' section as such:</p>

```<code>uses Unit1, Unit2...;
</code>```

Body:
In future, if this happens make sure any Units used in main units are tagged in the 'uses' section as such:

uses Unit1, Unit2...;


问:
Android SQL retrieve and set multiple rows
Hello I have setup a small SQL query which simply returns the users email address when two ID's match up. Now I have a very simple problem where now I want to return another row e.g. persons name but I'm little stuck on setting up the selection and then setting the text on another activity. In my current code I can set one value but some guidance would be nice.

Handler.java

```<code>public String getContactDetails(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = null;
    String name = "";

    try {
        cursor = db.rawQuery("SELECT email FROM person_list WHERE person_id=?", new String[] {id + ""});

        if(cursor.getCount() > 0) {

            cursor.moveToFirst();
            name = cursor.getString(cursor.getColumnIndex("email"));

            // how can I get another row?

        }
        return name;
    }finally {
        cursor.close();
    }
}
</code>```

Main Activity...

```<code>MyDatabaseHandler myDatabaseHandler = new MyDatabaseHandler(getApplicationContext(), null, null, 1);

String email = myDatabaseHandler.getContactDetails(id);
</code>```

Thanks
It's more than likely something really simple.

答:
To call next data, you can use cursorObject.moveToNext(). This method will return false if the cursor is already past the last entry in the result set.

Cursor Android Developer

```<code>public String getContactDetails(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = null;
    String name = "";

    try {
        cursor = db.rawQuery("SELECT email FROM person_list WHERE person_id=?", new String[] {id + ""});

        if(cursor.getCount() > 0) {

            if (cursor.moveToFirst()){
              do{
                  name = cursor.getString(cursor.getColumnIndex("email"));
                } while (cursor.moveToNext()); // more to next data.
            }
        }
        return name;
    }finally {
        cursor.close();
    }
}
</code>```

Body:
Hello I have setup a small SQL query which simply returns the users email address when two ID's match up. Now I have a very simple problem where now I want to return another row e.g. persons name but I'm little stuck on setting up the selection and then setting the text on another activity. In my current code I can set one value but some guidance would be nice.

Handler.java

public String getContactDetails(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = null;
    String name = "";

    try {
        cursor = db.rawQuery("SELECT email FROM person_list WHERE person_id=?", new String[] {id + ""});

        if(cursor.getCount() > 0) {

            cursor.moveToFirst();
            name = cursor.getString(cursor.getColumnIndex("email"));

            // how can I get another row?

        }
        return name;
    }finally {
        cursor.close();
    }
}

Main Activity...

MyDatabaseHandler myDatabaseHandler = new MyDatabaseHandler(getApplicationContext(), null, null, 1);

String email = myDatabaseHandler.getContactDetails(id);

Thanks
It's more than likely something really simple.

Body:
To call next data, you can use cursorObject.moveToNext(). This method will return false if the cursor is already past the last entry in the result set.

Cursor Android Developer

public String getContactDetails(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = null;
    String name = "";

    try {
        cursor = db.rawQuery("SELECT email FROM person_list WHERE person_id=?", new String[] {id + ""});

        if(cursor.getCount() > 0) {

            if (cursor.moveToFirst()){
              do{
                  name = cursor.getString(cursor.getColumnIndex("email"));
                } while (cursor.moveToNext()); // more to next data.
            }
        }
        return name;
    }finally {
        cursor.close();
    }
}


问:
this.props.params not existing after passing parameter on react-router
I'm passing parameter from react-router's route path to component but in this.props object, 'params' not existing

```<code>const routes = (
    <Router forceRefresh={true}>
        <div>
            <Route exact path="/" component={Firstpage}/>
            <Route exact path="/projects" component={Projectslist}/>
            <Route exact path="/projects/:projectId" component={Singleproject}/>
        </div>
    </Router>
);
</code>```

And this is my component:

```<code>class Singleproject extends React.Component{
    constructor(props) {
        super(props);
    }

    componentWillMount(){
        window.document.title = "Wploper | Project title";
    }
    render(){
        return(
            <div>
                <Mainheader/>
                <div id="single-project-container" className="sheet-max-width">
                    <h2>{this.props.params}</h2>
                </div>
                <Mainfooter/>
            </div>
        );
    }
}
</code>```

And the object (this.props) hasn't params:
enter image description here

答:
You can get the parameter from the route through context.
this.context.params.projectId

Body:
I'm passing parameter from react-router's route path to component but in this.props object, 'params' not existing

const routes = (
    <Router forceRefresh={true}>

            <Route exact path="/" component={Firstpage}/>
            <Route exact path="/projects" component={Projectslist}/>
            <Route exact path="/projects/:projectId" component={Singleproject}/>

    </Router>
);

And this is my component:

class Singleproject extends React.Component{
    constructor(props) {
        super(props);
    }

    componentWillMount(){
        window.document.title = "Wploper | Project title";
    }
    render(){
        return(

                <Mainheader/>

{this.props.params}

                <Mainfooter/>

        );
    }
}

And the object (this.props) hasn't params:
enter image description here


问:
NSMutablearray addobject , added objects not expected
I've a question about NSMutablearray addobject, I think it's about object lifecycle. Searched but not got answer.

Here's the code:

```<code>    NSMutableString *str1 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr1 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str1 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr1 addObject:str1] ;
        NSLog(@"arr1 inside loop:%@",arr1) ;
        [str1 setString:@""] ;    }
    NSLog(@"arr1 outside loop:%@",arr1) ;

    NSMutableString *str2 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr2 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr2 addObject:str2] ;        }
    [str2 setString:@"abc"] ;
    NSLog(@"arr1:%@",arr2) ;
</code>```

I expect that arr1 & arr2 both include 3 random number objects.
but the real output is:

```<code>arr1 inside loop:(
    83
)
arr1 inside loop:(
    "",
    86
)
arr1 inside loop:(
    "",
    "",
    77
)
arr1 outside loop:(
    "",
    "",
    ""
)
arr2:(
    15,
    93,
    abc
)
</code>```

Q1: Arr1, why the added objects changed to ""?
(If the reason is all 3 objects are just 3 pointers and they point to the same object, then I have Q2 --)

Q2: Arr2, why the last object of arr2 is "abc" but the others not.

Thanks!

答:
[str1 setString:@""] modifies the string you have added to the array. In the first step you have a mutable string with value "83" but at the end of the iteration you are rewriting this same mutable string with an empty string "".

You can remove the line because you don't use the same instance again, actually, you don't need a mutable string at all:

```<code>for (int i = 0; i < 3; i++) {
   NSString *randomString = [NSString stringWithFormat:@"%ld", (random() % 100)] ;
   [arr1 addObject:randomString];
   NSLog(@"arr1 inside loop:%@", arr1);
}
</code>```

Body:
I've a question about NSMutablearray addobject, I think it's about object lifecycle. Searched but not got answer.

Here's the code:

    NSMutableString *str1 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr1 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str1 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr1 addObject:str1] ;
        NSLog(@"arr1 inside loop:%@",arr1) ;
        [str1 setString:@""] ;    }
    NSLog(@"arr1 outside loop:%@",arr1) ;

    NSMutableString *str2 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr2 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr2 addObject:str2] ;        }
    [str2 setString:@"abc"] ;
    NSLog(@"arr1:%@",arr2) ;

I expect that arr1 & arr2 both include 3 random number objects.
but the real output is:

arr1 inside loop:(
    83
)
arr1 inside loop:(
    "",
    86
)
arr1 inside loop:(
    "",
    "",
    77
)
arr1 outside loop:(
    "",
    "",
    ""
)
arr2:(
    15,
    93,
    abc
)

Q1: Arr1, why the added objects changed to ""?
(If the reason is all 3 objects are just 3 pointers and they point to the same object, then I have Q2 --)

Q2: Arr2, why the last object of arr2 is "abc" but the others not.

Thanks!

Body:
[str1 setString:@""] modifies the string you have added to the array. In the first step you have a mutable string with value "83" but at the end of the iteration you are rewriting this same mutable string with an empty string "".

You can remove the line because you don't use the same instance again, actually, you don't need a mutable string at all:

for (int i = 0; i < 3; i++) {
   NSString *randomString = [NSString stringWithFormat:@"%ld", (random() % 100)] ;
   [arr1 addObject:randomString];
   NSLog(@"arr1 inside loop:%@", arr1);
}


问:
Javascript / JQuery how to loop through all html elements with attribute aria-invalid
I have some dynamically ajax generated form:

```<code><form id="formThatWillBeReplcaedViaAjax">

  <div class="col-main">

    <div class="row">
       <div class="input-group">
         <input id="some_unique_generated_id_27362"  aria-invalid="false" ... >
       </div>
    </div>

    <div class="row">
       <div class="input-group">
         <input id="some_unique_generated_id_27363"  aria-invalid="false" ... >
       </div>
    </div>

    <div class="row">
       <div class="input-group">
         <input id="some_unique_generated_id_27364"  aria-invalid="false" ... >
       </div>
    </div>

   </div>

</form>
</code>```

I have some animation function (loader()  )  and  the   function  that replaces the current form with the next form (  requestNextForm()   )

I want to  check by looping through form with pure JS or JQuery to check if all attributes aria-invalid are equal to "false".

If they are, then let the loader() load the animation and only then request the next form via requestNextForm().

How can I do it with JQuery or JS or maybe Lodash ?

Thank you in advance!

答:
get all inputs with the attribute aria-invalid whose value is not "false" using querySelectorAll

usr the selector 'input[aria-invalid]:not([aria-invalid="false"])' which translates to: return all input elements that have an attribute aria-invalid whose value is not "false"

if the above query returns any matches, you know that not all inputs with aria-invalid are "false"

Here's what the code could look like:

```<code>var ariaInvalidNotFalse = document.querySelectorAll('input[aria-invalid]:not([aria-invalid="false"])');

if(ariaInvalidNotFalse.length > 0){
  // Some elements have aria-invalid
  // but with a value that is not false
} else {
  // All inputs with aria-invalid
  // have it set to "false"
  // Call loader() etc...
}
</code>```

Body:
I have some dynamically ajax generated form:

<form id="formThatWillBeReplcaedViaAjax">

         <input id="some_unique_generated_id_27362"  aria-invalid="false" ... >

         <input id="some_unique_generated_id_27363"  aria-invalid="false" ... >

         <input id="some_unique_generated_id_27364"  aria-invalid="false" ... >

</form>

I have some animation function (loader()  )  and  the   function  that replaces the current form with the next form (  requestNextForm()   )

I want to  check by looping through form with pure JS or JQuery to check if all attributes aria-invalid are equal to "false".

If they are, then let the loader() load the animation and only then request the next form via requestNextForm().

How can I do it with JQuery or JS or maybe Lodash ?

Thank you in advance!

Body:
get all inputs with the attribute aria-invalid whose value is not "false" using querySelectorAll

usr the selector 'input[aria-invalid]:not([aria-invalid="false"])' which translates to: return all input elements that have an attribute aria-invalid whose value is not "false"

if the above query returns any matches, you know that not all inputs with aria-invalid are "false"

Here's what the code could look like:

var ariaInvalidNotFalse = document.querySelectorAll('input[aria-invalid]:not([aria-invalid="false"])');

if(ariaInvalidNotFalse.length > 0){
  // Some elements have aria-invalid
  // but with a value that is not false
} else {
  // All inputs with aria-invalid
  // have it set to "false"
  // Call loader() etc...
}


问:
Highlight NSImageView - Objective-c
Is there a way to "highlight" a NSImageView with the default highlight color of the mac? I'm simply looking for a way to tint my nsimageview so that the user can identify the object easily.

Thanks,

Kevin

答:
If one of the built-in options of NSImageView isn't sufficient, you could subclass NSImageView, and in drawRect, do:

```<code>- (void)drawRect:(NSRect)frame {
   [super drawRect:frame]; // this takes care of image
   [NSBezierPath setDefaultLineWidth:4.0];
   [[NSColor highlightColor] set];
   [NSBezierPath strokeRect:frame]; // will give a 2 pixel wide border
}
</code>```

Ahh, to have it as a variable state, I'd probably define an instance variable then, such as isHighlighted to keep track of that state. Then, whenever anything happens that would change the highlighted state, you'll set the view as needing redisplay. You could do this in the set/get methods for instance:

```<code>- (void)setHighlighted:(BOOL)aHighlighted {
   isHighlighted = aHighlighted;
   [self setNeedsDisplay:YES];
}
</code>```

Then, update your drawRect: method to take into account the isHighlighted flag. How you achieve an unhighlighted look may depend on the style of image view. You could try just calling super to do the drawing, but if in testing, you see any residual or stray highlighted pixel information that super's drawing didn't overwrite, you may want to first draw clear color, then call super.

So, something like this:

```<code>- (void)drawRect:(NSRect)frame {
   isHighlighted ? [[NSColor highlightColor] set] : [[NSColor clearColor] set];
   [NSBezierPath setDefaultLineWidth:4.0];
   if (isHighlighted) {
      [super drawRect:frame];
      [NSBezierPath strokeRect:frame]; // will give a 2 pixel wide border
   } else {
      [NSBezierPath fillRect:frame];
      [super drawRect:frame];
   }
}
</code>```

Title: Highlight NSImageView - Objective-c

Body:
If one of the built-in options of NSImageView isn't sufficient, you could subclass NSImageView, and in drawRect, do:

- (void)drawRect:(NSRect)frame {
   [super drawRect:frame]; // this takes care of image
   [NSBezierPath setDefaultLineWidth:4.0];
   [[NSColor highlightColor] set];
   [NSBezierPath strokeRect:frame]; // will give a 2 pixel wide border
}

Ahh, to have it as a variable state, I'd probably define an instance variable then, such as isHighlighted to keep track of that state. Then, whenever anything happens that would change the highlighted state, you'll set the view as needing redisplay. You could do this in the set/get methods for instance:

- (void)setHighlighted:(BOOL)aHighlighted {
   isHighlighted = aHighlighted;
   [self setNeedsDisplay:YES];
}

Then, update your drawRect: method to take into account the isHighlighted flag. How you achieve an unhighlighted look may depend on the style of image view. You could try just calling super to do the drawing, but if in testing, you see any residual or stray highlighted pixel information that super's drawing didn't overwrite, you may want to first draw clear color, then call super.

So, something like this:

- (void)drawRect:(NSRect)frame {
   isHighlighted ? [[NSColor highlightColor] set] : [[NSColor clearColor] set];
   [NSBezierPath setDefaultLineWidth:4.0];
   if (isHighlighted) {
      [super drawRect:frame];
      [NSBezierPath strokeRect:frame]; // will give a 2 pixel wide border
   } else {
      [NSBezierPath fillRect:frame];
      [super drawRect:frame];
   }
}


问:
how C_CreateObject , C_GenerateKey and C_GenerateKeyPair are different ?
Our PKCS#11 library miss the implementation of C_CreateObject. Before jumping into its implementation, i want to know the instances where C_CreateObject should be used instead of C_GenerateKey/C_GenerateKeyPair .</p>

答: C_CreateObjectimports existing data objects, certificates and/or keys generated externally into the device. C_GenerateKey generates new symmetric key (DES/AES/...) inside the device. C_GenerateKeyPair generates new asymmetric key pair (RSA/ECC/...) inside the device.


问:
Simple Java based Spark program doesn't get Finished
I created a very simple "Word count" Java based Spark program, and I am running it in a cluster running on YARN with the below details:

Hadoop details:

Master Node (NN, SNN, RM) - 192.168.0.100

Slave  Nodes (DN, NM) - 192.168.0.105, 192.168.0.108

Spark details:

Master running on : 192.168.0.100

Workers running on : 192.168.0.105, 192.168.0.108

I have created a client machine from where I submit the Spark job (The IP address of client machine is --> 192.168.0.240).

The below command I used to submit the Job to Spark:

```<code>spark-submit --class com.example.WordCountTask --master yarn /root/SparkCodeInJava/word-count/target/word-count-1.0-SNAPSHOT.jar /spark/input/inputText.txt /spark/output
</code>```

However the program doesn't terminate at all, the data-set is very small (10 text lines) and I expect it to finis without taking much time.

The below is the output I see on console after submitting the Job:

```<code>17/03/26 19:54:42 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:43 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:44 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:45 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:46 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
</code>```

And this continues forever. I am not sure why this isn't getting completed.

This is what I see in GUI for this application:

The below is the output of: yarn logs -applicationId application_1490572543329_0002

```<code>17/03/26 20:24:09 WARN util.NativeCodeLoader: Unable to load native-hadoop libra
/tmp/logs/root/logs/application_1490572543329_0002 does not exist.
</code>```

Log aggregation has not completed or is not enabled.

This is my first Spark program, and I configured to run it on YARN cluster.

I simulate the distributed environment using 4 VM's , Cent OS running on Virtualbox.

Can anyone help me why this program isn't functioning properly?

Update:

I set up the environment in AWS , with two launched instance with good configuration (8 Vcpu's and 32 GB RAM), but the job isn't still getting completed.

(A) yarn-site.xml

```<code>    <property>
            <name>yarn.nodemanager.auxservices</name>
            <value>mapreduce_shuffle</value>
    </property>

    <property>
            <name>yarn.resourcemanager.address</name>
            <value>ip-XXX-YYYY-ZZZ-AAA.us-west-2.compute.internal:8032</value>
    </property>
</code>```

(B) After submitting the Job using spark-submit, I see this in the output which is displayed on console:

```<code>17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**
</code>```

Has this to do anything with the Job not getting finished?

答: If "ACCEPTED" status keeps continuing with out any "FAILED" status at any time it means the cluster resource allocation allows your job to be submitted but currently there is no free resource in order to launch your job in container. The state machine looks similar to hadoop tasks' </p>

Body:
I created a very simple "Word count" Java based Spark program, and I am running it in a cluster running on YARN with the below details:

Hadoop details:

Master Node (NN, SNN, RM) - 192.168.0.100

Slave  Nodes (DN, NM) - 192.168.0.105, 192.168.0.108

Spark details:

Master running on : 192.168.0.100

Workers running on : 192.168.0.105, 192.168.0.108

I have created a client machine from where I submit the Spark job (The IP address of client machine is --> 192.168.0.240).

The below command I used to submit the Job to Spark:

spark-submit --class com.example.WordCountTask --master yarn /root/SparkCodeInJava/word-count/target/word-count-1.0-SNAPSHOT.jar /spark/input/inputText.txt /spark/output

However the program doesn't terminate at all, the data-set is very small (10 text lines) and I expect it to finis without taking much time.

The below is the output I see on console after submitting the Job:

17/03/26 19:54:42 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:43 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:44 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:45 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)
17/03/26 19:54:46 INFO yarn.Client: Application report for application_1490572543329_0001 (state: ACCEPTED)

And this continues forever. I am not sure why this isn't getting completed.

This is what I see in GUI for this application:

The below is the output of: yarn logs -applicationId application_1490572543329_0002

17/03/26 20:24:09 WARN util.NativeCodeLoader: Unable to load native-hadoop libra
/tmp/logs/root/logs/application_1490572543329_0002 does not exist.

Log aggregation has not completed or is not enabled.

This is my first Spark program, and I configured to run it on YARN cluster.

I simulate the distributed environment using 4 VM's , Cent OS running on Virtualbox.

Can anyone help me why this program isn't functioning properly?

Update:

I set up the environment in AWS , with two launched instance with good configuration (8 Vcpu's and 32 GB RAM), but the job isn't still getting completed.

(A) yarn-site.xml

    <property>
            <name>yarn.nodemanager.auxservices</name>
            <value>mapreduce_shuffle</value>
    </property>

    <property>
            <name>yarn.resourcemanager.address</name>
            <value>ip-XXX-YYYY-ZZZ-AAA.us-west-2.compute.internal:8032</value>
    </property>

(B) After submitting the Job using spark-submit, I see this in the output which is displayed on console:

17/03/29 15:51:35 INFO yarn.Client: Requesting a new application from cluster with **0 NodeManagers**

Has this to do anything with the Job not getting finished?


问:
iPhone Development - EXC_BAD_ACCESS error with no stack trace
Here's my case: I have a table view showing contacts. Add button in the navigation bar is used to load another view for data entry. This new view has images in table header, and each table cell has either a UITextField or a UITextView. When i press Cancel, the view is popped out and memory is released.

Here's my issue: When i open the "Add" interface, provide a value in any of the UITextField or UITextView, and press "Cancel" to to go back to the parent view, i get an EXC_BAD_ACCESS error. When i trace it, the "Add Controller" calls dealloc properly, but after the [super dealloc] when i press Continue, it throws this error. Just this, no trace, although i'm using NSZombieEnabled. When i run the code with Instruments, i don't get any error :(

I hope i'm clear in explaining the issue. Any pointers? Thanks.

答:
Although this is most often a result of mismanaged memory, it can happen for other reasons (and be harder to debug than simply turning on NSZombieEnabled). For example, if you fail to supply the correct number of arguments to a format string (i.e. while debugging another problem with NSLog), you could end up with no stack trace even with all debugging arguments enabled. Luckily, you can use GDB within Xcode to restore the stack trace to a previous state.

In the GDB console you should see the instruction that crashed your program. Locate the last successful return instruction before the one that failed. It should look something like this:

```<code>je    0x986cef35 <objc_msgSend+117>
</code>```

Note the hex value and execute the following in GDB:

```<code>set $eip = 0x986cef35
stepi
where
</code>```

You should (hopefully) have a more informative stack trace now.

Source (same as the link above)

OwnerDisplayName: Mustafa

LastEditorDisplayName: Chris Hanson

Body:
Although this is most often a result of mismanaged memory, it can happen for other reasons (and be harder to debug than simply turning on NSZombieEnabled). For example, if you fail to supply the correct number of arguments to a format string (i.e. while debugging another problem with NSLog), you could end up with no stack trace even with all debugging arguments enabled. Luckily, you can use GDB within Xcode to restore the stack trace to a previous state.

In the GDB console you should see the instruction that crashed your program. Locate the last successful return instruction before the one that failed. It should look something like this:

je    0x986cef35 <objc_msgSend+117>

Note the hex value and execute the following in GDB:

set $eip = 0x986cef35
stepi
where

You should (hopefully) have a more informative stack trace now.

Source (same as the link above)


问:
in_array() and multidimensional array
I use in_array() to check whether a value exists in an array like below,

```<code>$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
    echo "Got Irix";
}

//print_r($a);
</code>```

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

```<code>$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);
</code>```

or I shouldn't be using in_array() when comes to the multidimensional array?

答:
Here is my proposition based on json_encode() solution with :

case insensitive option

returning the count instead of true

anywhere in arrays (keys and values)

If word not found, it still returns 0 equal to false.

```<code>function in_array_count($needle, $haystack, $caseSensitive = true) {
    if(!$caseSensitive) {
        return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
    }
    return substr_count(json_encode($haystack), $needle);
}
</code>```

Hope it helps.

Title: in_array() and multidimensional array

Body:
I use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
    echo "Got Irix";
}

//print_r($a);

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

or I shouldn't be using in_array() when comes to the multidimensional array?

Body:
Here is my proposition based on json_encode() solution with :

case insensitive option

returning the count instead of true

anywhere in arrays (keys and values)

If word not found, it still returns 0 equal to false.

function in_array_count($needle, $haystack, $caseSensitive = true) {
    if(!$caseSensitive) {
        return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
    }
    return substr_count(json_encode($haystack), $needle);
}

Hope it helps.


问:
What does this Google Play APK publish error message mean?
I'm trying to publish a new version of my Android app to Google Play and get the following error?

This configuration cannot be published for the following reason(s):
      Version 1 is not served to any device configuration: all devices that might receive version 1 would receive version 4

I don't understand it. What does it mean?

答:
in my case
an older version of apk was published in beta testing. while i was trying to update my app over already published app with new apk.

just moved my new apk to beta testing and unpublished the old apk from beta testing.

and then finally moved the new apk from beta to prod.


问:
Make matrix out of the dictionary in Python
I have this data (taken part of random data coming from some server):

```<code> data={2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 3: [9,
 ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 5: [5, ['c', 'b', 'a',
 'b', 'b']], 7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}
</code>```

In this data, first number is the key, second value is the number of entries in the bracket following it. eg:-
For data

2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]

2 is the key. 9 is the total number of entries in the bracket which follows it.

Also, for keys having second value less than 9 are to be discarded.
I got that data.values() can give me the value as

[[9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [9, ['c',
  'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [5, ['c', 'b', 'a', 'b',
  'b']], [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

But I am not able to find any way to index within the matrix.

I need to make matrix out of this data as follows:

```<code>     a    b    c
2    4    5    0
3    4    4    1
7    4    3    2
</code>```

The matrix value [1][1] is the sum of a's in key value 2, [1][2] is the sum of b's in key value 2 and [1][3] is the sum of c's in key value 2, [2][1] is the sum of a's in key value 3, and so on..

答:
You can use Collections.Counter:

from collections import Counter

```<code>data = {
    2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    3: [9, ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    5: [5, ['c', 'b', 'a', 'b', 'b']],
    7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

matrix = {k: Counter(v[1]) for k, v in data.iteritems() if v[0] >= 9}
</code>```

The value of matrix is now:

```<code>{
     2: Counter({'b': 5, 'a': 4}),
     3: Counter({'a': 4, 'b': 4, 'c': 1}),
     7: Counter({'a': 4, 'b': 3, 'c': 2})
}
</code>```

Accessing a member of the matrix can be done as follows:

```<code>matrix[2].get('a', 0)
</code>```

(Note: using dict.get is to make the default return 0, which indicates no occurences so the key is not created in the Counter object).

Which will give the value:

```<code>4
</code>```

Body:
I have this data (taken part of random data coming from some server):

 data={2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 3: [9,
 ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 5: [5, ['c', 'b', 'a',
 'b', 'b']], 7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

In this data, first number is the key, second value is the number of entries in the bracket following it. eg:-
For data

2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]

2 is the key. 9 is the total number of entries in the bracket which follows it.

Also, for keys having second value less than 9 are to be discarded.
I got that data.values() can give me the value as

[[9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [9, ['c',
  'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [5, ['c', 'b', 'a', 'b',
  'b']], [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

But I am not able to find any way to index within the matrix.

I need to make matrix out of this data as follows:

     a    b    c
2    4    5    0
3    4    4    1
7    4    3    2

The matrix value [1][1] is the sum of a's in key value 2, [1][2] is the sum of b's in key value 2 and [1][3] is the sum of c's in key value 2, [2][1] is the sum of a's in key value 3, and so on..

Body:
You can use Collections.Counter:

from collections import Counter

data = {
    2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    3: [9, ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    5: [5, ['c', 'b', 'a', 'b', 'b']],
    7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

matrix = {k: Counter(v[1]) for k, v in data.iteritems() if v[0] >= 9}

The value of matrix is now:

{
     2: Counter({'b': 5, 'a': 4}),
     3: Counter({'a': 4, 'b': 4, 'c': 1}),
     7: Counter({'a': 4, 'b': 3, 'c': 2})
}

Accessing a member of the matrix can be done as follows:

matrix[2].get('a', 0)

(Note: using dict.get is to make the default return 0, which indicates no occurences so the key is not created in the Counter object).

Which will give the value:

4


问:
The datepart hour is not supported by date function dateadd for data type date
While I am running the following query in jasper reports, I got the exception. "net.sf.jasperreports.engine.JRException: Error executing SQL statement for : Activity_Summary".
Activity_Summery_Report is my jrxml file name.

The query is

```<code>declare @startdate as datetime;
declare @enddate as datetime;
declare @sitegroup as nvarchar(50);
set @startdate = DATEADD(hh, +0, $P{StartDate});
set @enddate = DATEADD(hh, +0, $P{EndDate});
set @sitegroup = 'BBXNCR';
set NOCOUNT ON; -- Added by JC230090: Fixes bug when running query with Jasper

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_invlines]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_invlines]
create table #temp_invlines (site_iid uniqueidentifier, invoice_line_type_iid int,    sub_total float, tax_total float,line_total float, product_type_iid int);
insert into #temp_invlines (site_iid,invoice_line_type_iid, sub_total, tax_total,   line_total, product_type_iid)
select h.site_iid, invoice_line_type_iid, l.sub_total, l.tax_total, l.line_total, l.product_type_iid
from invoice_lines l
    inner join invoices h on l.invoice_iid = h.invoice_iid
where h.invoice_dt >= @startdate and h.invoice_dt < @enddate

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_payment_invoices]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_payment_invoices]
create table #temp_payment_invoices (site_iid uniqueidentifier, inv_amount float);
insert into #temp_payment_invoices (site_iid, inv_amount)
select i.site_iid, i.total
from invoice_payments p
    inner join Invoice_Payment_Invoice_Xref pXref on p.invoice_payment_iid = pXref.invoice_payment_iid
    inner join invoices i on pXref.invoice_iid = i.invoice_iid
where p.payment_dt >= @startdate and p.payment_dt < @enddate

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_promocodes]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_promocodes]
create table #temp_promocodes (site_iid uniqueidentifier, invoice_promo_line_type_iid int, promo_amount float);
insert into #temp_promocodes (site_iid, invoice_promo_line_type_iid, promo_amount)
select h.site_iid, pl.invoice_promo_line_type_iid, pl.amount
from invoice_promo_lines pl
inner join invoices h on pl.invoice_iid = h.invoice_iid
where h.invoice_dt >= @startdate and h.invoice_dt < @enddate

select
 rtrim(s.site_id) as [Site ID]
 , rtrim(ss.Description) as [Status]
 , @startdate as [Date]
, datename(dw,@startdate) as [DoW]
, rtrim(s.name) as [Store Code]
, rtrim(isnull(sg.Description,'')) as [Site Group]
, rtrim(s.address1) + ', ' + rtrim(s.city) + ', ' + rtrim(s.state) + ' ' +   rtrim(s.Zip) as [Address]

, (select count(*) from invoices h where h.invoice_dt >= @startdate and h.invoice_dt < @enddate and h.site_iid = s.site_iid) as [Trans]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 1) as [Rent Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 2) as [Ext Day Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid = 2) as [Used Sell Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid <> 2) as [New Sell Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Rev Total]
, (select isnull(sum(tax_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Tax Total]
, (select isnull(sum(line_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Grand Total]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid) /
(select case when count(*) = 0 then 1 else count(*) end from invoices h where h.invoice_dt >= @startdate and h.invoice_dt < @enddate and h.site_iid = s.site_iid)
as [Rev/Trans]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 1) as [Rent Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 2) as [Ext Day Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid = 2) as [Used Sell Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid <> 2) as [New Sell Cnt]
, (select isnull(count(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 0) as [CustSrv Promo Cnt]
, (select isnull(sum(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 0) as [CustSrv Promo Amt]
, (select isnull(count(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 1) as [Marketing Promo Cnt]
, (select isnull(sum(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 1) as [Marketing Promo Amt]

, (SELECT
    isnull(count(*),0)
FROM Invoice_Lines ilrtn
    INNER JOIN Invoices ihrtn on ilrtn.invoice_iid = ihrtn.invoice_iid
    inner join customer_ids c on ihrtn.customer_id_iid = c.customer_id_iid
    INNER JOIN Invoices ihrent on ihrtn.customer_id_iid = ihrent.customer_id_iid
    INNER JOIN Invoice_lines ilrent on ihrent.invoice_iid = ilrent.invoice_iid
WHERE ihrtn.invoice_dt >= @startdate
    and ihrtn.invoice_dt < @enddate
    and ilrtn.invoice_line_type_iid in (0,2)
    AND ihrent.invoice_dt <= ihrtn.invoice_dt
    AND ilrent.invoice_line_type_iid in (1)
    AND ilrent.piece_id = ilrtn.piece_id
    and ihrtn.site_iid = s.site_iid
  ) as [Invoices]

, (SELECT
    isnull(sum(ilrent.line_total + ilrtn.line_total),0)
FROM Invoice_Lines ilrtn
    INNER JOIN Invoices ihrtn on ilrtn.invoice_iid = ihrtn.invoice_iid
    inner join customer_ids c on ihrtn.customer_id_iid = c.customer_id_iid
    INNER JOIN Invoices ihrent on ihrtn.customer_id_iid = ihrent.customer_id_iid
    INNER JOIN Invoice_lines ilrent on ihrent.invoice_iid = ilrent.invoice_iid
WHERE ihrtn.invoice_dt >= @startdate
    and ihrtn.invoice_dt < @enddate
    and ilrtn.invoice_line_type_iid in (0,2)
    AND ihrent.invoice_dt <= ihrtn.invoice_dt
    AND ilrent.invoice_line_type_iid in (1)
    AND ilrent.piece_id = ilrtn.piece_id
    and ihrtn.site_iid = s.site_iid
  ) as [Collectable]

, ( select isnull(sum(p.amount),0)
from invoice_payments p
where p.payment_dt >= @startdate and p.payment_dt < @enddate
and p.invoice_payment_iid in (
    select distinct p.invoice_payment_iid
    from invoice_payments p
    inner join Invoice_Payment_Invoice_Xref pXref on p.invoice_payment_iid = pXref.invoice_payment_iid
    inner join invoices i on pXref.invoice_iid = i.invoice_iid
    where p.payment_dt >= @startdate and p.payment_dt < @enddate
    and i.site_iid = s.site_iid
    group by p.invoice_payment_iid, pXref.invoice_iid)
) as [Payments Collected]

from sites s
inner join Site_Statuses_Enum ss on s.site_status_iid = ss.site_status_iid
left outer join Site_SiteGroup_XRef sgx on s.site_iid = sgx.site_iid
left outer join Site_Groups sg on sgx.site_group_iid = sg.site_group_iid

order by s.site_id

drop table #temp_promocodes;
drop table #temp_payment_invoices;
drop table #temp_invlines;
</code>```

And the exception stack is

```<code>Error filling print...
Error executing SQL statement for : Activity_Summary
net.sf.jasperreports.engine.JRException: Error executing SQL statement for : Activity_Summary
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:141)
at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:656)
at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:588)
at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1196)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:833)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:782)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:63)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:402)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:234)
at it.businesslogic.ireport.IReportCompiler.run(IReportCompiler.java:947)
at java.lang.Thread.run(Unknown Source)         Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The datepart hour is not supported by date function dateadd for data type date.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
 at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:285)
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:135)
 ... 10 more
 Print was not filled. Try using an EmptyDataSource...
</code>```

Please help me anybody how to resolve it.
Thanks in advance

答:
To avoid the error message "The datepart hour is not supported by date function dateadd for data type date" it's sometimes necessary to do a double cast after getting the current time (firstly to cast it as date to get rid of the time, and then back to datetime to enable adding time to it). For example, if you need 11:00 today, use:</p>

```<code>DATEADD(hour, 11, cast(cast(getdate() as date) as datetime))
</code>```

Body:
While I am running the following query in jasper reports, I got the exception. "net.sf.jasperreports.engine.JRException: Error executing SQL statement for : Activity_Summary".
Activity_Summery_Report is my jrxml file name.

The query is

declare @startdate as datetime;
declare @enddate as datetime;
declare @sitegroup as nvarchar(50);
set @startdate = DATEADD(hh, +0, $P{StartDate});
set @enddate = DATEADD(hh, +0, $P{EndDate});
set @sitegroup = 'BBXNCR';
set NOCOUNT ON; -- Added by JC230090: Fixes bug when running query with Jasper

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_invlines]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_invlines]
create table #temp_invlines (site_iid uniqueidentifier, invoice_line_type_iid int,    sub_total float, tax_total float,line_total float, product_type_iid int);
insert into #temp_invlines (site_iid,invoice_line_type_iid, sub_total, tax_total,   line_total, product_type_iid)
select h.site_iid, invoice_line_type_iid, l.sub_total, l.tax_total, l.line_total, l.product_type_iid
from invoice_lines l
    inner join invoices h on l.invoice_iid = h.invoice_iid
where h.invoice_dt >= @startdate and h.invoice_dt < @enddate

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_payment_invoices]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_payment_invoices]
create table #temp_payment_invoices (site_iid uniqueidentifier, inv_amount float);
insert into #temp_payment_invoices (site_iid, inv_amount)
select i.site_iid, i.total
from invoice_payments p
    inner join Invoice_Payment_Invoice_Xref pXref on p.invoice_payment_iid = pXref.invoice_payment_iid
    inner join invoices i on pXref.invoice_iid = i.invoice_iid
where p.payment_dt >= @startdate and p.payment_dt < @enddate

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#temp_promocodes]') AND type in (N'U'))
DROP TABLE [dbo].[#temp_promocodes]
create table #temp_promocodes (site_iid uniqueidentifier, invoice_promo_line_type_iid int, promo_amount float);
insert into #temp_promocodes (site_iid, invoice_promo_line_type_iid, promo_amount)
select h.site_iid, pl.invoice_promo_line_type_iid, pl.amount
from invoice_promo_lines pl
inner join invoices h on pl.invoice_iid = h.invoice_iid
where h.invoice_dt >= @startdate and h.invoice_dt < @enddate

select
 rtrim(s.site_id) as [Site ID]
 , rtrim(ss.Description) as [Status]
 , @startdate as [Date]
, datename(dw,@startdate) as [DoW]
, rtrim(s.name) as [Store Code]
, rtrim(isnull(sg.Description,'')) as [Site Group]
, rtrim(s.address1) + ', ' + rtrim(s.city) + ', ' + rtrim(s.state) + ' ' +   rtrim(s.Zip) as [Address]

, (select count(*) from invoices h where h.invoice_dt >= @startdate and h.invoice_dt < @enddate and h.site_iid = s.site_iid) as [Trans]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 1) as [Rent Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 2) as [Ext Day Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid = 2) as [Used Sell Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid <> 2) as [New Sell Rev]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Rev Total]
, (select isnull(sum(tax_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Tax Total]
, (select isnull(sum(line_total),0) from #temp_invlines l where l.site_iid = s.site_iid) as [Grand Total]
, (select isnull(sum(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid) /
(select case when count(*) = 0 then 1 else count(*) end from invoices h where h.invoice_dt >= @startdate and h.invoice_dt < @enddate and h.site_iid = s.site_iid)
as [Rev/Trans]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 1) as [Rent Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 2) as [Ext Day Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid = 2) as [Used Sell Cnt]
, (select isnull(count(sub_total),0) from #temp_invlines l where l.site_iid = s.site_iid and l.invoice_line_type_iid = 0 and l.product_type_iid <> 2) as [New Sell Cnt]
, (select isnull(count(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 0) as [CustSrv Promo Cnt]
, (select isnull(sum(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 0) as [CustSrv Promo Amt]
, (select isnull(count(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 1) as [Marketing Promo Cnt]
, (select isnull(sum(promo_amount),0) from #temp_promocodes p where p.site_iid = s.site_iid and p.invoice_promo_line_type_iid = 1) as [Marketing Promo Amt]

, (SELECT
    isnull(count(*),0)
FROM Invoice_Lines ilrtn
    INNER JOIN Invoices ihrtn on ilrtn.invoice_iid = ihrtn.invoice_iid
    inner join customer_ids c on ihrtn.customer_id_iid = c.customer_id_iid
    INNER JOIN Invoices ihrent on ihrtn.customer_id_iid = ihrent.customer_id_iid
    INNER JOIN Invoice_lines ilrent on ihrent.invoice_iid = ilrent.invoice_iid
WHERE ihrtn.invoice_dt >= @startdate
    and ihrtn.invoice_dt < @enddate
    and ilrtn.invoice_line_type_iid in (0,2)
    AND ihrent.invoice_dt <= ihrtn.invoice_dt
    AND ilrent.invoice_line_type_iid in (1)
    AND ilrent.piece_id = ilrtn.piece_id
    and ihrtn.site_iid = s.site_iid
  ) as [Invoices]

, (SELECT
    isnull(sum(ilrent.line_total + ilrtn.line_total),0)
FROM Invoice_Lines ilrtn
    INNER JOIN Invoices ihrtn on ilrtn.invoice_iid = ihrtn.invoice_iid
    inner join customer_ids c on ihrtn.customer_id_iid = c.customer_id_iid
    INNER JOIN Invoices ihrent on ihrtn.customer_id_iid = ihrent.customer_id_iid
    INNER JOIN Invoice_lines ilrent on ihrent.invoice_iid = ilrent.invoice_iid
WHERE ihrtn.invoice_dt >= @startdate
    and ihrtn.invoice_dt < @enddate
    and ilrtn.invoice_line_type_iid in (0,2)
    AND ihrent.invoice_dt <= ihrtn.invoice_dt
    AND ilrent.invoice_line_type_iid in (1)
    AND ilrent.piece_id = ilrtn.piece_id
    and ihrtn.site_iid = s.site_iid
  ) as [Collectable]

, ( select isnull(sum(p.amount),0)
from invoice_payments p
where p.payment_dt >= @startdate and p.payment_dt < @enddate
and p.invoice_payment_iid in (
    select distinct p.invoice_payment_iid
    from invoice_payments p
    inner join Invoice_Payment_Invoice_Xref pXref on p.invoice_payment_iid = pXref.invoice_payment_iid
    inner join invoices i on pXref.invoice_iid = i.invoice_iid
    where p.payment_dt >= @startdate and p.payment_dt < @enddate
    and i.site_iid = s.site_iid
    group by p.invoice_payment_iid, pXref.invoice_iid)
) as [Payments Collected]

from sites s
inner join Site_Statuses_Enum ss on s.site_status_iid = ss.site_status_iid
left outer join Site_SiteGroup_XRef sgx on s.site_iid = sgx.site_iid
left outer join Site_Groups sg on sgx.site_group_iid = sg.site_group_iid

order by s.site_id

drop table #temp_promocodes;
drop table #temp_payment_invoices;
drop table #temp_invlines;

And the exception stack is

Error filling print...
Error executing SQL statement for : Activity_Summary
net.sf.jasperreports.engine.JRException: Error executing SQL statement for : Activity_Summary
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:141)
at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:656)
at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:588)
at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1196)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:833)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:782)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:63)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:402)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:234)
at it.businesslogic.ireport.IReportCompiler.run(IReportCompiler.java:947)
at java.lang.Thread.run(Unknown Source)         Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The datepart hour is not supported by date function dateadd for data type date.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
 at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:285)
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:135)
 ... 10 more
 Print was not filled. Try using an EmptyDataSource...

Please help me anybody how to resolve it.
Thanks in advance

Body:
To avoid the error message "The datepart hour is not supported by date function dateadd for data type date" it's sometimes necessary to do a double cast after getting the current time (firstly to cast it as date to get rid of the time, and then back to datetime to enable adding time to it). For example, if you need 11:00 today, use:

DATEADD(hour, 11, cast(cast(getdate() as date) as datetime))


问:
Extracting different length of numbers (latitude and longitude) from unstructured text file with R
I want to extract differents latitudes and longitudes from  from unstructured text file. The coordinates can take these forms :
"0.41566" ; "-0.41566" ; "21.36584785" ; "100.2457

This syntax works only for numbers like that 120.564874

```<code>library(stringr)
lat <- c("([0-9]{3}) [.] ([0-9]{6})")
essailat<-str_extract_all(essai,lat, simplify=F)
</code>```

But As I said, I would like to extract all the other formats presented above.

```<code>library(stringr)
lat <- c("([0-9]{1}) [.] ([0-9]{4})", "([0-9]{3}) [.] ([0-9]{6})")
essailat<-str_extract_all(essai,lat, simplify=F)
</code>```

But it does not seems to work. Plus sometimes, my lat is a negative number (-0.41567) so I would like to specify that it extract as well the negative sign

Thank you in advance for your help.

PS: this is what I meant to specify a unstructured file and as lon and lat works by pair I can extract first all the lat with a certain type of format but all of them at once respecting the order.

THANK YOU in advance for your help !

Sample input:

```<code>cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"900.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"-0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacac
</code>```

Body:
I want to extract differents latitudes and longitudes from  from unstructured text file. The coordinates can take these forms :
"0.41566" ; "-0.41566" ; "21.36584785" ; "100.2457

This syntax works only for numbers like that 120.564874

library(stringr)
lat <- c("([0-9]{3}) [.] ([0-9]{6})")
essailat<-str_extract_all(essai,lat, simplify=F)

But As I said, I would like to extract all the other formats presented above.

library(stringr)
lat <- c("([0-9]{1}) [.] ([0-9]{4})", "([0-9]{3}) [.] ([0-9]{6})")
essailat<-str_extract_all(essai,lat, simplify=F)

But it does not seems to work. Plus sometimes, my lat is a negative number (-0.41567) so I would like to specify that it extract as well the negative sign

Thank you in advance for your help.

PS: this is what I meant to specify a unstructured file and as lon and lat works by pair I can extract first all the lat with a certain type of format but all of them at once respecting the order.

THANK YOU in advance for your help !

Sample input:

cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"900.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"-0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacac


问:
UIAlertController foreground is dimmed when it should not be
I have a strange issue which is affecting all of many UIAlertControllers shown throughout my app - the AlertControllers' white foreground appears dimmed, or less bright, than it should be.

The easiest way to describe it is to illustrate the desired and expected effect I obtain by placing the relevant code in a fresh 'Test' Single View application (Swift 3 - I should note that the actual app is a Single View application using Swift 2.3).

In my 'Test' app, the code below uses a deprecated AlertView to show a sample message, then builds a AlertController and shows that immediately 'after'.  There is no need to use the AlertView except to highlight the contrast in foreground 'white' - the problematic behaviour is the same if I comment out the AlertView.

Problematic behaviour:

Image 1: Test app: the AlertView is shown and the AlertController then shows behind it. Note the whiteness/brightness of the AlertView foreground.

Image 2: Test app: when the AlertView is dismissed, the AlertController is then the uppermost viewcontroller and as expected and desired, its foreground brightness is exactly the same as the AlertView's previously was

Image 3: real app: same code, also positioned in viewDidAppear - the AlertView is shown with the expected whiteness/brightness

Image 4: real app: when the AlertView is dismissed, the AlertController is then uppermost, but its foreground is nowhere near as bright / white as the AlertView's was, OR as it was in the Test app example, image 2.

As previously stated, the behaviour is the same even if I eliminate the AlertView step (which is just for contrast).

One further observation - often when I observe the behaviour, just momentarily when an affected AlertController first appears, as in for maybe 1/4 or 1/8 of a second, its foreground is the correct whiteness/brightness, but then an instant later it becomes dimmed, per the stated problem.

One other observation - some AlertControllers in the real app display properly with the correct level of brightness, but many others do not.

One last observation - I have user the 'View UI Hierarchy' in Xcode and there does not appear to be anything 'on top of' the affected AlertController.

```<code>import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    UIAlertView(title: "My AlertView Title", message: "My AlertView Message", delegate: self, cancelButtonTitle: "OK").show()

    let alertTitle = "My AlertController Title"
    let msg = "\r\r\r\r\r\r\r\rMy AlertController Msg"

    let alertController = UIAlertController(title: alertTitle, message: msg, preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "Don't show this again", style: .cancel) { (action:UIAlertAction!) in
        print("Dismiss button pressed")

    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "Action 1", style: .default) { (action:UIAlertAction!) in

        print("I'm action1!!")
    }

    alertController.addAction(OKAction)

    let OK2Action = UIAlertAction(title: "Action2", style: .default) { (action:UIAlertAction!) in

        print("I'm action2")
    }

    alertController.addAction(OK2Action)

    present(alertController, animated: false, completion: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
</code>```

}

Any help as to this puzzle gratefully received, thanks!

EDIT:

thanks to @Richard G for putting me on the right track - I still have the problem but with more clarity.

So, it you look at the two screenshots below side by side, they are both from the real app, both use the code shown above to generate the UIAlertController (I have now delete the UIAlertView line as it isn't needed), the only difference between the one on the left and one on the right is the one on the right has these 3 lines of code added:

```<code>let backView = alertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.whiteColor()
</code>```

side by side UIAlertControllers 1 transparent 1 not

According to Apple, "The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified."  OK, so this is hacking into it, and it proves that somehow the alertController has acquired, prior to displaying it, a backgroundColor which was partly transparent.

By setting the backgroundColor to UIColor.whiteColor() the problem is fixed, but the solution should be unnecessary - how on earth did the problem arise in the first place?

How was the backgroundColor somehow set to have a transparency when Apple doesn't even expose that property to me to be able to set?

any answers gratefully received!

答:
UIAlertView and UIAlertController has same background color and alpha value.
But in your case AlertView is displayed above AlertController, ie why it feels like UIAlertView is Whitier than UIAlertController.</p>

Body:
I have a strange issue which is affecting all of many UIAlertControllers shown throughout my app - the AlertControllers' white foreground appears dimmed, or less bright, than it should be.

The easiest way to describe it is to illustrate the desired and expected effect I obtain by placing the relevant code in a fresh 'Test' Single View application (Swift 3 - I should note that the actual app is a Single View application using Swift 2.3).

In my 'Test' app, the code below uses a deprecated AlertView to show a sample message, then builds a AlertController and shows that immediately 'after'.  There is no need to use the AlertView except to highlight the contrast in foreground 'white' - the problematic behaviour is the same if I comment out the AlertView.

Problematic behaviour:

Image 1: Test app: the AlertView is shown and the AlertController then shows behind it. Note the whiteness/brightness of the AlertView foreground.

Image 2: Test app: when the AlertView is dismissed, the AlertController is then the uppermost viewcontroller and as expected and desired, its foreground brightness is exactly the same as the AlertView's previously was

Image 3: real app: same code, also positioned in viewDidAppear - the AlertView is shown with the expected whiteness/brightness

Image 4: real app: when the AlertView is dismissed, the AlertController is then uppermost, but its foreground is nowhere near as bright / white as the AlertView's was, OR as it was in the Test app example, image 2.

As previously stated, the behaviour is the same even if I eliminate the AlertView step (which is just for contrast).

One further observation - often when I observe the behaviour, just momentarily when an affected AlertController first appears, as in for maybe 1/4 or 1/8 of a second, its foreground is the correct whiteness/brightness, but then an instant later it becomes dimmed, per the stated problem.

One other observation - some AlertControllers in the real app display properly with the correct level of brightness, but many others do not.

One last observation - I have user the 'View UI Hierarchy' in Xcode and there does not appear to be anything 'on top of' the affected AlertController.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    UIAlertView(title: "My AlertView Title", message: "My AlertView Message", delegate: self, cancelButtonTitle: "OK").show()

    let alertTitle = "My AlertController Title"
    let msg = "\r\r\r\r\r\r\r\rMy AlertController Msg"

    let alertController = UIAlertController(title: alertTitle, message: msg, preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "Don't show this again", style: .cancel) { (action:UIAlertAction!) in
        print("Dismiss button pressed")

    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "Action 1", style: .default) { (action:UIAlertAction!) in

        print("I'm action1!!")
    }

    alertController.addAction(OKAction)

    let OK2Action = UIAlertAction(title: "Action2", style: .default) { (action:UIAlertAction!) in

        print("I'm action2")
    }

    alertController.addAction(OK2Action)

    present(alertController, animated: false, completion: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Any help as to this puzzle gratefully received, thanks!

EDIT:

thanks to @Richard G for putting me on the right track - I still have the problem but with more clarity.

So, it you look at the two screenshots below side by side, they are both from the real app, both use the code shown above to generate the UIAlertController (I have now delete the UIAlertView line as it isn't needed), the only difference between the one on the left and one on the right is the one on the right has these 3 lines of code added:

let backView = alertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.whiteColor()

side by side UIAlertControllers 1 transparent 1 not

According to Apple, "The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified."  OK, so this is hacking into it, and it proves that somehow the alertController has acquired, prior to displaying it, a backgroundColor which was partly transparent.

By setting the backgroundColor to UIColor.whiteColor() the problem is fixed, but the solution should be unnecessary - how on earth did the problem arise in the first place?

How was the backgroundColor somehow set to have a transparency when Apple doesn't even expose that property to me to be able to set?

any answers gratefully received!