问:
this with static field JAVA
Lets say I have next situation:

```<code>private static int a;
private int b;
public void setMethod(int a){
   //Do something with static a and parameter a for example
   b = this.a + a;
}
</code>```

How to reference static a in this calculation? I tried this.a but I have Idea warning(because static member is accessed via reference which is wrong). Of course there is a way to rename parameter or static member but I don't want that if I am not forced.

答:
Just access it using the class name:

```<code>public class Foo {
    private static int a;
    private int b;
    public void setMethod(int a){
       //Do something with static a and parameter a for example
       b = Foo.a + a;
    }
}
</code>```

Don't forget to protect you method if you are calling it concurrently.

Title: this with static field JAVA

Body:
Lets say I have next situation:

private static int a;
private int b;
public void setMethod(int a){
   //Do something with static a and parameter a for example
   b = this.a + a;
}

How to reference static a in this calculation? I tried this.a but I have Idea warning(because static member is accessed via reference which is wrong). Of course there is a way to rename parameter or static member but I don't want that if I am not forced.

Body:
Just access it using the class name:

public class Foo {
    private static int a;
    private int b;
    public void setMethod(int a){
       //Do something with static a and parameter a for example
       b = Foo.a + a;
    }
}

Don't forget to protect you method if you are calling it concurrently.


来源: stackexchange

问:
mysql trigger to calculate a duration based on starttime and endtime
I want to make a trigger to calculate an entry duration in hours.

I have the following code, but it's incorrect and i don't know why.

```<code>create trigger Calculate_Duration
before insert or update on Tbl_Eventos

for each row
declare
begin
    :new.duration := :new.endtime - :new.starttime
END;
</code>```

and my table is like this:

答:
let's try this,

it will work

```<code>CREATE TRIGGER Calculate_Duration BEFORE INSERT OR UPDATE ON Tbl_Eventos FOR EACH ROW SET NEW.duration = TIMEDIFF(NEW.endtime, NEW.starttime);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make a trigger to calculate an entry duration in hours.

I have the following code, but it's incorrect and i don't know why.

create trigger Calculate_Duration
before insert or update on Tbl_Eventos

for each row
declare
begin
    :new.duration := :new.endtime - :new.starttime
END;

and my table is like this:

Body:
let's try this,

it will work

CREATE TRIGGER Calculate_Duration BEFORE INSERT OR UPDATE ON Tbl_Eventos FOR EACH ROW SET NEW.duration = TIMEDIFF(NEW.endtime, NEW.starttime);


问:
Superfluous buffers/inverters in synthesised netlist
This is another follow-up question to Combinatorial synthesis: Better technology mapping results.

This is my Yosys TCL control script:

```<code>yosys -import
set libfile osu018_stdcells.lib
read_liberty -lib  $libfile
read_verilog test.v
hierarchy;
procs; opt
memory; opt
fsm -norecode; opt -full
techmap; opt -full
dfflibmap -liberty $libfile
abc -liberty $libfile \
    -script {+strash;ifraig;scorr;dc2;dretime;strash;&get,-n;&dch,-f;&nf,{D};&put}
clean
write_verilog test_synth.v
</code>```

The osu018_stdcells.lib file used is part of the Qflow version 1.1 package.

This is the test.v file:

```<code>module test (
    input rx_clk,
    input rxena,
    input rstn,
    input [2:0] d,
    output reg [2:0] q
  );
  wire rx_rstn = rstn & rxena;
  always @ (negedge rx_clk or negedge rx_rstn) begin
    if (!rx_rstn) begin
      q <= 0;
    end else begin
      q <= d;
    end
  end
endmodule
</code>```

Yosys (version 0.5+ (git sha1 f13e387, gcc 5.3.1-8ubuntu2 -O2 -fstack-protector-strong -fPIC -Os)) produces the following test_synth.v output netlist:

```<code>/* Generated by Yosys 0.5+ (git sha1 f13e387, gcc 5.3.1-8ubuntu2 -O2 -fstack-protector-strong -fPIC -Os) */

