问:
gvpack (graphviz) not preserving labels of the individual digraphs
There are four dot files (cluster_0, cluster_1, cluster_2, cluster_3) which need to be merged into a single dot file.

The code of the individual dot files is as follows.

```<code>digraph cluster_0{
sortv=1;
penwidth=0;pencolor=transparent;
label="1A";
rankdir=LR;
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    1 [label="1:A"];
    2 [label="2:C"];
    3 [label="3:G"];
    3 -> 1
    1 -> 2
    3 -> 2
    2 -> 3
}
digraph cluster_1 {
sortv=2;
penwidth=0;pencolor=transparent;
 label="1B";
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    rankdir=LR;
    11 [label="1:A"];
    12 [label="2:C"];
    13 [label="3:G"];
    14 [label="4:T"];
    14 -> 11
    11 -> 12
    12 -> 13
    12 -> 14
    13 -> 14
}
digraph cluster_2 {
    rankdir=LR;
  sortv=3;
penwidth=0;pencolor=transparent;
  label="1C";
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    21 [label="1:A"];
    22 [label="2:C"];
    23 [label="3:G"];
    24 [label="4:T"];
    25 [label="5:A"];
    24 -> 21
    21 -> 22
    21 -> 25
    25 -> 22
    22 -> 23
    23 -> 24
}
digraph cluster_3{
        sortv=4;
penwidth=0;pencolor=transparent;
        label="1D"
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    rankdir=LR;
    31 [label="1:A"];
    32 [label="2:C"];
    33 [label="3:G"];
    31:c -> 31:w
    32 -> 31 [dir=both,len=1.25];
    33 -> 31 [dir=both,];
    32 -> 32
    33 -> 32 [dir=both,];
    33 -> 33
}
</code>```

To generate a merged single dot file ...I ran the following command.

```<code>neato -Gstart=5 cluster_0.dot cluster_1.dot cluster_2.dot cluster_3.dot | gvpack -array_u4 | neato -n2 -s -Teps -o merge.eps
</code>```

merge.eps came perfectly well but the labels of the individual graphs went missing. How can we preserve the labels of the individual graphs in the output merge file ? Can anyone help to fix this ?

Here I am attaching the single individual file where the label is shown
I compiled the individual file with the following command.

```<code>neato -Gstart=5 cluster_0.dot -Teps -o cluster_0.eps
</code>```

Also I am attaching the merge output file which removed the labels of the graphs.

答:
This is not an answer but rather sharing experiences: As it turns out while experimenting with various options, it seems to be the neato engine that supresses the labels. If you use dot, you may not get the exact layout you want but you get the labels:

```<code>dot -Gstart=5 cluster_0.dot cluster_1.dot cluster_2.dot cluster_3.dot | gvpack -array_u4 | dot -n2 -s -T jpg -o merge.jpg
</code>```

gives you

My personal preference would by to have one master file so.m4

```<code>digraph so
{
    define(`digraph',`subgraph')
    rankdir=LR;
    include(cluster_0.dot)
    include(cluster_1.dot)
    include(cluster_2.dot)
    include(cluster_3.dot)
}
</code>```

that I process with

```<code>m4 so.m4 > so.dot
</code>```

In the resulting so.dot file, I have all clusters combined, and I can go to the next step (here producing a JPG) with a simple

```<code>dot -T png -o so.png so.dot
</code>```

The advantage of that is that you can use the master file for "global options". I think it is easier to maintain and less unwieldy than the command with all the pipes and options. But that's a matter of taste.

With the option rankdir=LR; this version is produced:

Have fun - happy to do more but I'd need to know more about your project.

ContentLicense: CC BY-SA 4.0

Body:
There are four dot files (cluster_0, cluster_1, cluster_2, cluster_3) which need to be merged into a single dot file.

The code of the individual dot files is as follows.

digraph cluster_0{
sortv=1;
penwidth=0;pencolor=transparent;
label="1A";
rankdir=LR;
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    1 [label="1:A"];
    2 [label="2:C"];
    3 [label="3:G"];
    3 -> 1
    1 -> 2
    3 -> 2
    2 -> 3
}
digraph cluster_1 {
sortv=2;
penwidth=0;pencolor=transparent;
 label="1B";
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    rankdir=LR;
    11 [label="1:A"];
    12 [label="2:C"];
    13 [label="3:G"];
    14 [label="4:T"];
    14 -> 11
    11 -> 12
    12 -> 13
    12 -> 14
    13 -> 14
}
digraph cluster_2 {
    rankdir=LR;
  sortv=3;
penwidth=0;pencolor=transparent;
  label="1C";
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    21 [label="1:A"];
    22 [label="2:C"];
    23 [label="3:G"];
    24 [label="4:T"];
    25 [label="5:A"];
    24 -> 21
    21 -> 22
    21 -> 25
    25 -> 22
    22 -> 23
    23 -> 24
}
digraph cluster_3{
        sortv=4;
penwidth=0;pencolor=transparent;
        label="1D"
 node [fontname = "times-roman-bold",fontsize=12];
        edge [fontname = "times-roman-bold",fontsize=12,arrowsize=0.75];
    rankdir=LR;
    31 [label="1:A"];
    32 [label="2:C"];
    33 [label="3:G"];
    31:c -> 31:w
    32 -> 31 [dir=both,len=1.25];
    33 -> 31 [dir=both,];
    32 -> 32
    33 -> 32 [dir=both,];
    33 -> 33
}

To generate a merged single dot file ...I ran the following command.

neato -Gstart=5 cluster_0.dot cluster_1.dot cluster_2.dot cluster_3.dot | gvpack -array_u4 | neato -n2 -s -Teps -o merge.eps

merge.eps came perfectly well but the labels of the individual graphs went missing. How can we preserve the labels of the individual graphs in the output merge file ? Can anyone help to fix this ?

Here I am attaching the single individual file where the label is shown
I compiled the individual file with the following command.

neato -Gstart=5 cluster_0.dot -Teps -o cluster_0.eps

Also I am attaching the merge output file which removed the labels of the graphs.

Body:
This is not an answer but rather sharing experiences: As it turns out while experimenting with various options, it seems to be the neato engine that supresses the labels. If you use dot, you may not get the exact layout you want but you get the labels:

dot -Gstart=5 cluster_0.dot cluster_1.dot cluster_2.dot cluster_3.dot | gvpack -array_u4 | dot -n2 -s -T jpg -o merge.jpg

gives you

My personal preference would by to have one master file so.m4

digraph so
{
    define(`digraph',`subgraph')
    rankdir=LR;
    include(cluster_0.dot)
    include(cluster_1.dot)
    include(cluster_2.dot)
    include(cluster_3.dot)
}

that I process with

m4 so.m4 > so.dot

In the resulting so.dot file, I have all clusters combined, and I can go to the next step (here producing a JPG) with a simple

dot -T png -o so.png so.dot

The advantage of that is that you can use the master file for "global options". I think it is easier to maintain and less unwieldy than the command with all the pipes and options. But that's a matter of taste.

With the option rankdir=LR; this version is produced:

Have fun - happy to do more but I'd need to know more about your project.


来源: stackexchange

问:
Make Node.js Redis client's .multi() and .batch() return errors in results for testing purposes
I can read in the docs from Node.js Redis client:

If your code contains an syntax error an EXECABORT error is going to be thrown and all commands are going to be aborted. That error contains a .errors property that contains the concret errors. If all commands were queued successfully and an error is thrown by redis while processing the commands that error is going to be returned in the result array! No other command is going to be aborted though than the onces failing.

How do I write a Node.js Redis client's .multi() and .batch() in order to have errors in results for testing purposes?

答:
Not sure if it is still relevant for you but following code produces the EXECABORT error for MULTI.
PS. I am not a nodejs developer :)

Code:

