问:
how to send minicom to background?
I need to log some data from a serial device. So I would like to first call minicom with the & parameter:

```<code>minicom -D /dev/ttyXYZ -b 115200 -C logFile &
</code>```

But taking a look to ps aux shows, that minicom had become a terminated zombie process:

```<code>edeviser   8835  0.0  0.0  19696  2628 pts/0    T    15:29   0:00 minicom -D /dev/ttyXYZ -b 115200 -C logFile
</code>```

How to send minicom to background?

Further information:
I would like to send it to background because I'll need to trigger some actions after minicom has started to log the serial data to the logFile. Using cat /dev/ttyXYZ > logFile is no option, because I must specify the baudrate. Using a second terminal is also no option, because this work will be done by a bash script.

答:
Have you tried:

```<code>nohup minicom -D /dev/ttyXYZ -b 115200 -C logFile &
</code>```

I ran into the same issue when I was trying to convert movies with handbrake-cli.
nohup will background the task and push the output into a txt file called nohup.txt.

Title: how to send minicom to background?

Body:
I need to log some data from a serial device. So I would like to first call minicom with the & parameter:

minicom -D /dev/ttyXYZ -b 115200 -C logFile &

But taking a look to ps aux shows, that minicom had become a terminated zombie process:

edeviser   8835  0.0  0.0  19696  2628 pts/0    T    15:29   0:00 minicom -D /dev/ttyXYZ -b 115200 -C logFile

How to send minicom to background?

Further information:
I would like to send it to background because I'll need to trigger some actions after minicom has started to log the serial data to the logFile. Using cat /dev/ttyXYZ > logFile is no option, because I must specify the baudrate. Using a second terminal is also no option, because this work will be done by a bash script.

Body:
Have you tried:

nohup minicom -D /dev/ttyXYZ -b 115200 -C logFile &

I ran into the same issue when I was trying to convert movies with handbrake-cli.
nohup will background the task and push the output into a txt file called nohup.txt.


来源: stackexchange

问:
How to organize multiple flash projects sharing common lib as for classpaths
Let's say I have multiple projects organized as

```commonlib
superorg
   org1
     suborg11
     suborg12
   org2
     suborg21
```

How do you declare import and manage classpaths as for classes in commonlib package ?

答: Compile your "reused classes" to swc files and add them to your projects. If you are changing your classes often you could setup a Flex Library Project and add the whole library Project to your source in the Project settings. This will keep the files up to date. </p>

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have multiple projects organized as

commonlib
superorg
   org1
     suborg11
     suborg12
   org2
     suborg21

How do you declare import and manage classpaths as for classes in commonlib package ?


问:
KNX and KNXnet/IP implementation in Python
I am looking high and low for anything related to KNX implementation in Python, especially KNXnet/IP. So far I couldn't find anything. I know there are few projects written in Java but I thought I'd give it a shot asking here before I start porting code from other languages.

Also, does anyone know of any free documentation of the KNX standard, its data structures and  KNXnet/IP? The official documentation from the KNX association is ridiculously expensive, especially for something supposed to be an "open" standard.

thanks

答:
You might want to have a look a this (if by that time you are still looking for such a library) : https://github.com/leadrien/knxnet
This allows me to command KNX devices through an IP/KNX interface pretty well.

Alexandre

ContentLicense: CC BY-SA 3.0


问:
Android Studio desgn mode for fullscreen app
I'm using AS 2.3.3 with a full screen app. I know how to put the app into full screen at run time but the design view still shows the status bar, a title and the nav buttons. How can I remove those from the preview so it looks as it will be when deployed?</p>

答:
Open the Preview panel and click on Theme in Editor as shown in below screenshot.

After clicking on that you can see this dialog and you can choose your
  own theme for preview.


问:
Parse JSON data in swift
I am trying to parse my json data in swift 3.0. I am using Alamofire 4.0+
Here is my json

```<code>{
"token":

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

"user":
[{"user_id":13,"user_first_name":"Himanshu","user_last_name":"Srivastava","full_name":"Himanshu Srivastava"}]
}
</code>```

Here is my model class to hold these values

```<code>import Foundation
import ObjectMapper
class LoginResult:Mappable{
    var token:String?
    var expires:Double?
    var users:[[String:Any]]?
    required init?(map:Map){

    }

    func mapping(map:Map)->Void{
        self.token <- map["token"]
        self.expires <- map["expires"]
        self.users <- map["user"]
    }
}
</code>```

None of the solution available on internet worked for me. How can I parse this json and map to the model class?
Any help here?

答:
I was mistaken, the value for key user is indeed a regular array.

This is a solution without a third party mapper and with an extra User struct (by the way the value for key expires is an Int rather than Double).
Assuming the user data comes from a database which always sends all fields the user keys are forced unwrapped. If this is not the case use optional binding also for the user data:

```<code>struct User {
    let firstName : String
    let lastName : String
    let fullName : String
    let userID : Int
}

class LoginResult {
    let token : String
    let expires : Int
    var users = [User]()

    init(json : [String:Any]) {
        self.token = json["token"] as? String ?? ""
        self.expires = json["expires"] as? Int ?? 0
        if let users = json["user"] as? [[String:Any]] {
            self.users = users.map { User(firstName: $0["user_first_name"] as! String,
                                          lastName: $0["user_last_name"] as! String,
                                          fullName: $0["full_name"] as! String,
                                          userID: $0["user_id"] as! Int)
            }
        }
    }
}

let json = "{\"token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\":504428378111,\"user\":[{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"
let jsonData = json.data(using: .utf8)!
do {
    if let userData = try JSONSerialization.jsonObject(with: jsonData) as? [String:Any] {
        let loginResult = LoginResult(json: userData)
        print(loginResult.users[0])
        // do something with loginResult
    }
} catch {
    print(error)
}
</code>```

Title: Parse JSON data in swift

Body:
I am trying to parse my json data in swift 3.0. I am using Alamofire 4.0+
Here is my json

{
"token":

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

"user":
[{"user_id":13,"user_first_name":"Himanshu","user_last_name":"Srivastava","full_name":"Himanshu Srivastava"}]
}

Here is my model class to hold these values

import Foundation
import ObjectMapper
class LoginResult:Mappable{
    var token:String?
    var expires:Double?
    var users:[[String:Any]]?
    required init?(map:Map){

    }

    func mapping(map:Map)->Void{
        self.token <- map["token"]
        self.expires <- map["expires"]
        self.users <- map["user"]
    }
}

None of the solution available on internet worked for me. How can I parse this json and map to the model class?
Any help here?

Body:
I was mistaken, the value for key user is indeed a regular array.

This is a solution without a third party mapper and with an extra User struct (by the way the value for key expires is an Int rather than Double).
Assuming the user data comes from a database which always sends all fields the user keys are forced unwrapped. If this is not the case use optional binding also for the user data:

struct User {
    let firstName : String
    let lastName : String
    let fullName : String
    let userID : Int
}

class LoginResult {
    let token : String
    let expires : Int
    var users = [User]()

    init(json : [String:Any]) {
        self.token = json["token"] as? String ?? ""
        self.expires = json["expires"] as? Int ?? 0
        if let users = json["user"] as? [[String:Any]] {
            self.users = users.map { User(firstName: $0["user_first_name"] as! String,
                                          lastName: $0["user_last_name"] as! String,
                                          fullName: $0["full_name"] as! String,
                                          userID: $0["user_id"] as! Int)
            }
        }
    }
}

let json = "{\"token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\":504428378111,\"user\":[{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"
let jsonData = json.data(using: .utf8)!
do {
    if let userData = try JSONSerialization.jsonObject(with: jsonData) as? [String:Any] {
        let loginResult = LoginResult(json: userData)
        print(loginResult.users[0])
        // do something with loginResult
    }
} catch {
    print(error)
}


问:
How to compare 2 fields of same dataframe values and update result in another column
How to compare 2 columns of same dataframe and update result in another column, if its matches update as True else False.

df:

```<code>Col1    Col2    Result
1234569 1234569 TRUE
256132  453543  FALSE
DSDFDSF DSDFDSF TRUE
TRYTR   FGFH    FALSE
</code>```

答: This returns a boolean series:    df.col1==df.col2

ContentLicense: CC BY-SA 4.0

Body:
How to compare 2 columns of same dataframe and update result in another column, if its matches update as True else False.

df:

Col1    Col2    Result
1234569 1234569 TRUE
256132  453543  FALSE
DSDFDSF DSDFDSF TRUE
TRYTR   FGFH    FALSE


问:
Remove lines from text file if it starts with
I have large text files that contain invalid records.

I would like to remove all lines where the first field is blank. The file delimiter is a tilde , so essentially I want to remove all lines where the first character is ~

Can someone assist with the PowerShell code - I cannot seem to get it right.

答:
I think that you can also do it this way:</p>

```<code>sls -n '^~' file.txt | set-content filtered.txt
</code>```

Body:
I think that you can also do it this way:

sls -n '^~' file.txt | set-content filtered.txt