(* src = "test.v:1" *)
module test(rx_clk, rxena, rstn, d, q);
  wire _0_;
  wire _1_;
  wire _2_;
  (* src = "test.v:5" *)
  input [2:0] d;
  (* src = "test.v:6" *)
  output [2:0] q;
  (* src = "test.v:4" *)
  input rstn;
  (* src = "test.v:2" *)
  input rx_clk;
  (* src = "test.v:8" *)
  wire rx_rstn;
  (* src = "test.v:3" *)
  input rxena;
  INVX1 _3_ (
    .A(rx_clk),
    .Y(_0_)
  );
  AND2X1 _4_ (
    .A(rstn),
    .B(rxena),
    .Y(rx_rstn)
  );
  INVX1 _5_ (
    .A(rx_clk),
    .Y(_1_)
  );
  INVX1 _6_ (
    .A(rx_clk),
    .Y(_2_)
  );
  DFFSR _7_ (
    .CLK(_1_),
    .D(d[0]),
    .Q(q[0]),
    .R(rx_rstn),
    .S(1'b1)
  );
  DFFSR _8_ (
    .CLK(_2_),
    .D(d[1]),
    .Q(q[1]),
    .R(rx_rstn),
    .S(1'b1)
  );
  DFFSR _9_ (
    .CLK(_0_),
    .D(d[2]),
    .Q(q[2]),
    .R(rx_rstn),
    .S(1'b1)
  );
endmodule
</code>```

Obviously, there are 3 instances of the INVX1 cell, one for each of the three flip-flops in this design.  I would have expected only one of these inverters and its driven net shared between the flip-flop CLK inputs.

In another design (with about 30 registers that are triggered off the falling clock edge), I have seen just one inverter but its output goes through one buffer per flip-flop, which is also not ideal.

Is there a way to get Yosys to combine/share these resources among the registers?

答:
Is there a way to get Yosys to combine/share these resources among the registers?

Simply run opt_merge after running dfflibmap.

Body:
This is another follow-up question to Combinatorial synthesis: Better technology mapping results.

This is my Yosys TCL control script:

yosys -import
set libfile osu018_stdcells.lib
read_liberty -lib  $libfile
read_verilog test.v
hierarchy;
procs; opt
memory; opt
fsm -norecode; opt -full
techmap; opt -full
dfflibmap -liberty $libfile
abc -liberty $libfile \
    -script {+strash;ifraig;scorr;dc2;dretime;strash;&get,-n;&dch,-f;&nf,{D};&put}
clean
write_verilog test_synth.v

The osu018_stdcells.lib file used is part of the Qflow version 1.1 package.

This is the test.v file:

module test (
    input rx_clk,
    input rxena,
    input rstn,
    input [2:0] d,
    output reg [2:0] q
  );
  wire rx_rstn = rstn & rxena;
  always @ (negedge rx_clk or negedge rx_rstn) begin
    if (!rx_rstn) begin
      q <= 0;
    end else begin
      q <= d;
    end
  end
endmodule

Yosys (version 0.5+ (git sha1 f13e387, gcc 5.3.1-8ubuntu2 -O2 -fstack-protector-strong -fPIC -Os)) produces the following test_synth.v output netlist:

/* Generated by Yosys 0.5+ (git sha1 f13e387, gcc 5.3.1-8ubuntu2 -O2 -fstack-protector-strong -fPIC -Os) */

(* src = "test.v:1" *)
module test(rx_clk, rxena, rstn, d, q);
  wire _0_;
  wire _1_;
  wire _2_;
  (* src = "test.v:5" *)
  input [2:0] d;
  (* src = "test.v:6" *)
  output [2:0] q;
  (* src = "test.v:4" *)
  input rstn;
  (* src = "test.v:2" *)
  input rx_clk;
  (* src = "test.v:8" *)
  wire rx_rstn;
  (* src = "test.v:3" *)
  input rxena;
  INVX1 _3_ (
    .A(rx_clk),
    .Y(_0_)
  );
  AND2X1 _4_ (
    .A(rstn),
    .B(rxena),
    .Y(rx_rstn)
  );
  INVX1 _5_ (
    .A(rx_clk),
    .Y(_1_)
  );
  INVX1 _6_ (
    .A(rx_clk),
    .Y(_2_)
  );
  DFFSR _7_ (
    .CLK(_1_),
    .D(d[0]),
    .Q(q[0]),
    .R(rx_rstn),
    .S(1'b1)
  );
  DFFSR _8_ (
    .CLK(_2_),
    .D(d[1]),
    .Q(q[1]),
    .R(rx_rstn),
    .S(1'b1)
  );
  DFFSR _9_ (
    .CLK(_0_),
    .D(d[2]),
    .Q(q[2]),
    .R(rx_rstn),
    .S(1'b1)
  );
endmodule

Obviously, there are 3 instances of the INVX1 cell, one for each of the three flip-flops in this design.  I would have expected only one of these inverters and its driven net shared between the flip-flop CLK inputs.

In another design (with about 30 registers that are triggered off the falling clock edge), I have seen just one inverter but its output goes through one buffer per flip-flop, which is also not ideal.

Is there a way to get Yosys to combine/share these resources among the registers?


问:
Xamarin.ios on premise Build Failes on VSTS with return code 1
We are trying to create a build definition for xamarin.ios and we have a on premise build agent, we have syncfusion references included in the project, getting a error while the build is running.

答:
One way is that you can add nuget.config file to source control and specify it for NuGet restore step/task (Path to NuGet.config)

Another way is that, you can add Command Line step/task to add sources (Tool: [nuget.exe path (include nuget.exe to source control and map to build agent)], Arguments: sources add [name] -Source [feed address] -username [user name] -password [password] -StorePasswordInClearText


问:
Local install or remote install of a MySQL database?
Could someone explain the advantages and disadvantages of installing a MySQL database on a local machine compared to a remote machine (on a server)?

Thanks.
L.

答:
The main disadvantage of putting both application and database on the same machine is that they are then competing for the same resources (CPU, memory, disk). For many small applications, this is unlikely to be an issue. The main advantage is that you only need one machine and can balance resources between the application and database to suit. And connecting the two is slightly easier.

The main disadvantage of putting it on another server is that now you need another machine. But the main advantage is that you now have a lot more resources available and can configure MySQL to use most of the machine's resources. (The default settings are extremely conservative, suiting a shared install.) This also means the application cannot inadvertantly impact the database and vice-versa.

The relative importance of these differences is affected by the usage model. A local development environment can often get away with a local database. Usually you consider moving it to another box when multiple developers start needing to use it, but then, too, there's nothing wrong with every developer having their own, too. A production environment will probably want a separate server, but it depends on the application. A standalone, dedicated terminal will probably not need a seperate database. An internal website for fifteen employees might not, either. A public facing website for an ordering system almost certainly will.

ContentLicense: CC BY-SA 2.5


问:
Select Case VBA not working
I have the below code which I wish to hide columns based on the case. However it is not working. I suspect it may be to do with the groupings and layout of the sheet however have never come across an issue when using this code before.

```<code>Private Sub worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("C2")) Is Nothing Then
    On Error GoTo bm_Safe_Exit
    ActiveSheet.Unprotect Password:="Password"
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Columns("AD:JF").Hidden = False

    Select Case Range("C2").Value2
        Case 1
            Columns("AQ:DC,DR:GD,GS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 2
            Columns("BD:DC,EE:GD,HF:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 3
            Columns("BQ:DC,ER:GD,HS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 4
            Columns("CD:DC,FE:GD,IF:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 5
            Columns("CQ:DC,FR:GD,IS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 6
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
    End Select
End If

bm_Safe_Exit:
Application.EnableEvents = True
Application.ScreenUpdating = True
ActiveSheet.Protect Password:="password"

End Sub
</code>```

Picture included of spreadsheet layout

答:
When I tried

```<code>Columns("AQ:DC,DR:GD,GS:JE").Hidden = True
</code>```

I get an error (Type mismatch), so try to split the hide commands like this:

```<code>Columns("AQ:DC").Hidden = True
Columns("DR:GD").Hidden = True
Columns("GS:JE").Hidden = True
</code>```

Title: Select Case VBA not working

Body:
I have the below code which I wish to hide columns based on the case. However it is not working. I suspect it may be to do with the groupings and layout of the sheet however have never come across an issue when using this code before.

Private Sub worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("C2")) Is Nothing Then
    On Error GoTo bm_Safe_Exit
    ActiveSheet.Unprotect Password:="Password"
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Columns("AD:JF").Hidden = False

    Select Case Range("C2").Value2
        Case 1
            Columns("AQ:DC,DR:GD,GS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 2
            Columns("BD:DC,EE:GD,HF:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 3
            Columns("BQ:DC,ER:GD,HS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 4
            Columns("CD:DC,FE:GD,IF:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 5
            Columns("CQ:DC,FR:GD,IS:JE").Hidden = True
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
        Case 6
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=3
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=2
            ActiveSheet.Outline.ShowLevels RowLevels:=0, ColumnLevels:=1
    End Select
End If

bm_Safe_Exit:
Application.EnableEvents = True
Application.ScreenUpdating = True
ActiveSheet.Protect Password:="password"

End Sub

Picture included of spreadsheet layout

Body:
When I tried

Columns("AQ:DC,DR:GD,GS:JE").Hidden = True

I get an error (Type mismatch), so try to split the hide commands like this:

Columns("AQ:DC").Hidden = True
Columns("DR:GD").Hidden = True
Columns("GS:JE").Hidden = True


问:
What is the difference between gnustl_shared and gnustl_static in Android NDK library .a file?
I want to create android library using c++ stl.

my build tools are visual studio 2015, Visual GDB.

source code is

.cpp

```<code>#include <jni.h>
#include "AndroidProject2.h"
#include <vector>
void foo() { std::vector<int> aaa; aaa.push_back(1); }
</code>```

Android.mk

```<code># Generated by VisualGDB
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := AndroidProject2-shared
LOCAL_SRC_FILES := AndroidProject2.cpp
COMMON_SRC_FILES := $(LOCAL_SRC_FILES)
include $(BUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE    := AndroidProject2-static
LOCAL_SRC_FILES :=  $(COMMON_SRC_FILES)
include $(BUILD_STATIC_LIBRARY)
</code>```

Application.mk

```<code>APP_MODULES := AndroidProject2-static AndroidProject2-shared
APP_ABI := all
APP_STL := gnustl_static
NDK_TOOLCHAIN_VERSION :=4.9
</code>```

I succeed build, so, created lib files libAndroidProject2-static.a, libAndroidProject2-static.so

than, I try to change APP_STL option in Application.mk

```<code>APP_MODULES := AndroidProject2-static AndroidProject2-shared
APP_ABI := all
APP_STL := gnustl_shared
NDK_TOOLCHAIN_VERSION :=4.9
</code>```

surely, succeed build. so, created lib files libAndroidProject2-shared.a, libAndroidProject2-shared.so

than, I Compare it and previous build outputs.

I Found the difference about .so file. gnustl_static option's .so file is more bigger than gnustl_shared option's it.
but .a is same.

why?
I used nm, readelf but can't find difference.
what is diff???

答: The difference is that when you use static, the code of std is compiled into resulting .so file, while using shared, resulting so file requires to have std in separate so file

Body:
I want to create android library using c++ stl.

my build tools are visual studio 2015, Visual GDB.

source code is

.cpp

#include <jni.h>
#include "AndroidProject2.h"
#include <vector>
void foo() { std::vector<int> aaa; aaa.push_back(1); }

Android.mk

# Generated by VisualGDB
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := AndroidProject2-shared
LOCAL_SRC_FILES := AndroidProject2.cpp
COMMON_SRC_FILES := $(LOCAL_SRC_FILES)
include $(BUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE    := AndroidProject2-static
LOCAL_SRC_FILES :=  $(COMMON_SRC_FILES)
include $(BUILD_STATIC_LIBRARY)

Application.mk

APP_MODULES := AndroidProject2-static AndroidProject2-shared
APP_ABI := all
APP_STL := gnustl_static
NDK_TOOLCHAIN_VERSION :=4.9

I succeed build, so, created lib files libAndroidProject2-static.a, libAndroidProject2-static.so

than, I try to change APP_STL option in Application.mk

APP_MODULES := AndroidProject2-static AndroidProject2-shared
APP_ABI := all
APP_STL := gnustl_shared
NDK_TOOLCHAIN_VERSION :=4.9

surely, succeed build. so, created lib files libAndroidProject2-shared.a, libAndroidProject2-shared.so

than, I Compare it and previous build outputs.

I Found the difference about .so file. gnustl_static option's .so file is more bigger than gnustl_shared option's it.
but .a is same.

why?
I used nm, readelf but can't find difference.
what is diff???


问:
In Neo4j how to exclude results of one query from another
Say I have two queries

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
RETURN a

MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
RETURN a

I want to combine the two. Such that I have results from query2 that donot fit query1

So far I have tried the following

MATCH (a:User)-[:Likes]->(b:Object)
 MATCH (a:User)-[:HasVisited]->(c:Location)
 WHERE
    <condition on c>
    AND NOT <condition on b>
 RETURN a

but this approach does not exclude all results that i wanted excluded.

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
WITH collect(DISTINCT a) as exc
MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
    AND NOT a IN exc
RETURN a

This gives the right results but gets inefficient once query1 and query2 start becoming more complicated

I have also tried

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
WITH collect(DISTINCT a) as exc
MATCH (a:User)
    WHERE NOT a IN exc
    WITH a
MATCH MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
RETURN a

I had hoped reducing the number of nodes that a can match against upfront would improve performance but this approach doesnt seem to work any better.

Is there a standard/better way to exclude results matching one query from another?

答:
The problem with the first example is that it could still match some relation for (a:User)-[:Likes]->(b:Object) where 'b' does not meet the condition, while you want to completely exclude 'a' from the results when it is related to the selected 'b'.

To achieve this you could use an OPTIONAL MATCH clause:

```<code>MATCH (a:User)-[:HasVisited]->(c:Location)
WHERE <condition on c>
OPTIONAL MATCH (a)-[:Likes]->(b:Object)
WHERE <condition on b>
WITH a, b, c
WHERE b IS NULL
RETURN a
</code>```

Body:
The problem with the first example is that it could still match some relation for (a:User)-[:Likes]->(b:Object) where 'b' does not meet the condition, while you want to completely exclude 'a' from the results when it is related to the selected 'b'.

To achieve this you could use an OPTIONAL MATCH clause:

MATCH (a:User)-[:HasVisited]->(c:Location)
WHERE <condition on c>
OPTIONAL MATCH (a)-[:Likes]->(b:Object)
WHERE <condition on b>
WITH a, b, c
WHERE b IS NULL
RETURN a


问:
AggregationBuilders throws an error JsonGenerationException
I am using elasticsearch API (elasticsearch5.2.1.jar)to do the aggregation query as follows,

```<code>StatsAggregationBuilder statAggBuild = AggregationBuilders.stats("agg").field("ipAddress");
</code>```

This returns the follows exception

```<code>{ "error" : "JsonGenerationException[Can not write a field name, expecting a value]"}
</code>```

Am I doing anything wrong here ?

答:
It is not causing any issue while setting this Object in the request. It returns the response as expected

It looks the actual problem exist in the toString method, Which throws the error when we try to look what exist in the project

Body:
I am using elasticsearch API (elasticsearch5.2.1.jar)to do the aggregation query as follows,

StatsAggregationBuilder statAggBuild = AggregationBuilders.stats("agg").field("ipAddress");

This returns the follows exception

{ "error" : "JsonGenerationException[Can not write a field name, expecting a value]"}

Am I doing anything wrong here ?


问:
Upgrade to Visual Studio 2015 and now can't hit break points in debugging
I have a multi-project solution that I was building in Visual Studio 2013 and it was working fine but now that I have upgraded to Visual Studio 2015 I can no longer hit break points in debug mode for any project exect the main project selected as the Startup project in the Project Properties page. I used to be able to click on the other projects and just choose Debug -> Start New Instance. I am getting the error The breakpoint will not currently be hit. No symbols have been loaded for this document. I have tried a lot of things found on Google including:

Clean/Rebuild

Delete the OBJ and BIN folder form the projects

Did VS repair

Rebooted

Uninstalled/Reinstalled

Confirmed Define DEBUG constraint is enabled for Properties -> Build

Confirmed Optimize Code is unchecked for Properties -> Build

Confirmed Properties -> Build => Platform target was set to Any CPU for all projects

Tried running VS using "Run as Administrator"

Deleted all the files in /AppData/Local/Temp/Temporary ASP.Net Files/

Made sure Debug -> Attack to Process -> Select had "Automatically determine the type of code to debug" was selected

Made sure the Properties -> Web -> Debuggerts had ASP.Net checked (my properties has ASP.NEt and Enable Edit and Continue Checked, Natvie Code SQL Server and Silverlight unchecked)

Confirmed Target framework in Properties -> Application was set to the same version (4.6) as in the Web.Config/App.Config files.

So what am I missing here? Why can I no longer debug the other projects?

答:
In my case I just changed the setting of my running mode.

Before, I used "release" running mode:

And now, I'm using "debug" running mode:

ContentLicense: CC BY-SA 4.0


问:
set geolocation in data object after mounted vuejs
I'm relatively new to VueJS scene. Recently I'm trying to work on my side project which requires to get User's Geolocation Data as soon as the main component had mounted.

My code is here,

```<code>var app = new Vue({
  el: '#app',
  data: {
    position: null
  },
  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(function(position){
        this.position = position.coords;
      })
    }

  }
});
</code>```

I wanted to set position in data object to current geolocation after mounted but unfortunately it isn't working. Is there anything I'm missing?

答:
It's context issue, this inside navigator is bounded to wrong context, so when you write this.position, this is not set to Vue object.

To prevent that you can use arrow functions:

```<code>  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(position => {
        this.position = position.coords;
      })
    }
  }
</code>```

or declate the variable before navigator object that would hold correct context

```<code>  mounted: function() {
    if(navigator.geolocation) {
       var self = this;
       navigator.geolocation.getCurrentPosition(function(position){
        self.position = position.coords;
      })
    }
  }
</code>```

BTW just let you know - the position.coords would return Object that holds properties such as latitude, longitude etc, so If you want one of them you will need point that:

```<code>self.position = position.coords.latitude;
</code>```

Body:
I'm relatively new to VueJS scene. Recently I'm trying to work on my side project which requires to get User's Geolocation Data as soon as the main component had mounted.

My code is here,

var app = new Vue({
  el: '#app',
  data: {
    position: null
  },
  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(function(position){
        this.position = position.coords;
      })
    }

  }
});

I wanted to set position in data object to current geolocation after mounted but unfortunately it isn't working. Is there anything I'm missing?

Body:
It's context issue, this inside navigator is bounded to wrong context, so when you write this.position, this is not set to Vue object.

To prevent that you can use arrow functions:

  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(position => {
        this.position = position.coords;
      })
    }
  }

or declate the variable before navigator object that would hold correct context

  mounted: function() {
    if(navigator.geolocation) {
       var self = this;
       navigator.geolocation.getCurrentPosition(function(position){
        self.position = position.coords;
      })
    }
  }

BTW just let you know - the position.coords would return Object that holds properties such as latitude, longitude etc, so If you want one of them you will need point that:

self.position = position.coords.latitude;


问:
Convert CSV to XML when CSV contains both character and number data
From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

Thanks!

答:
While I'm almost always against regular expression, here's a solution using it.

Assume you have data as such:

```<code>"first name","last name","phone number"
"john,jane","doe","555-5555"
</code>```

Then, the following code:

```<code>string csv = GetCSV();  // will load your CSV, or the above data
foreach (string  line in csv.Split('\n'))
{
    Console.WriteLine("--- Begin record ---");
    foreach (Match m in Regex.Matches(line, "\".+?\""))
        Console.WriteLine(m.Value);
}
</code>```

will output this:

```<code>--- Begin record ---
"first name"
"last name"
"phone number"
 --- Begin record ---
"john,jane"
"doe"
"555-5555"
</code>```

But I would not recommend the Regex approach if you have like a 2 GB csv file.

So you can use that as your baseline for making up your XML records.

Body:
While I'm almost always against regular expression, here's a solution using it.

Assume you have data as such:

"first name","last name","phone number"
"john,jane","doe","555-5555"

Then, the following code:

string csv = GetCSV();  // will load your CSV, or the above data
foreach (string  line in csv.Split('\n'))
{
    Console.WriteLine("--- Begin record ---");
    foreach (Match m in Regex.Matches(line, "\".+?\""))
        Console.WriteLine(m.Value);
}

will output this:

--- Begin record ---
"first name"
"last name"
"phone number"
 --- Begin record ---
"john,jane"
"doe"
"555-5555"

But I would not recommend the Regex approach if you have like a 2 GB csv file.

So you can use that as your baseline for making up your XML records.


问:
Uncaught Error: Module build failed: Error: No PostCSS Config found in: \ng2-admin\node_modules\bootstrap-loader at Error (native)
I have clone ng2-admin directory from git hub few days back and run npm install after that i am able to run and see the UI, now I had been deleted node_modules folder, docs folder, and dist folder from ng2-admin now facing below error in browser console with scattered UI.

So how to fix below error,
`

```<code>Uncaught Error: Module build failed: Error: No PostCSS Config found in: D:\ng2-admin\node_modules\bootstrap-loader
    at Error (native)
    at D:\ng2-admin\node_modules\postcss-load-config\index.js:51:26
    at Error (native)
    at D:\ng2-admin\node_modules\postcss-load-config\index.js:51:26
    at Object../node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:56497:7)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:88168:15)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/bootstrap-loader/lib/bootstrap.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:52755:22)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/bootstrap-loader/loader.js (http://localhost:5000/assets/vendor.bundle.js:52782:18)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../src/vendor.browser.ts (http://localhost:5000/assets/vendor.bundle.js:90058:1)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object.5 (http://localhost:5000/assets/vendor.bundle.js:90087:18)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at webpackJsonpCallback (http://localhost:5000/assets/polyfills.bundle.js:25:23)
    at http://localhost:5000/assets/vendor.bundle.js:2:1
./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js @ util.js:164
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js @ no-op.js?6a4c:4
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/bootstrap-loader/lib/bootstrap.loader.js!./node_modules/bootstrap-loader/no-op.js @ no-op.js:1
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/bootstrap-loader/loader.js @ loader.js:1
__webpack_require__ @ bootstrap 7cfd64b…:52
./src/vendor.browser.ts @ vendor.browser.ts:24
__webpack_require__ @ bootstrap 7cfd64b…:52
5 @ src async:7
__webpack_require__ @ bootstrap 7cfd64b…:52
webpackJsonpCallback @ bootstrap 7cfd64b…:23
(anonymous) @ vendor.bundle.js:2
lang.js:134 Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
client:38 [WDS] Errors while compiling.
client:80 ./~/css-loader!./~/postcss-loader!./~/resolve-url-loader!./~/sass-loader?sourceMap!./~/bootstrap-loader/lib/bootstrap.styles.loader.js!./~/bootstrap-loader/no-op.js
Module build failed: Error: No PostCSS Config found in: D:\ng2-admin\node_modules\bootstrap-loader
    at Error (native)
    at D:\Client2\ng2-admin\node_modules\postcss-load-config\index.js:51:26
 @ ./~/style-loader!./~/css-loader!./~/postcss-loader!./~/resolve-url-loader!./~/sass-loader?sourceMap!./~/bootstrap-loader/lib/bootstrap.styles.loader.js!./~/bootstrap-loader/no-op.js 4:14-193
 @ ./~/bootstrap-loader/lib/bootstrap.loader.js!./~/bootstrap-loader`  /no-op.js`
 @ ./~/bootstrap-loader/loader.js
 @ ./src/vendor.browser.ts
 @ multi vendor

`
</code>```

答: Create node_modules/bootstrap-loader/postcss.config.js with the contents module.exports={};</p>

Body:
I have clone ng2-admin directory from git hub few days back and run npm install after that i am able to run and see the UI, now I had been deleted node_modules folder, docs folder, and dist folder from ng2-admin now facing below error in browser console with scattered UI.

So how to fix below error,
`

Uncaught Error: Module build failed: Error: No PostCSS Config found in: D:\ng2-admin\node_modules\bootstrap-loader
    at Error (native)
    at D:\ng2-admin\node_modules\postcss-load-config\index.js:51:26
    at Error (native)
    at D:\ng2-admin\node_modules\postcss-load-config\index.js:51:26
    at Object../node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:56497:7)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:88168:15)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/bootstrap-loader/lib/bootstrap.loader.js!./node_modules/bootstrap-loader/no-op.js (http://localhost:5000/assets/vendor.bundle.js:52755:22)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../node_modules/bootstrap-loader/loader.js (http://localhost:5000/assets/vendor.bundle.js:52782:18)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object../src/vendor.browser.ts (http://localhost:5000/assets/vendor.bundle.js:90058:1)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at Object.5 (http://localhost:5000/assets/vendor.bundle.js:90087:18)
    at __webpack_require__ (http://localhost:5000/assets/polyfills.bundle.js:54:30)
    at webpackJsonpCallback (http://localhost:5000/assets/polyfills.bundle.js:25:23)
    at http://localhost:5000/assets/vendor.bundle.js:2:1
./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js @ util.js:164
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/postcss-loader/index.js!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/index.js?sourceMap!./node_modules/bootstrap-loader/lib/bootstrap.styles.loader.js!./node_modules/bootstrap-loader/no-op.js @ no-op.js?6a4c:4
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/bootstrap-loader/lib/bootstrap.loader.js!./node_modules/bootstrap-loader/no-op.js @ no-op.js:1
__webpack_require__ @ bootstrap 7cfd64b…:52
./node_modules/bootstrap-loader/loader.js @ loader.js:1
__webpack_require__ @ bootstrap 7cfd64b…:52
./src/vendor.browser.ts @ vendor.browser.ts:24
__webpack_require__ @ bootstrap 7cfd64b…:52
5 @ src async:7
__webpack_require__ @ bootstrap 7cfd64b…:52
webpackJsonpCallback @ bootstrap 7cfd64b…:23
(anonymous) @ vendor.bundle.js:2
lang.js:134 Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
client:38 [WDS] Errors while compiling.
client:80 ./~/css-loader!./~/postcss-loader!./~/resolve-url-loader!./~/sass-loader?sourceMap!./~/bootstrap-loader/lib/bootstrap.styles.loader.js!./~/bootstrap-loader/no-op.js
Module build failed: Error: No PostCSS Config found in: D:\ng2-admin\node_modules\bootstrap-loader
    at Error (native)
    at D:\Client2\ng2-admin\node_modules\postcss-load-config\index.js:51:26
 @ ./~/style-loader!./~/css-loader!./~/postcss-loader!./~/resolve-url-loader!./~/sass-loader?sourceMap!./~/bootstrap-loader/lib/bootstrap.styles.loader.js!./~/bootstrap-loader/no-op.js 4:14-193
 @ ./~/bootstrap-loader/lib/bootstrap.loader.js!./~/bootstrap-loader`  /no-op.js`
 @ ./~/bootstrap-loader/loader.js
 @ ./src/vendor.browser.ts
 @ multi vendor

`


问:
node.js request post retrieve last id from db.json
After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck

I have in my db.json a "table" positions with an id automatically generated

my request is

```<code>request({
    url: url + '/api/positions,
    method: 'POST',
    form: transaction
}, ????);
</code>```

I want in my callback retrieve position.id (as I have to use it in another part of code).

Thanks a lot

Olivier

答:
Maybe some thing like that.</p>

```<code>...
var router = jsonServer.router('db.json');
...

// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];
</code>```

Body:
After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck

I have in my db.json a "table" positions with an id automatically generated

my request is

request({
    url: url + '/api/positions,
    method: 'POST',
    form: transaction
}, ????);

I want in my callback retrieve position.id (as I have to use it in another part of code).

Thanks a lot

Olivier

Body:
Maybe some thing like that.

...
var router = jsonServer.router('db.json');
...

// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];


问:
How to implement scss in react
I am trying to implement SCSS in my project. I have ran the npm command to install the loader "npm install sass-loader node-sass --save-dev". I have created a scss file. but the problem is it is not working. i tried multiple configurations to make it runable but no luck. below are my webpack configuration. please advice,</p>

```<code>rules: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            options: {
                cacheDirectory: true
            }
        }]
</code>```

答:
Did you configure your loaders correctly? Cant at least see any css/scss loaders in your provided code? https://github.com/webpack-contrib/sass-loader

UPDATE::

Add ExtractTextPlugin into your config. What this does is, it moves all the require("style.css")s in entry chunks into a separate single CSS file. So your styles are no longer inlined into the JS bundle, but separate in a CSS bundle file (styles.css) https://github.com/webpack-contrib/extract-text-webpack-plugin

Include the following into your webpack.config file.

```<code>// webpack.config.js
import ExtractTextPlugin from 'extract-text-webpack-plugin'

 {
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract({
      fallbackLoader: 'style',
      loader: [
        'css',
        'postcss',
        {
          loader: 'sass',
          query: {
            sourceMap: false,
          }
        }
      ],
    })
  }
</code>```

and import your .scss files ::

```<code>import 'scss/myfile.scss'
</code>```

Title: How to implement scss in react

Body:
I am trying to implement SCSS in my project. I have ran the npm command to install the loader "npm install sass-loader node-sass --save-dev". I have created a scss file. but the problem is it is not working. i tried multiple configurations to make it runable but no luck. below are my webpack configuration. please advice,

rules: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            options: {
                cacheDirectory: true
            }
        }]

Body:
Did you configure your loaders correctly? Cant at least see any css/scss loaders in your provided code? https://github.com/webpack-contrib/sass-loader

UPDATE::

Add ExtractTextPlugin into your config. What this does is, it moves all the require("style.css")s in entry chunks into a separate single CSS file. So your styles are no longer inlined into the JS bundle, but separate in a CSS bundle file (styles.css) https://github.com/webpack-contrib/extract-text-webpack-plugin

Include the following into your webpack.config file.

// webpack.config.js
import ExtractTextPlugin from 'extract-text-webpack-plugin'

 {
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract({
      fallbackLoader: 'style',
      loader: [
        'css',
        'postcss',
        {
          loader: 'sass',
          query: {
            sourceMap: false,
          }
        }
      ],
    })
  }

and import your .scss files ::

import 'scss/myfile.scss'


问:
Implementation How to use expand in snakemake when some particular combinations of wildcards are not desired?
I tried to implement How to use expand in snakemake when some particular combinations of wildcards are not desired?

The goal is to only process crossed combinations between SUPERGROUPS:

```<code>from itertools import product

DOMAINS=["Metallophos"]
SUPERGROUPS=["2supergroups","5supergroups"]
SUPERGROUPS_INVERSED=["5supergroups","2supergroups"]
CUTOFFS=["0"]

def filter_combinator(combinator, blacklist):
    def filtered_combinator(*args, **kwargs):
        for wc_comb in combinator(*args, **kwargs):
            # Use frozenset instead of tuple
            # in order to accomodate
            # unpredictable wildcard order
            if frozenset(wc_comb) not in blacklist:
                yield wc_comb
    return filtered_combinator

# "2supergroups/5supergroups" and "5supergroups/2supergroups" are undesired
forbidden = {
    frozenset({("supergroup", "2supergroups"), ("supergroup_other", "2supergroups")}),
    frozenset({("supergroup", "5supergroups"), ("supergroup_other", "5supergroups")})}

filtered_product = filter_combinator(product, forbidden)

rule target :
    input:
        expand(expand("results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics", filtered_product, supergroup=SUPERGROUPS, supergroup_other = SUPERGROUPS_INVERSED), cutoff=CUTOFFS, domain = DOMAINS)

rule tree_measures:
    input:
        tree="results/{domain}/{supergroup}/RAxML_bipartitionsBranchLabels.bbhlist.txt.{domain}.fa.aligned.rp.me-25.id.phylip.supergroups.for.notung",
        list="results/{domain}/{supergroup}/hmmer_search_bbh_1/bbhlist.txt.{domain}.fa.OGs.tbl.txt.0.list.txt.nh.OGs.txt",
        mapping1="results/{domain}/{supergroup_other}/{supergroup}/OGSmapping.txt.list",
        categories="results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.categories",
        mapping2="results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.list",
        supergroups="results/{domain}/{supergroup}/hmmer_search_2/{domain}.fa.OGs.tbl.txt.{cutoff}.supergroups.csv"
    output:
        "results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{cutoff}.statistics"
    shell:
        "~/tools/Python-2.7.11/python scripts/tree_measures.py {input.tree} {input.list} {input.mapping1} {input.categories} {input.mapping2} {input.supergroups} {wildcards.cutoff} results/{wildcards.domain}/{wildcards.supergroup}/{wildcards.supergroup_other}/"
</code>```

But I still get an error message:

Missing input files for rule tree_measures:
results/Metallophos/5supergroups/5supergroups/OGSmapping.txt.list
results/Metallophos/5supergroups/5supergroups/OGSmapping.txt.categories
```

What am I missing?

答:
I seems that you need to perform the expand in 2 steps, as follows:

```<code>rule target :
    input:
        expand(expand("results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics", filtered_product, supergroup=SUPERGROUPS, supergroup_other = SUPERGROUPS_INVERSED), cutoff=CUTOFFS, domain = DOMAINS)
</code>```

The inner expand uses the filtered_product trick, and the outer is a normal one.

Another approach is to use itertools.permutations for the inner list:

```<code>from itertools import permutations

DOMAINS=["Metallophos"]
SUPERGROUPS=["2supergroups","5supergroups"]
CUTOFFS=["0"]

rule target :
    input:
        expand(
            ["results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics".format(supergroup=sgrp1, supergroup_other=sgrp2)
                for (sgrp1, sgrp2) in permutations(SUPERGROUPS)],
            cutoff=CUTOFFS, domain = DOMAINS)
</code>```

Yet another possibility is to use zip:

```<code>rule target :
    input:
        expand(
            ["results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics".format(supergroup=sgrp1, supergroup_other=sgrp2)
                for (sgrp1, sgrp2) in zip(SUPERGROUPS, SUPERGROUPS_INVERSED)],
            cutoff=CUTOFFS, domain = DOMAINS)
</code>```

Body:
I tried to implement How to use expand in snakemake when some particular combinations of wildcards are not desired?

The goal is to only process crossed combinations between SUPERGROUPS:

from itertools import product

DOMAINS=["Metallophos"]
SUPERGROUPS=["2supergroups","5supergroups"]
SUPERGROUPS_INVERSED=["5supergroups","2supergroups"]
CUTOFFS=["0"]

def filter_combinator(combinator, blacklist):
    def filtered_combinator(*args, **kwargs):
        for wc_comb in combinator(*args, **kwargs):
            # Use frozenset instead of tuple
            # in order to accomodate
            # unpredictable wildcard order
            if frozenset(wc_comb) not in blacklist:
                yield wc_comb
    return filtered_combinator

# "2supergroups/5supergroups" and "5supergroups/2supergroups" are undesired
forbidden = {
    frozenset({("supergroup", "2supergroups"), ("supergroup_other", "2supergroups")}),
    frozenset({("supergroup", "5supergroups"), ("supergroup_other", "5supergroups")})}

filtered_product = filter_combinator(product, forbidden)

rule target :
    input:
        expand(expand("results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics", filtered_product, supergroup=SUPERGROUPS, supergroup_other = SUPERGROUPS_INVERSED), cutoff=CUTOFFS, domain = DOMAINS)

rule tree_measures:
    input:
        tree="results/{domain}/{supergroup}/RAxML_bipartitionsBranchLabels.bbhlist.txt.{domain}.fa.aligned.rp.me-25.id.phylip.supergroups.for.notung",
        list="results/{domain}/{supergroup}/hmmer_search_bbh_1/bbhlist.txt.{domain}.fa.OGs.tbl.txt.0.list.txt.nh.OGs.txt",
        mapping1="results/{domain}/{supergroup_other}/{supergroup}/OGSmapping.txt.list",
        categories="results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.categories",
        mapping2="results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.list",
        supergroups="results/{domain}/{supergroup}/hmmer_search_2/{domain}.fa.OGs.tbl.txt.{cutoff}.supergroups.csv"
    output:
        "results/{domain}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{cutoff}.statistics"
    shell:
        "~/tools/Python-2.7.11/python scripts/tree_measures.py {input.tree} {input.list} {input.mapping1} {input.categories} {input.mapping2} {input.supergroups} {wildcards.cutoff} results/{wildcards.domain}/{wildcards.supergroup}/{wildcards.supergroup_other}/"

But I still get an error message:

Missing input files for rule tree_measures:
results/Metallophos/5supergroups/5supergroups/OGSmapping.txt.list
results/Metallophos/5supergroups/5supergroups/OGSmapping.txt.categories

What am I missing?

Body:
I seems that you need to perform the expand in 2 steps, as follows:

rule target :
    input:
        expand(expand("results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics", filtered_product, supergroup=SUPERGROUPS, supergroup_other = SUPERGROUPS_INVERSED), cutoff=CUTOFFS, domain = DOMAINS)

The inner expand uses the filtered_product trick, and the outer is a normal one.

Another approach is to use itertools.permutations for the inner list:

from itertools import permutations

DOMAINS=["Metallophos"]
SUPERGROUPS=["2supergroups","5supergroups"]
CUTOFFS=["0"]

rule target :
    input:
        expand(
            ["results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics".format(supergroup=sgrp1, supergroup_other=sgrp2)
                for (sgrp1, sgrp2) in permutations(SUPERGROUPS)],
            cutoff=CUTOFFS, domain = DOMAINS)

Yet another possibility is to use zip:

rule target :
    input:
        expand(
            ["results/{{domain}}/{supergroup}/{supergroup_other}/OGSmapping.txt.list.{{cutoff}}.statistics".format(supergroup=sgrp1, supergroup_other=sgrp2)
                for (sgrp1, sgrp2) in zip(SUPERGROUPS, SUPERGROUPS_INVERSED)],
            cutoff=CUTOFFS, domain = DOMAINS)


问:
How to replace () with empty spacein notepad ++
How to replace empty braces ( ) with empty space in notepad++.

Thanks

答:
Ctrl+H

Find what: \(\)

Replace with: EMPTY

Replace all

You have to escape the parenthesis because they have special meaning in a regex


问:
Calculating the probability of the UUID to be Unique
I don't have the possibility of using Boost, hence I wrote a rather simple code to generate a UUID. However, I don't know how to calculate how unique a UUID generated by this code is! Can someone please explain how can I calculate the probability of the UUID, as generated by the following code, to be unique?</p>

```<code>string UUID;
uint8_t uuidLength = 32;
uint8_t asciiSets[][2]={
     {48, 10},     //Numbers 0-1
     {65, 26},     //Alphabet a-z
     {97, 26}      //Alphabet A-Z
};
UUID.reserve(uuidLength);

uint8_t counter;
srand(time(NULL));

for(counter = 0;counter<uuidLength;counter++)
{
    uint8_t set = rand()%3;//Choose one of the three sets of ascii ranges
    uint8_t start = asciiSets[set][0];
    uint8_t range = asciiSets[set][1];
    UUID[counter] = rand()%range+start;
}
</code>```

答:
The probabilities associated with each character is 1/30 for digits and 1/(3*26) for letters. That makes an entropy of 4.038 bits compared to 4.13 if the distribution was uniformed. This amounts to H=32*4.038=129.22 bits of entropy total. This is roughly equivalent to sampling for a uniform distribution with 2^129.22 possibilities

If you look for the probability of collisions, it will depend on the number of uuid you have generated obviously. You should have a look at https://en.wikipedia.org/wiki/Birthday_attack as suggested. As you will see, the probability of having a collision with n samples is given, you can apply this formula to 2^H with H given above.

The code to compute entropy:

```<code>import numpy as np
probs = [1/30.]*10 + [1/(3*26.)]*52
ent = -np.sum(probs*np.log(probs))
</code>```

Body:
I don't have the possibility of using Boost, hence I wrote a rather simple code to generate a UUID. However, I don't know how to calculate how unique a UUID generated by this code is! Can someone please explain how can I calculate the probability of the UUID, as generated by the following code, to be unique?

string UUID;
uint8_t uuidLength = 32;
uint8_t asciiSets[][2]={
     {48, 10},     //Numbers 0-1
     {65, 26},     //Alphabet a-z
     {97, 26}      //Alphabet A-Z
};
UUID.reserve(uuidLength);

uint8_t counter;
srand(time(NULL));

for(counter = 0;counter<uuidLength;counter++)
{
    uint8_t set = rand()%3;//Choose one of the three sets of ascii ranges
    uint8_t start = asciiSets[set][0];
    uint8_t range = asciiSets[set][1];
    UUID[counter] = rand()%range+start;
}

Body:
The probabilities associated with each character is 1/30 for digits and 1/(3*26) for letters. That makes an entropy of 4.038 bits compared to 4.13 if the distribution was uniformed. This amounts to H=32*4.038=129.22 bits of entropy total. This is roughly equivalent to sampling for a uniform distribution with 2^129.22 possibilities

If you look for the probability of collisions, it will depend on the number of uuid you have generated obviously. You should have a look at https://en.wikipedia.org/wiki/Birthday_attack as suggested. As you will see, the probability of having a collision with n samples is given, you can apply this formula to 2^H with H given above.

The code to compute entropy:

import numpy as np
probs = [1/30.]*10 + [1/(3*26.)]*52
ent = -np.sum(probs*np.log(probs))


问:
Android: Obtaining a class after a call to startService()
I am getting confused with all the different terminology when using Android: Activity, Service...

Right now I create a service:

```<code>startService(new Intent(this, RingerServer.class));
</code>```

And this service starts a thread:

```<code>public class RingerServer extends Service {

    public void onCreate() {
        super.onCreate();

        new Thread(new Ringer()).start();
    }

    public class Ringer implements Runnable { ... }

    public void refuseConnection() { ... }

}
</code>```

In this service, the RingerServer, I also have methods that I want to use. I would like to keep a reference to the RingerServer. I would basically like the Activity that created the service to be able to call refuseConnection(), but not make that method static.

startService returns a ComponentName, so I've been trying to cast it back to RingerServer but that doesn't seem to work. I see that it has getClass() and I've checked and getClassName() gives me the correct class. I haven't been able to use getClass() properly though.

Is there any way I can please keep a reference to the newly created RingerServer class? I am sure this is trivial, but I am stuck right now.

Thank you very much,

James

答:
You can use a ServiceConnection to get access to your service class.  See sample code here:

Android service running after pressing Home key

That said, managing things via the service's onStart handler is much simpler.

Body:
I am getting confused with all the different terminology when using Android: Activity, Service...

Right now I create a service:

startService(new Intent(this, RingerServer.class));

And this service starts a thread:

public class RingerServer extends Service {

    public void onCreate() {
        super.onCreate();

        new Thread(new Ringer()).start();
    }

    public class Ringer implements Runnable { ... }

    public void refuseConnection() { ... }

}

In this service, the RingerServer, I also have methods that I want to use. I would like to keep a reference to the RingerServer. I would basically like the Activity that created the service to be able to call refuseConnection(), but not make that method static.

startService returns a ComponentName, so I've been trying to cast it back to RingerServer but that doesn't seem to work. I see that it has getClass() and I've checked and getClassName() gives me the correct class. I haven't been able to use getClass() properly though.

Is there any way I can please keep a reference to the newly created RingerServer class? I am sure this is trivial, but I am stuck right now.

Thank you very much,

James


问:
Best way to represent sets of 3 values
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

```<code>position["time"]["x"]["y"]
</code>```

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

答:
You can use the Tuple class (See Tuple class on msdn)

```<code>Tuple.Create("time", "x", "y"); //creates a Tuple with 3 elements, aka triple
</code>```

Title: Best way to represent sets of 3 values

Body:
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

position["time"]["x"]["y"]

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

Body:
You can use the Tuple class (See Tuple class on msdn)

Tuple.Create("time", "x", "y"); //creates a Tuple with 3 elements, aka triple


问:
Laravel only retrieve Model Records if they belong to authenticated user
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}
</code>```

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

```<code>/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}
</code>```

And I've registered it in the AuthServiceProvider.php:

```<code>protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];
</code>```

I can still check the Order for another user.

答:
You have a few options. The best option in my option is the use Policies. The documentation for this can be found here:

https://laravel.com/docs/5.4/authorization

Alternatively do could do something like:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $user = request()->user();

    $order = $user->orders()->with('products')->find($id)->get();

    return view('order.show', compact('order'));
}
</code>```