```<code>var redis = require("redis"),
client = redis.createClient();
client.sadd("bigset", "a member");
client.sadd("bigset", "another member");
set_size = 20;

while (set_size > 0) {
    client.sadd("bigset", "member " + set_size);
    set_size -= 1;
}

// multi chain with an individual callback
client.multi()
    .scard("bigset")
    .smembers("bigset")
    .set("a")
    .keys("*", function (err, replies) {
        // NOTE: code in this callback is NOT atomic
        // this only happens after the the .exec call finishes.
        client.mget(replies, redis.print);
    })
    .dbsize()
    .exec(function (err, replies) {
//        console.log("MULTI got " + replies.length + " replies");
  //      replies.forEach(function (reply, index) {
//            console.log("Reply " + index + ": " + reply.toString());
    //    });
        console.log(replies);
        console.log(err);
        client.quit();
    });
</code>```

Output :

undefined

{ [ReplyError: EXECABORT Transaction discarded because of previous
  errors.]   command: 'EXEC',   code: 'EXECABORT',   errors: [ {
  [ReplyError: ERR wrong number of arguments for 'set' command] command:
  'SET', args: [Object], code: 'ERR', position: 2 } ] }

Explanation : SET command takes 2 arguments. I gave only one and print the err to console.

Detailed explanation about the topic is in this issue. See the last but one comment by BridgeAR.

Sample Code taken from the nodejs git repo

ContentLicense: CC BY-SA 3.0

Body:
Not sure if it is still relevant for you but following code produces the EXECABORT error for MULTI.
PS. I am not a nodejs developer :)

Code:

var redis = require("redis"),
client = redis.createClient();
client.sadd("bigset", "a member");
client.sadd("bigset", "another member");
set_size = 20;

while (set_size > 0) {
    client.sadd("bigset", "member " + set_size);
    set_size -= 1;
}

// multi chain with an individual callback
client.multi()
    .scard("bigset")
    .smembers("bigset")
    .set("a")
    .keys("*", function (err, replies) {
        // NOTE: code in this callback is NOT atomic
        // this only happens after the the .exec call finishes.
        client.mget(replies, redis.print);
    })
    .dbsize()
    .exec(function (err, replies) {
//        console.log("MULTI got " + replies.length + " replies");
  //      replies.forEach(function (reply, index) {
//            console.log("Reply " + index + ": " + reply.toString());
    //    });
        console.log(replies);
        console.log(err);
        client.quit();
    });

Output :

undefined

{ [ReplyError: EXECABORT Transaction discarded because of previous
  errors.]   command: 'EXEC',   code: 'EXECABORT',   errors: [ {
  [ReplyError: ERR wrong number of arguments for 'set' command] command:
  'SET', args: [Object], code: 'ERR', position: 2 } ] }

Explanation : SET command takes 2 arguments. I gave only one and print the err to console.

Detailed explanation about the topic is in this issue. See the last but one comment by BridgeAR.

Sample Code taken from the nodejs git repo


问:
Is a LINQ statement faster than a 'foreach' loop?
I am writing a Mesh Rendering manager and thought it would be a good idea to group all of the meshes which use the same shader and then render these while I'm in that shader pass.

I am currently using a foreach loop, but wondered if utilising LINQ might give me a performance increase?

答:
I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

```<code>Exists = True
Time   = 174
Exists = True
Time   = 149
</code>```

It would be interesting if some of you could copy & paste this code in a console app and test as well.
Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

```<code>public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }

    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}
</code>```

Body:
I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well.
Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }

    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}


问:
XAMPP Ports Change On its Own
My Apache Ports are set to:

80 and 443

Looking at the XAMPP control panel a few hours later, I noticed the Ports had changed to:

05 and 59895

Would XAMPP switch to these Ports automatically for some reason after several hours?

Is there a danger in using/opening these Ports?

答:
Well, I had this problem so I got here.

I understand that this is not a problema with xampp so I started to check my code.

I was working with this code last friday.

$conn = new mysqli($host, $user, $pass, $database);

Today the code wasn't working so I have updated to this:

$conn = new mysqli($host."8000", $user, $pass, $database); //8000 is the apache port, you can change it to 80

It work's fine for me!

Hope this help you guys

Title: XAMPP Ports Change On its Own


问:
Creating partitions
Hei, I am having problem with creating partitions using PL/SQL procedure:

ORA-14019: partition bound element must be one of: string, datetime or
  interval literal, number, or MAXVALUE

It seems like problem is in format of attribute r.partition_date, I already run some tests script and tried different date format, but nothing helped.

Format of column partition_date : 2017-09-01

I am running this procedure:

```<code>    declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where a.PARTITION_NAME =  'PARTITION_20170831'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at (''N'',to_date(' || r.partition_date || ',''yyyy.mm.dd''))
      into (partition ' || r.partition_name || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/
</code>```

Even though this one is working:

```<code> declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where rownum = '1'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at ("N",to_date(''2017-01-29'',''yyyy.mm.dd''))
      into (partition ' || 'PARTITION_20170129' || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/
</code>```

Thank you for advice.

答:
first of all remove asterisks in this

(''N'',to_date(' || **r.partition_date** || ',''yyyy.mm.dd'')) part of first sentence.

And format inthe cursor

for r in (select distinct to_char(a.partition_date,'yyyy.mm.dd')
  par_date , a.partition_name from XX a  where rownum = '1'  order by 1)

And add two quotations around :

(''N'',to_date(' ''|| r.par_date||'' ',''yyyy.mm.dd''))

```<code>  SQL>set serveroutput on;
  SQL> declare
    v_new_part varchar2(30);
    v_prev_part varchar2(30);
    v_sql varchar2(4000);
    v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
    begin
    for r in (select distinct to_char(a.partition_date,'yyyy.mm.dd') par_date , a.partition_name from XX a
    where a.PARTITION_NAME =  'PARTITION_20170831'
    order by 1)
    loop
          v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
          PARTITION_30000101
          at (''N'',to_date('''|| r.par_date || ''',''yyyy.mm.dd''))
          into (partition ' || r.partition_name || ' ,partition
          PARTITION_30000101)';
      dbms_output.put_line(v_sql);
      execute immediate v_sql;
    end loop;
 end;
 /
</code>```

Title: Creating partitions

Body:
Hei, I am having problem with creating partitions using PL/SQL procedure:

ORA-14019: partition bound element must be one of: string, datetime or
  interval literal, number, or MAXVALUE

It seems like problem is in format of attribute r.partition_date, I already run some tests script and tried different date format, but nothing helped.

Format of column partition_date : 2017-09-01

