问:
Compare two column values and get distinct values from first column
I want to compare column1 and column2 and get the unique values from column1 (ignoring NaN). So in this case, I should get test1, test4.

Also, can we create and store the result in another column?

```<code>    Column1 column2
0   test1   test2
1   test2   test3
2   test3   hello
3   test4   world
4     NaN     how
5     NaN     are
6     NaN     you
</code>```

答:
You can get these values by doing

```<code>set(df.column1)-set(df.column2)-set([None])
</code>```

Also, if you want to store the result in another column, you can do something like that:

```<code>import pandas as pd
df=pd.DataFrame({'column1':['t1','t2','t3',None],'column2':['t1','a',None,None]})
unique_vals=list(set(df.column1)-set(df.column2)-set([None]))
df['new_col']=unique_vals+['None']*(len(df)-len(unique_vals))
df
</code>```

and the result is:

```<code>  column1   column2 new_col
0   t1       t1      t2
1   t2       a       t3
2   t3      None    None
3   None    None    None
</code>```

Body:
I want to compare column1 and column2 and get the unique values from column1 (ignoring NaN). So in this case, I should get test1, test4.

Also, can we create and store the result in another column?

    Column1 column2
0   test1   test2
1   test2   test3
2   test3   hello
3   test4   world
4     NaN     how
5     NaN     are
6     NaN     you

Body:
You can get these values by doing

set(df.column1)-set(df.column2)-set([None])

Also, if you want to store the result in another column, you can do something like that:

import pandas as pd
df=pd.DataFrame({'column1':['t1','t2','t3',None],'column2':['t1','a',None,None]})
unique_vals=list(set(df.column1)-set(df.column2)-set([None]))
df['new_col']=unique_vals+['None']*(len(df)-len(unique_vals))
df

and the result is:

  column1   column2 new_col
0   t1       t1      t2
1   t2       a       t3
2   t3      None    None
3   None    None    None


来源: stackexchange

问:
Json parse date time format
I'm using Newtonsoft.Json to parse json objects but one object that have date and time in it wont be parsed as it's stated.

```<code>JObject a = JObject.Parse(response);
</code>```

a will get the whole json and last is the object i want.

,  "last_activity_date": "2017-03-29T18:05:38.707Z"}

```<code>var date = a["last_activity_date"];
</code>```

will output

```<code>date = 2017-03-29 18:05:38
</code>```

Is it possible to keep the date time as it is? 2017-03-29T18:05:38.707Z
Or do i need to use regex?

答:
Due to default JObject parsing configuration, your last_activity_date will be treated as Date type, if you want to treat it as a string, you'll need to create dedicated class and deserialize your JSON into object.

```<code>public class Root
{
    [JsonProperty("last_activity_date")]
    public string LastActivityDate { get; set; }
}
</code>```

You can use JsonConvert:

```<code>var obj = (Root)JsonConvert.DeserializeObject(json, typeof(Root));
Console.WriteLine(obj.LastActivityDate); //outputs: 2017-03-29T18:05:38.707Z
</code>```

ContentLicense: CC BY-SA 3.0

Title: Json parse date time format

Body:
I'm using Newtonsoft.Json to parse json objects but one object that have date and time in it wont be parsed as it's stated.

JObject a = JObject.Parse(response);

a will get the whole json and last is the object i want.

,  "last_activity_date": "2017-03-29T18:05:38.707Z"}

var date = a["last_activity_date"];

will output

date = 2017-03-29 18:05:38

Is it possible to keep the date time as it is? 2017-03-29T18:05:38.707Z
Or do i need to use regex?

Body:
Due to default JObject parsing configuration, your last_activity_date will be treated as Date type, if you want to treat it as a string, you'll need to create dedicated class and deserialize your JSON into object.

public class Root
{
    [JsonProperty("last_activity_date")]
    public string LastActivityDate { get; set; }
}

You can use JsonConvert:

var obj = (Root)JsonConvert.DeserializeObject(json, typeof(Root));
Console.WriteLine(obj.LastActivityDate); //outputs: 2017-03-29T18:05:38.707Z


问:
Silverlight (w/ SQL database) desktop application example?
Are there any freeware/shareware examples of Silverlight desktop applications with a local SQL backend?
I am planning to write a freeware/shareware personal finance application and I'm thinking if whether to do it on Silverlight or WPF.</p>

答:
If you plan on having the SQL backend, you should go with WPF.

Silverlight is restricted in what it can access on the filesystem, even if you run it in the trusted mode and sign the app properly.

People have been implementing all kinds of "good enough" databases that use Isolated Storage. You might use them depending on your level of comfort with the non-mainstream storage engine.

Are you sure you'd need a local SQL database? How much data are we talking about and what is the frequency of inserts/complexity of selects?

ContentLicense: CC BY-SA 2.5


问:
laravel - rss display
Welcome ! Can someone tell me how to display rss from another site on mine? Exactly this rss  link http://awiacja.imgw.pl/rss/metar00.php?airport=EPWA I'm using laravel 5.3

Regards and thank You for help

答:
The most easy way is to use file_get_contents:

```<code>$rss = file_get_contents(http://awiacja.imgw.pl/rss/metar00.php?airport=EPWA);
return response($rss);
</code>```

Title: laravel - rss display

Body:
The most easy way is to use file_get_contents:

$rss = file_get_contents(http://awiacja.imgw.pl/rss/metar00.php?airport=EPWA);
return response($rss);


问:
Finding and extracting the substring from a damaged text
It is easy to find a substring in a string, like the following:

```<code>substring: "060MHXEA"
string: "DVM MINI(RD040/050/060MHXGA, RD040/050/060MHXEA)"
</code>```

But if the string is destroyed, like the following;

```<code>string: DV@@ M MIN@@ I ( R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ GA , R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ EA )
</code>```

How can I find and extract "06@@ 0@@ M@@ H@@ X@@ EA" from the string, since it is the destroyed form of 060MHXEA?

Note: Destruction is done by splitting chars with "@@ " in my case.

答:
WARNING! That solution may be irrational, feel free to improve algorithm in your answers.

Full code is here: https://repl.it/Gn3N

Generate our first list with format [[character, 0]] (where character - chars from initial string a), then replace all zeros with indexes (via range(), it's important):

```<code>a = 'DV@@ M MIN@@ I ( R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ GA , R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ EA )'

positions = [[x, 0] for x in a]

for x in range(len(positions)):
    positions[x][1] = x
</code>```

Then, we are going to define function-clearer, which replace our substring-damager in positions, while keeping it's initial indexes:

```<code>def clearer(lst):
     trig = []
     for x in lst:
         if x[0] is '@':
             trig.append(x)
         elif x[0] is ' ' and x[1] == trig[-1][1]+1:
             trig.append(x)
     for x in trig:
         lst.remove(x)
     return lst

clr = clearer(positions)
</code>```

Now, we should look for index of first occurrence of substring in cleared text, generate range with initial indexes and iterate over initial text with it:

```<code>substr = '060MHXEA'

indexes = range(clr[''.join([x[0] for x in clr]).find(substr)][1], clr[''.join([x[0] for x in clr]).find(substr)+len(substr)][1])

result = ''

for x in indexes:
     result += a[x]
print(result) #06@@ 0@@ M@@ H@@ X@@ EA
</code>```

Body:
It is easy to find a substring in a string, like the following:

substring: "060MHXEA"
string: "DVM MINI(RD040/050/060MHXGA, RD040/050/060MHXEA)"

But if the string is destroyed, like the following;

string: DV@@ M MIN@@ I ( R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ GA , R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ EA )

How can I find and extract "06@@ 0@@ M@@ H@@ X@@ EA" from the string, since it is the destroyed form of 060MHXEA?

Note: Destruction is done by splitting chars with "@@ " in my case.

Body:
WARNING! That solution may be irrational, feel free to improve algorithm in your answers.

Full code is here: https://repl.it/Gn3N

Generate our first list with format [[character, 0]] (where character - chars from initial string a), then replace all zeros with indexes (via range(), it's important):

a = 'DV@@ M MIN@@ I ( R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ GA , R@@ D@@ 0@@ 40 / 0@@ 50 / 06@@ 0@@ M@@ H@@ X@@ EA )'

positions = [[x, 0] for x in a]

for x in range(len(positions)):
    positions[x][1] = x

Then, we are going to define function-clearer, which replace our substring-damager in positions, while keeping it's initial indexes:

def clearer(lst):
     trig = []
     for x in lst:
         if x[0] is '@':
             trig.append(x)
         elif x[0] is ' ' and x[1] == trig[-1][1]+1:
             trig.append(x)
     for x in trig:
         lst.remove(x)
     return lst

clr = clearer(positions)

Now, we should look for index of first occurrence of substring in cleared text, generate range with initial indexes and iterate over initial text with it:

substr = '060MHXEA'

indexes = range(clr[''.join([x[0] for x in clr]).find(substr)][1], clr[''.join([x[0] for x in clr]).find(substr)+len(substr)][1])

result = ''

for x in indexes:
     result += a[x]
print(result) #06@@ 0@@ M@@ H@@ X@@ EA


问:
DynamoDB loading old local database file
A while ago I loaded a bunch of JSON data into a local DynamoDB instance for practice. I did some queries and stored the data into a CSV and ended up closing my connection.

So I have this sample_data.db file on my laptop that's 7GB and need to access it again. Normally when I create a DynamoDB instance, I say:

```<code>java \
    -Djava.library.path=./DynamoDBLocal_lib \
    -jar DynamoDBLocal.jar \
    -dbPath /Users/myname/Documents/data/sample_data.db
</code>```

So I did that to create the file but how do I now open another connection to that pre-existing file? Whenever I do the above, it just says:

```<code>Invalid directory for database creation.
</code>```

Clearly that means the above command is only for creating a new DB - sorry if this is a trivial question but how do I open a connection to an old one?

Do I have to upload it to AWS somehow? Or is there a way?

EDIT: I was using this as a reference, but didn't see a command to specify path to a pre-existing DB. http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html

答:
The problem is rooted in the fact that local DynamoDB does not allow you to directly specify the database file name, only the path where the file should be stored/loaded. The file name(s) is/are derived from your AWS access key for DynamoDB local and the AWS region. Alternately, if you specify the -sharedDb option, the single database file is stored as shared-local-instance.db. The -dbPath option defines where the DynamoDB local instance should look for these database files.

In order to load your old database file, I would recommend renaming it to conform to the naming conventions (so that DynamoDB will recognize it), and specifying the -dbPath option without the filename part. Hopefully, this will allow you to access your data.

Example:

```<code>mv sample_data.db shared-local-instance.db
java \
    -Djava.library.path=./DynamodDBLocal_lib \
    -jar DynamoDBLocal.jar \
    -dbPath /Users/myname/Documents/data
</code>```

Note: the database file naming is a little vaguely defined (at least, my very limited search for naming criteria didn't turn up much). You may need to play around with it a bit to figure out the exact naming that is expected.

Body:
A while ago I loaded a bunch of JSON data into a local DynamoDB instance for practice. I did some queries and stored the data into a CSV and ended up closing my connection.

So I have this sample_data.db file on my laptop that's 7GB and need to access it again. Normally when I create a DynamoDB instance, I say:

java \
    -Djava.library.path=./DynamoDBLocal_lib \
    -jar DynamoDBLocal.jar \
    -dbPath /Users/myname/Documents/data/sample_data.db

So I did that to create the file but how do I now open another connection to that pre-existing file? Whenever I do the above, it just says:

Invalid directory for database creation.

Clearly that means the above command is only for creating a new DB - sorry if this is a trivial question but how do I open a connection to an old one?

Do I have to upload it to AWS somehow? Or is there a way?

EDIT: I was using this as a reference, but didn't see a command to specify path to a pre-existing DB. http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html

Body:
The problem is rooted in the fact that local DynamoDB does not allow you to directly specify the database file name, only the path where the file should be stored/loaded. The file name(s) is/are derived from your AWS access key for DynamoDB local and the AWS region. Alternately, if you specify the -sharedDb option, the single database file is stored as shared-local-instance.db. The -dbPath option defines where the DynamoDB local instance should look for these database files.

In order to load your old database file, I would recommend renaming it to conform to the naming conventions (so that DynamoDB will recognize it), and specifying the -dbPath option without the filename part. Hopefully, this will allow you to access your data.

Example:

mv sample_data.db shared-local-instance.db
java \
    -Djava.library.path=./DynamodDBLocal_lib \
    -jar DynamoDBLocal.jar \
    -dbPath /Users/myname/Documents/data

Note: the database file naming is a little vaguely defined (at least, my very limited search for naming criteria didn't turn up much). You may need to play around with it a bit to figure out the exact naming that is expected.


问:
Pass an input variable to PHP using AJAX, but not with POST
My form is like the one above:

```<code><form id="calculator">
<input type="text" name="height" id="height"/>
<input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
<button type="button" onclick="calculatePanels();">
</form>
</code>```

Jquery script is the next one:

```<code>function calculatePanels() {
     var Height = document.forms["calculator"]["height"].value;

     $.ajax({
                url: "includes/inferiorPanel.php",
                success: function(result){
            $("#inferiorPanel").val(result);
            }});
}
</code>```

And PHP code from inferiorPanel.php is:

```<code><?php
$height = ????;

        switch ($height) {

            case ($height > 0 && $height <= 1845):
            echo 615;
            break;

            case ($height > 1845 && $height <= 1980):
            echo 495;
            break;

            case ($height > 1980 && $height <= 2100):
            echo 495;
            break;

            case ($height > 2100 && $height <= 2220):
            echo 495;
            break;

            case ($height > 2220 && $height <= 2340):
            echo 615;
            break;

            case ($height > 2340 && $height <= 2460):
            echo 615;
            break;

            case ($height > 2460 && $height <= 2475):
            echo 495;
            break;

            case ($height > 2475 && $height <= 2595):
            echo 615;
            break;

            case ($height > 2595 && $height <= 2715):
            echo 615;
            break;

            case ($height > 2715 && $height <= 2835):
            echo 615;
            break;

            case ($height > 2835 && $height <= 2955):
            echo 615;
            break;

            case ($height > 2955 && $height <= 3000):
            echo 615;
            break;
}
</code>```

My question is:
How to pass the variable height in PHP without using POST on Ajax, in order to show the result in input inferiorPanel?

I do not want to use <input type="submit" /> because will refresh the page

答:
You can specify GET in the Ajax call and have height in the URL as follows

```<code>var height = $('#height').val();

 $.ajax({
        type        : 'GET',
        url         : 'inferiorPanel.php?height=' + height,
</code>```

Within your php you can just say if(isset($_GET['height']) $height = $_GET['height'];

Body:
My form is like the one above:

<form id="calculator">
<input type="text" name="height" id="height"/>
<input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
<button type="button" onclick="calculatePanels();">
</form>

Jquery script is the next one:

function calculatePanels() {
     var Height = document.forms["calculator"]["height"].value;

     $.ajax({
                url: "includes/inferiorPanel.php",
                success: function(result){
            $("#inferiorPanel").val(result);
            }});
}

And PHP code from inferiorPanel.php is:

<?php
$height = ????;

        switch ($height) {

            case ($height > 0 && $height <= 1845):
            echo 615;
            break;

            case ($height > 1845 && $height <= 1980):
            echo 495;
            break;

            case ($height > 1980 && $height <= 2100):
            echo 495;
            break;

            case ($height > 2100 && $height <= 2220):
            echo 495;
            break;

            case ($height > 2220 && $height <= 2340):
            echo 615;
            break;

            case ($height > 2340 && $height <= 2460):
            echo 615;
            break;

            case ($height > 2460 && $height <= 2475):
            echo 495;
            break;

            case ($height > 2475 && $height <= 2595):
            echo 615;
            break;

            case ($height > 2595 && $height <= 2715):
            echo 615;
            break;

            case ($height > 2715 && $height <= 2835):
            echo 615;
            break;

            case ($height > 2835 && $height <= 2955):
            echo 615;
            break;

            case ($height > 2955 && $height <= 3000):
            echo 615;
            break;
}

My question is:
How to pass the variable height in PHP without using POST on Ajax, in order to show the result in input inferiorPanel?

I do not want to use <input type="submit" /> because will refresh the page

Body:
You can specify GET in the Ajax call and have height in the URL as follows

var height = $('#height').val();

 $.ajax({
        type        : 'GET',
        url         : 'inferiorPanel.php?height=' + height,

Within your php you can just say if(isset($_GET['height']) $height = $_GET['height'];


问:
php MySql 2 column as index and 1 as another index?
I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.

they both must be varchar.

i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.

fetch all for first varchar column.

insert if not exist for both values.

I'm hoping to do it in the most efficient way.

what is the best way to insert without checking with another query if exist?

what is the best way other then:

```<code>SELECT * FROM table WHERE id = id
</code>```

to fetch when the column needed is varchar?

答:
You should consider a normalized table structure like this:</p>

```<code>CREATE TABLE user (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE page (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE pages_visted (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED,
    page_id INT UNSIGNED,
    UNIQUE KEY (user_id, page_id)
);

INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);

SELECT page_id FROM pages_visted WHERE user_id = :userId;
</code>```

Body:
I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.

they both must be varchar.

i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.

fetch all for first varchar column.

insert if not exist for both values.

I'm hoping to do it in the most efficient way.

what is the best way to insert without checking with another query if exist?

what is the best way other then:

SELECT * FROM table WHERE id = id

to fetch when the column needed is varchar?

Body:
You should consider a normalized table structure like this:

CREATE TABLE user (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE page (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE pages_visted (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED,
    page_id INT UNSIGNED,
    UNIQUE KEY (user_id, page_id)
);

INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);

SELECT page_id FROM pages_visted WHERE user_id = :userId;


问:
Printer.print to text document in VB6
Im not 100% about this, so bear with me and hopefully you can help me make sense and solve the issue.

So in my code there are a lot of printer.print "Some String" and right at the end, like there should be, is a printer.enddoc.

Occasionally we get an issue where, for what ever reason, the printer isnt ready and crashes the software out with an error 482 which basically means the printer isnt ready.

What I want to do is push the document that will be printed into a text file before printing so if there is an issue, the document isnt lost, and it also helps with saving data to be reprinted at a later date.

I assumed (wrongly, I think) that printer.print pushes data into something that will be fired to the printer and can be viewed before hand, but I am not convinced.

I want to just clarify that the code I am working on is at least 15 years old, been played with by at least 5 different coders and its all a bit of a jumble.

答: The scenario you defined is exactly what print spoolers, or "printers" (a.k.a. printer drivers) are designed to handle through Windows.  Except for the ability to reprint at a later time.  Any failed document should still be in your printer's queue, and can be restarted from there, so there should be no loss in that sense.  If you want to have reports stored in a file format, as in the comments, it's been suggested you can print to a PDF file.  In my accounting system I use various methods, including Crystal Reports, direct-to-printer, and direct-to-pdf.  If you want something more complex than just manually handling it through the print queue, you may have to re-design the report structure, or purchase a third-party set of utilities.  Component-One includes lots of printer stuff in their Active-X package including print-preview, for example.</p>

Title: Printer.print to text document in VB6


问:
Using Custom Colored Cursors in a C# Windows Application
I am developing a SDG (Single Display Groupware) application, and for that I need multiple cursors (to the simplest of different colors) for the single window. I came to know that with C# you can just use black and white cursors, which does not solve my problem.</p>

答:
I also tried something different and it seems to work with different colored cursors, but the only problem with this piece of code is that the Hotspot coordinates for the mouse cursors are not exact i.e. the are moved slightly to the right. But this can be fixed by considering an offset in the code.

The code is as follows:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace MID
{
    public partial class CustomCursor : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr LoadCursorFromFile(string filename);

        public CustomCursor()
        {
            InitializeComponent();

            Bitmap bmp = (Bitmap)Bitmap.FromFile("Path of the cursor file saved as .bmp");
            bmp.MakeTransparent(Color.Black);
            IntPtr ptr1 = blue.GetHicon();

            Cursor cur = new Cursor(ptr1);
            this.Cursor = cur;

        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I also tried something different and it seems to work with different colored cursors, but the only problem with this piece of code is that the Hotspot coordinates for the mouse cursors are not exact i.e. the are moved slightly to the right. But this can be fixed by considering an offset in the code.

The code is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace MID
{
    public partial class CustomCursor : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr LoadCursorFromFile(string filename);

        public CustomCursor()
        {
            InitializeComponent();

            Bitmap bmp = (Bitmap)Bitmap.FromFile("Path of the cursor file saved as .bmp");
            bmp.MakeTransparent(Color.Black);
            IntPtr ptr1 = blue.GetHicon();

            Cursor cur = new Cursor(ptr1);
            this.Cursor = cur;

        }
    }
}


问:
What codec to use for converting bigint to Long?
I have a bigint field in my Cassandra that I want to convert to a long value.
However, I am not sure how to specify the same in my DataStax-mapper-entity-class.

Here is the code:

```<code>@PartitionKey(1)
@Column(name="phone", codec=TypeCodec.)
private Double phoneNumber;
</code>```

Can someone please tell what to use in the Column annotation?

UPDATE

If I use

```<code>@PartitionKey(1)
@Column(name="phone")
private Long phoneNumber;
</code>```

I get an error: java.lang.Double cannot be cast to java.lang.Long

And if I use

```<code>@PartitionKey(1)
@Column(name="phone")
private Double phoneNumber;
</code>```

I get an error: Codec not found for requested operation: [bigint <-> java.lang.Double]

Long or Double does not matter that much to me.

I just want to be able to read it as a number.

I also tried:

```<code>@PartitionKey(1)
@Column(name="phone", codec=TypeCodec.PrimitiveDoubleCodec.class)
private Double phoneNumber;
</code>```

But then it gives me an error: java.lang.NoSuchMethodException: com.datastax.driver.core.TypeCodec$PrimitiveDoubleCodec.<init>()

答:
By Default Cassandra bigint type map to java long type,So if you define phone as bigint in cassandra then you have to define phone as long in java. If you want to map bigint to Double you have to write custom codec.

Here is the CQL to Java Type Map :

```<code>--------------------------------
| CQL3 data type  | Java type   |
--------------------------------|
| bigint          | long        |
| double          | double      |
---------------------------------
</code>```

Source : http://docs.datastax.com/en/developer/java-driver/3.1/manual/#cql-to-java-type-mapping

Body:
I have a bigint field in my Cassandra that I want to convert to a long value.
However, I am not sure how to specify the same in my DataStax-mapper-entity-class.

Here is the code:

@PartitionKey(1)
@Column(name="phone", codec=TypeCodec.)
private Double phoneNumber;

Can someone please tell what to use in the Column annotation?

UPDATE

If I use

@PartitionKey(1)
@Column(name="phone")
private Long phoneNumber;

I get an error: java.lang.Double cannot be cast to java.lang.Long

And if I use

@PartitionKey(1)
@Column(name="phone")
private Double phoneNumber;

I get an error: Codec not found for requested operation: [bigint <-> java.lang.Double]

Long or Double does not matter that much to me.

I just want to be able to read it as a number.

I also tried:

@PartitionKey(1)
@Column(name="phone", codec=TypeCodec.PrimitiveDoubleCodec.class)
private Double phoneNumber;

But then it gives me an error: java.lang.NoSuchMethodException: com.datastax.driver.core.TypeCodec$PrimitiveDoubleCodec.<init>()

Body:
By Default Cassandra bigint type map to java long type,So if you define phone as bigint in cassandra then you have to define phone as long in java. If you want to map bigint to Double you have to write custom codec.

Here is the CQL to Java Type Map :

--------------------------------
| CQL3 data type  | Java type   |
--------------------------------|
| bigint          | long        |
| double          | double      |
---------------------------------

Source : http://docs.datastax.com/en/developer/java-driver/3.1/manual/#cql-to-java-type-mapping


问:
How to take stereo images using single camera?
I want to find the depth map for stereo images.At present i am working on the internet image,I want to take stereo images so that i can work on it by my own.How to take best stereo images without much noise.I have single camera.IS it necessary to do rectification?How much distance must be kept between the cameras?</p>

答:
In my experience:

-I did the rectification, so I had to obtain the fundamental matrix, and this may not be correct with some image pairs.

-Better resolution of your camera is better for the matching, I use OpenCV and it has an implementation of BRISK descriptor, it was useful for me.

-Try to cover the same area and try not to do unnecessary rotations.

-Once you understand the Theory, OpenCV is a good friend. Here is some result, but I am still working on it:

Depth map:

Rectified images:


问:
Node update a specific package
I want to update my Browser-sync without updating all my node packages. How can I achieve this? My current version of Browser-sync does not have the Browser-sync GUI :(

```<code>├─┬ browser-sync@1.9.2
│ ├── browser-sync-client@1.0.2
</code>```

答:
Most of the time you can just npm update (or pnpm update or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

```<code>npm update browser-sync
-------
pnpm update browser-sync
-------
yarn upgrade browser-sync
</code>```

Use [p]npm|yarn outdated to see which modules have newer versions

Use [p]npm update|yarn upgrade (without a package name) to update all modules

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

```<code>npm install browser-sync@2 --save-dev
-------
pnpm add browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev
</code>```

...or the latest 2.1.x by doing:

```<code>npm install browser-sync@2.1 --save-dev
-------
pnpm add browser-sync@2.1 --save-dev
-------
yarn add browser-sync@2.1 --dev
</code>```

...or the latest and greatest by doing:

```<code>npm install browser-sync@latest --save-dev
-------
pnpm add browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev
</code>```

Note: the last one is no different than doing uninstall followed by install like this:

```<code>npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
pnpm remove browser-sync --save-dev
pnpm add browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev
</code>```

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

Title: Node update a specific package

Body:
I want to update my Browser-sync without updating all my node packages. How can I achieve this? My current version of Browser-sync does not have the Browser-sync GUI :(

├─┬ browser-sync@1.9.2
│ ├── browser-sync-client@1.0.2

Body:
Most of the time you can just npm update (or pnpm update or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
pnpm update browser-sync
-------
yarn upgrade browser-sync

Use [p]npm|yarn outdated to see which modules have newer versions

Use [p]npm update|yarn upgrade (without a package name) to update all modules

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
pnpm add browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install browser-sync@2.1 --save-dev
-------
pnpm add browser-sync@2.1 --save-dev
-------
yarn add browser-sync@2.1 --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
pnpm add browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing uninstall followed by install like this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
pnpm remove browser-sync --save-dev
pnpm add browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.


问:
Python from csv file analyze data in columns and cells
I am trying to create a code for the following data:

I have imported the data using the code:

```<code>import csv
import itertools
import pandas as pd

input_file="computation.csv"
cmd=pd.read_csv(input_file)
subset = cmd[['Carbon A', 'Carbon B']]
carbon_pairs = [tuple(y) for y in subset.values]
c_pairs = carbon_pairs
</code>```

I want to create a code that has the output:

```<code>1 is connected to
  2
  4
  6
  7
  8
2 is connected to
  1
  4
  5
</code>```

Note that for 'carbon' 2, I would like it to repeat that it is connected to carbon 1.  I was thinking that some permutation would be able to show this, but I am very unsure where to start.  Basically, the code needs to output:

```<code>for every cell with the same value, print adjacent cell
</code>```

答:
Starting from the end of your question:

```<code>c_pairs = [(1, 2), (1, 4), (1, 6), (1, 7), (1, 8), (2, 1), (2, 4), (2, 5)]
</code>```

You presumably want to end up with something more like:

```<code>groups = {1: [2, 4, 6, 7, 8], 2: [1, 4, 5]}
</code>```

There are many ways to obtain this.

A very fast way, if you know your data is sorted, is to use itertools.groupby, e.g.:

```<code>first_item = lambda (a, b): a
for key, items in itertools.groupby(c_pairs, first_item):
    print '%s is connected to' % key
    for (a, b) in items:
        print '  %s' % b
</code>```

it is still probably the fastest way if your data is not sorted, simply sort it first:

```<code>c_pairs = sorted(c_pairs, key=first_item)
</code>```

A more do-it-yourself solution is to use defaultdict or a standard dictionary to create a mapping from one to the other.

```<code>groups = collections.defaultdict(list)
for a, b in c_pairs:
    groups[a].append(b)
</code>```

which is equivalent to without collections:

```<code>groups = {}
for a, b in c_pairs:
    groups.setdefault(a, [])  # many ways to do this as well
    groups[a].append(b)
</code>```

Body:
I am trying to create a code for the following data:

I have imported the data using the code:

import csv
import itertools
import pandas as pd

input_file="computation.csv"
cmd=pd.read_csv(input_file)
subset = cmd[['Carbon A', 'Carbon B']]
carbon_pairs = [tuple(y) for y in subset.values]
c_pairs = carbon_pairs

I want to create a code that has the output:

1 is connected to
  2
  4
  6
  7
  8
2 is connected to
  1
  4
  5

Note that for 'carbon' 2, I would like it to repeat that it is connected to carbon 1.  I was thinking that some permutation would be able to show this, but I am very unsure where to start.  Basically, the code needs to output:

for every cell with the same value, print adjacent cell

Body:
Starting from the end of your question:

c_pairs = [(1, 2), (1, 4), (1, 6), (1, 7), (1, 8), (2, 1), (2, 4), (2, 5)]

You presumably want to end up with something more like:

groups = {1: [2, 4, 6, 7, 8], 2: [1, 4, 5]}

There are many ways to obtain this.

A very fast way, if you know your data is sorted, is to use itertools.groupby, e.g.:

first_item = lambda (a, b): a
for key, items in itertools.groupby(c_pairs, first_item):
    print '%s is connected to' % key
    for (a, b) in items:
        print '  %s' % b

it is still probably the fastest way if your data is not sorted, simply sort it first:

c_pairs = sorted(c_pairs, key=first_item)

A more do-it-yourself solution is to use defaultdict or a standard dictionary to create a mapping from one to the other.

groups = collections.defaultdict(list)
for a, b in c_pairs:
    groups[a].append(b)

which is equivalent to without collections:

groups = {}
for a, b in c_pairs:
    groups.setdefault(a, [])  # many ways to do this as well
    groups[a].append(b)


问:
How to force Firefox Dev tools to reuse same window? (like firebug)
In Firebug, there was just one window and it would become the debug window for whatever page you were on, in the browser.  (although you might have to 'enable firebug for this page')

With the built in Dev tools, it seems you need a new window, for each page you want to work on.  Can this be changed?

答: The Firefox DevTools do not have this feature yet, unfortunately. Though it is requested in bug 1219917.</p>


问:
Progress bar not showing whilst retrieving data from web APIs
Swift 3/Xcode 8/ios 10

I have a method that fetches a bunch of data from a few api endpoints. I pick out the bits I want to keep and then format and print that data to a text file.

When the app starts up, it checks to see whether or not the text file is empty. If it is empty, then the API requests are run and the text file is populated accordingly. So far so good. This all works as expected.

I now want to show the user the progress of the data being retrieved via a progress bar. This is where I am getting stuck. I cannot seem to get the progress bar to display before and during the data retrieval. It only displays after data retrieval is complete - and indicates as much too. Via some print statements in the protocol method, I can see that the progress bar is seemingly being updated - it's just that the segue to the progress bar does not happen when I want it to.

There are 3 classes involved in the above description:

MasterVC - checks text file and segues to ProgressBar if necessary.      Initiates API calls via GetData.start(), immediately after calling performSegue to ProgressBar.

ProgressBar - shows the progress bar and receives updates from GetData.

GetData - contains the method that fetches data from APIs.

In viewDidAppear of MasterVC, the code below shows the first block of code:

```<code>    if fileSize == 0{

        //SHOW PROGRESS OVERLAY AND RETRIEVE API DATA
        performSegue(withIdentifier: "toProgressBarOverlay", sender: self)

        GetData.start() //IF THIS IS ACTIVE, DATA IS RETRIEVED BUT PROGRESS BAR APPEARS AT THE END.

    }
</code>```

Any code after this runs only once the text file has been populated via the API calls. I have done this via the use of semaphores contained within the API calling method. If instead, I place GetData.start() in viewDidAppear of ProgressBar, I get errors in this section relating to variables/arrays etc being empty.

From googling and searching SO, I get the impression that the late showing of the progress bar has to do with the updating of views only being done at the end of each cycle and that although I call the performSegue first, it only happens last, after the rest of the code in the class has been iterated through.

How can I make this progress bar appear as intended?

EDIT 1:

OK, so I have managed to get the progress bar to now appear at the start of the API calls. Sadly however, the progress bar is not updating properly. The updates are, however, still being reported correctly in the console. The progress bar appears with the default start value, then once the API calling is done, the progress bar suddenly shoots to 100% with no intermediate values. Using dispatchQueue.main.async/sync still does not work. Below are the changes I have made:

The code section above (which is in MasterVC) now looks like the following:

```<code>//FETCH MP INFO AND POPULATE MPDATA.TXT.
    if fileSize == 0{

        //SHOW PROGRESS OVERLAY AND RETRIEVE API DATA
        performSegue(withIdentifier: "toProgressBarOverlay", sender: self)

    }
</code>```

All the code after this (which dealt with the populated text file) has been moved to its own method (called processTextFile).

So when the app starts, it checks for an empty file, and if it finds as much, segues to ProgressBar. ProgressBar also now contains a new reference to MasterVC (called masterVcReference), which is set during prepareForSegue.

ProgressBar now initiates the API calls with:

```<code>GetData.start(masterVc: masterVcReference!)
</code>```

Once all the data has been retrieved and written to file, GetData uses masterVcReference to call processTextFile.

The actual protocol method is as follows:

```<code>func updateProgressBar(message: String, percentComplete: Float) {

    print("Progress: \(percentComplete)%") << this is being reported correctly.

    ProgressBar?.setProgress(percentComplete, animated: true)
    ProgressBarMessageField.text = message

    if percentComplete == 100{
        //dismiss(animated: true, completion: nil)
    }
}
</code>```

If I place "ProgressBar?.setProgress(percentComplete, animated: true)" and
        "ProgressBarMessageField.text = message" in a dispatchQueue.main.async/sync block, no difference is made.

So currently, the app works as it should except for the progress bar not updating as it should.

EDIT 2:

OK, so using DispatchQueue.global(qos: .userInteractive).async, instead of dispatchQueue.main.async to update the progress bar has made a small difference. The progress bar updates, sort of. Of the 649 updates (from the 649 items of data that are processed) that the progress bar should go through, it updates only 1, 2 or maybe 3 times if I'm lucky. Also, the update frequency is not the same between each run of the app.

EDIT 3:

OK - turns out dispatchQueue.main.async has been working, but it seems to be queueing up all of the updates and executing everything right at the end instead of executing with each protocol method call. Confusion reigns.

Solved at Last!

I was using semaphores to ensure that data from the API calls were processed in the correct order. The solution was to place the "semaphore.signal()" statement BEFORE the call to the delegate method. Originally, the delegate call lay between "let semaphore = DispatchSemaphore(value: 0)" and "semaphore.signal()". Somehow (I don't understand it yet), this was causing the UI updates to queue up and not execute until all of the API data had finished processing.

Voila!

答: I was using semaphores to ensure that data from the API calls were processed in the correct order. The solution was to place the "semaphore.signal()" statement BEFORE the call to the delegate method. Originally, the delegate call lay between "let semaphore = DispatchSemaphore(value: 0)" and "semaphore.signal()". Somehow (I don't understand it yet), this was causing the UI updates to queue up and not execute until all of the API data had finished processing.</p>

Body:
Swift 3/Xcode 8/ios 10

I have a method that fetches a bunch of data from a few api endpoints. I pick out the bits I want to keep and then format and print that data to a text file.

When the app starts up, it checks to see whether or not the text file is empty. If it is empty, then the API requests are run and the text file is populated accordingly. So far so good. This all works as expected.

I now want to show the user the progress of the data being retrieved via a progress bar. This is where I am getting stuck. I cannot seem to get the progress bar to display before and during the data retrieval. It only displays after data retrieval is complete - and indicates as much too. Via some print statements in the protocol method, I can see that the progress bar is seemingly being updated - it's just that the segue to the progress bar does not happen when I want it to.

There are 3 classes involved in the above description:

MasterVC - checks text file and segues to ProgressBar if necessary.      Initiates API calls via GetData.start(), immediately after calling performSegue to ProgressBar.

ProgressBar - shows the progress bar and receives updates from GetData.

GetData - contains the method that fetches data from APIs.

In viewDidAppear of MasterVC, the code below shows the first block of code:

    if fileSize == 0{

        //SHOW PROGRESS OVERLAY AND RETRIEVE API DATA
        performSegue(withIdentifier: "toProgressBarOverlay", sender: self)

        GetData.start() //IF THIS IS ACTIVE, DATA IS RETRIEVED BUT PROGRESS BAR APPEARS AT THE END.

    }

Any code after this runs only once the text file has been populated via the API calls. I have done this via the use of semaphores contained within the API calling method. If instead, I place GetData.start() in viewDidAppear of ProgressBar, I get errors in this section relating to variables/arrays etc being empty.

From googling and searching SO, I get the impression that the late showing of the progress bar has to do with the updating of views only being done at the end of each cycle and that although I call the performSegue first, it only happens last, after the rest of the code in the class has been iterated through.

How can I make this progress bar appear as intended?

EDIT 1:

OK, so I have managed to get the progress bar to now appear at the start of the API calls. Sadly however, the progress bar is not updating properly. The updates are, however, still being reported correctly in the console. The progress bar appears with the default start value, then once the API calling is done, the progress bar suddenly shoots to 100% with no intermediate values. Using dispatchQueue.main.async/sync still does not work. Below are the changes I have made:

The code section above (which is in MasterVC) now looks like the following:

//FETCH MP INFO AND POPULATE MPDATA.TXT.
    if fileSize == 0{

        //SHOW PROGRESS OVERLAY AND RETRIEVE API DATA
        performSegue(withIdentifier: "toProgressBarOverlay", sender: self)

    }

All the code after this (which dealt with the populated text file) has been moved to its own method (called processTextFile).

So when the app starts, it checks for an empty file, and if it finds as much, segues to ProgressBar. ProgressBar also now contains a new reference to MasterVC (called masterVcReference), which is set during prepareForSegue.

ProgressBar now initiates the API calls with:

GetData.start(masterVc: masterVcReference!)

Once all the data has been retrieved and written to file, GetData uses masterVcReference to call processTextFile.

The actual protocol method is as follows:

func updateProgressBar(message: String, percentComplete: Float) {

    print("Progress: \(percentComplete)%") << this is being reported correctly.

    ProgressBar?.setProgress(percentComplete, animated: true)
    ProgressBarMessageField.text = message

    if percentComplete == 100{
        //dismiss(animated: true, completion: nil)
    }
}

If I place "ProgressBar?.setProgress(percentComplete, animated: true)" and
        "ProgressBarMessageField.text = message" in a dispatchQueue.main.async/sync block, no difference is made.

So currently, the app works as it should except for the progress bar not updating as it should.

EDIT 2:

OK, so using DispatchQueue.global(qos: .userInteractive).async, instead of dispatchQueue.main.async to update the progress bar has made a small difference. The progress bar updates, sort of. Of the 649 updates (from the 649 items of data that are processed) that the progress bar should go through, it updates only 1, 2 or maybe 3 times if I'm lucky. Also, the update frequency is not the same between each run of the app.

EDIT 3:

OK - turns out dispatchQueue.main.async has been working, but it seems to be queueing up all of the updates and executing everything right at the end instead of executing with each protocol method call. Confusion reigns.

Solved at Last!

I was using semaphores to ensure that data from the API calls were processed in the correct order. The solution was to place the "semaphore.signal()" statement BEFORE the call to the delegate method. Originally, the delegate call lay between "let semaphore = DispatchSemaphore(value: 0)" and "semaphore.signal()". Somehow (I don't understand it yet), this was causing the UI updates to queue up and not execute until all of the API data had finished processing.

Voila!


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
I think

```<code>var castList = list.Cast<typeof(T)>();
</code>```

should be

```<code>var castList = list.Cast<T>();
</code>```

@Jon Limjap The most glaring error I can see is
  that an IList is definitely different from an IList<T>. An IList is non-generic
  (e.g., ArrayList).

The original question was already using an IList<T>. It was removed when someone edited the formatting. Probably a problem with Markdown.

Fixed now.

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

Body:
I think

var castList = list.Cast<typeof(T)>();

should be

var castList = list.Cast<T>();

@Jon Limjap The most glaring error I can see is
  that an IList is definitely different from an IList<T>. An IList is non-generic
  (e.g., ArrayList).

The original question was already using an IList<T>. It was removed when someone edited the formatting. Probably a problem with Markdown.

Fixed now.

OwnerDisplayName: John

LastEditorDisplayName: Orion Edwards


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
As you just now mentioned you're using a hash-table with several look-ups parallel to insertions, I'd recommend to check whether you can use a concurrent hash-table.

As the exact look-up results are non-deterministic when you're inserting elements simultaneously, such a concurrent hash-map may be exactly what you need.  I do not have used concurrent hash-tables in C++, though, but as they are available in Java, you'll for sure find a library doing this in C++.

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly

OwnerDisplayName: gimpf


问:
WPF Tree Parent Child Insertion:
I am trying to create Below parent child structur using WPF tree.

```<code>Tree

 ->Parent

    ->Child

      ->Grand Child.
</code>```

I have written the below code which is not able to insert for child. Please help me to fix this.

```<code><Window x:Class="NewTree_DynamicNode.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TreeView Name="treeFileSystem" TreeViewItem.Expanded="treeFileSystem_Expanded_1">
            <TreeViewItem Header="Categories" x:Name="_ImageTree" Tag="hi"
                  x:FieldModifier="private">
                <TreeViewItem TextBlock.FontStyle="Italic"
                    Header="Loading..." Name="treeFileSystem2"/>
            </TreeViewItem>
        </TreeView>
    </Grid>
</Window>

private void treeFileSystem_Expanded_1(object sender, RoutedEventArgs e)
        {
            this._ImageTree = (TreeViewItem)e.OriginalSource;
            this._ImageTree.Items.Clear();

            try
            {
                for(int i=0 ; i<2; i++)
                {
                   TreeViewItem temp = new TreeViewItem();
                   TreeViewItem temp1 = new TreeViewItem();
                    temp.Header = "Parent";
                    temp1.Header = "Child";
                    temp.Items.Add(temp1);
                    this._ImageTree.Items.Add(temp);
                }
            }
            catch
            {
                  /////
            }
        }
</code>```

答:
Your problem is that every time you expand a node, the child node for the node you expand is always 'Parent'

Im not sure exactly what you are trying to achieve but heres some code:

```<code>TreeViewItem temp = new TreeViewItem();
temp.Header = "Child";
temp.Items.Add(null);
this._ImageTree.Items.Add(temp);
</code>```

EDIT - this is for specific names in hierarchy

```<code>TreeViewItem temp = new TreeViewItem();
var header = string.Empty;
switch (_ImageTree.Header.ToString())
{
    case "Categories":
        header = "Parent";
        break;
    case "Parent":
        header = "Child";
        break;
    case "Child":
        header = "GrandChild";
        break;
    default:
        header = "Child of " + _ImageTree.Header;
        break;
}
temp.Header = header;
temp.Items.Add(null);
this._ImageTree.Items.Add(temp);
</code>```

Title: WPF Tree Parent Child Insertion:

Body:
I am trying to create Below parent child structur using WPF tree.

Tree

 ->Parent

    ->Child

      ->Grand Child.

I have written the below code which is not able to insert for child. Please help me to fix this.

<Window x:Class="NewTree_DynamicNode.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TreeView Name="treeFileSystem" TreeViewItem.Expanded="treeFileSystem_Expanded_1">
            <TreeViewItem Header="Categories" x:Name="_ImageTree" Tag="hi"
                  x:FieldModifier="private">
                <TreeViewItem TextBlock.FontStyle="Italic"
                    Header="Loading..." Name="treeFileSystem2"/>
            </TreeViewItem>
        </TreeView>
    </Grid>
</Window>

private void treeFileSystem_Expanded_1(object sender, RoutedEventArgs e)
        {
            this._ImageTree = (TreeViewItem)e.OriginalSource;
            this._ImageTree.Items.Clear();

            try
            {
                for(int i=0 ; i<2; i++)
                {
                   TreeViewItem temp = new TreeViewItem();
                   TreeViewItem temp1 = new TreeViewItem();
                    temp.Header = "Parent";
                    temp1.Header = "Child";
                    temp.Items.Add(temp1);
                    this._ImageTree.Items.Add(temp);
                }
            }
            catch
            {
                  /////
            }
        }

Body:
Your problem is that every time you expand a node, the child node for the node you expand is always 'Parent'

Im not sure exactly what you are trying to achieve but heres some code:

TreeViewItem temp = new TreeViewItem();
temp.Header = "Child";
temp.Items.Add(null);
this._ImageTree.Items.Add(temp);

EDIT - this is for specific names in hierarchy

TreeViewItem temp = new TreeViewItem();
var header = string.Empty;
switch (_ImageTree.Header.ToString())
{
    case "Categories":
        header = "Parent";
        break;
    case "Parent":
        header = "Child";
        break;
    case "Child":
        header = "GrandChild";
        break;
    default:
        header = "Child of " + _ImageTree.Header;
        break;
}
temp.Header = header;
temp.Items.Add(null);
this._ImageTree.Items.Add(temp);


问:
What's wrong with my Python 3/PyQt5 code?
I have this code and want to do some calculations after pressing buttons and show results in QTextEdit widget (ted). Everything works well, but if I run the program and press the button (button1) it crashes.

Any idea what's wrong with my code?

Thanks a lot for answers!

The code is here:

```<code>import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QTextEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'STATISTICIAN'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 600, 600)

        button1 = QPushButton('1D statistics', self)
        button1.setToolTip('Start calculations of 1D statistics')
        button1.move(50, 25)
        button1.resize(500,70)
        button1.clicked.connect(self.on_click1)

        button2 = QPushButton('2D statistics', self)
        button2.setToolTip('Start calculations of 2D statistics')
        button2.move(50, 105)
        button2.resize(500,70)
        button2.clicked.connect(self.on_click2)

        ted = QTextEdit(self)
        ted.move(50, 250)
        ted.resize(500, 250)
        ted.setReadOnly(True)
        scrb = ted.verticalScrollBar()
        scrb.setValue(scrb.maximum())

        self.show()

    @pyqtSlot()
    def on_click1(self):
        # Reading of data from file will be here
        # Some calculations will be here
        text = 'Results are:' # There will be finally more text
        ted.insertPlainText(text) # I'm trying to show results in QTextEdit (ted)

    def on_click2(self):
        print('2D statistics')
        print()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

答:
The ted variable can not be accessed from on_click1, you must use the self instance to use it, replace ted with self.ted.

Complete code:

```<code>import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QTextEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'STATISTICIAN'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 600, 600)

        button1 = QPushButton('1D statistics', self)
        button1.setToolTip('Start calculations of 1D statistics')
        button1.move(50, 25)
        button1.resize(500,70)
        button1.clicked.connect(self.on_click1)

        button2 = QPushButton('2D statistics', self)
        button2.setToolTip('Start calculations of 2D statistics')
        button2.move(50, 105)
        button2.resize(500,70)
        button2.clicked.connect(self.on_click2)

        self.ted = QTextEdit(self)
        self.ted.move(50, 250)
        self.ted.resize(500, 250)
        self.ted.setReadOnly(True)
        scrb = self.ted.verticalScrollBar()
        scrb.setValue(scrb.maximum())

        self.show()

    def on_click1(self):
        # Reading of data from file will be here
        # Some calculations will be here
        text = 'Results are:' # There will be finally more text
        self.ted.insertPlainText(text) # I'm trying to show results in QTextEdit (ted)

    def on_click2(self):
        print('2D statistics')
        print()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

Body:
I have this code and want to do some calculations after pressing buttons and show results in QTextEdit widget (ted). Everything works well, but if I run the program and press the button (button1) it crashes.

Any idea what's wrong with my code?

Thanks a lot for answers!

The code is here:

import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QTextEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'STATISTICIAN'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 600, 600)

        button1 = QPushButton('1D statistics', self)
        button1.setToolTip('Start calculations of 1D statistics')
        button1.move(50, 25)
        button1.resize(500,70)
        button1.clicked.connect(self.on_click1)

        button2 = QPushButton('2D statistics', self)
        button2.setToolTip('Start calculations of 2D statistics')
        button2.move(50, 105)
        button2.resize(500,70)
        button2.clicked.connect(self.on_click2)

        ted = QTextEdit(self)
        ted.move(50, 250)
        ted.resize(500, 250)
        ted.setReadOnly(True)
        scrb = ted.verticalScrollBar()
        scrb.setValue(scrb.maximum())

        self.show()

    @pyqtSlot()
    def on_click1(self):
        # Reading of data from file will be here
        # Some calculations will be here
        text = 'Results are:' # There will be finally more text
        ted.insertPlainText(text) # I'm trying to show results in QTextEdit (ted)

    def on_click2(self):
        print('2D statistics')
        print()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

Body:
The ted variable can not be accessed from on_click1, you must use the self instance to use it, replace ted with self.ted.

Complete code:

import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QTextEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'STATISTICIAN'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 600, 600)

        button1 = QPushButton('1D statistics', self)
        button1.setToolTip('Start calculations of 1D statistics')
        button1.move(50, 25)
        button1.resize(500,70)
        button1.clicked.connect(self.on_click1)

        button2 = QPushButton('2D statistics', self)
        button2.setToolTip('Start calculations of 2D statistics')
        button2.move(50, 105)
        button2.resize(500,70)
        button2.clicked.connect(self.on_click2)

        self.ted = QTextEdit(self)
        self.ted.move(50, 250)
        self.ted.resize(500, 250)
        self.ted.setReadOnly(True)
        scrb = self.ted.verticalScrollBar()
        scrb.setValue(scrb.maximum())

        self.show()

    def on_click1(self):
        # Reading of data from file will be here
        # Some calculations will be here
        text = 'Results are:' # There will be finally more text
        self.ted.insertPlainText(text) # I'm trying to show results in QTextEdit (ted)

    def on_click2(self):
        print('2D statistics')
        print()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


问:
IntelliJ IDEA - different "targets"
I have a project (maven + spring + hibernate) for a web app. I'm no pro at Java and I'm wondering if there's a way to use the same project for another app. The two version would share a lot of code, but there will be some unique classes and functions. Ideally, when I'll make a change in one shared functions, I won't have to manually edit both projects.

I'm a iOS Developer and usually I use macros for this purpose (here's explained in detail http://www.itexico.com/blog/bid/99497/iOS-Mobile-Development-Using-Xcode-Targets-to-Reuse-the-Code):

```<code>#if APP1
#define SERVER_URL @"http://server.com/green/"
#define PROJECT_NAME @"GREEN APP"
#else
#define SERVER_URL @"http://server.com/yellow/"
#define PROJECT_NAME @"YELLOW APP"
#endif
</code>```

Is there any way to do something like this in Java using IntelliJ IDEA?

答:
Since you mentioned Maven, I guess the best would be using your build tool rather than IntelliJ idea as you mention in a question.

So in Java you might want to create an "infrastructure" module that would contain all the "shared" functionality. This module will by built into a dedicated jar by Maven.

Then in all your project you'll just include this module as a Maven dependency tag like this:

```<code> <dependency>
     <groupId>,,,,</groupId>
     <artifactId>youSharedModuleName</artifactId>
     <version>...</version>
 </dependency>
</code>```

That's the easiest way. After all, in run-time JAR is nothing more than a container for you classes that Java can handle transparently for you.

Now you can keep this infrastructure as a completely separated project in your source control system so that you'll be able to release it independently of your main project jars buts its a different story.

Title: IntelliJ IDEA - different "targets"

Body:
I have a project (maven + spring + hibernate) for a web app. I'm no pro at Java and I'm wondering if there's a way to use the same project for another app. The two version would share a lot of code, but there will be some unique classes and functions. Ideally, when I'll make a change in one shared functions, I won't have to manually edit both projects.

I'm a iOS Developer and usually I use macros for this purpose (here's explained in detail http://www.itexico.com/blog/bid/99497/iOS-Mobile-Development-Using-Xcode-Targets-to-Reuse-the-Code):

#if APP1
#define SERVER_URL @"http://server.com/green/"
#define PROJECT_NAME @"GREEN APP"
#else
#define SERVER_URL @"http://server.com/yellow/"
#define PROJECT_NAME @"YELLOW APP"
#endif

Is there any way to do something like this in Java using IntelliJ IDEA?

Body:
Since you mentioned Maven, I guess the best would be using your build tool rather than IntelliJ idea as you mention in a question.

So in Java you might want to create an "infrastructure" module that would contain all the "shared" functionality. This module will by built into a dedicated jar by Maven.

Then in all your project you'll just include this module as a Maven dependency tag like this:

 <dependency>
     <groupId>,,,,</groupId>
     <artifactId>youSharedModuleName</artifactId>
     <version>...</version>
 </dependency>

That's the easiest way. After all, in run-time JAR is nothing more than a container for you classes that Java can handle transparently for you.

Now you can keep this infrastructure as a completely separated project in your source control system so that you'll be able to release it independently of your main project jars buts its a different story.


问:
Open XML configuration to the Configuration XML rather than Message Flow
Is there a setting in AnyPoint 6.1.2 that would allow opening a config file directly into the Configuration XML rather than the graphical Message Flow?

I prefer to edit directly in the XML editor.

I have looked in Window/Preferences and throughout. I am unable to find a setting that would default to the Configuration XML tab.

Thanks!

答:
not as far as i know. some colleague of mine started using the default xml editor provided by eclipse for the same reason. it has some drawbacks, but works surprisingly well.

things like code assist in mule expressions will be missing.

mule configuration editor with code assist

plain xml editor without code assist

xml-related features like available elements and attributes and validation according to xml schema will work.

available elements in plain xml editor

warning because of empty flow


问:
Visual Composer / WordPress - Edit Multiple Pages of the Same Template at Once
When using Visual Composer on WordPress, I am able to set up a template and then use that template for every page I build. HOWEVER, when I want to change something to pages using this template, I have to go back and edit each & every single page.

Is there a better way of doing this? Is there a way set up a global Visual Composer template that must abide by the latest configuration? Can it at least be hard coded into an existing PHP template so global changes can be made there?

答:
That was a pain for years. One of the options now is to use WP ACF-VC Bridge plugin (http://wpacfvcbridge.com/). Here are the steps you need to take:

1) Create your page template as VC Snippet (here is a video overview http://wpacfvcbridge.com/vc-snippets/)

2) Set your static content with Visual Composer. You can also dynamically include data from your posts by using ACF Field Picker (here is an overview http://wpacfvcbridge.com/acf-field-picker/).

Note 1: Field context must be custom.

Note 2: these fields must be created with Advanced Custom Fields plugin (https://www.advancedcustomfields.com/pro/) which is included in WP ACF-VC Bridge. This is enough to cover 99% cases. If you'll need to include other post fields list post title or custom meta field, then you need to look for suitable Visual Composer add-on or write this custom shortcode.

3) Add VC Snippet to your post content with ```[vc-vc-snippet id="{VC Snippet Template Post ID}"]```
If you have Visual Composer enabled for your post type (or you can enable it under Visual Composer -> Role Manager) you can use ready VC shortcode to embed VC Snippet.

Now if you'll change your VC Snippet, the changes will be immediately reflected across all posts.

Body:
That was a pain for years. One of the options now is to use WP ACF-VC Bridge plugin (http://wpacfvcbridge.com/). Here are the steps you need to take:

1) Create your page template as VC Snippet (here is a video overview http://wpacfvcbridge.com/vc-snippets/)

2) Set your static content with Visual Composer. You can also dynamically include data from your posts by using ACF Field Picker (here is an overview http://wpacfvcbridge.com/acf-field-picker/).

Note 1: Field context must be custom.

Note 2: these fields must be created with Advanced Custom Fields plugin (https://www.advancedcustomfields.com/pro/) which is included in WP ACF-VC Bridge. This is enough to cover 99% cases. If you'll need to include other post fields list post title or custom meta field, then you need to look for suitable Visual Composer add-on or write this custom shortcode.

3) Add VC Snippet to your post content with
[vc-vc-snippet id="{VC Snippet Template Post ID}"]

If you have Visual Composer enabled for your post type (or you can enable it under Visual Composer -> Role Manager) you can use ready VC shortcode to embed VC Snippet.

Now if you'll change your VC Snippet, the changes will be immediately reflected across all posts.


问:
Common results of two MySQL queries
I am looking to combine two MySQL queries so it returns the common results so I know I am not looking to use UNION on this one. I tried writing a subselect statement but that didn't work out

First query:

```<code>SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 4 and m.answer = 3 and h.page = 4
</code>```

Second query:

```<code>SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 114 and m.answer = 1 and h.page = 114
</code>```

Failed merge query:

```<code>SELECT s.ses_id FROM session s, multiple, history h
JOIN (
    SELECT session.ses_id
    FROM session, history, multiple
    WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
    ) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id
</code>```

The multiple table contains questions and answers and I am looking to find the ids of those who have answered the two questions with those specific answers.

I realize this should be easy and I am most likely overthinking and/or missing something.

答:
You simply need to join both the history and multiple tables an additional time each for the 2nd question/answer combination.

```<code>SELECT s.ses_id,
       m1.question, m1.answer, h1.page,
       m2.question, m2.answer, h2.page
FROM session s
INNER JOIN history h1
   ON h1.ses_id = s.ses_id AND h1.page = 4
INNER JOIN multiple m1
   ON m1.ses_id = s.ses_id
   AND m1.question = 4 AND m1.answer = 3
INNER JOIN history h2
   ON h2.ses_id = s.ses_id AND h2.page = 114
INNER JOIN multiple m2
   ON m2.ses_id = s.ses_id
   AND m2.question = 114 and m2.answer = 1
WHERE s.interview = 'lifestyle' and s.finished = 'y'
</code>```

Title: Common results of two MySQL queries

Body:
I am looking to combine two MySQL queries so it returns the common results so I know I am not looking to use UNION on this one. I tried writing a subselect statement but that didn't work out

First query:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 4 and m.answer = 3 and h.page = 4

Second query:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id
WHERE m.question = 114 and m.answer = 1 and h.page = 114

Failed merge query:

SELECT s.ses_id FROM session s, multiple, history h
JOIN (
    SELECT session.ses_id
    FROM session, history, multiple
    WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
    ) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id

The multiple table contains questions and answers and I am looking to find the ids of those who have answered the two questions with those specific answers.

I realize this should be easy and I am most likely overthinking and/or missing something.

Body:
You simply need to join both the history and multiple tables an additional time each for the 2nd question/answer combination.

SELECT s.ses_id,
       m1.question, m1.answer, h1.page,
       m2.question, m2.answer, h2.page
FROM session s
INNER JOIN history h1
   ON h1.ses_id = s.ses_id AND h1.page = 4
INNER JOIN multiple m1
   ON m1.ses_id = s.ses_id
   AND m1.question = 4 AND m1.answer = 3
INNER JOIN history h2
   ON h2.ses_id = s.ses_id AND h2.page = 114
INNER JOIN multiple m2
   ON m2.ses_id = s.ses_id
   AND m2.question = 114 and m2.answer = 1
WHERE s.interview = 'lifestyle' and s.finished = 'y'


问:
Wrong output in mySQL query
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

```<code>SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
</code>```

And here is a picture to go along with what the output looks like:

答:
In mySQL you are supposed to use the backticks ` for columns and table names. Here mySQL considers "Units Sold" as a variable from your side, which is why it is printed like this in the result.</p>

```<code>SELECT b.`brand_name`, b.`brand_type`, Round(sub1.`avgprice`, 2) AS "Average Price", sub2.`Units Sold`
FROM lgbrand b JOIN (SELECT `brand_id`, Avg(`prod_price`) AS avgprice
            FROM lgproduct
            GROUP BY `brand_id`) sub1
ON b.`brand_id` = sub1.`brand_id`
    JOIN (SELECT `brand_id`, Sum(`line_qty`) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.`prod_sku` = l.`prod_sku`
GROUP BY `brand_id`) sub2
    ON b.`brand_id` = sub2.`brand_id`
ORDER BY `brand_name`;
</code>```

Title: Wrong output in mySQL query

Body:
I'm relatively new to mySQL and phpMyAdmin and I am having problems with a query I am trying to put in. I want the "Units Sold" to be a number, but the whole column prints out "Units Sold" for some reason. I already tried removing both "Units Sold" and i've tried removing just one, but I am not sure what is going wrong here. Sorry if I am not clear enough, but here is my query:

SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
            FROM lgproduct
            GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
    JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
    ON b.brand_id = sub2.brand_id
ORDER BY brand_name;

And here is a picture to go along with what the output looks like:

Body:
In mySQL you are supposed to use the backticks ` for columns and table names. Here mySQL considers "Units Sold" as a variable from your side, which is why it is printed like this in the result.

SELECT b.`brand_name`, b.`brand_type`, Round(sub1.`avgprice`, 2) AS "Average Price", sub2.`Units Sold`
FROM lgbrand b JOIN (SELECT `brand_id`, Avg(`prod_price`) AS avgprice
            FROM lgproduct
            GROUP BY `brand_id`) sub1
ON b.`brand_id` = sub1.`brand_id`
    JOIN (SELECT `brand_id`, Sum(`line_qty`) AS "Units Sold"
    FROM lgproduct p JOIN lgline l ON p.`prod_sku` = l.`prod_sku`
GROUP BY `brand_id`) sub2
    ON b.`brand_id` = sub2.`brand_id`
ORDER BY `brand_name`;


问:
Selecting an item from a dropdown menu using Python/Selenium
I am trying to fill out a form for states where I would select one at the bottom Oregon. From https://www.adidas.com/us/delivery-start.
New to coding thank you!

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

state = driver.find_element_by_xpath('//*[@id="dwfrm_delivery"]/div[2]/div[2]/div/fieldset/div/div[1]/div[6]/div[1]/div/div/a/span')
stateselect = state.select_by_visible_test("Oregon")
</code>```

This is the error I am getting

AttributeError: 'WebElement' object has no attribute 'select_by_visible_test'.

And with

```<code>state = driver.find_element_by_xpath('//*[@id="dwfrm_delivery"]/div[2]/div[2]/div/fieldset/div/div[1]/div[6]/div[1]/div/div/a/span')
stateselect = state.send_keys("Oregon")
</code>```

I get the following :

error:WebDriverException: Message: unknown error: cannot focus element

Please help me understand the error for both cases to further my understanding. And point me in the right direction.

答:
When you're copying code always double-check you've copied it correctly.

select_by_visible_test should be select_by_visible_text

But that won't work because you're not using the select class. Before using stateselect you need:

```<code>stateselect = Select(state)
</code>```

And then you can do:

```<code>stateselect.select_by_visible_text("Oregon")
</code>```

You should also check the official documentation. In this case, the documentation for the python selenium api for WebElement and Select. You can almost always find the documentation by searching for, e.g., "python selenium select"

Body:
I am trying to fill out a form for states where I would select one at the bottom Oregon. From https://www.adidas.com/us/delivery-start.
New to coding thank you!

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

state = driver.find_element_by_xpath('//*[@id="dwfrm_delivery"]/div[2]/div[2]/div/fieldset/div/div[1]/div[6]/div[1]/div/div/a/span')
stateselect = state.select_by_visible_test("Oregon")

This is the error I am getting

AttributeError: 'WebElement' object has no attribute 'select_by_visible_test'.

And with

state = driver.find_element_by_xpath('//*[@id="dwfrm_delivery"]/div[2]/div[2]/div/fieldset/div/div[1]/div[6]/div[1]/div/div/a/span')
stateselect = state.send_keys("Oregon")

I get the following :

error:WebDriverException: Message: unknown error: cannot focus element

Please help me understand the error for both cases to further my understanding. And point me in the right direction.

Body:
When you're copying code always double-check you've copied it correctly.

select_by_visible_test should be select_by_visible_text

But that won't work because you're not using the select class. Before using stateselect you need:

stateselect = Select(state)

And then you can do:

stateselect.select_by_visible_text("Oregon")

You should also check the official documentation. In this case, the documentation for the python selenium api for WebElement and Select. You can almost always find the documentation by searching for, e.g., "python selenium select"


问:
Issue activating a generic type with generic array in constructor parameters
I have a very strange issue with the following code:

```<code>using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuples1 = GimeStringTuples("foo", "bar");
            var testTuples2 = GimeTuples("foo", "bar");
            Console.ReadKey();
        }

        public static object GimeStringTuples(params string[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(specificType, values);
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);

            dynamic result;
            string[] testArgs = { "foo", "bar" };
            result = Activator.CreateInstance(specificType, testArgs);
            result = Activator.CreateInstance(specificType, values);
            return result;
        }
    }
}
</code>```

It's failing on the second to last line:

```<code>result = Activator.CreateInstance(specificType, values);
</code>```

This is weird since it's basically identical to the line that executes just before it:

```<code>result = Activator.CreateInstance(specificType, testArgs);
</code>```

In both cases, the same argument is being passed as the specificType parameter and a string[2] is being passed as the second parameter.

And the GimeStringTuples method works just fine... although there are no generics involved there - which is maybe the hint.

Can anyone explain this unusual behaviour?

答:
I can tell you what happens. Having a look at the resulting assembly you can see that the compiler introduces an object[] wrapping the values argument:

```<code>Activator.CreateInstance(specificType, new string[] { "foo", "bar" });
Activator.CreateInstance(specificType, new object[] { values });
</code>```

Now the right overload can not be found anymore.
If you add a cast you will get the expected result and the code works again:

```<code>Activator.CreateInstance(specificType, values as string[])
</code>```

But i can not tell you why this happens, maybe it can be digged out of the specs.

Body:
I have a very strange issue with the following code:

using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuples1 = GimeStringTuples("foo", "bar");
            var testTuples2 = GimeTuples("foo", "bar");
            Console.ReadKey();
        }

        public static object GimeStringTuples(params string[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(specificType, values);
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);

            dynamic result;
            string[] testArgs = { "foo", "bar" };
            result = Activator.CreateInstance(specificType, testArgs);
            result = Activator.CreateInstance(specificType, values);
            return result;
        }
    }
}

It's failing on the second to last line:

result = Activator.CreateInstance(specificType, values);

This is weird since it's basically identical to the line that executes just before it:

result = Activator.CreateInstance(specificType, testArgs);

In both cases, the same argument is being passed as the specificType parameter and a string[2] is being passed as the second parameter.

And the GimeStringTuples method works just fine... although there are no generics involved there - which is maybe the hint.

Can anyone explain this unusual behaviour?

Body:
I can tell you what happens. Having a look at the resulting assembly you can see that the compiler introduces an object[] wrapping the values argument:

Activator.CreateInstance(specificType, new string[] { "foo", "bar" });
Activator.CreateInstance(specificType, new object[] { values });

Now the right overload can not be found anymore.
If you add a cast you will get the expected result and the code works again:

Activator.CreateInstance(specificType, values as string[])

But i can not tell you why this happens, maybe it can be digged out of the specs.


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答:
Update: it's fixed!

I have submitted a bug to Apple. They have replied that they are aware of the problem and have people looking into it. They will contact me when they have resolved the issue.  I'll post an update here when they do.


问:
Changing array element?
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?</p>

```<code>public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }
</code>```

答:
Well, let me check if I correctly understood it. As per I understood, you want to check each array value if it is less than 0 or higher than 100. If so, the value should be removed from the original array (replaced by 0) and copied into the last position of the new array. So, if I got it, there is my suggestion:

```<code>public int[] validateMarks(int [] originalArray){
    int[] returnArray = new Int[originalArray.length];
    int i,j;

    j=originalArray.length; //returnArray will be visited backwards

    for(i=0;i<originalArray.length;i++){ //originalArray will be visited forwards
        if(originalArray[i]<0 || originalArray[i]>100){
            returnArray[j] = originalArray[i]
            //Last valid returnArray's position will receive originalArray's value which, is less than 0 or higher than 1000
            originalArray[i] = 0;
            //The value which was less then 0 or higher than 100 will be replaed by 0 at the originalArray
            j--;
            //returnArray's counter is decreased so it can be visited backwards
        }
    }

    return returnArray;
    //The new processed array will be returned by this method. If you prefer, you can set this method as void and work it your way.
}
</code>```

Hope it helps you. Cheers!

Title: Changing array element?

Body:
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?

public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }

Body:
Well, let me check if I correctly understood it. As per I understood, you want to check each array value if it is less than 0 or higher than 100. If so, the value should be removed from the original array (replaced by 0) and copied into the last position of the new array. So, if I got it, there is my suggestion:

public int[] validateMarks(int [] originalArray){
    int[] returnArray = new Int[originalArray.length];
    int i,j;

    j=originalArray.length; //returnArray will be visited backwards

    for(i=0;i<originalArray.length;i++){ //originalArray will be visited forwards
        if(originalArray[i]<0 || originalArray[i]>100){
            returnArray[j] = originalArray[i]
            //Last valid returnArray's position will receive originalArray's value which, is less than 0 or higher than 1000
            originalArray[i] = 0;
            //The value which was less then 0 or higher than 100 will be replaed by 0 at the originalArray
            j--;
            //returnArray's counter is decreased so it can be visited backwards
        }
    }

    return returnArray;
    //The new processed array will be returned by this method. If you prefer, you can set this method as void and work it your way.
}

Hope it helps you. Cheers!


问:
Calling service from Html
i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration  that will help me to acheive that??
thanks in advance</p>

答:
The below link is a pretty decent method from my experience.

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

OwnerDisplayName: Shoun

Title: Calling service from Html


问:
Got error at iReport 5.6 on opening JRXML: "Attribute 'hTextAlign' is not allowed to appear in element 'style'"
Has anyone ever gotten this error in iReport 5.6 when trying to open the jrxml file?

Attribute 'hTextAlign' is not allowed to appear in element 'style'

答:
The cause of problem

The jrxml file is just a xml file. It is a common practice to validate xml files with help of XSD schema.

The JasperReports engine is doing the same - it is using xsd schema to validate the report's template (jrxml file).

The xsd was changed at 6.x version compared with 5.x version.

The schema for latest version of JasperReports is available with url. You can always find the link to schema at header of jrxml file:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ... xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" ...>
```

Looks like your template (jrxml file) was created or edited with JasperReports Studio of 6.x version and saved without applying compatitbility with 5.x version option (Compatibility warning dialog).

How to solve this issue:

You can use Jaspersoft Studio (JSS) for modifying report's template. Maybe it is the best choice because the iReport is deprecated (it is not supported since the end of 2015 year) and supports only 5.6 and oldest versions of JasperReports templates/features.

You can save the template at compatitbility mode as 5.x version at JSS and after this continue edit the jrxml file with iReport

The dialog appears during saving template at JSS and looks like this:

To enable this dialog you should change settings at form called via Window -> Preferences menu.

Always use only iReport designer. But be aware: it does not support 6+ version of JasperReports templates.

How to check the difference in schemas of 5.x and 6.x versions

The xsd schema for any version of JasperReports can be found at JasperReports package with source code or at repository of source code.

This is a fragment (screenshot) of comparing xsd files of 5.6.1 (left panel) and 6.3.0 (right panel) versions.

As you can see that the hTextAlign attribute from your error message presents only at xsd of 6.x version. This is a cause of the error you got

Body:
The cause of problem

The jrxml file is just a xml file. It is a common practice to validate xml files with help of XSD schema.

The JasperReports engine is doing the same - it is using xsd schema to validate the report's template (jrxml file).

The xsd was changed at 6.x version compared with 5.x version.

The schema for latest version of JasperReports is available with url. You can always find the link to schema at header of jrxml file:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ... xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" ...>

Looks like your template (jrxml file) was created or edited with JasperReports Studio of 6.x version and saved without applying compatitbility with 5.x version option (Compatibility warning dialog).

How to solve this issue:

You can use Jaspersoft Studio (JSS) for modifying report's template. Maybe it is the best choice because the iReport is deprecated (it is not supported since the end of 2015 year) and supports only 5.6 and oldest versions of JasperReports templates/features.

You can save the template at compatitbility mode as 5.x version at JSS and after this continue edit the jrxml file with iReport

The dialog appears during saving template at JSS and looks like this:

To enable this dialog you should change settings at form called via Window -> Preferences menu.

Always use only iReport designer. But be aware: it does not support 6+ version of JasperReports templates.

How to check the difference in schemas of 5.x and 6.x versions

The xsd schema for any version of JasperReports can be found at JasperReports package with source code or at repository of source code.

This is a fragment (screenshot) of comparing xsd files of 5.6.1 (left panel) and 6.3.0 (right panel) versions.

As you can see that the hTextAlign attribute from your error message presents only at xsd of 6.x version. This is a cause of the error you got