With an orders relationship function on your user model.

Updated Reply

With the policy you gave, and with your resource route, you should be able to do:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show(CustomerOrder $order)
{
    $this->authorize('view', $order);

    return view('order.show', compact('order'));
}
</code>```

Body:
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}

And I've registered it in the AuthServiceProvider.php:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];

I can still check the Order for another user.

Body:
You have a few options. The best option in my option is the use Policies. The documentation for this can be found here:

https://laravel.com/docs/5.4/authorization

Alternatively do could do something like:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $user = request()->user();

    $order = $user->orders()->with('products')->find($id)->get();

    return view('order.show', compact('order'));
}

With an orders relationship function on your user model.

Updated Reply

With the policy you gave, and with your resource route, you should be able to do:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show(CustomerOrder $order)
{
    $this->authorize('view', $order);

    return view('order.show', compact('order'));
}


问:
How to wget a file from Nexus components?
I want to get a .war file from Nexus to put it on a Tomcat. But I don't succeed to wget a file from Nexus 3.2 ... Many questions resolved with 2.x but not for 3.2.

Or if you have another method to deploy a .war file from Nexus to Tomcat ... =)

File that I want to wget

答:
It was really simple. I just need to right click on the red circle like on the screenshot and copy link adress.

Screenshot


问:
replace multiple spaces by non breaking spaces
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

```<code>"This is     my text."
</code>```

Should be converted into

```<code>"This is     my text."
</code>```

答:
More than one space is >=2

PHP code demo

```<code><?php