I am running this procedure:

    declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where a.PARTITION_NAME =  'PARTITION_20170831'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at (''N'',to_date(' || r.partition_date || ',''yyyy.mm.dd''))
      into (partition ' || r.partition_name || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/

Even though this one is working:

 declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where rownum = '1'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at ("N",to_date(''2017-01-29'',''yyyy.mm.dd''))
      into (partition ' || 'PARTITION_20170129' || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/

Thank you for advice.

Body:
first of all remove asterisks in this

(''N'',to_date(' || **r.partition_date** || ',''yyyy.mm.dd'')) part of first sentence.

And format inthe cursor

for r in (select distinct to_char(a.partition_date,'yyyy.mm.dd')
  par_date , a.partition_name from XX a  where rownum = '1'  order by 1)

And add two quotations around :

(''N'',to_date(' ''|| r.par_date||'' ',''yyyy.mm.dd''))

  SQL>set serveroutput on;
  SQL> declare
    v_new_part varchar2(30);
    v_prev_part varchar2(30);
    v_sql varchar2(4000);
    v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
    begin
    for r in (select distinct to_char(a.partition_date,'yyyy.mm.dd') par_date , a.partition_name from XX a
    where a.PARTITION_NAME =  'PARTITION_20170831'
    order by 1)
    loop
          v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
          PARTITION_30000101
          at (''N'',to_date('''|| r.par_date || ''',''yyyy.mm.dd''))
          into (partition ' || r.partition_name || ' ,partition
          PARTITION_30000101)';
      dbms_output.put_line(v_sql);
      execute immediate v_sql;
    end loop;
 end;
 /


问:
Changing the Sender's email address and name when sending an email using an Outlook object in C#
I have been trying to figure this one out for the last 2 days. I feel like I'm really close, but just can't get it. I've gotten my c# program to successfully send an email with all the required information in it, but I can't change the sender's name and email address. Here is my code so far:

```<code>Outlook.Application oApp = new Outlook.Application();

string emailrecipient = (Convert.ToString(txtAdmin1.Text) + "@domain.com");

            Outlook.MailItem email = (Outlook.MailItem)(oApp.CreateItem(Outlook.OlItemType.olMailItem));
            email.Recipients.Add(emailrecipient);
            email.Subject = "Your Recent Admin Rights Request";
            email.Body = "Your admin rights request has been processed. The user " + txtAdmin1.Text + " has been added as an administrator on computer " + txtName.Text + ". Please reboot your computer for these changes to take effect.";

            email.Send();
</code>```

any advice would be amazing. I've searched all over the place, and haven't found anything that has worked so far.

答: Better change the profile name from server if you are using Interop.Outlook.dll</p>

Body:
I have been trying to figure this one out for the last 2 days. I feel like I'm really close, but just can't get it. I've gotten my c# program to successfully send an email with all the required information in it, but I can't change the sender's name and email address. Here is my code so far:

Outlook.Application oApp = new Outlook.Application();

string emailrecipient = (Convert.ToString(txtAdmin1.Text) + "@domain.com");

            Outlook.MailItem email = (Outlook.MailItem)(oApp.CreateItem(Outlook.OlItemType.olMailItem));
            email.Recipients.Add(emailrecipient);
            email.Subject = "Your Recent Admin Rights Request";
            email.Body = "Your admin rights request has been processed. The user " + txtAdmin1.Text + " has been added as an administrator on computer " + txtName.Text + ". Please reboot your computer for these changes to take effect.";

            email.Send();

any advice would be amazing. I've searched all over the place, and haven't found anything that has worked so far.


问:
How to do dependency injection in multiple controller in a single step
I'm using ionic1 and I have multiple controller each one is for different page.
Consider the following injections:

```<code>.controller('login', function($scope, $http, $location, $state,$rootScope , auth,$timeout)
.controller('Home', function($scope, $rootScope, $http, $state,$location, $ionicNavBarDelegate, $timeout, auth, getData)
</code>```

So on I have about 10 of them.
Most of the injections are common to all the controllers such as $scope,$rootScope and few others.
So I want to know if there is a one liner to inject all the dependencies in one go.

答:
Injecting all dependencies contradicts the concept of dependency injection (besides the fact that controllers can have local dependencies). A dependency is what a controller depends on.

If there are several controllers that have matching dependencies, they can inherit base controller. If child controllers should have their own dependencies, this can be done with base class that automatically assigns dependencies to controller instance. Controller inheritance works best with ES6 classes:

```<code>class BaseController {
  static get $inject() {
    return ['$rootScope', '$scope', '$timeout'];
  }

  constructor(...deps) {
    this.constructor.$inject.forEach((depName, i) => {
      this[depName] = deps[i];
    });
  }
}

class SomeController extends BaseController {
  static get $inject() {
    return [...super.$inject, 'some'];
  }

  constructor(...deps) {
    super(...deps);
    ...
  }
}

app.controller('SomeController', SomeController);
</code>```

Body:
I'm using ionic1 and I have multiple controller each one is for different page.
Consider the following injections:

.controller('login', function($scope, $http, $location, $state,$rootScope , auth,$timeout)
.controller('Home', function($scope, $rootScope, $http, $state,$location, $ionicNavBarDelegate, $timeout, auth, getData)

So on I have about 10 of them.
Most of the injections are common to all the controllers such as $scope,$rootScope and few others.
So I want to know if there is a one liner to inject all the dependencies in one go.

Body:
Injecting all dependencies contradicts the concept of dependency injection (besides the fact that controllers can have local dependencies). A dependency is what a controller depends on.

If there are several controllers that have matching dependencies, they can inherit base controller. If child controllers should have their own dependencies, this can be done with base class that automatically assigns dependencies to controller instance. Controller inheritance works best with ES6 classes:

class BaseController {
  static get $inject() {
    return ['$rootScope', '$scope', '$timeout'];
  }

  constructor(...deps) {
    this.constructor.$inject.forEach((depName, i) => {
      this[depName] = deps[i];
    });
  }
}

class SomeController extends BaseController {
  static get $inject() {
    return [...super.$inject, 'some'];
  }

  constructor(...deps) {
    super(...deps);
    ...
  }
}

app.controller('SomeController', SomeController);


问:
Multimodule spring hibernate, difficulty with access to dao, need create spring bean xml?
I make multimodule application (vaadin, spring, hibernate)
I have big problem with access to DAO (or model, generally with persistence in persistence module)

I need create spring xml bean definition in core or create spring bean in web (in applicationContext.xml) ?

I get error :

```<code>services/TestService.java:[3,11] package dao does not exist
cannot find symbol  symbol:   class User
Generally core don't see persistence class
</code>```

Generally, i have 3 modules :

core

persistence

web

Core pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <parent>
    <artifactId>eControl</artifactId>
    <groupId>pl.cwik.dawid</groupId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>core</artifactId>

<dependencies>
    <dependency>
        <groupId>pl.cwik.dawid</groupId>
        <artifactId>persistence</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.13.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.11.7.RELEASE</version>
    </dependency>

</dependencies>
</code>```

And persistence pom

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
    <artifactId>eControl</artifactId>
    <groupId>pl.cwik.dawid</groupId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>persistence</artifactId>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.11.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.0.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.1.4</version>
    </dependency>

</dependencies>
</code>```

答:
The problem solves by comment @Vlasec .

I noticed one problem in your XML. You are asking for persistence 1.0-SNAPSHOT, but your current version is 1.0.0-SNAPSHOT. That means you either get an older version, or you could also get no library at all if you never had 1.0-SNAPSHOT version. – Vlasec Nov 9 at 10:12

That's my fault, it is a really stupid thing ! Thanks !

Body:
I make multimodule application (vaadin, spring, hibernate)
I have big problem with access to DAO (or model, generally with persistence in persistence module)

I need create spring xml bean definition in core or create spring bean in web (in applicationContext.xml) ?

I get error :

services/TestService.java:[3,11] package dao does not exist
cannot find symbol  symbol:   class User
Generally core don't see persistence class

Generally, i have 3 modules :

core

persistence

web

Core pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <parent>
    <artifactId>eControl</artifactId>
    <groupId>pl.cwik.dawid</groupId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>core</artifactId>

<dependencies>
    <dependency>
        <groupId>pl.cwik.dawid</groupId>
        <artifactId>persistence</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.13.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.11.7.RELEASE</version>
    </dependency>

</dependencies>

And persistence pom

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
    <artifactId>eControl</artifactId>
    <groupId>pl.cwik.dawid</groupId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>persistence</artifactId>

<dependencies>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.11.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.1.4</version>
    </dependency>

</dependencies>


问:
Enable button if the mentioned input boxed are filled using jquery?
HTML:

```<code><input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>
</code>```

This code displays two input boxes and one submit button.

jQuery:

```<code>$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});
</code>```

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

答:
You need to get value of each textbox separately like following. And the you can use prop method like following.

$("#message, #message1").keyup(function() {
  var msg = !$("#message").val(),
      msg1 = !$("#message1").val();

    $('.sendButton').prop('disabled', (msg || msg1));
}).keyup(); //to call on page load```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" />
<input type="text" id="message1" />
<input type="button" class="sendButton" value="submit" /></code>```

Body:
HTML:

<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>

This code displays two input boxes and one submit button.

jQuery:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

Body:
You need to get value of each textbox separately like following. And the you can use prop method like following.

$("#message, #message1").keyup(function() {
  var msg = !$("#message").val(),
      msg1 = !$("#message1").val();

    $('.sendButton').prop('disabled', (msg || msg1));
}).keyup(); //to call on page load

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" />
<input type="text" id="message1" />
<input type="button" class="sendButton" value="submit" />


问:
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

```<code>$ myapp -n 3,4,5,6
</code>```

or

```<code>$ myapp -n 3-6
</code>```

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

```<code>$ myapp -n 22-27, 51-64
</code>```

答:
```<code>import argparse

def parse_range(astr):
    result = set()
    for part in astr.split(','):
        x = part.split('-')
        result.update(range(int(x[0]), int(x[-1]) + 1))
    return sorted(result)

parser = argparse.ArgumentParser()
parser.add_argument('-n', type=parse_range)
args = parser.parse_args()
print(args.n)
</code>```

yields

```<code>% script.py -n 3-6
[3, 4, 5, 6]

% script.py -n 3,6
[3, 6]

% script.py -n 22-27,51-64
[22, 23, 24, 25, 26, 27, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Parsing command line input for numbers

Body:
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64

Body:
import argparse

def parse_range(astr):
    result = set()
    for part in astr.split(','):
        x = part.split('-')
        result.update(range(int(x[0]), int(x[-1]) + 1))
    return sorted(result)

parser = argparse.ArgumentParser()
parser.add_argument('-n', type=parse_range)
args = parser.parse_args()
print(args.n)

yields

% script.py -n 3-6
[3, 4, 5, 6]

% script.py -n 3,6
[3, 6]

% script.py -n 22-27,51-64
[22, 23, 24, 25, 26, 27, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]


问:
Sed how to add variable with vertical bar to the end of first line
i want to append variable with string to the first line of my_file

sed -i "1 s/$/   $my_variable/" ~/my_file

Now i have this:

42 192.168.1.1   string_from_my_variable

It works. But the task become harder, now i need to add delimiter before string_from_my_variable

I tried to sed -i "1 s#$#   \|\$my_variable#" ~/my_file, of course it does not help. I need to have this:

42 192.168.1.1   | string_from_my_variable

How can i do this ? Thanks for your attention.

答:
I think there's a coincidence in your command sed -i "1 s#$#   \|\$my_variable#", the $# is a special parameter in the double quotation marks(""), which means the number of parameters are given, you can get more informations by man bash:

Special Parameters
   #      Expands to the number of positional parameters in decimal.

so, your command is illegal.

```<code># $# is a special parameter, so the command is illegal:
$ sed "1s#$#   |${my_variable}#" my_file
sed: -e expression #1, char 32: unterminated `s' command
# when used ', the special meaning of $# is gone,
# and the command is legal, but doesn't work for your expection:
$ sed '1s#$#   |${my_variable}#' my_file
42 192.168.1.1   |${my_variable}
# add a space beteween `$#`, and the command is legal too,
# but still doesn't work for your expection:
$ sed "1s#$ #   |${my_variable}#" my_file
42 192.168.1.1
</code>```

you can use a different delimiter instead of #:

```<code>my_variable="string_from_my_variable"
sed -i "1s/$/   |${my_variable}/" ~/my_file
</code>```

P.S:

the \ before $my_variable should NOT exist.

the \ before | is unnecessary if the delimiter  is NOT |.

Body:
I think there's a coincidence in your command sed -i "1 s#$#   \|\$my_variable#", the $# is a special parameter in the double quotation marks(""), which means the number of parameters are given, you can get more informations by man bash:

Special Parameters
   #      Expands to the number of positional parameters in decimal.

so, your command is illegal.

# $# is a special parameter, so the command is illegal:
$ sed "1s#$#   |${my_variable}#" my_file
sed: -e expression #1, char 32: unterminated `s' command
# when used ', the special meaning of $# is gone,
# and the command is legal, but doesn't work for your expection:
$ sed '1s#$#   |${my_variable}#' my_file
42 192.168.1.1   |${my_variable}
# add a space beteween `$#`, and the command is legal too,
# but still doesn't work for your expection:
$ sed "1s#$ #   |${my_variable}#" my_file
42 192.168.1.1

you can use a different delimiter instead of #:

my_variable="string_from_my_variable"
sed -i "1s/$/   |${my_variable}/" ~/my_file

P.S:

the \ before $my_variable should NOT exist.

the \ before | is unnecessary if the delimiter  is NOT |.


问:
Debug phoenix test with IEx
I know you can debug the webapp with IEx but is it possible to set a breakpoint inside a test?

For example in the following test I would like to check what's inside conn or check any other variable or macro.

```<code>defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  require IEx
  test "GET /", %{conn: conn} do
    IEx.pry
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end
</code>```

In order to make it work with the webapp you must have phoenix.server running with iex -S mix phoenix.server

But in this case is a test not the webapp so it complains with:

```<code>Cannot pry #PID<0.406.0> at ... Is an IEx shell running?
</code>```

答:
To check what is inside conn structure (or any other variable) you can just use IO.inspect conn and run tests as usual with mix test - there is no need to use pry here. For example:

```<code>defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  test "GET /", %{conn: conn} do
    IO.inspect conn, limit: :infinity
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end
</code>```

However, if you really need a shell you can then call it like this:

```<code>iex -S mix test
</code>```

Title: Debug phoenix test with IEx

Body:
I know you can debug the webapp with IEx but is it possible to set a breakpoint inside a test?

For example in the following test I would like to check what's inside conn or check any other variable or macro.

defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  require IEx
  test "GET /", %{conn: conn} do
    IEx.pry
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end

In order to make it work with the webapp you must have phoenix.server running with iex -S mix phoenix.server

But in this case is a test not the webapp so it complains with:

Cannot pry #PID<0.406.0> at ... Is an IEx shell running?

Body:
To check what is inside conn structure (or any other variable) you can just use IO.inspect conn and run tests as usual with mix test - there is no need to use pry here. For example:

defmodule HelloWeb.PageControllerTest do
  use HelloWeb.ConnCase
  test "GET /", %{conn: conn} do
    IO.inspect conn, limit: :infinity
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end

However, if you really need a shell you can then call it like this:

iex -S mix test


问:
How to set "123" mode as default mode in iOS keyboard Swift 3
Code to set the keyboard's overall type:

```<code>self.Value.keyboardType = UIKeyboardTypeDefault
</code>```

How can I set the default keyboard's mode from "ABC to "123" at launch? Or even only "123" mode.

Any ideas?

答:
Please set UIKeyboardTypeNumbersAndPunctuation.

self.Value.keyboardType = UIKeyboardTypeNumbersAndPunctuation

Body:
Code to set the keyboard's overall type:

self.Value.keyboardType = UIKeyboardTypeDefault

How can I set the default keyboard's mode from "ABC to "123" at launch? Or even only "123" mode.

Any ideas?


问:
Swift - How to do specific action on last row of a UITableView when the last row isn't visible?
I am trying to achieve a custom action on the last row of my UITableView.

I found a nice extension in order to know if I'm on the last row :

```<code>extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}
</code>```

The only issue I'm facing is that if my tableView has many rows, with scrollable content, the last row isn't visible.
Thus, in my cellForRow I am doing this :

```<code>if tableView.isLast(for: indexPath) {
   print("Last Row - Do Specific action")
} else {
}
</code>```

It is working, except that imagine my screen can display 6 rows, but the total number of rows of my tableView is 15.
It will apply my specific action on the row at indexPath 5 and 15.

I am guessing it is because each time cellForRow is called, it is checking for the last row, and it apply on the last visible row also.

How can I achieve a custom action ONLY on the last row even if it is not visible yet?

EDIT: After more investigation, the issue comes from UITableView not able to prefetch the cell, and cellLoaded and cellVisible is the same.

答:
You can try with tableview delegate method:</p>

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
</code>```

Body:
I am trying to achieve a custom action on the last row of my UITableView.

I found a nice extension in order to know if I'm on the last row :

extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}

The only issue I'm facing is that if my tableView has many rows, with scrollable content, the last row isn't visible.
Thus, in my cellForRow I am doing this :

if tableView.isLast(for: indexPath) {
   print("Last Row - Do Specific action")
} else {
}

It is working, except that imagine my screen can display 6 rows, but the total number of rows of my tableView is 15.
It will apply my specific action on the row at indexPath 5 and 15.

I am guessing it is because each time cellForRow is called, it is checking for the last row, and it apply on the last visible row also.

How can I achieve a custom action ONLY on the last row even if it is not visible yet?

EDIT: After more investigation, the issue comes from UITableView not able to prefetch the cell, and cellLoaded and cellVisible is the same.

Body:
You can try with tableview delegate method:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)


问:
Looking for effective way to retrieve cts:element-values() count
I need to test the number of entry of a specific lexicon (range index). I can do it using fn:count(cts:element-values()), but this will end up running too slowly with a large lexicon. Is there a better way to compute the total number of values ?

Note that I don't wan't the number of fragment as returned by cts:count-aggregate, but the number of values.

Thanks for help

答:
No. There is no better query. Maybe run once and cache the results for reuse. </p>

<p>You don’t say how slow it is. It shouldn’t take more than a few seconds usually if you’ve got the right cluster size. </p>

Body:
No. There is no better query. Maybe run once and cache the results for reuse.

You don’t say how slow it is. It shouldn’t take more than a few seconds usually if you’ve got the right cluster size.


问:
invalidation of std::function objects
The following code does not work as per my understanding. When the Raise
 method of the handler object is called, random (I assume uninitialised variable) values are printed. My suspicion is that the map::insert calls made in CreateTests results in some sort of move that results in the invalidation of this parameters provides to the std::function objects provided to EventCoordinator::Register. The intended output of this program would be 2 lines printed in the console, with values 0 & 1 printed. Can somebody advise what the error here is?

```<code>#include <map>
#include <functional>
#include <vector>
#include <iostream>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;

    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }

    }
};

class test
{
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }
    test(const int id, EventCoordinator& handler) : mId(id)
    {
        handler.Register(mId, std::bind(&test::func, *this));
    }

    void other()
    {
        std::cout << this << '\n';
    }

    void func() const
    {

        std::cout << this <<'\n';
        std::cout << mId << '\n';
    }
    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
    int mId;
};

std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0, handler)));
    returnMap.emplace(std::make_pair(1, test(1, handler)));
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    ret[0].other();
    handler.Raise(1);
    ret[1].other();
    std::cin.get();
}
</code>```

答:
After a few tries, I found the little error.

When you use Register member function in the Test constructor, you use the pointer this, but you need the reference, not the pointer so, change this for *this and I think that the code runs properly:

```<code> test ( const int id , EventCoordinator& handler ) : mId ( id )
  {
    handler.Register ( mId , std::bind ( &test::func , *this ) );
  }