问:
How do I declare an array from a function globally?
I am trying to declare an array from the function globally so that my other functions can use it as well but I have no idea how to since I am using a csvtojson for converter which makes the whole thing very long and was wondering if this is the way to declare or no?

JS:

```<code>//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
 // create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv",function(err, result, callback){
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
}
});
</code>```

var array=[JSarray(function(err,doc)] This is how I declare the array.
My array is doc and so I can return callback but how should I get the array considering I have converter.fromFile("./NTA-SAM-Inventory-List-Security-
    Management-New_2017.csv" which is too long so do I omit it when declaring the array or am I doing it wrong ? Thanks.

Update
 Just wanted to clarify if I did it correctly.

```<code>var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-M
anagement-New_2017.csv",function(err, result, callback){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
    var myArray= doc;
    GLOBAL.GlobalMyArray = myArray;
});
});
</code>```

Is this correct following your answer in declaring it globally?

答:
global variables are not considered good programming practice.

Though you can create a global object module and reference this modules in all other modules in your project and play with exposed properties from it.

A simple example to achieve this is as following in node.js:

Create module GlobalArray. This module will expose a singleton object of the class it defines. The constructor of this class creates member variable. This class now expose the member variable using methods such as Add, Get. The instance of this class is exported from the module.

```<code>// File: GlobalArray.js

class GlobalArray {
    constructor(){
        this.array = [];
    }
    Add(item) {
        this.array.push(item);
    }
    Get(){
        return this.array;
    }
}

let globalArray = new GlobalArray();
module.exports = globalArray;
</code>```

Module for the class which add data to Global Array can be created as following:

```<code>// File: Add.js

const globalArray = require("./GlobalArray");

class Add {
    AddToGlobalArray(){
        globalArray.Add("1");
        globalArray.Add("2");
        globalArray.Add("3");
        globalArray.Add("4");
        globalArray.Add("5");
    }
}

module.exports = Add;
</code>```

Module for the class which print data from Global Array can be created as following:

```<code>// File: Print.js

const globalArray = require("./GlobalArray");

class Print {
    PrintGlobalArray(){
        let array = globalArray.Get();
        for(let i=0; i<array.length; i++){
            console.log(array[i] + "\n");
        }
    }
}

module.exports = Print;
</code>```

Both Add and Print modules used statement const globalArray = require("./GlobalArray") to reference the Global Array.

Now, we can use Add and Print modules by referencing them in index.js to add and print data respectively using the Global Array.

```<code>// File: index.js

const Add = require("./Add");
const Print = require("./Print");

// Creating object of Add module to add data to global array
let addObject = new Add();
addObject.AddToGlobalArray();

// Creating object of Print module to print data from global array
let printObject = new Print();
printObject.PrintGlobalArray();
</code>```

After executing index.js, it renders the following output:

```<code>>node index.js

1

2

3

4

5
</code>```

Body:
I am trying to declare an array from the function globally so that my other functions can use it as well but I have no idea how to since I am using a csvtojson for converter which makes the whole thing very long and was wondering if this is the way to declare or no?

JS:

//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
 // create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your
// csv file as well as a callback function
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv",function(err, result, callback){
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
}
});

var array=[JSarray(function(err,doc)] This is how I declare the array.
My array is doc and so I can return callback but how should I get the array considering I have converter.fromFile("./NTA-SAM-Inventory-List-Security-
    Management-New_2017.csv" which is too long so do I omit it when declaring the array or am I doing it wrong ? Thanks.

Update
 Just wanted to clarify if I did it correctly.

var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-M
anagement-New_2017.csv",function(err, result, callback){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
    if(err) throw err;
    console.log('ohhhhh');
    return callback(null, doc);
    var myArray= doc;
    GLOBAL.GlobalMyArray = myArray;
});
});

Is this correct following your answer in declaring it globally?

Body:
global variables are not considered good programming practice.

Though you can create a global object module and reference this modules in all other modules in your project and play with exposed properties from it.

A simple example to achieve this is as following in node.js:

Create module GlobalArray. This module will expose a singleton object of the class it defines. The constructor of this class creates member variable. This class now expose the member variable using methods such as Add, Get. The instance of this class is exported from the module.

// File: GlobalArray.js

class GlobalArray {
    constructor(){
        this.array = [];
    }
    Add(item) {
        this.array.push(item);
    }
    Get(){
        return this.array;
    }
}

let globalArray = new GlobalArray();
module.exports = globalArray;

Module for the class which add data to Global Array can be created as following:

// File: Add.js

const globalArray = require("./GlobalArray");

class Add {
    AddToGlobalArray(){
        globalArray.Add("1");
        globalArray.Add("2");
        globalArray.Add("3");
        globalArray.Add("4");
        globalArray.Add("5");
    }
}

module.exports = Add;

Module for the class which print data from Global Array can be created as following:

// File: Print.js

const globalArray = require("./GlobalArray");

class Print {
    PrintGlobalArray(){
        let array = globalArray.Get();
        for(let i=0; i<array.length; i++){
            console.log(array[i] + "\n");
        }
    }
}

module.exports = Print;

Both Add and Print modules used statement const globalArray = require("./GlobalArray") to reference the Global Array.

Now, we can use Add and Print modules by referencing them in index.js to add and print data respectively using the Global Array.

// File: index.js

const Add = require("./Add");
const Print = require("./Print");

// Creating object of Add module to add data to global array
let addObject = new Add();
addObject.AddToGlobalArray();

// Creating object of Print module to print data from global array
let printObject = new Print();
printObject.PrintGlobalArray();

After executing index.js, it renders the following output:

>node index.js

1

2

3

4

5


问:
TextBox TextMode = Time -> always show seconds
So i use asp Textboxes with TextMode='Time'  but it won´t show the seconds correctly, espacially when they are 00 and if there are some seconds you can´t edit them becouse they are grayed out.

How can i set the textbox for accepting hh:mm:ss ?

I tryed a few things wich didn´t worked, like:

```<code><asp:TextBox runat="server" ID="tbDuration" TextMode="Time"  format="HH:mm:ss" CssClass="elementsmall" />
</code>```

I wanted to use TextMode so i do not need to control if the input is a time format.

答:
You can use the step attribute:

```<code><asp:TextBox runat="server" ID="tbDuration" TextMode="Time" step="1"  format="HH:mm:ss" CssClass="elementsmall" />
</code>```

That's not an ASP.NET- but HTML 5 attribute.

Body:
So i use asp Textboxes with TextMode='Time'  but it won´t show the seconds correctly, espacially when they are 00 and if there are some seconds you can´t edit them becouse they are grayed out.

How can i set the textbox for accepting hh:mm:ss ?

I tryed a few things wich didn´t worked, like:

<asp:TextBox runat="server" ID="tbDuration" TextMode="Time"  format="HH:mm:ss" CssClass="elementsmall" />

I wanted to use TextMode so i do not need to control if the input is a time format.

Body:
You can use the step attribute:

<asp:TextBox runat="server" ID="tbDuration" TextMode="Time" step="1"  format="HH:mm:ss" CssClass="elementsmall" />

That's not an ASP.NET- but HTML 5 attribute.


问:
Python: Is there a way to sort a string using only selected characters in the string?
For example, is there a way to sort the following:

```<code>model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82
</code>```

using only the integer that comes after "model"? I have tried to capture only these integers using re.sub("_", "", re.sub(r'[^\w]', '', key[6:8])) to get the integers to sort, but I'm unable to use the sorted result to locate back the original strings since there will be some duplicates, like '1' belongs to both model_1_point/weights/read/_76__cf__76 and model_1_depth/depth_w/read/_79__cf__79 and it won't be possible to distinguish the two.

Is there an elegant way to do this?

EDIT: To clarify, the following strings are in a dictionary, and I'm wanting to sort such that 1 is the smallest and 13 is the largest.

答:
a version using regex:

```<code>rgx = re.compile('model_(?P<number>\d+)')
srtd = sorted(mods, key=lambda x: int(rgx.match(x).group('number')))
</code>```

the regular expression model_(?P<number>\d+) captures the numbers \d+ (greedy) after the string model_. in the key of sorted this is then converted to an int.

i assumed your input is in a list called mods of the form:

```<code>mods = [
    'model_1_depth/depth_w/read/_79__cf__79',
    'model_2_depth/depth_w/read/_73__cf__73',
    'model_3_depth/depth_w/read/_67__cf__67',
    'model_4_depth/depth_w/read/_61__cf__61',
    ...
    ]
</code>```

if it is just the string you presented you'd have somehow bring it into this form.

a little less verbose (no named group) the very same could be achieved like this:

```<code>rgx = re.compile('model_(\d+)')
srtd = sorted(mods, key=lambda x: int(rgx.match(x).group(1)))
</code>```

Body:
For example, is there a way to sort the following:

model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82

using only the integer that comes after "model"? I have tried to capture only these integers using re.sub("_", "", re.sub(r'[^\w]', '', key[6:8])) to get the integers to sort, but I'm unable to use the sorted result to locate back the original strings since there will be some duplicates, like '1' belongs to both model_1_point/weights/read/_76__cf__76 and model_1_depth/depth_w/read/_79__cf__79 and it won't be possible to distinguish the two.