echo preg_replace("!\s{2,}!", "  ", "Welcome to stack  overflow");
</code>```

Output:

```<code>Welcome to stack  overflow
</code>```

Body:
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

"This is     my text."

Should be converted into

"This is     my text."

Body:
More than one space is >=2

PHP code demo

<?php

echo preg_replace("!\s{2,}!", " &nbsp;", "Welcome to stack  overflow");

Output:

Welcome to stack &nbsp;overflow


问:
Setting an option selected in a combobox as a variable that changes as the option selected in the combobox does
I am trying to set the option selected in the dropdown of a combobox as a variable, however, the label I am using to represent the variable is currently just reading   .!combobox   . For example if I selected 'Customer 2' from the dropdown , the label would change to customer 2. I may need to use a button to do this but I am unsure how to make that work.

```<code>import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)

label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)
</code>```

To put it simply I want the option selected in the dropdown to be set as a variable that I can use later on in my code. I am quite new to coding so I might be missing something really obvious, any help would be appreciated :)

答:
You can use <<ComboboxSelected>> event with the get() method.

```<code>def update_label(event):
    label_ICustVar.configure(text=ICustomer.get())

ICustomer.bind("<<ComboboxSelected>>", update_label)
</code>```

update_label method will be fired each time you select an item from combobox dropdown.

Using StringVar() is not necessary with this approach, so you can remove ICus.

Body:
I am trying to set the option selected in the dropdown of a combobox as a variable, however, the label I am using to represent the variable is currently just reading   .!combobox   . For example if I selected 'Customer 2' from the dropdown , the label would change to customer 2. I may need to use a button to do this but I am unsure how to make that work.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)

label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)

To put it simply I want the option selected in the dropdown to be set as a variable that I can use later on in my code. I am quite new to coding so I might be missing something really obvious, any help would be appreciated :)

Body:
You can use <<ComboboxSelected>> event with the get() method.

def update_label(event):
    label_ICustVar.configure(text=ICustomer.get())

ICustomer.bind("<<ComboboxSelected>>", update_label)

update_label method will be fired each time you select an item from combobox dropdown.

Using StringVar() is not necessary with this approach, so you can remove ICus.


答:
The first thing to observe is that this is very unlikely to generate a UUID. A UUID contains 32 hexadecimal digits, and only 22 out of 62 characters that you generate are hexadecimal digits. That's about 1 in 3 per digit, so the chances are 1 in 250 trillion that you will actually generate a 32 digit hexadecimal number.

Just use Boost.

Title: Calculating the probability of the UUID to be Unique


问:
cosine similarity optimized implementation
I am trying to understand this optimized code to find cosine similarity between users matrix.

```<code>def fast_similarity(ratings,epsilon=1e-9):
    # epsilon -> small number for handling dived-by-zero errors
    sim = ratings.T.dot(ratings) + epsilon
    norms = np.array([np.sqrt(np.diagonal(sim))])
    return (sim / norms / norms.T)