</code>```

Title: invalidation of std::function objects

Body:
The following code does not work as per my understanding. When the Raise
 method of the handler object is called, random (I assume uninitialised variable) values are printed. My suspicion is that the map::insert calls made in CreateTests results in some sort of move that results in the invalidation of this parameters provides to the std::function objects provided to EventCoordinator::Register. The intended output of this program would be 2 lines printed in the console, with values 0 & 1 printed. Can somebody advise what the error here is?

#include <map>
#include <functional>
#include <vector>
#include <iostream>

class EventCoordinator
{
    using Handler = std::function<void()>;
    using Handlers = std::vector<Handler>;

    std::map<int, Handlers> HandlerMap;

public:

    void Register(const int id, std::function<void()> handler)
    {
        HandlerMap[id].emplace_back(handler);
    }

    void Raise(const int id)
    {
        try {
            auto handlers = HandlerMap.at(id);
            for (const auto& handler : handlers) {
                handler();
            }
        }
        catch (std::exception& e) {
            std::cout << e.what();
        }

    }
};

class test
{
public:
    test() : mId(-1)
    {
        std::cout << "test default constructor\n";
    }
    test(const int id, EventCoordinator& handler) : mId(id)
    {
        handler.Register(mId, std::bind(&test::func, *this));
    }

    void other()
    {
        std::cout << this << '\n';
    }

    void func() const
    {

        std::cout << this <<'\n';
        std::cout << mId << '\n';
    }
    ~test() = default;
    test(const test& other) = default;
    test(test&& other) noexcept = default;
    test& operator=(const test& other) = default;
    test& operator=(test&& other) noexcept = default;
    int mId;
};

std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.emplace(std::make_pair(0, test(0, handler)));
    returnMap.emplace(std::make_pair(1, test(1, handler)));
    return returnMap;
}

int main(int argc, char** args)
{
    EventCoordinator handler;
    auto ret = CreateTests(handler);
    handler.Raise(0);
    ret[0].other();
    handler.Raise(1);
    ret[1].other();
    std::cin.get();
}

Body:
After a few tries, I found the little error.

When you use Register member function in the Test constructor, you use the pointer this, but you need the reference, not the pointer so, change this for *this and I think that the code runs properly:

 test ( const int id , EventCoordinator& handler ) : mId ( id )
  {
    handler.Register ( mId , std::bind ( &test::func , *this ) );
  }


问:
.net SQL Server stored procs wrapper class structure
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

```<code>void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}
</code>```

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

答:
Personally, i prefer

```<code>void RunStoredProc1(object arg1)
{
    try
    {
        using(SqlConnection conn = new SqlConnection(connStr))
        {
            using SqlCommand cmd = new SqlCommand("storedProc1", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@input1", arg1);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
      //handle the exception appropriately.
    }
}
</code>```

Over the traditional try catch finally that you would need to do to manage your resources.

But overall, I like doing it with separate methods, so that you can custom tailor your catch blocks for the sproc.

Also, You might need more than one parameter down the road, and you would just be making a mess of a fairly straight-forward function

Body:
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

Body:
Personally, i prefer

void RunStoredProc1(object arg1)
{
    try
    {
        using(SqlConnection conn = new SqlConnection(connStr))
        {
            using SqlCommand cmd = new SqlCommand("storedProc1", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@input1", arg1);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
      //handle the exception appropriately.
    }
}

Over the traditional try catch finally that you would need to do to manage your resources.

But overall, I like doing it with separate methods, so that you can custom tailor your catch blocks for the sproc.

Also, You might need more than one parameter down the road, and you would just be making a mess of a fairly straight-forward function


问:
Cant create migration phinx
When I try create migration I get this exception, but I have not got curly braces in my migration path

[Exception]
You probably used curly braces to define the migration path in your Phinx configuration file, but no directories have been matched using this pattern. You need to create a migration directory manually.

My config:

```<code>paths:
  migrations: %%PHINX_CONFIG_DIR%%/db/migrations
  seeds: %%PHINX_CONFIG_DIR%%/db/seeds

environments:
  default_migration_table: phinxlog
  default_database: development
  production:
    adapter: mysql
    host: localhost
    name: production_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

  development:
    adapter: mysql
    host: localhost
    name: development_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

  testing:
    adapter: mysql
    host: localhost
    name: testing_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

version_order: creation
</code>```

答: Probably you are running "php vendor/bin/phinx " from inside the migration directory. Try this from root directory. I was getting same error and fixed from root folder.</p>

Title: Cant create migration phinx

Body:
When I try create migration I get this exception, but I have not got curly braces in my migration path

[Exception]
You probably used curly braces to define the migration path in your Phinx configuration file, but no directories have been matched using this pattern. You need to create a migration directory manually.

My config:

paths:
  migrations: %%PHINX_CONFIG_DIR%%/db/migrations
  seeds: %%PHINX_CONFIG_DIR%%/db/seeds

environments:
  default_migration_table: phinxlog
  default_database: development
  production:
    adapter: mysql
    host: localhost
    name: production_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

  development:
    adapter: mysql
    host: localhost
    name: development_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

  testing:
    adapter: mysql
    host: localhost
    name: testing_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

version_order: creation


问:
Why does StreamingQueryStatus.isDataAvailable is turned on when no records are available in Kafka topic?
I have to stop spark structured streaming query. So first, I check the status is there any data available in Kafka to process. if yes, processes it and then stop the query.

if (query.status.isDataAvailable) {
                    query.processAllAvailable()
                  }
query.stop()
```

<p>After Jacek Laskowski's suggestion, I have modified the implementation.
I have list of streaming queries,</p>

<pre class="lang-scala prettyprint-override"><code>streamingQueryList.foreach{query =>
query.stop()
}
</code>```

After every stopping of query, it throws following exception:

```<code>java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:998)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304)
    at scala.concurrent.impl.Promise$DefaultPromise.tryAwait(Promise.scala:202)
    at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:218)
    at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:153)
    at org.apache.spark.util.ThreadUtils$.awaitReady(ThreadUtils.scala:222)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:621)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2022)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply$mcV$sp(FileFormatWriter.scala:179)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.streaming.FileStreamSink.addBatch(FileStreamSink.scala:123)
    at org.apache.spark.