Is there an elegant way to do this?

EDIT: To clarify, the following strings are in a dictionary, and I'm wanting to sort such that 1 is the smallest and 13 is the largest.

Body:
a version using regex:

rgx = re.compile('model_(?P<number>\d+)')
srtd = sorted(mods, key=lambda x: int(rgx.match(x).group('number')))

the regular expression model_(?P<number>\d+) captures the numbers \d+ (greedy) after the string model_. in the key of sorted this is then converted to an int.

i assumed your input is in a list called mods of the form:

mods = [
    'model_1_depth/depth_w/read/_79__cf__79',
    'model_2_depth/depth_w/read/_73__cf__73',
    'model_3_depth/depth_w/read/_67__cf__67',
    'model_4_depth/depth_w/read/_61__cf__61',
    ...
    ]

if it is just the string you presented you'd have somehow bring it into this form.

a little less verbose (no named group) the very same could be achieved like this:

rgx = re.compile('model_(\d+)')
srtd = sorted(mods, key=lambda x: int(rgx.match(x).group(1)))


问:
How to activate a specific Anaconda environment from PHP
I'm using PHP to run python scripts using the exec() function.

After installing Anaconda and making it the default Python install by placing it first in myPATH variable, I was able to import all the modules I needed like Scikit Learn, Numpy etc, and still run the script from PHP using exec().

Here's the problem: when I installed Tensorflow (with Anaconda), by following the instruction on this page, it needs you to activate the Anaconda environment after the install before you can actually use it. It works when I do it on the command line, but I how can I reproduce that activation process from a PHP script? I, understandably get the ModuleNotFoundError. Or to rephrase, how can I make importing Tensorflow as effortless as the other modules that come with Anaconda? Am I missing something?

答: I solved it by installing Tensorflow in the root, rather than an environment. Keep in mind though, if you're on Windows like me, you'll need to have Python 3.5.2. More on that here</p>


问:
Restore single stub in sandbox
```<code>sandbox = sinon.sandbox.create();

sandbox.stub(db, 'query', () => {
    return Promise.resolve();
});

sandbox.stub(process, 'exit', () => { });
</code>```

sandbox.restore(); removes all the stubs.

I want to remove ONE stub so I can restub it. For example the query stub.

Is this possible? I can't find any information on this.

答:
You can restore single method like this:

```<code>db.query.restore();
</code>```

for your particular case.

Per sinon documentation:

var stub = sinon.stub(object, "method");

Replaces object.method with a stub function. An exception is thrown if
  the property is not already a function.

The original function can be restored by calling
  object.method.restore(); (or stub.restore();).

See http://sinonjs.org/releases/v2.3.6/stubs/

Title: Restore single stub in sandbox

Body:
sandbox = sinon.sandbox.create();

sandbox.stub(db, 'query', () => {
    return Promise.resolve();
});

sandbox.stub(process, 'exit', () => { });

sandbox.restore(); removes all the stubs.

I want to remove ONE stub so I can restub it. For example the query stub.

Is this possible? I can't find any information on this.

Body:
You can restore single method like this:

db.query.restore();

for your particular case.

Per sinon documentation:

var stub = sinon.stub(object, "method");

Replaces object.method with a stub function. An exception is thrown if
  the property is not already a function.

The original function can be restored by calling
  object.method.restore(); (or stub.restore();).

See http://sinonjs.org/releases/v2.3.6/stubs/


问:
Java Delegates?
Does the Java language have delegate features, similar to how C# has support for delegates?</p>

答:
Not really, no.

You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).

You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (@blueskyprojects.com)

OwnerDisplayName: Mark

Title: Java Delegates?

OwnerDisplayName: Matt Sheppard


问:
Dynamic CSS for ASP.NET MVC?
It looks like the .NET community in general has not picked up on CSS compilers. In searching Google I've not found anything even remotely relevant.  </p>

<p>Has anyone that is using ASP.NET MVC figured out a scheme to more intelligently generate their CSS? I'd love to be able to run my CSS through Razor for example, or for SASS to get ported over or what have you. Maybe I have a new side project on my hands :) </p>

答:
Phil Haack has made a blog post about LessCSS and .net:

http://haacked.com/archive/2009/12/02/t4-template-for-less-css.aspx

Title: Dynamic CSS for ASP.NET MVC?

Body:
It looks like the .NET community in general has not picked up on CSS compilers. In searching Google I've not found anything even remotely relevant.

Has anyone that is using ASP.NET MVC figured out a scheme to more intelligently generate their CSS? I'd love to be able to run my CSS through Razor for example, or for SASS to get ported over or what have you. Maybe I have a new side project on my hands :)


问:
unique records by one column
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

```<code>A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r
</code>```

This should return

```<code>A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r
</code>```

Which query wil give me this result? Until now I have this but it does not work well:

```<code>SELECT DISTINCT A, B, FROM myTable WHERE C=f
</code>```

答:
You could use Row_Number() to rank the rows within each distinct A value, then get the first row of each.

```<code>SELECT
    a, b, c, d
FROM
    (SELECT
        a, b, c, d,
        Row_Number() OVER (PARTITION BY a ORDER BY b, c, d) rn
    FROM
        myTable) mt
WHERE
    rn = 1
</code>```

Title: unique records by one column

Body:
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r

This should return

A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r

Which query wil give me this result? Until now I have this but it does not work well:

SELECT DISTINCT A, B, FROM myTable WHERE C=f

Body:
You could use Row_Number() to rank the rows within each distinct A value, then get the first row of each.

SELECT
    a, b, c, d
FROM
    (SELECT
        a, b, c, d,
        Row_Number() OVER (PARTITION BY a ORDER BY b, c, d) rn
    FROM
        myTable) mt
WHERE
    rn = 1


问:
Moving a word forward in z shell
In zshell how to move forward word, I can set -o vi and use vi format. Is there a way to move forward in zshell by a word</p>

答:
forward word [Meta]+[f]

backward word [Meta]+[b]

On macOS, [option]+[→] and [option]+[←] work too.

Title: Moving a word forward in z shell


问:
ImportError: cannot import name DependencyWarning
I am using python 2.7.12. When i do import requests, I see the error below.

Tried uninstalling & installing requests, upgrading pip as well, but no luck, still same issue.

```<code>Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
/home/test/.local/lib/python2.7/site-packages/requests/__init__.py:80:
RequestsDependencyWarning: urllib3 (1.13.1) or chardet (2.3.0) doesn't match a supported version!
RequestsDependencyWarning)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/test/.local/lib/python2.7/site-packages/requests/__init__.py", line 90, in <module>
from urllib3.exceptions import DependencyWarning
ImportError: cannot import name DependencyWarning
</code>```

How can I solve this?

答:
There are two cases that occur this problem.

There is duplicated PATH of pip.

apt-get remove python-pip

easy_install pip

This problem is caused by a mismatch between your pip installation and your requests installation.

You can solve this issue by updating pip.

Body:
I am using python 2.7.12. When i do import requests, I see the error below.

Tried uninstalling & installing requests, upgrading pip as well, but no luck, still same issue.

Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
/home/test/.local/lib/python2.7/site-packages/requests/__init__.py:80:
RequestsDependencyWarning: urllib3 (1.13.1) or chardet (2.3.0) doesn't match a supported version!
RequestsDependencyWarning)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/test/.local/lib/python2.7/site-packages/requests/__init__.py", line 90, in <module>
from urllib3.exceptions import DependencyWarning
ImportError: cannot import name DependencyWarning

How can I solve this?


问:
SQL Server is reading only first row from valid JSON
My JSON is like below. This JSON is read by ADF without problem and imports all rows.

```<code>{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
</code>```

However when I read this from SQL using below query, it returns only first record.

```<code>SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Row.Col1'
);
</code>```

Do you know why?

答:
If you can't change the input format to use an array, and you know that the objects are delimited by newlines, you can use STRING_SPLIT to get each into its own row:

```<code>SELECT JSON_VALUE(value, '$.Row.Col1')
FROM STRING_SPLIT(@JSONDATA, CHAR(10))
</code>```

Or you can preprocess the input so it is parsable by OPENJSON:

```<code>SELECT *
FROM OPENJSON(N'[' + REPLACE(@JSONDATA, CHAR(13) + CHAR(10), ',') + N']')
WITH (
    Col1 VARCHAR(25) '$.Row.Col1'
);
</code>```

If you have no row delimiters, I'm not sure this can be done cleanly in T-SQL.

Body:
My JSON is like below. This JSON is read by ADF without problem and imports all rows.

{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}

However when I read this from SQL using below query, it returns only first record.

SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Row.Col1'
);

Do you know why?

Body:
If you can't change the input format to use an array, and you know that the objects are delimited by newlines, you can use STRING_SPLIT to get each into its own row:

SELECT JSON_VALUE(value, '$.Row.Col1')
FROM STRING_SPLIT(@JSONDATA, CHAR(10))