</code>```

If ratings =

```<code>           items
     u  [
     s    [1,2,3]
     e    [4,5,6]
     r    [7,8,9]
     s  ]
</code>```

nomrs will be equal to = [1^2 + 5^2 + 9^2]

but why we are writing sim/norms/norms.T to calculate cosine similarity?
Any help is appreciated.

答:
Going through the code we have that:

And this means that, one the diagonal of the sim matrix we have the result of the multiplication of each column.

You can give it a try if you want using a simple matrix:

And you can easily check that this gram matrix (that's how this matrix product is named) has this property.

Now the code defines norms that is nothing but an array taking the diagonal of our gram matrix and apply a sqrt on each element of it.

This will give us an array containing the norm value for each column:

So basically the norms vector contains the norm value of each column of the result matrix.

Once we have all those data we can evaluate the cosine similarity between those users, so we know that cosine similarity is evaluated like:

Note that :

So we have that our similarity is going to be:

So we just have to substitute the terms with our code variable to get:

And this explain why you have this line of code:

```<code>return sim / norms / norms.T
</code>```

EDIT:
Since it seems that I was not clear, every time I am talking about matrix multiplication in this answer I am reffering to the DOT PRODUCT of two matrices.

This actually means that when it's written A*B we actually develop and
  solve as A.T * B

Body:
I am trying to understand this optimized code to find cosine similarity between users matrix.

def fast_similarity(ratings,epsilon=1e-9):
    # epsilon -> small number for handling dived-by-zero errors
    sim = ratings.T.dot(ratings) + epsilon
    norms = np.array([np.sqrt(np.diagonal(sim))])
    return (sim / norms / norms.T)

If ratings =

           items
     u  [
     s    [1,2,3]
     e    [4,5,6]
     r    [7,8,9]
     s  ]

nomrs will be equal to = [1^2 + 5^2 + 9^2]

but why we are writing sim/norms/norms.T to calculate cosine similarity?
Any help is appreciated.

Body:
Going through the code we have that:

And this means that, one the diagonal of the sim matrix we have the result of the multiplication of each column.

You can give it a try if you want using a simple matrix:

And you can easily check that this gram matrix (that's how this matrix product is named) has this property.

Now the code defines norms that is nothing but an array taking the diagonal of our gram matrix and apply a sqrt on each element of it.

This will give us an array containing the norm value for each column:

So basically the norms vector contains the norm value of each column of the result matrix.

Once we have all those data we can evaluate the cosine similarity between those users, so we know that cosine similarity is evaluated like:

Note that :

So we have that our similarity is going to be:

So we just have to substitute the terms with our code variable to get:

And this explain why you have this line of code:

return sim / norms / norms.T

EDIT:
Since it seems that I was not clear, every time I am talking about matrix multiplication in this answer I am reffering to the DOT PRODUCT of two matrices.

This actually means that when it's written A*B we actually develop and
  solve as A.T * B


问:
String search
What is the best way to search strings for something like forum? i seen horrible string search and typically get worse the more strings you use rather then better.

I also may implement a title search so if the way to search title that is better then a body of string i'd love to hear that too

答:
Not sure what you mean exactly by "Forum", but Regular Expressions may be a good place to start.

Too general?

Title: String search

OwnerDisplayName: TJB


问:
how to convert object to collection or list
I save a linq list()/collection result into HttpContext.Current.Cache as object, when I try to get object as collection it is null, although HttpContext.Current.Cache.Get("data") is not empty:

```<code>ICollection<ActionEntity> actions = HttpContext.Current.Cache.Get("data") as ICollection<ActionEntity>;
</code>```

答:
Try print the type of the data. Something like:

```<code>System.Diagnostics.Debug.WriteLine(HttpContext.Current.Cache.Get("data").GetType().ToString()).
</code>```

Then cast it with that data type.

You can see the result in windows Output -> Debug.

EDIT:

You can not cast an AnonymousType. What you can do is create an object with the same structure of the AnonymousType and use it instead.
For example, you have a

```<code>new {  List = new List<ActionEntity>() }
</code>```

You can create a ListOfList<T> class like this one:

```<code>class ListOfList<T> { public List<T> List { get; set; } }
</code>```

And instead of using an AnonymousType, use:

```<code>new ListOfList<ActionEntity> {  List = new List<ActionEntity>() }
</code>```

Then you can cast, using this:

```<code>ListOfList<ActionEntity> data = HttpContext.Current.Cache.Get("data") as ListOfList<ActionEntity>;
</code>```

Body:
I save a linq list()/collection result into HttpContext.Current.Cache as object, when I try to get object as collection it is null, although HttpContext.Current.Cache.Get("data") is not empty:

ICollection<ActionEntity> actions = HttpContext.Current.Cache.Get("data") as ICollection<ActionEntity>;

Body:
Try print the type of the data. Something like:

System.Diagnostics.Debug.WriteLine(HttpContext.Current.Cache.Get("data").GetType().ToString()).

Then cast it with that data type.

You can see the result in windows Output -> Debug.

EDIT:

You can not cast an AnonymousType. What you can do is create an object with the same structure of the AnonymousType and use it instead.
For example, you have a

new {  List = new List<ActionEntity>() }

You can create a ListOfList<T> class like this one:

class ListOfList<T> { public List<T> List { get; set; } }

And instead of using an AnonymousType, use:

new ListOfList<ActionEntity> {  List = new List<ActionEntity>() }

Then you can cast, using this:

ListOfList<ActionEntity> data = HttpContext.Current.Cache.Get("data") as ListOfList<ActionEntity>;


问:
how to add multiple selections to segment controllers?

In xcode you can implement a segment controller, but it just allows to select one at the time!
What is the easiest way to make something like this?

答:
use ATHMultiSelectionSegmentedControl from Github

This is the Cocoapod


问:
UICollection is very slow in showing Image with Swift 3
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

```<code>  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale
</code>```

and

```<code>extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}
</code>```

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?

答:
You can give an attempt to SDWebimage All async Thread operations maintained well.

That can provide following advantages

Asynchronously download

Auto Purging Image Cache if memory warnings happen for the app

Image URL caching

Image Caching

Avoid Duplicate Downloads

You can directly use a single method in cell as below

[cell.storeImg sd_setImageWithURL:[NSURL URLWithString:strURL] placeholderImage:kDefaultImageForDisplay];

In your code following line should creates problem as that operation can happen on main thread
 let data = NSData(contentsOf:url! as URL)

Body:
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale

and

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?


问:
how make notification scrollable as fb on css
<img src="https://i.stack.imgur.com/13Lkd.png" alt="enter image description here">   i want to make notifications (li) scrollable when i put the li of notification in one div class="notification-body" it doesn't give me the result i want as bellow on the picture. </p>

```<code><li ng-if="vm.logged">
      <div class="dropdown">
        <button class="btn-noti" id="dropdownNoti" ng-click="vm.showDropdown($event)">
          <span class="fa fa-bell-o"></span>
        </button>
        <ul class="dropdown-menu notification-menu" aria-labelledby="dropdownNoti">
          <div class="col-md-12 col-xs-12" style="border-bottom: #655771;border-bottom-style: double;">
            <h5 class="notification-title"><i class="fa fa-bell"></i> Notifications</h5>
            <a class="mark-all" ng-click="vm.markAllRead()">Mark all as read</a>
          </div>
          <div class="notification-body">
            <li ng-if="!vm.notifications.length"><a>You have no new notification yet.</a></li>
            <li class="notification-type"  ng-repeat="notification in vm.notifications" ng-style="{'background-color': notification.unread==false? 'white' : '#f5f5f5'}" style="border-bottom-style: ridge;">
              <a ui-sref="profile({id: post.user.id})">{{notification.description}}
                <h6><i class="fa fa-clock-o"></i> {{vm.timeOf(notification)}}</h6>
              </a>
              <a class="mark-as btn btn-default " ng-click="vm.markAsRead(notification)" data-toggle="popover" data-trigger="hover" data-content="as read" ng-class="{'add-white' : notification.unread==true }" ></a>
            </li>

          </div>
        </ul>
      </div>
    </li>