</code>```

For debugging purpose, I have printed the recentProgress of query to know the current topic from where spark is reading. And I have checked the topic using console consumer and there is no data in Kafka and but query.status.isDataAvailable prints true. And even if recentProgress is empty, it is still waiting for data to process. Due to which it is infinitely waiting.

答:
I'm not sure why isDataAvailable gives true, but processAllAvailable gives you exactly the solution you're aiming at with if (query.status.isDataAvailable) block.

processAllAvailable Blocks until all available data in the source has been processed and committed to the sink.

That's your use case, isn't it?

Mind however that "This method is intended for testing." as "this method may block forever" (quoting the scaladoc of processAllAvailable).

You should use awaitTermination instead to keep the main thread blocked (so your streaming application is up and running) and stop the query (and its background thread) at your convenience from another "monitoring" thread.

awaitTermination() Waits for the termination of this query, either by query.stop() or by an exception. If the query has terminated with an exception, then the exception will be thrown.

Body:
I have to stop spark structured streaming query. So first, I check the status is there any data available in Kafka to process. if yes, processes it and then stop the query.

if (query.status.isDataAvailable) {
                    query.processAllAvailable()
                  }
query.stop()

After Jacek Laskowski's suggestion, I have modified the implementation.
I have list of streaming queries,

streamingQueryList.foreach{query =>
query.stop()
}

After every stopping of query, it throws following exception:

java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:998)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304)
    at scala.concurrent.impl.Promise$DefaultPromise.tryAwait(Promise.scala:202)
    at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:218)
    at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:153)
    at org.apache.spark.util.ThreadUtils$.awaitReady(ThreadUtils.scala:222)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:621)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2022)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply$mcV$sp(FileFormatWriter.scala:179)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:164)
    at org.apache.spark.sql.execution.streaming.FileStreamSink.addBatch(FileStreamSink.scala:123)
    at org.apache.spark.

For debugging purpose, I have printed the recentProgress of query to know the current topic from where spark is reading. And I have checked the topic using console consumer and there is no data in Kafka and but query.status.isDataAvailable prints true. And even if recentProgress is empty, it is still waiting for data to process. Due to which it is infinitely waiting.


问:
Get Keys with Multi Patterns in Redis
I want to get all keys start with 460  or 45412.

keys 460*  combine keys 45412*

I try the method in this Link: https://redis.io/commands/keys but Failed

答:
I finally Use Jedis to get all result by Set DataStructure

```<code> Set<String> FirstSet = js.keys("460*");
 Set<String> SecondSet = js.keys("45412*");
 SecondSet.addAll(FirstSet );