Or you can preprocess the input so it is parsable by OPENJSON:

SELECT *
FROM OPENJSON(N'[' + REPLACE(@JSONDATA, CHAR(13) + CHAR(10), ',') + N']')
WITH (
    Col1 VARCHAR(25) '$.Row.Col1'
);

If you have no row delimiters, I'm not sure this can be done cleanly in T-SQL.


问:
How do I delay an animation using my character movement script?
Below is a copy of my player movement script which contains functions to animate my character moving left and right, jumping and shooting his bow. I have also been able to get my character to transition from shooting his bow to being in an alert animation, but I am wondering how to write the code so that for 5 seconds after I shoot my bow I will be alert before going back to my default "idle" animation.

I would also like my character to be able to walk around (i.e. transition the alert animation to the walk animation) while being alert, but if he stops moving he goes back to alert. Currently my character will go back to idle if he walks during his alert stance. The script below, specifically lines 98-102 (my "playerAlert" function) present another problem in that my character cannot perform his "shoot" animation after this function has occurred, but I do not know/can't wrap my head around how to code what I mentioned above.

I am using Unity 5.6.

I appreciate any help you guys may be able to give me.

```<code>     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class player_1_controller : MonoBehaviour {

         Rigidbody2D myRB;
         Animator myAnim;
         bool facingRight;

         //movement variables
         public float maxSpeed;

         //jumping variables
         bool grounded = false;
         float groundCheckRadius = 0.2f;
         public LayerMask groundLayer;
         public Transform groundCheck;
         public float jumpHeight;

         //arrow shooting variables
         bool firing = true;
         public float arrowShoot;
         public Transform arrowTip;
         public GameObject arrow;
         public float fireRate = 0.5f;
         public float nextFire = 0f;

         // Use this for initialization
         void Start () {

             myRB = GetComponent<Rigidbody2D> ();
             myAnim = GetComponent<Animator> ();
             facingRight = true;
             }

         // Update is called once per frame
         void Update () {

             //player jump
             if (grounded && Input.GetButtonDown ("Jump")) {
                 grounded = false;
                 myAnim.SetBool ("isGrounded", grounded);
                 myRB.AddForce (new Vector2 (0, jumpHeight));
             }

             //player shooting
             if (grounded && Input.GetButtonDown ("Fire1")) {
                 myAnim.SetBool ("arrowShoot", firing);
                 Invoke ("fireArrow", 1);
             }

         }

             void FixedUpdate() {

             //player movement
             float move = Input.GetAxis ("Horizontal");
             myAnim.SetFloat ("speed", Mathf.Abs (move));

             myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);

             if (move > 0 && !facingRight) {
                 flip ();
             } else if (move < 0 && facingRight) {
                 flip ();
             }

             //player jump; check if we are grounded - if not, then we are falling
             grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
             myAnim.SetBool ("isGrounded", grounded);

             myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
         }

             void flip () {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;

         }

         void fireArrow() {

             if (Time.time > nextFire) {
                 nextFire = Time.time + fireRate;
                 if (facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
                 } else if (!facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 180)));
                 }
             }
             playerAlert ();

           }

         void playerAlert () {

                 firing = false;
                 myAnim.SetBool ("arrowShoot", firing);
         }
     }
</code>```

答:
Have you considered implementing it inside the animator?

You could create a transition from your Alert animation to your Idle animation, with a fixed exit time of 5 seconds.

This way, after 5 seconds of being in the Alert animation, it will transition to the Idle animation.

Body:
Below is a copy of my player movement script which contains functions to animate my character moving left and right, jumping and shooting his bow. I have also been able to get my character to transition from shooting his bow to being in an alert animation, but I am wondering how to write the code so that for 5 seconds after I shoot my bow I will be alert before going back to my default "idle" animation.

I would also like my character to be able to walk around (i.e. transition the alert animation to the walk animation) while being alert, but if he stops moving he goes back to alert. Currently my character will go back to idle if he walks during his alert stance. The script below, specifically lines 98-102 (my "playerAlert" function) present another problem in that my character cannot perform his "shoot" animation after this function has occurred, but I do not know/can't wrap my head around how to code what I mentioned above.

I am using Unity 5.6.

I appreciate any help you guys may be able to give me.

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class player_1_controller : MonoBehaviour {

         Rigidbody2D myRB;
         Animator myAnim;
         bool facingRight;

         //movement variables
         public float maxSpeed;

         //jumping variables
         bool grounded = false;
         float groundCheckRadius = 0.2f;
         public LayerMask groundLayer;
         public Transform groundCheck;
         public float jumpHeight;

         //arrow shooting variables
         bool firing = true;
         public float arrowShoot;
         public Transform arrowTip;
         public GameObject arrow;
         public float fireRate = 0.5f;
         public float nextFire = 0f;

         // Use this for initialization
         void Start () {

             myRB = GetComponent<Rigidbody2D> ();
             myAnim = GetComponent<Animator> ();
             facingRight = true;
             }

         // Update is called once per frame
         void Update () {

             //player jump
             if (grounded && Input.GetButtonDown ("Jump")) {
                 grounded = false;
                 myAnim.SetBool ("isGrounded", grounded);
                 myRB.AddForce (new Vector2 (0, jumpHeight));
             }

             //player shooting
             if (grounded && Input.GetButtonDown ("Fire1")) {
                 myAnim.SetBool ("arrowShoot", firing);
                 Invoke ("fireArrow", 1);
             }

         }

             void FixedUpdate() {

             //player movement
             float move = Input.GetAxis ("Horizontal");
             myAnim.SetFloat ("speed", Mathf.Abs (move));

             myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);

             if (move > 0 && !facingRight) {
                 flip ();
             } else if (move < 0 && facingRight) {
                 flip ();
             }

             //player jump; check if we are grounded - if not, then we are falling
             grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
             myAnim.SetBool ("isGrounded", grounded);

             myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
         }

             void flip () {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;

         }

         void fireArrow() {

             if (Time.time > nextFire) {
                 nextFire = Time.time + fireRate;
                 if (facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
                 } else if (!facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 180)));
                 }
             }
             playerAlert ();

           }

         void playerAlert () {

                 firing = false;
                 myAnim.SetBool ("arrowShoot", firing);
         }
     }


问:
What is the maximum recommended number of rows that a SQL 2008 R2 standalone server should store in a single table?
I'm designing my DB for functionality and performance for realtime AJAX web applications, and I don't currently have the resources to add DB server redundancy or load-balancing.

Unfortunately, I have a table in my DB that could potentially end up storing hundreds of millions of rows, and will need to read and write quickly to prevent lagging the web-interface.

Most, if not all, of the columns in this table are individually indexed, and I'd love to know if there are other ways to ease the burden on the server when running querys on large tables. But is there eventually a cap for the size (in rows or GB) of a table before a single unclustered SQL server starts to choke?

My DB only has a dozen tables, with maybe a couple dozen foriegn key relationships. None of my tables have more than 8 or so columns, and only one or two of these tables will end up storing a large number of rows. Hopefully the simplicity of my DB will make up for the massive amounts of data in these couple tables ...

答:
Rows are limited strictly by the amount of disk space you have available.  We have SQL Servers with hundreds of millions of rows of data in them.  Of course, those servers are rather large.

In order to keep the web interface snappy you will need to think about how you access that data.

One example is to stay away from any type of aggregate queries which require processing large swaths of data.  Things like SUM() can be a killer depending on how much data it's trying to process.  In these situations you are much better off calculating any summary or grouped data ahead of time and letting your site query these analytic tables.

Next you'll need to partition the data.  Split those partitions across different drive arrays.  When SQL needs to go to disk it makes it easier to parallelize the reads. (@Simon touched on this).

Basically, the problem boils down to how much data you need to access at any one time.  This is the main problem regardless of the amount of data you have on disk.  Even small databases can be choked if the drives are slow and the amount of available RAM in the DB server isn't enough to keep enough of the DB in memory.

Usually for systems like this large amounts of data are basically inert, meaning that it's rarely accessed.  For example, a PO system might maintain a history of all invoices ever created, but they really only deal with any active ones.

If your system has similar requirements, then you might have a table that is for active records and simply archive them to another table as part of a nightly process.  You could even have statistics like monthly averages (as an example) recomputed as part of that archival.

Just some thoughts.


问:
How to add an index to such sql query?
Please tell me how to add an index to this sql query?

SELECT *
FROM table
WHERE (cities IS NULL) AND (position_id = '2') AND (is_pub = '1')
ORDER BY ordering asc
LIMIT 1

Field types:

cities = text

position_id = int(11)

is_pub = tinyint(1)

I try so:
ALTER TABLE table ADD FULLTEXT ( 'cities', 'position_id', 'is_pub' );

But I get an error: The used table type doesn't support FULLTEXT indexes

答:
You need to change the engine for your table to MyISAM.

possible duplicate of #1214 - The used table type doesn't support FULLTEXT indexes

Title: How to add an index to such sql query?