</code>```

答:
By setting Height and Width property of not-body style you can achive it.

Try doing it. I think it'll work as you want.

Body:
   i want to make notifications (li) scrollable when i put the li of notification in one div class="notification-body" it doesn't give me the result i want as bellow on the picture.

        <button class="btn-noti" id="dropdownNoti" ng-click="vm.showDropdown($event)">

        </button>

 Notifications

            Mark all as read

You have no new notification yet.

              {{notification.description}}

 {{vm.timeOf(notification)}}

Body:
By setting Height and Width property of not-body style you can achive it.

<div class="not-body" style="height:200px; width:100px; overflow:scroll;">

Try doing it. I think it'll work as you want.


问:
Connection to database (SQLSRV_Connect())
I have a database on a MSSQL Server. There are 2 users.
The first one is a local db user. The second one is a windows user. Both have the same permission.

If I try to connect the db with my local user, it works!

```<code>class db {

static $serverName = "SERVERNAME";
static $connectionInfo = array( "Database"=>"DBName", "UID"=>"local_user", "PWD"=>"password_local");
static $conn;

function connectToDB(){

    global $serverName,$connectionInfo,$conn;

    $conn = sqlsrv_connect(self::$serverName , self::$connectionInfo);

    if( $conn ) {
         //echo "Connection established.<br />";
    }else{
         echo "Connection to Database could not be established, please contact your admin!<br />";
         //die( print_r( sqlsrv_errors(), true));
    }
</code>```

...but when I try to connect the database with my windows user, I've got an error. I only changed the user name to DOMAIN\win_user and the pw to the windows pw.

Here is the error message:

```<code>message: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'DOMAIN\win_user'.
SQLSTATE: 28000
code: 18456
</code>```

答:
Maybe you don't mapped user to database.
Go to Security->User Account->Right click to user and then Property. Go to User Mapping, select DB and below click to "db_owner" role</p>

Body:
I have a database on a MSSQL Server. There are 2 users.
The first one is a local db user. The second one is a windows user. Both have the same permission.

If I try to connect the db with my local user, it works!

class db {

static $serverName = "SERVERNAME";
static $connectionInfo = array( "Database"=>"DBName", "UID"=>"local_user", "PWD"=>"password_local");
static $conn;

function connectToDB(){

    global $serverName,$connectionInfo,$conn;

    $conn = sqlsrv_connect(self::$serverName , self::$connectionInfo);

    if( $conn ) {
         //echo "Connection established.
";
    }else{
         echo "Connection to Database could not be established, please contact your admin!
";
         //die( print_r( sqlsrv_errors(), true));
    }

...but when I try to connect the database with my windows user, I've got an error. I only changed the user name to DOMAIN\win_user and the pw to the windows pw.

Here is the error message:

message: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'DOMAIN\win_user'.
SQLSTATE: 28000
code: 18456


问:
Why I'm getting trash on this pipe?
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}
</code>```

fd_server.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}
</code>```

fullduplex.h

```<code>#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255
</code>```

答:
These lines produce bad output:

```<code>buf[numread] = '0';
printf("Full Duplex Server : Read From the pipe : %s \n", buf);
</code>```

First, buf[numread] = '0'; Overwrites your null-terminator.

With this overwritten, printf(%s) doesn't know where to stop printing.

The null-terminator tells C where the string ends.

After you overwrote it, C no longer knows where the end of the string is, and prints your string "HAHAHA", but keeps printing garbage after that.

Title: Why I'm getting trash on this pipe?

Body:
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}

fd_server.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}

fullduplex.h

#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255

Body:
These lines produce bad output:

buf[numread] = '0';
printf("Full Duplex Server : Read From the pipe : %s \n", buf);

First, buf[numread] = '0'; Overwrites your null-terminator.

With this overwritten, printf(%s) doesn't know where to stop printing.

The null-terminator tells C where the string ends.

After you overwrote it, C no longer knows where the end of the string is, and prints your string "HAHAHA", but keeps printing garbage after that.


答:
I suggest defining an immutable type for this purpose and use a dictionary to store values since an object can be in one place at a specific time.

```<code>public class Position
{
    public Position(double x, double y)
    {
        X = x;
        Y = y;
    }

    public double X { get; }
    public double Y { get; }
}
</code>```

use it like this:

```<code>var data = new Dictionary<TimeSpan, Position>();

//add data in two different ways
data.Add(TimeSpan.FromMilliseconds(10), new Position(0.1, 1));
data[TimeSpan.FromMilliseconds(15)] = new Position(10, 15);

//accessing data
var pos = data[TimeSpan.FromMilliseconds(10)];

//check if data exist for specific time
if (data.ContainsKey(TimeSpan.FromMilliseconds(15)))
{
    //do what you want
}
</code>```

Title: Best way to represent sets of 3 values

Body:
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :

position["time"]["x"]["y"]

so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.

Body:
I suggest defining an immutable type for this purpose and use a dictionary to store values since an object can be in one place at a specific time.

public class Position
{
    public Position(double x, double y)
    {
        X = x;
        Y = y;
    }

    public double X { get; }
    public double Y { get; }
}

use it like this:

var data = new Dictionary<TimeSpan, Position>();

//add data in two different ways
data.Add(TimeSpan.FromMilliseconds(10), new Position(0.1, 1));
data[TimeSpan.FromMilliseconds(15)] = new Position(10, 15);

//accessing data
var pos = data[TimeSpan.FromMilliseconds(10)];

//check if data exist for specific time
if (data.ContainsKey(TimeSpan.FromMilliseconds(15)))
{
    //do what you want
}


问:
SELECTING with multiple WHERE conditions on same column
Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...

My table is a very simple linking setup for applying flags to a user ...

```<code>ID   contactid  flag        flag_type
-----------------------------------
118  99         Volunteer   1
119  99         Uploaded    2
120  100        Via Import  3
121  100        Volunteer   1
122  100        Uploaded    2
</code>```

etc... in this case you'll see both contact 99 and 100 are flagged as both "Volunteer" and "Uploaded"...

What I need to be able to do is return those contactid's ONLY that match multiple criteria entered via a search form...the contactid's have to match ALL chosen flags... in my head the SQL should look something like:

```<code>SELECT contactid
 WHERE flag = 'Volunteer'
   AND flag = 'Uploaded'...
</code>```

but... that returns nothing... What am I doing wrong here?

答:
Consider using INTERSECT like this:

```<code>SELECT contactid WHERE flag = 'Volunteer'
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'
</code>```

I think it it the most logistic solution.

Body:
Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...

My table is a very simple linking setup for applying flags to a user ...

ID   contactid  flag        flag_type
-----------------------------------
118  99         Volunteer   1
119  99         Uploaded    2
120  100        Via Import  3
121  100        Volunteer   1
122  100        Uploaded    2

etc... in this case you'll see both contact 99 and 100 are flagged as both "Volunteer" and "Uploaded"...

What I need to be able to do is return those contactid's ONLY that match multiple criteria entered via a search form...the contactid's have to match ALL chosen flags... in my head the SQL should look something like:

SELECT contactid
 WHERE flag = 'Volunteer'
   AND flag = 'Uploaded'...

but... that returns nothing... What am I doing wrong here?

Body:
Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer'
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.


问:
Combine F# async and maybe computation expression
Say i want to return an Option while in an async workflow:

let run =
    async {
        let! x = doAsyncThing
        let! y = doNextAsyncThing x
        match y with
        | None -> return None
        | Some z -> return Some <| f z
    }
```

<p>Ideally I would use the maybe computation expression from FSharpx at the same time as async to avoid doing the <code>match</code>. I could make a custom builder, but is there a way to generically combine two computation expressions? It might look something like this:</p>

```let run =
    async {
        let! x = doAsyncThing
        let! y = doNextAsyncThing x
        return! f y
    }
```

答:
```<code>type MaybeMonad() =
    member __.Bind(x, f) =
        match x with
        | Some v -> f v
        | None -> None
    member __.Return(x) =
        Some x

let maybe = MaybeMonad()

let run = async {
    let! x = doAsyncThing
    let! y = doNextAsyncThing x
    return maybe {
        let! y_val = y
        return f y_val
    }
}
</code>```

just use f# Computation expressions inside.

Body:
Say i want to return an Option while in an async workflow:

let run =
    async {
        let! x = doAsyncThing
        let! y = doNextAsyncThing x
        match y with
        | None -> return None
        | Some z -> return Some <| f z
    }

Ideally I would use the maybe computation expression from FSharpx at the same time as async to avoid doing the match. I could make a custom builder, but is there a way to generically combine two computation expressions? It might look something like this:

let run =
    async {
        let! x = doAsyncThing
        let! y = doNextAsyncThing x
        return! f y
    }

Body:
type MaybeMonad() =
    member __.Bind(x, f) =
        match x with
        | Some v -> f v
        | None -> None
    member __.Return(x) =
        Some x

let maybe = MaybeMonad()

let run = async {
    let! x = doAsyncThing
    let! y = doNextAsyncThing x
    return maybe {
        let! y_val = y
        return f y_val
    }
}

just use f# Computation expressions inside.