</code>```

The Second Set is what I want.

Title: Get Keys with Multi Patterns in Redis

Body:
I finally Use Jedis to get all result by Set DataStructure

 Set<String> FirstSet = js.keys("460*");
 Set<String> SecondSet = js.keys("45412*");
 SecondSet.addAll(FirstSet );

The Second Set is what I want.


问:
kivy language not handling enums?
I have a file with constants, like this:

```<code>from enum import Enum
class Ear(Enum):
    LEFT = 0
    RIGHT = 1
</code>```

Then I import it in a kv file like this:

```<code>#: import Ear vocelab.ark_const
</code>```

And finally use it to set an ObjectProperty named "ear":

```<code>Audiogram:
    id: audiogram
    ear: Ear.LEFT
</code>```

And then I get this error (well the traceback is very long, this is just a part of it):

```<code>kivy.lang.builder.BuilderException: Parser: File "C:\Users\Laci\Python\Projects\VoceLab\vocelab\vocelab.kv", line 224:
 ...
     222:                            Audiogram:
     223:                                id: audiogram
 >>  224:                                ear: Ear.LEFT
     225:                    TabbedPanelItem:
     226:                        id: tp_devices
 ...
 BuilderException: Parser: File "C:\Users\Laci\Python\Projects\VoceLab\vocelab\vocelab.kv", line 224:
 ...
     222:                            Audiogram:
     223:                                id: audiogram
 >>  224:                                ear: Ear.LEFT
     225:                    TabbedPanelItem:
     226:                        id: tp_devices
 ...
 AttributeError: 'module' object has no attribute 'LEFT'
</code>```

I think this may be a bug, or at least the error message if wrong. It says "AttributeError: 'module' object has no attribute 'LEFT'" but "Ear" is not a module. I'm not sure about this but maybe kivy tries to get the "LEFT" attribute of the ark_consts module, instead of the enum?

答:
You have imported the module, not the class

try this:

```<code>#: import Ear vocelab.ark_const.Ear
</code>```

the next of import in this is the name that you give to what you import, what you import is the last

Title: kivy language not handling enums?

Body:
I have a file with constants, like this:

from enum import Enum
class Ear(Enum):
    LEFT = 0
    RIGHT = 1

Then I import it in a kv file like this:

#: import Ear vocelab.ark_const

And finally use it to set an ObjectProperty named "ear":

Audiogram:
    id: audiogram
    ear: Ear.LEFT

And then I get this error (well the traceback is very long, this is just a part of it):

kivy.lang.builder.BuilderException: Parser: File "C:\Users\Laci\Python\Projects\VoceLab\vocelab\vocelab.kv", line 224:
 ...
     222:                            Audiogram:
     223:                                id: audiogram
 >>  224:                                ear: Ear.LEFT
     225:                    TabbedPanelItem:
     226:                        id: tp_devices
 ...
 BuilderException: Parser: File "C:\Users\Laci\Python\Projects\VoceLab\vocelab\vocelab.kv", line 224:
 ...
     222:                            Audiogram:
     223:                                id: audiogram
 >>  224:                                ear: Ear.LEFT
     225:                    TabbedPanelItem:
     226:                        id: tp_devices
 ...
 AttributeError: 'module' object has no attribute 'LEFT'

I think this may be a bug, or at least the error message if wrong. It says "AttributeError: 'module' object has no attribute 'LEFT'" but "Ear" is not a module. I'm not sure about this but maybe kivy tries to get the "LEFT" attribute of the ark_consts module, instead of the enum?

Body:
You have imported the module, not the class

try this:

#: import Ear vocelab.ark_const.Ear

the next of import in this is the name that you give to what you import, what you import is the last


答:
In this function:

```<code>std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.insert({ 0, test(0, handler)});
    returnMap.insert({ 1, test(1, handler)});
    return returnMap;
}
</code>```

you create two temporary test classes. These go out of scope when CreateTests returns.

In main(),

```<code>auto ret = CreateTests(handler);
handler.Raise(0);
handler.Raise(1);
</code>```

func is called, and test::mId is accessed, but does not exist anymore, hence the corrupted values.

Title: invalidation of std::function objects

Body:
In this function:

std::map<int, test> CreateTests(EventCoordinator& handler)
{
    auto returnMap = std::map<int, test>();
    returnMap.insert({ 0, test(0, handler)});
    returnMap.insert({ 1, test(1, handler)});
    return returnMap;
}

you create two temporary test classes. These go out of scope when CreateTests returns.

In main(),

auto ret = CreateTests(handler);
handler.Raise(0);
handler.Raise(1);

func is called, and test::mId is accessed, but does not exist anymore, hence the corrupted values.


问:
How to select identical rows from a pandas dataframe along with null
I'm new to pandas and I'm having problem with row selections from dataframe.

Following is my DataFrame :

```<code> Index Column1 Column2 Column3       Column4  Column5
   0   1234    500     NEWYORK       NY       NaN
   1   5678    700     AUSTIN        TX       5678956010
   2   1234    300     NEWYORKCITY   NY       NaN
   3   8910    235     RICHMOND      FL       8484883666
   4   8910    250     AUSTIN        TX       8484883666
   5   5324    150     AUSTIN        TX       NaN