问:
Programatic way to retrieve the Ruby version specified in the Gemfile?
I am looking for an efficient a programatic way to retrieve the Ruby version specified in a Rails app Gemfile.</p>

```<code># Gemfile
ruby '2.3.4'
</code>```

答:
You can use Gem.ruby_version

```<code>Gem.ruby_version.to_s
=> "2.2.5.319"
</code>```

Body:
I am looking for an efficient a programatic way to retrieve the Ruby version specified in a Rails app Gemfile.

# Gemfile
ruby '2.3.4'

Body:
You can use Gem.ruby_version

Gem.ruby_version.to_s
=> "2.2.5.319"


问:
Filter list results with <select/> drop-down list value
I am trying to filter a 'Project Index' by tags using jQuery and CSS.

I am currently taking the .val() of the selected option in a <select> dropdown list and checking if it's equal to the inner .html() of a .tag. If they match it will make the project entry black, if else it will make it light gray.

My current code works when the project has one tag, but once there are multiple tags it breaks. My guess is that because although there is one .tag equal to the selected dropdown value, the other .tag are not,  therefore using the else condition?

What am I missing? Is there a better/more efficient way to do this?

HTML

```<code><main>
  <div class="index__container">
     <section class="index">
        <ul class="index__header">
            <li>Project</li>
            <li>Filter: <select id="index__filter">
                <option selected="selected" value='ALL'>All</option>
                <option value="Pedagogical Explorations">Pedagogical Explorations</option>
                <option value="Research Production">Research Production</option>
                <option value="Spatial Practice">Spatial Practice</option>
                <option value="Exhibition">Exhibition</option>
            </select></li>
            <li>Year</li>
        </ul>
        <a href="">
            <ul class="index__entry">
                <li>Multiscale Strategies to Reactivate Transhumance in Spain</li>
                <li>
                    <span class="tag">Spatial Practice</span>
                </li>
                <li>2017</li>
            </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>Architecture after Speculation</li>
                <li>
                    <span class="tag">Research Production</span>
                </li>
                <li>2017</li>
            </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>Polyester Merino Chair</li>
                <li>
                    <span class="tag">Spatial Practice</span>
                </li>
                <li>2017</li>
            </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>1500 caracteres</li>
                <li>
                    <span class="tag">Spatial Practice</span>
                    <span class="tag">Research Production</span>
                </li>
                <li>2017</li>
            </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>Europan 13: Die Arbeitersiedlung</li>
                <li>
                    <span class="tag">Spatial Practice</span>
                </li>
                <li>2015</li>
            </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>Asymmetric Meta-Mapping</li>
                <li>
                    <span class="tag">Pedagogical Explorations</span>
                </li>
                <li>2017</li>
             </ul>
        </a>
        <a href="">
            <ul class="index__entry">
                <li>Chicago Architecture Biennial</li>
                <li>
                    <span class="tag">Spatial Practice</span>
                    <span class="tag">Research Production</span>
                    <span class="tag">Exhibition</span></li>
                <li>2015</li>
            </ul>
        </a>
    </section>
</div>
</code>```

JS

```<code>  // Filter Project Index
  var $indexSelect = $('#index__filter');
  var $indexEntry = $('.index__entry');
  var $tag = $('.tag');

  $indexSelect.change(function(){
    var selectedValue = $(this).val();
    if(selectedValue == 'ALL'){
       $indexEntry.css('color', 'black');
     return;
    }

    $tag.each(function(i,option){
     if ($(this).html() == selectedValue) {
        $(this).closest('ul').css('color', 'black');
        console.log($(this).text());
      } else {
       $(this).closest('ul').css('color', 'lightgray');
      }
    });
  });
</code>```

答:
Try this </p>

```<code>var $indexSelect = $('#index__filter');
var $indexEntry = $('.index__entry');

$indexSelect.change(function() {
    var selectedValue = $(this).val();
    if (selectedValue == 'ALL') {
        $indexEntry.css('color', 'black');
        return;
    }

    $indexEntry.each(function(i, option) {
        debugger;
        var $tag = $(this).find('.tag');
        var flag = true;
        $tag.each(function(i, option) {
            if (flag == true) {
                if ($(this).html() == selectedValue) {
                    $(this).closest('ul').css('color', 'black');
                    console.log($(this).text());
                    flag = false;
                } else {
                    $(this).closest('ul').css('color', 'lightgray');
                }
            }
        });
    });
});
</code>```

Body:
I am trying to filter a 'Project Index' by tags using jQuery and CSS.

I am currently taking the .val() of the selected option in a <select> dropdown list and checking if it's equal to the inner .html() of a .tag. If they match it will make the project entry black, if else it will make it light gray.

My current code works when the project has one tag, but once there are multiple tags it breaks. My guess is that because although there is one .tag equal to the selected dropdown value, the other .tag are not,  therefore using the else condition?

What am I missing? Is there a better/more efficient way to do this?

HTML

Project

Filter: <select id="index__filter">
                <option selected="selected" value='ALL'>All</option>
                <option value="Pedagogical Explorations">Pedagogical Explorations</option>
                <option value="Research Production">Research Production</option>
                <option value="Spatial Practice">Spatial Practice</option>
                <option value="Exhibition">Exhibition</option>
            </select>

Year

Multiscale Strategies to Reactivate Transhumance in Spain

                    Spatial Practice

2017

Architecture after Speculation

                    Research Production

2017

Polyester Merino Chair

                    Spatial Practice

2017

1500 caracteres

                    Spatial Practice
                    Research Production

2017

Europan 13: Die Arbeitersiedlung

                    Spatial Practice

2015

Asymmetric Meta-Mapping

                    Pedagogical Explorations

2017

Chicago Architecture Biennial

                    Spatial Practice
                    Research Production
                    Exhibition

2015

JS

  // Filter Project Index
  var $indexSelect = $('#index__filter');
  var $indexEntry = $('.index__entry');
  var $tag = $('.tag');

  $indexSelect.change(function(){
    var selectedValue = $(this).val();
    if(selectedValue == 'ALL'){
       $indexEntry.css('color', 'black');
     return;
    }

    $tag.each(function(i,option){
     if ($(this).html() == selectedValue) {
        $(this).closest('ul').css('color', 'black');
        console.log($(this).text());
      } else {
       $(this).closest('ul').css('color', 'lightgray');
      }
    });
  });

Body:
Try this

var $indexSelect = $('#index__filter');
var $indexEntry = $('.index__entry');

$indexSelect.change(function() {
    var selectedValue = $(this).val();
    if (selectedValue == 'ALL') {
        $indexEntry.css('color', 'black');
        return;
    }

    $indexEntry.each(function(i, option) {
        debugger;
        var $tag = $(this).find('.tag');
        var flag = true;
        $tag.each(function(i, option) {
            if (flag == true) {
                if ($(this).html() == selectedValue) {
                    $(this).closest('ul').css('color', 'black');
                    console.log($(this).text());
                    flag = false;
                } else {
                    $(this).closest('ul').css('color', 'lightgray');
                }
            }
        });
    });
});


问:
Eclipse : Could not open editor after Eclipse PDT upgrade to version 5.0.1.201706221952
I just upgraded my Eclipse PHP IDE by downloading Eclipse PDT Version 5.0.1.201706221952 but that was a bad idea since I can't work with Eclipse anymore. I think I'm facing a bug because I could not open any files of my project, the Eclipse file Editor seems broken. The DLTK indexing seems broken too (for my current project at least...). Sometimes the editor could open one of my files but the name of the file is not displayed and I can't save modifications.

I tried to clean my project since I've found a similiar issue (Could not open the editor: Editor could not be initialized. NoClassDefFoundError) but I got a building workspace error.

Any idea on how I can get the Eclipse editor working ?

Version: Neon.3 Release (4.6.3)

Build id: 20170314-1500

My project uses Symfony 3 (could give more details if required)

Building workspace error :

```<code>Errors occurred during the build.
Errors running builder 'Script Builder' on project 'PROJET_VISA_ECLIPSE'.
java.lang.NoClassDefFoundError:
org/eclipse/php/internal/core/compiler/ast/visitor/PHPASTVisitor
</code>```

Error at launch:

```<code>An internal error occurred during: "Initialize DLTK".
java.lang.NoClassDefFoundError:
org/eclipse/php/internal/core/compiler/ast/visitor/PHPASTVisitor
</code>```

Dubture plugin is also encountering errors :

```<code>com.dubture.twig.core.index.TwigIndexingVisitorExtension.
</code>```

Editor error: No editor descriptor for id org.eclipse.ui.internal.emptyEditorTab

```<code>java.lang.Exception
at org.eclipse.ui.internal.EditorReference.createErrorPart(EditorReference.java:340)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:321)
</code>```

答:
This problem seems to come from an incompatibility between the new PDT version and the Symfony plugin.

I have the same error in both version of Eclipse (4.6 and 4.7, with PDT at 5.0.1), and just uninstalling the Symfony plugin (along with Twig plugin) works for me.