</code>```

1.) I want to select rows that are having same values in Column5. So the output dataframe should contain rows with index 0,2,3 and 4. Note that two rows with NaN in Column 5 should be selected only if their Column1 value is same(example. rows with index 0 and 2).

Can any one help me with a step-by-step procedure for this custom selection. Thanks in advance...

答:
I think you need 2 sets of conditions - for NaNs in Column5 and for non NaNs and last chain them by | (or):

```<code>m1 = df['Column1'].duplicated(keep=False) & df['Column5'].isnull()
m2 = df['Column5'].duplicated(keep=False) & df['Column5'].notnull()

df = df[m1 | m2]
print (df)
   Index  Column1  Column2      Column3 Column4       Column5
0      0     1234      500      NEWYORK      NY           NaN
2      2     1234      300  NEWYORKCITY      NY           NaN
3      3     8910      235     RICHMOND      FL  8.484884e+09
4      4     8910      250       AUSTIN      TX  8.484884e+09
</code>```

Detail:

```<code>print (m1)
0     True
1    False
2     True
3    False
4    False
5    False
dtype: bool

print (m2)
0    False
1    False
2    False
3     True
4     True
5    False
Name: Column5, dtype: bool
</code>```

Body:
I'm new to pandas and I'm having problem with row selections from dataframe.

Following is my DataFrame :

 Index Column1 Column2 Column3       Column4  Column5
   0   1234    500     NEWYORK       NY       NaN
   1   5678    700     AUSTIN        TX       5678956010
   2   1234    300     NEWYORKCITY   NY       NaN
   3   8910    235     RICHMOND      FL       8484883666
   4   8910    250     AUSTIN        TX       8484883666
   5   5324    150     AUSTIN        TX       NaN

1.) I want to select rows that are having same values in Column5. So the output dataframe should contain rows with index 0,2,3 and 4. Note that two rows with NaN in Column 5 should be selected only if their Column1 value is same(example. rows with index 0 and 2).

Can any one help me with a step-by-step procedure for this custom selection. Thanks in advance...

Body:
I think you need 2 sets of conditions - for NaNs in Column5 and for non NaNs and last chain them by | (or):

m1 = df['Column1'].duplicated(keep=False) & df['Column5'].isnull()
m2 = df['Column5'].duplicated(keep=False) & df['Column5'].notnull()

df = df[m1 | m2]
print (df)
   Index  Column1  Column2      Column3 Column4       Column5
0      0     1234      500      NEWYORK      NY           NaN
2      2     1234      300  NEWYORKCITY      NY           NaN
3      3     8910      235     RICHMOND      FL  8.484884e+09
4      4     8910      250       AUSTIN      TX  8.484884e+09

Detail:

print (m1)
0     True
1    False
2     True
3    False
4    False
5    False
dtype: bool

print (m2)
0    False
1    False
2    False
3     True
4     True
5    False
Name: Column5, dtype: bool


问:
Create toplist with unique users
I have a table with the fields id, user_id, condition1, condition2, condition3, score. And each user can have several rows in the table. What I want to do now is to create several toplists. It could be for example a toplist where condition1 = foo and I only want to count each user once but I want the complete best row from each user.

So SELECT user_id, MAX(score) AS s FROM table WHERE condition1 = foo ORDER BY s DESC LIMIT 50 don't work.

There are so many different toplists I want so creating a second table where I store the users best result isn't really an option. Because each user would probably have more then 100 different best results.

The two things that are important is that getting the top 50 i quick. But also getting which place a specific user is placed on (which is pretty easy by just checking how many unique users have a bigger score than the specific user).

Update: I tested both Thomas and Quassnoi ideas and Thomas idea took 11 seconds and Quassnoi took 4.5 seconds.

Then I figured out another way to do it which is:

```<code>SELECT (
    SELECT id
    FROM table AS ti
    WHERE ti.user_id = t.user_id
        AND condition1 = foo
    ORDER BY score DESC
    LIMIT 1
)
FROM table as t
WHERE condition1 = foo
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 50
</code>```

And then I just make another query where a pick out all rows WHERE id IN(all ids returned from the first query) and this way takes 0.4 seconds.

Is this a good way of doing it or am I just lucky in my testdata?

答:
```<code>Select T.Id, T.user_id, T.condition1, T.condition2, T.condition3, T.score
From Table As T
Where Exists    (
                Select 1
                From Table As T2
                Where T2.user_id = T.user_id
                    And T2.condition1 = 'foo'
                Having Max(T2.score) = T.score
                )
Limit 50
</code>```

Title: Create toplist with unique users

Body:
I have a table with the fields id, user_id, condition1, condition2, condition3, score. And each user can have several rows in the table. What I want to do now is to create several toplists. It could be for example a toplist where condition1 = foo and I only want to count each user once but I want the complete best row from each user.

So SELECT user_id, MAX(score) AS s FROM table WHERE condition1 = foo ORDER BY s DESC LIMIT 50 don't work.

There are so many different toplists I want so creating a second table where I store the users best result isn't really an option. Because each user would probably have more then 100 different best results.

The two things that are important is that getting the top 50 i quick. But also getting which place a specific user is placed on (which is pretty easy by just checking how many unique users have a bigger score than the specific user).

Update: I tested both Thomas and Quassnoi ideas and Thomas idea took 11 seconds and Quassnoi took 4.5 seconds.

Then I figured out another way to do it which is:

SELECT (
    SELECT id
    FROM table AS ti
    WHERE ti.user_id = t.user_id
        AND condition1 = foo
    ORDER BY score DESC
    LIMIT 1
)
FROM table as t
WHERE condition1 = foo
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 50

And then I just make another query where a pick out all rows WHERE id IN(all ids returned from the first query) and this way takes 0.4 seconds.

Is this a good way of doing it or am I just lucky in my testdata?


答: In Storyboard click on the textfield and then go to the attribute, there you will find the keyboard from the you can select the number pad or number and punctuation

Title: How to set "123" mode as default mode in iOS keyboard Swift 3

Body:
Code to set the keyboard's overall type:

self.Value.keyboardType = UIKeyboardTypeDefault

How can I set the default keyboard's mode from "ABC to "123" at launch? Or even only "123" mode.

Any ideas?


问:
Rails: Param problems with delete button
index.html:

```<code>  <% @partners.each do |j| %>
            <% if j.link == nil %>
                <div class="column_left"><%= j.name %></div>
            <% else %>
                <div class="column_left"><%= image_tag("#{j.link}") %></div>
            <% end %>
            <div class="column_right"><%= j.description %></div>
            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>