Body:
I just upgraded my Eclipse PHP IDE by downloading Eclipse PDT Version 5.0.1.201706221952 but that was a bad idea since I can't work with Eclipse anymore. I think I'm facing a bug because I could not open any files of my project, the Eclipse file Editor seems broken. The DLTK indexing seems broken too (for my current project at least...). Sometimes the editor could open one of my files but the name of the file is not displayed and I can't save modifications.

I tried to clean my project since I've found a similiar issue (Could not open the editor: Editor could not be initialized. NoClassDefFoundError) but I got a building workspace error.

Any idea on how I can get the Eclipse editor working ?

Version: Neon.3 Release (4.6.3)

Build id: 20170314-1500

My project uses Symfony 3 (could give more details if required)

Building workspace error :

Errors occurred during the build.
Errors running builder 'Script Builder' on project 'PROJET_VISA_ECLIPSE'.
java.lang.NoClassDefFoundError:
org/eclipse/php/internal/core/compiler/ast/visitor/PHPASTVisitor

Error at launch:

An internal error occurred during: "Initialize DLTK".
java.lang.NoClassDefFoundError:
org/eclipse/php/internal/core/compiler/ast/visitor/PHPASTVisitor

Dubture plugin is also encountering errors :

com.dubture.twig.core.index.TwigIndexingVisitorExtension.

Editor error: No editor descriptor for id org.eclipse.ui.internal.emptyEditorTab

java.lang.Exception
at org.eclipse.ui.internal.EditorReference.createErrorPart(EditorReference.java:340)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:321)


问:
Deedle: Setting header names when using SaveCsv
I'm trying to use Deedle to save .csv files

```<code>type all_trades_schema = CsvProvider<"/trading/backtesting/strategy logs/all_trades.csv">

(new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv")
</code>```

the problem I have is that the original (template) file has column names,
but the new file doesn't have any column names.

How can i fix my (little) problem ? thanks

(of note, my first column is DateTime, the others are float, but if this is important i'd like to know the right syntax when there are other types)

答:
From the documentation, you have two options:

Pass includeRowKeys=true as a parameter to SaveCsv

Pass keyNames=*keynames* as a parameter to SaveCsv, where *keynames* is a list of header names

See http://bluemountaincapital.github.io/Deedle/features.html for the documentation.

To get the header names from the CsvProvider, you can do:
all_trades_schema.GetSample().Headers

This will give you a string [] option, so you will need to unwrap the DU like:

match all_trades_schema.GetSample().Headers with
| Some headers
   -> (new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv", keyNames = headers)
| None
   -> (new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv")
```

Body:
I'm trying to use Deedle to save .csv files

type all_trades_schema = CsvProvider<"/trading/backtesting/strategy logs/all_trades.csv">

(new_trades |> Frame.ofRecords).SaveCsv(log_dirname+"/new_trades.csv")

the problem I have is that the original (template) file has column names,
but the new file doesn't have any column names.

How can i fix my (little) problem ? thanks

(of note, my first column is DateTime, the others are float, but if this is important i'd like to know the right syntax when there are other types)


问:
Filter Firebase Database DataSnapshot children on Android
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

```<code>Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });
</code>```

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

答:
Please use the following code:

```<code>Firebase rootRef = new Firebase("https://....../myCoffee/" + phone);
rootRef.addValueEventListener(new ValueEventListener() {
    Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int size = 0;
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String coffeeNo = ds.child("coffeeNo").getValue(String.class);
            if(coffeeNo.equals("Acoffee")) {
                size++;
            }
        }
        txtMyCoffee.setText(String.valueOf(size));
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});
</code>```

Edit: Another approach is to use a simple query like this:

```<code>Firebase rootRef = new Firebase("https://....../myCoffee/"+phone+"");
Query query = rootRef.orderByChild("coffeeNo").equalTo("Acoffee");
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int size = (int) dataSnapshot.getChildrenCount();
        txtMyCoffee.setText(String.valueOf(size));
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});
</code>```

Your txtMyCoffee in both cases will display: 2.

Body:
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

Body:
Please use the following code:

Firebase rootRef = new Firebase("https://....../myCoffee/" + phone);
rootRef.addValueEventListener(new ValueEventListener() {
    Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int size = 0;
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String coffeeNo = ds.child("coffeeNo").getValue(String.class);
            if(coffeeNo.equals("Acoffee")) {
                size++;
            }
        }
        txtMyCoffee.setText(String.valueOf(size));
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});

Edit: Another approach is to use a simple query like this:

Firebase rootRef = new Firebase("https://....../myCoffee/"+phone+"");
Query query = rootRef.orderByChild("coffeeNo").equalTo("Acoffee");
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int size = (int) dataSnapshot.getChildrenCount();
        txtMyCoffee.setText(String.valueOf(size));
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});

Your txtMyCoffee in both cases will display: 2.


问:
Location of System.Web.MVC so I can reflect over it with reflector
I installed MVC 1.0.  Where's the System.Web.MVC dll so that I can use reflector to see how the helper methods are coded? I've looked in the bin folder of my ASP.NET MVC web app but it's not there.  I am not quite sure where the MVC 1.0 installer installs the dll and how that wires up to the web.config of your MVC apps.  Is System.Web.MVC installed in the GAC or something?  If so, how the heck can I reflect over the assembly?</p>

答:
Looks like this has changed for VS2015/Windows10. Mine is under:

```<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\Web\Razor\v3.0\MVC5.1
</code>```

OR

```<code>C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45
</code>```

Body:
Looks like this has changed for VS2015/Windows10. Mine is under:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\Web\Razor\v3.0\MVC5.1

OR

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45


问:
Identify multiple regex matches in a single string and get substring for each match
I would like to find strings with regex pattern.
For example:

```<code># header ## smaller header
</code>```

I would like to find two string set as follows.

```<code># header
## smaller header
</code>```

So I make the regex pattern as follows.

```<code>pattern = re.compile("(?:^#+|\s#+)\s")
</code>```

With this pattern, I can find # header.

```<code># header
</code>```

But I can't find the string such as ## smaller header

How can I make the regex so that find two set of strings?

答:
You can do the following

```<code>import re
p = re.compile(r"#+(\s\w+)+")
for m in p.finditer('# header ## smaller header'):
    print(m.group())
</code>```

which outputs

```<code># header
## smaller header
</code>```

Body:
I would like to find strings with regex pattern.
For example:

# header ## smaller header

I would like to find two string set as follows.

# header
## smaller header

So I make the regex pattern as follows.

pattern = re.compile("(?:^#+|\s#+)\s")

With this pattern, I can find # header.

# header

But I can't find the string such as ## smaller header

How can I make the regex so that find two set of strings?

Body:
You can do the following

import re
p = re.compile(r"#+(\s\w+)+")
for m in p.finditer('# header ## smaller header'):
    print(m.group())

which outputs

# header
## smaller header


答:
I'd love to be able to run my CSS through Razor

What stops you?

```<code>public class CssViewResult : PartialViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "text/css";
        base.ExecuteResult(context);
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new CssViewResult();
    }
}
</code>```

and in ~/Views/Home/Index.cshtml:

```<code>@{
    var color = "White";
    if (DateTime.Now.Hour > 18 || DateTime.Now.Hour < 8)
    {
        color = "Black";
    }
}
.foo {
    color: @color;
}
</code>```

Now all that's left is to include it:

```<code><link href="@Url.Action("index")" rel="stylesheet" type="text/css" />
</code>```

You can also make the template strongly typed to a view model, write loops, ifs, inclusions, ...

Title: Dynamic CSS for ASP.NET MVC?

Body:
It looks like the .NET community in general has not picked up on CSS compilers. In searching Google I've not found anything even remotely relevant.

Has anyone that is using ASP.NET MVC figured out a scheme to more intelligently generate their CSS? I'd love to be able to run my CSS through Razor for example, or for SASS to get ported over or what have you. Maybe I have a new side project on my hands :)

Body:
I'd love to be able to run my CSS through Razor

What stops you?

public class CssViewResult : PartialViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "text/css";
        base.ExecuteResult(context);
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new CssViewResult();
    }
}

and in ~/Views/Home/Index.cshtml:

@{
    var color = "White";
    if (DateTime.Now.Hour > 18 || DateTime.Now.Hour < 8)
    {
        color = "Black";
    }
}
.foo {
    color: @color;
}

Now all that's left is to include it:

<link href="@Url.Action("index")" rel="stylesheet" type="text/css" />

You can also make the template strongly typed to a view model, write loops, ifs, inclusions, ...


问:
Static initialization with necessary sideeffects is optimized away
I want to send a signal to each subclass of a class.
To achieve this I am using the signals2 library from boost. Because of the usage of the code I need to use a CRTP.

Minimal example, which is included in a header file:

```<code>class A {
    static boost::signals2::signal<void()>& getSignal() {
        static boost::signals2::signal<void()> signal;
        return signal;
    }

public:
    static void sendSignal() {
        getSignal()();
    }

protected:
    template <typename slot_t>
    static boost::signals2::connection addSlot(slot_t slot) {
        return _entityToBeDeleted().connect(slot);
    }
};

template <typename concrete_B>
class B : A {
    static boost::signals2::connection _installHandler() {
        return A::addSlot([]() {
            //Do something
        });
    }

    static const boost::signals2::connection connection;
};
template<typename concrete_B>
const boost::signals2::connection B<concrete_B>::connection = _installHandler();

class C : public B<C> {
    //Concrete subclass
};
</code>```

Some client class, that wants to notify the subclasses makes a call to A::sendSignal, which invokes all slots connected to the signal. What exactly the content of this notification is is irrelevant for the purpose of this question. As you can see, the side effect of the static initializer of B<concrete_B>::connection is needed for this to work, but as the object itself is never used (nor needed) the complete initialization is skipped.

The problem is: The call to _installHandler() is completely optimized away by the compiler (I'm using MSVC with Visual Studio 2017). I verified this by writing an additional test case, which explicitly tests if the connection object is valid. When I used the object this way the code worked and all other test cases passed. When I removed the additional test case the others failed again.

I tried declaring the static variable volatile as suggested in an answer to this question, but it did not help.

How do I prevent the initialization of the the static connection object to be optimized away. Or: How do I ensure a function with sideeffects that is created by template instanciation is always called once at the beginning of the executable, even though the returned object is never actually used; ideally during static initialization.

I thought about using the connection somehow in another static initializer of this class (std::cout << connection.connected() << '\n'; or something like this) that is already safe to be called (because the object this initializes is definitely used), but this seems like a nasty hack.

Edit: I implemented the "hack" and it works flawlessly, nontheless I am interested if there is a way to implement the desired behaviour in a "cleaner" way.

答:
The members of a class template get instantiated on demand. One possible fix is to refer to B<concrete_B>::connection from B's constructor or destructor:

```<code>B() { static_cast<void>(&connection); }
</code>```

Body:
I want to send a signal to each subclass of a class.
To achieve this I am using the signals2 library from boost. Because of the usage of the code I need to use a CRTP.

Minimal example, which is included in a header file:

class A {
    static boost::signals2::signal<void()>& getSignal() {
        static boost::signals2::signal<void()> signal;
        return signal;
    }

public:
    static void sendSignal() {
        getSignal()();
    }

protected:
    template <typename slot_t>
    static boost::signals2::connection addSlot(slot_t slot) {
        return _entityToBeDeleted().connect(slot);
    }
};

template <typename concrete_B>
class B : A {
    static boost::signals2::connection _installHandler() {
        return A::addSlot([]() {
            //Do something
        });
    }

    static const boost::signals2::connection connection;
};
template<typename concrete_B>
const boost::signals2::connection B<concrete_B>::connection = _installHandler();

class C : public B<C> {
    //Concrete subclass
};

Some client class, that wants to notify the subclasses makes a call to A::sendSignal, which invokes all slots connected to the signal. What exactly the content of this notification is is irrelevant for the purpose of this question. As you can see, the side effect of the static initializer of B<concrete_B>::connection is needed for this to work, but as the object itself is never used (nor needed) the complete initialization is skipped.

The problem is: The call to _installHandler() is completely optimized away by the compiler (I'm using MSVC with Visual Studio 2017). I verified this by writing an additional test case, which explicitly tests if the connection object is valid. When I used the object this way the code worked and all other test cases passed. When I removed the additional test case the others failed again.

I tried declaring the static variable volatile as suggested in an answer to this question, but it did not help.

How do I prevent the initialization of the the static connection object to be optimized away. Or: How do I ensure a function with sideeffects that is created by template instanciation is always called once at the beginning of the executable, even though the returned object is never actually used; ideally during static initialization.

I thought about using the connection somehow in another static initializer of this class (std::cout << connection.connected() << '\n'; or something like this) that is already safe to be called (because the object this initializes is definitely used), but this seems like a nasty hack.

Edit: I implemented the "hack" and it works flawlessly, nontheless I am interested if there is a way to implement the desired behaviour in a "cleaner" way.

Body:
The members of a class template get instantiated on demand. One possible fix is to refer to B<concrete_B>::connection from B's constructor or destructor:

B() { static_cast<void>(&connection); }


问:
SQL: No Sub-Query but only Joins
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')
</code>```

So, it should be something like...

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'
</code>```

Can somebody help me here?

答:
The queries you posted are very different.  One is inclusive (where SC.NUMBER_C IN.... - and the other is exclusive (left outer join where E.Reference is NULL).  Because of these completely different queries, it's unclear what you're trying to do.

This is how you would accomplish your first query with a join instead of the subquery.

```<code>SELECT COUNT(SC.NUMBER_C)
FROM FNQP2PORTAL.SA.SEC_CAS SC
JOIN FNQP2HQ.dbo.Entities E
    ON SC.NUMBER_C = E.Reference
JOIN FNQP2HQ.dbo.Classes C
    ON C.ID = E.ClassID
WHERE C.Reference = 'Assembly Case'
</code>```

EDIT:

You need to use a subquery and NOT IN to get what you're asking for in your comment.  You can't only use joins.

```<code>SELECT COUNT(SC.NUMBER_C)
FROM FNQP2PORTAL.SA.SEC_CAS SC
WHERE SC.NUMBER_C NOT IN
    (
        SELECT E.Reference
        FROM FNQP2HQ.dbo.Entities E
        JOIN FNQP2HQ.dbo.Classes C
            ON C.ID = E.ClassID
        WHERE C.Reference = 'Assembly Case'
    )
</code>```

Title: SQL: No Sub-Query but only Joins

Body:
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')

So, it should be something like...

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'

Can somebody help me here?

Body:
The queries you posted are very different.  One is inclusive (where SC.NUMBER_C IN.... - and the other is exclusive (left outer join where E.Reference is NULL).  Because of these completely different queries, it's unclear what you're trying to do.

This is how you would accomplish your first query with a join instead of the subquery.

SELECT COUNT(SC.NUMBER_C)
FROM FNQP2PORTAL.SA.SEC_CAS SC
JOIN FNQP2HQ.dbo.Entities E
    ON SC.NUMBER_C = E.Reference
JOIN FNQP2HQ.dbo.Classes C
    ON C.ID = E.ClassID
WHERE C.Reference = 'Assembly Case'

EDIT:

You need to use a subquery and NOT IN to get what you're asking for in your comment.  You can't only use joins.

SELECT COUNT(SC.NUMBER_C)
FROM FNQP2PORTAL.SA.SEC_CAS SC
WHERE SC.NUMBER_C NOT IN
    (
        SELECT E.Reference
        FROM FNQP2HQ.dbo.Entities E
        JOIN FNQP2HQ.dbo.Classes C
            ON C.ID = E.ClassID
        WHERE C.Reference = 'Assembly Case'
    )


问:
In NetStandard 1.3: How I get all classes that implement an interface to avoid the Error CS0117 'Assembly' does not contain a definition
I tried to use this code in a NetStandard 1.3  class library:

```<code>    foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
    .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
        //do stuff
     }
</code>```

but a compilation error is raised:

```<code>    Error   CS0117  'Assembly' does not contain a definition for 'GetExecutingAssembly'
</code>```

I reached What is the equivalent of Assembly.GetEntryAssembly() in .NET Core?, but it can't help.

I know that this service may be available in NetStandard 2, but until it's released(it's now in preview):

What is the modification to be done to the above code to support NetStandard 1.3

Update:

The question isn't a duplicate, i mentioned this link in my question and said it doesn't help.

Based on the comment of @ mjwills, it's probably worth adding that it's best to avoid using netstandard 1.5 or 1.6, as they won't be compatible with netstandard 2.0 https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/#div-comment-136675

C# library for .NET Core and .NET Framework

I ask for an equivalent code (not necessary using GetExecutingAssembly):

How I get all classes that implement an interface in NetStandard 1.1 up to 1.4 ?

答:
The following code is running in NetStandard1.3 and get all classes that implement interface without compilation error:

```<code>            Assembly asm = typeof(ICustomeAttribute).GetTypeInfo().Assembly; //thanks to @mjwills  for his helpfull comment

            var types = asm.DefinedTypes.Where(x=>x.ImplementedInterfaces.Contains(typeof(ICustomeAttribute)));
            foreach (var type in types)
            {
                //do stuff
                Console.WriteLine("class name: {0} - {1}",type.Name,type.FullName);
            }