</code>```

controller:

```<code>    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end
</code>```

routes.rb:

```<code>  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]
</code>```

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

答:
Thanks for the help Gabbar, but now I found the solution on my own. Was a pretty stupid one.
I called

```<code>method: destroy
</code>```

but it must be:  method: delete
otherwise the wrong path is chosen.

Then the routes.rb need to be:  delete '/partner' => 'partner#delete'

Body:
index.html:

  <% @partners.each do |j| %>
            <% if j.link == nil %>

<%= j.name %>

            <% else %>

<%= image_tag("#{j.link}") %>

            <% end %>

<%= j.description %>

            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>

controller:

    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end

routes.rb:

  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

Body:
Thanks for the help Gabbar, but now I found the solution on my own. Was a pretty stupid one.
I called

method: destroy

but it must be:  method: delete
otherwise the wrong path is chosen.

Then the routes.rb need to be:  delete '/partner' => 'partner#delete'


问:
What could possibly cause JQuery's selector to break?
I am trying to get an element using JQuery's selector, but it does not find it even though the element actually exists. Moreover, I can actually find the element using getElementById.

For example:

$('#outputDiv') gives me a null value. But document.getElementById("outputDiv") returns me the Div I was trying to access.

Any idea?

答:
Are you using any other libraries that might overload $ ? I know that e.g. that Prototype does this.

You might want to try issuing a jQuery('#outputDiv') instead to see if it is actually jQuery that you are invoking.

OwnerDisplayName: Marcel Tjandraatmadja

LastEditorDisplayName: Marcel Tjandraatmadja

OwnerDisplayName: mookid


问:
Boost fresh documents with Lucene
Does Lucene provide a means to boost fresh documents?

For example suppose that the Lucene document includes a date field. Is it possible, without having the user to alter her query anyhow, to present the most recent documents with a higher score?

I do not want to resort to a coarse "sort by date" solution as it will completely cancel the scoring algorithm.

答:
Use Document.setBoost(float value) when putting documents into the index.

You can either constantly re-adjust the value on existing documents, OR have a float value that increments with date, so that you only need to apply it to the time that documents are inserted.

For example, start with a boost value of 0 for day 1 documents. Each day, increment the boost by 1. It's a float value, incrementing by 365 each year will last a long time.

You may have to experiment with the strength of the boost to get the effect you want.

Title: Boost fresh documents with Lucene


问:
ObjectInputStream block my socket
I want to make use of ObjectInputStream and ObjectOutputStream to send data over Socket. I looked on the internet, but even with several explanation, i'm unable to fix my problem.

Here is my contructor succession:

```<code>public class Server {
    //Entry point of the application
    public static void main(String[] args) {
        Integer port;
        if(args.length<=0)
            port=new Integer("3000"); // si pas d'argument : port 3000 par d�faut
        else
            port = new Integer(args[0]); // sinon il s'agit du num�ro de port pass� en argument

        ClientListener server = new ClientListener(port); // instance de la classe principale
    }
}

public ClientListener(Integer port) { // THIS IS THE MAIN THREAD
        try
        {
          server = new ServerSocket(port.intValue()); // ouverture d'un socket serveur sur port
          new IOCommande(this); // RUN IN ANOTHER THREAD
          while (true) // attente en boucle de connexion (bloquant sur ss.accept)
          {
            new ClientSocketStream(server.accept(),this); // un client se connecte, un nouveau thread client est lanc�
          }
        }
        catch (Exception e) {
            //server.close();
        }
    }

public ClientSocketStream(Socket incomingClient, ClientListener ref) { // THIS IS NOT A THREAD
        this.client = incomingClient;
        this.server = ref;

        //Ajout des IO et generation d'un UID
        try{
            out = new ClientOutputWriter(client.getOutputStream());
            in = new ClientInputReader(((MessageReader)this),client.getInputStream());

            // ajoute du client dans la liste
            id = server.addClient(this);
        }catch (IOException e){
            e.printStackTrace();
        }finally {// En cas de probl�me (que le client s'est d�connect�)
            try {
                server.removeClient(id);
                client.close();
            }catch(IOException e) {

            }
        }
    }

public ClientInputReader(MessageReader client, InputStream in) throws IOException { //THIS IS A THREAD
        this.client = client;
        try {
            this.in = new ObjectInputStream(in);
        }catch(Exception e){
            e.printStackTrace();
        }
        this.runtime = new Thread(this);
        this.runtime.start();
    }

public ClientOutputWriter(OutputStream out) throws IOException { //THIS IS NOT A THREAD
        this.out = new ObjectOutputStream(out);
    }
</code>```

Please suppose that the socket is fully working, so i'm able to connect using Telnet.

So i'm stuck when instanciating the ObjectInputStream, in the ClientInputReader class. The constructor appears to be blocking,and i'm unable to make a correct use of this.

Solution :

Instead of testing using telnet, try to create another runnable project. Don't forget to Declare the objectOutputStream before the ObjectInputStream and do something like the following :

```<code>public class TestClient {
    //Entry point of the application
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 3000);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            out.writeObject(new Message("test"));
            Message msg = (Message)in.readObject();
            socket.close();
        }catch(Exception e){}
    }
}
</code>```

答: Your client isn't constructing an ObjectOutputStream, so your ObjectInputStream constructor is blocking for reasons explained in the Javadoc.

Title: ObjectInputStream block my socket

Body:
I want to make use of ObjectInputStream and ObjectOutputStream to send data over Socket. I looked on the internet, but even with several explanation, i'm unable to fix my problem.

Here is my contructor succession:

public class Server {
    //Entry point of the application
    public static void main(String[] args) {
        Integer port;
        if(args.length<=0)
            port=new Integer("3000"); // si pas d'argument : port 3000 par d�faut
        else
            port = new Integer(args[0]); // sinon il s'agit du num�ro de port pass� en argument

        ClientListener server = new ClientListener(port); // instance de la classe principale
    }
}

public ClientListener(Integer port) { // THIS IS THE MAIN THREAD
        try
        {
          server = new ServerSocket(port.intValue()); // ouverture d'un socket serveur sur port
          new IOCommande(this); // RUN IN ANOTHER THREAD
          while (true) // attente en boucle de connexion (bloquant sur ss.accept)
          {
            new ClientSocketStream(server.accept(),this); // un client se connecte, un nouveau thread client est lanc�
          }
        }
        catch (Exception e) {
            //server.close();
        }
    }

public ClientSocketStream(Socket incomingClient, ClientListener ref) { // THIS IS NOT A THREAD
        this.client = incomingClient;
        this.server = ref;

        //Ajout des IO et generation d'un UID
        try{
            out = new ClientOutputWriter(client.getOutputStream());
            in = new ClientInputReader(((MessageReader)this),client.getInputStream());

            // ajoute du client dans la liste
            id = server.addClient(this);
        }catch (IOException e){
            e.printStackTrace();
        }finally {// En cas de probl�me (que le client s'est d�connect�)
            try {
                server.removeClient(id);
                client.close();
            }catch(IOException e) {

            }
        }
    }

public ClientInputReader(MessageReader client, InputStream in) throws IOException { //THIS IS A THREAD
        this.client = client;
        try {
            this.in = new ObjectInputStream(in);
        }catch(Exception e){
            e.printStackTrace();
        }
        this.runtime = new Thread(this);
        this.runtime.start();
    }

public ClientOutputWriter(OutputStream out) throws IOException { //THIS IS NOT A THREAD
        this.out = new ObjectOutputStream(out);
    }

Please suppose that the socket is fully working, so i'm able to connect using Telnet.

So i'm stuck when instanciating the ObjectInputStream, in the ClientInputReader class. The constructor appears to be blocking,and i'm unable to make a correct use of this.

Solution :

Instead of testing using telnet, try to create another runnable project. Don't forget to Declare the objectOutputStream before the ObjectInputStream and do something like the following :

public class TestClient {
    //Entry point of the application
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 3000);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            out.writeObject(new Message("test"));
            Message msg = (Message)in.readObject();
            socket.close();
        }catch(Exception e){}
    }
}


问:
Where can I download Azure SDK for Visual Studio 2010?
Has anyone recently tried to download Azure SDK for Visual Studio 2010? Going to the Azure site doesn't give the option any more; it only allows downloading SDK for VS2012 and VS2013.

Is VS2010 no longer supported?

答: Unfortunately, this is not working with Visual Studio 2010 Ultimate. The web platform installer is responding with a list of errors. </p>


问:
Does ImageProcessor ImageFactory Load System.Drawing.Image modify by reference argument
ImageProcessor ImageFactory supports Load method with argument System.Drawing.Image. But Save method does not support similar argument. Is there a way with ImageProcessor ImageFactory to Load a System.Drawing.Image, manipulate the image, e.g., Brightness, then Save the modified image to System.Drawing.Image?

答:
You can't use a reference to the original image since that is tightly bound to the input stream.

You can either.
1. Save to the output stream and use Image.FromStream to create a new image.
2. Use a binary formatter to perform a deep clone of the ImageFactory.Image property https://stackoverflow.com/a/43042865/427899