</code>```

Remarks

Excerpt from: Assembly.DefinedTypes Property

The DefinedTypes property is comparable to the Assembly.GetTypes
  method, except that the DefinedTypes property returns a collection of
  TypeInfo objects, and the Assembly.GetTypes method returns an array of
  Type objects.

Body:
I tried to use this code in a NetStandard 1.3  class library:

    foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
    .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
        //do stuff
     }

but a compilation error is raised:

    Error   CS0117  'Assembly' does not contain a definition for 'GetExecutingAssembly'

I reached What is the equivalent of Assembly.GetEntryAssembly() in .NET Core?, but it can't help.

I know that this service may be available in NetStandard 2, but until it's released(it's now in preview):

What is the modification to be done to the above code to support NetStandard 1.3

Update:

The question isn't a duplicate, i mentioned this link in my question and said it doesn't help.

Based on the comment of @ mjwills, it's probably worth adding that it's best to avoid using netstandard 1.5 or 1.6, as they won't be compatible with netstandard 2.0 https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/#div-comment-136675

C# library for .NET Core and .NET Framework

I ask for an equivalent code (not necessary using GetExecutingAssembly):

How I get all classes that implement an interface in NetStandard 1.1 up to 1.4 ?

Body:
The following code is running in NetStandard1.3 and get all classes that implement interface without compilation error:

            Assembly asm = typeof(ICustomeAttribute).GetTypeInfo().Assembly; //thanks to @mjwills  for his helpfull comment

            var types = asm.DefinedTypes.Where(x=>x.ImplementedInterfaces.Contains(typeof(ICustomeAttribute)));
            foreach (var type in types)
            {
                //do stuff
                Console.WriteLine("class name: {0} - {1}",type.Name,type.FullName);
            }

Remarks

Excerpt from: Assembly.DefinedTypes Property

The DefinedTypes property is comparable to the Assembly.GetTypes
  method, except that the DefinedTypes property returns a collection of
  TypeInfo objects, and the Assembly.GetTypes method returns an array of
  Type objects.


问:
How do I retrieve the workerSize via Get-AzureRmAppServicePlan
When creating a new AppServicePlan via the Azure PowerShell cmdlet New-AzureRmAppServicePlan, it is expected for me to add a WorkerSize such as Small, Medium or Large. For example:

```<code>$appServicePlanSettings = @{
    Name = "testingServicePlan";
    Location = "westeurope";
    Tier = "Basic";
    ResourceGroupName = "testingResourceGroup";
    NumberofWorkers = 1;
    WorkerSize = "Medium";
}

New-AzureRmAppServicePlan @appServicePlanSettings
</code>```

However, when I retrieve this same AppServicePlan via Get-AzureRmAppServicePlan, I am unable to find this information. Instead I come across the Sku property, which contains a Size property with for example the value B2, indicating the WorkerSize was medium. Example:

```<code>> $plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $plan.Sku
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1
</code>```

Am I supposed to keep track of these conversions in for example a HashList if I want to be able to compare the equivalent values, or is there some other way for me to retrieve the 'Medium'? I might have missed something but couldn't find this information.

According to PowerShell's GetType() method, the object returned is a ServerFarmWithRichSku, with as base type Microsoft.Azure.Management.WebSites.Models.Resource, but the documentation for this object was a bit lacking for me to get any further

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.management.websites.models.resource?view=azuremgmtwebsites-1.6.0-preview

答:
I think the best way is to use Hash map for this.

But you can use "Family" from "Sku" to come over all B1,B2,M1,M2etc.,

```<code>>$hash = @{}
>$hash['S'] = "Small"
>$hash['M'] = "Medium"
>$hash['L'] = "Large"
>$hash['EL'] = "Extra Large"

>$plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $val=$plan.Sku.Fmaily
>echo $hash[$val]
</code>```

Body:
When creating a new AppServicePlan via the Azure PowerShell cmdlet New-AzureRmAppServicePlan, it is expected for me to add a WorkerSize such as Small, Medium or Large. For example:

$appServicePlanSettings = @{
    Name = "testingServicePlan";
    Location = "westeurope";
    Tier = "Basic";
    ResourceGroupName = "testingResourceGroup";
    NumberofWorkers = 1;
    WorkerSize = "Medium";
}

New-AzureRmAppServicePlan @appServicePlanSettings

However, when I retrieve this same AppServicePlan via Get-AzureRmAppServicePlan, I am unable to find this information. Instead I come across the Sku property, which contains a Size property with for example the value B2, indicating the WorkerSize was medium. Example:

> $plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $plan.Sku
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1

Am I supposed to keep track of these conversions in for example a HashList if I want to be able to compare the equivalent values, or is there some other way for me to retrieve the 'Medium'? I might have missed something but couldn't find this information.

According to PowerShell's GetType() method, the object returned is a ServerFarmWithRichSku, with as base type Microsoft.Azure.Management.WebSites.Models.Resource, but the documentation for this object was a bit lacking for me to get any further

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.management.websites.models.resource?view=azuremgmtwebsites-1.6.0-preview

Body:
I think the best way is to use Hash map for this.

But you can use "Family" from "Sku" to come over all B1,B2,M1,M2etc.,

>$hash = @{}
>$hash['S'] = "Small"
>$hash['M'] = "Medium"
>$hash['L'] = "Large"
>$hash['EL'] = "Extra Large"

>$plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $val=$plan.Sku.Fmaily
>echo $hash[$val]


问:
Replace all unicode codes with characters in python
I have a text file which looks like this:

l\u00f6yt\u00e4\u00e4

but all unicode chars need to be replaced with corresponding characters and should look like this:

löytää

the problem is that I do not want to replace all unicode codes by myself, what is the most efficient way to do this automatically?
my code looks like this right now but it needs to be refined for sure!(the code is in Python3)

```<code>import io
input = io.open("input.json", "r", encoding="utf-8")
output = io.open("output.txt", "w", encoding="utf-8")
with input, output:
    # Read input file.
    file = input.read()
    file = file.replace("\\u00e4", "ä")
    # I think last line is the same as line below:
    # file = file .replace("\\u00e4", u"\u00e4")
    file = file.replace("\\u00c4", "Ä")
    file = file.replace("\\u00f6", "ö")
    file = file.replace("\\u00d6", "Ö")
    .
    .
    .
    # I cannot put all codes in unicode here manually!
    .
    .
    .
    # writing output file
    output.write(file)
</code>```

答:
Just decode the JSON as JSON, and then write out a new JSON document without ensuring the data is ASCII safe:

```<code>import json

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        document = json.load(input)
        json.dump(document, output, ensure_ascii=False)
</code>```

From the json.dump() documentation:

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

Demo:

```<code>>>> import json
>>> print(json.loads(r'"l\u00f6yt\u00e4\u00e4"'))
löytää
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"')))
"l\u00f6yt\u00e4\u00e4"
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"'), ensure_ascii=False))
"löytää"
</code>```

If you have extremely large documents, you could still process them textually, line by line, but use regular expressions to do the replacements:

```<code>import re

unicode_escape = re.compile(
    r'(?<!\\)'
    r'(?:\\u([dD][89abAB][a-fA-F0-9]{2})\\u([dD][c-fC-F][a-fA-F0-9]{2})'
    r'|\\u([a-fA-F0-9]{4}))')
def replace(m):
    return bytes.fromhex(''.join(m.groups(''))).decode('utf-16-be')

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        for line in input:
            output.write(unicode_escape.sub(replace, line))
</code>```

This however fails if your JSON has embedded JSON documents in strings or if the escape sequence is preceded by an escaped backslash.

Body:
I have a text file which looks like this:

l\u00f6yt\u00e4\u00e4

but all unicode chars need to be replaced with corresponding characters and should look like this:

löytää

the problem is that I do not want to replace all unicode codes by myself, what is the most efficient way to do this automatically?
my code looks like this right now but it needs to be refined for sure!(the code is in Python3)

import io
input = io.open("input.json", "r", encoding="utf-8")
output = io.open("output.txt", "w", encoding="utf-8")
with input, output:
    # Read input file.
    file = input.read()
    file = file.replace("\\u00e4", "ä")
    # I think last line is the same as line below:
    # file = file .replace("\\u00e4", u"\u00e4")
    file = file.replace("\\u00c4", "Ä")
    file = file.replace("\\u00f6", "ö")
    file = file.replace("\\u00d6", "Ö")
    .
    .
    .
    # I cannot put all codes in unicode here manually!
    .
    .
    .
    # writing output file
    output.write(file)

Body:
Just decode the JSON as JSON, and then write out a new JSON document without ensuring the data is ASCII safe:

import json

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        document = json.load(input)
        json.dump(document, output, ensure_ascii=False)

From the json.dump() documentation:

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

Demo:

>>> import json
>>> print(json.loads(r'"l\u00f6yt\u00e4\u00e4"'))
löytää
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"')))
"l\u00f6yt\u00e4\u00e4"
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"'), ensure_ascii=False))
"löytää"

If you have extremely large documents, you could still process them textually, line by line, but use regular expressions to do the replacements:

import re

unicode_escape = re.compile(
    r'(?<!\\)'
    r'(?:\\u([dD][89abAB][a-fA-F0-9]{2})\\u([dD][c-fC-F][a-fA-F0-9]{2})'
    r'|\\u([a-fA-F0-9]{4}))')
def replace(m):
    return bytes.fromhex(''.join(m.groups(''))).decode('utf-16-be')

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        for line in input:
            output.write(unicode_escape.sub(replace, line))

This however fails if your JSON has embedded JSON documents in strings or if the escape sequence is preceded by an escaped backslash.