问:
string.substring vs string.take
If you want to only take a part of a string, the substring method is mostly used.
This has a drawback that you must first test on the length of the string to avoid errors.
For example you want to save data into a database, and want to cut off a value to the first 20 characters.

If you do  temp.substring(0,20) but temp only holds 10 chars, an exception is thrown.

There are 2 solutions that I see :

test on the length, and do the substring if needed

use the extension method Take

```<code>    string temp = "1234567890";
    var data= new string( temp.Take(20).ToArray());
    --> data now holds "1234657890"
</code>```

Is there any disadvantage in terms of speed or memory use , when one uses the Take method.
The benefit is that you do not have to write all those if statements.

答:
A variation of @Daniel answer that seems more accurate to me.

a Guid's length is 36. We're creating a list with a variable length of strings from 1 to 36, and we'll aim for taking 18 with the substring / take methods, so around half will go through.

The results I'm getting suggest that Take will be 6-10 times slower than Substring.

Results example :

```<code>Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms

Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms
</code>```

so, for 5 million strings, doing roughly 2.5 millions operations, total time is 2.1 seconds , or around 0.0008564 milliseconds = ~ 1 micro second per operation. If you feel you need to cut it by 5 for substring, go for it, but I doubt in real life situations, outside of tights loop, you'll ever feel the difference.

```<code>void Main()
{
    Console.WriteLine("Build time: {0} ms", BuildInput());
    Console.WriteLine("Time substring: {0} ms, Time take: {1} ms", MeasureSubstring(), MeasureTake());
}

internal const int RETRIES = 5000000;
static internal List<string> input;

// Measure substring time
private static long MeasureSubstring()
{
    var v = new List<string>();
    long ini = Environment.TickCount;

    foreach (string test in input)
        if (test.Length > 18)
        {
            v.Add(test.Substring(18));
        }
    //v.Count().Dump("entries with substring");
    //v.Take(5).Dump("entries with Sub");

    return Environment.TickCount - ini;
}

// Measure take time
private static long MeasureTake()
{
    var v = new List<string>();
    long ini = Environment.TickCount;

    foreach (string test in input)
        if (test.Length > 18) v.Add(new string(test.Take(18).ToArray()));

    //v.Count().Dump("entries with Take");
    //v.Take(5).Dump("entries with Take");

    return Environment.TickCount - ini;
}

// Create a list with random strings with random lengths
private static long BuildInput()
{
    long ini = Environment.TickCount;
    Random r = new Random();
    input = new List<string>();

    for (int i = 0; i < RETRIES; i++)
        input.Add(Guid.NewGuid().ToString().Substring(1,r.Next(0,36)));

    return Environment.TickCount - ini;
}
</code>```

Title: string.substring vs string.take

Body:
If you want to only take a part of a string, the substring method is mostly used.
This has a drawback that you must first test on the length of the string to avoid errors.
For example you want to save data into a database, and want to cut off a value to the first 20 characters.

If you do  temp.substring(0,20) but temp only holds 10 chars, an exception is thrown.

There are 2 solutions that I see :

test on the length, and do the substring if needed

use the extension method Take

    string temp = "1234567890";
    var data= new string( temp.Take(20).ToArray());
    --> data now holds "1234657890"

Is there any disadvantage in terms of speed or memory use , when one uses the Take method.
The benefit is that you do not have to write all those if statements.

Body:
A variation of @Daniel answer that seems more accurate to me.

a Guid's length is 36. We're creating a list with a variable length of strings from 1 to 36, and we'll aim for taking 18 with the substring / take methods, so around half will go through.

The results I'm getting suggest that Take will be 6-10 times slower than Substring.

Results example :

Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms

Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms

so, for 5 million strings, doing roughly 2.5 millions operations, total time is 2.1 seconds , or around 0.0008564 milliseconds = ~ 1 micro second per operation. If you feel you need to cut it by 5 for substring, go for it, but I doubt in real life situations, outside of tights loop, you'll ever feel the difference.

void Main()
{
    Console.WriteLine("Build time: {0} ms", BuildInput());
    Console.WriteLine("Time substring: {0} ms, Time take: {1} ms", MeasureSubstring(), MeasureTake());
}

internal const int RETRIES = 5000000;
static internal List<string> input;

// Measure substring time
private static long MeasureSubstring()
{
    var v = new List<string>();
    long ini = Environment.TickCount;

    foreach (string test in input)
        if (test.Length > 18)
        {
            v.Add(test.Substring(18));
        }
    //v.Count().Dump("entries with substring");
    //v.Take(5).Dump("entries with Sub");

    return Environment.TickCount - ini;
}

// Measure take time
private static long MeasureTake()
{
    var v = new List<string>();
    long ini = Environment.TickCount;

    foreach (string test in input)
        if (test.Length > 18) v.Add(new string(test.Take(18).ToArray()));

    //v.Count().Dump("entries with Take");
    //v.Take(5).Dump("entries with Take");

    return Environment.TickCount - ini;
}

// Create a list with random strings with random lengths
private static long BuildInput()
{
    long ini = Environment.TickCount;
    Random r = new Random();
    input = new List<string>();

    for (int i = 0; i < RETRIES; i++)
        input.Add(Guid.NewGuid().ToString().Substring(1,r.Next(0,36)));

    return Environment.TickCount - ini;
}


来源: stackexchange

问:
C# MVVM pattern update UI in Infinite loop thread?
I have a background thread to listen data, so this infinite loop to output data.

And, I using a ObservableCollection to bind a ListBox and show log.

I try to use Dispather.BeginInvoke, but no use, it not realtime. I have no idea for update UI in MVVM.

xaml

```<code><ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>
</code>```

code

```<code>private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
     get
     {
         return _displayLogs;
     }
}

public Testpro()
{
    _displayLogs = new ObservableCollection<string>();

    Task.Run(new Action(outputData));
}

private void outputData()
{
    string str = "";
    while (true)
    {
        string newString = GetInfoString();

        if (string.IsNullOrWhiteSpace(newString) || str == newString)
            continue;

        str = newString;

        Debug.WriteLine(str);
        Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
        {
                DisplayLogs.Add(str);
        });
    }
}
</code>```

*Edit:

GetInfoString will call by a dll file.

答:
You should really use something designed for this kind of update. I'm going to suggest Microsoft's Reactive Framework (NuGet "System.Reactive" & "System.Reacive.Windows.Threading").

Then you can do this after the _displayLogs = new ObservableCollection<string>(); line:

```<code>IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0))
        .Select(_ => GetInfoString())
        .Where(newString => !string.IsNullOrWhiteSpace(newString))
        .DistinctUntilChanged()
        .ObserveOnDispatcher()
        .Subscribe(newString =>
        {
            Debug.WriteLine(newString);
            DisplayLogs.Add(newString);
        });
</code>```

That should call GetInfoString() every second and update your UI. It handles all of the threading and marshalling issues.

If you keep a reference to subscription you can stop it at any stage by calling subscription.Dispose().

ContentLicense: CC BY-SA 3.0

Body:
I have a background thread to listen data, so this infinite loop to output data.

And, I using a ObservableCollection to bind a ListBox and show log.

I try to use Dispather.BeginInvoke, but no use, it not realtime. I have no idea for update UI in MVVM.

xaml

<ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>

code

private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
     get
     {
         return _displayLogs;
     }
}

public Testpro()
{
    _displayLogs = new ObservableCollection<string>();

    Task.Run(new Action(outputData));
}

private void outputData()
{
    string str = "";
    while (true)
    {
        string newString = GetInfoString();

        if (string.IsNullOrWhiteSpace(newString) || str == newString)
            continue;

        str = newString;

        Debug.WriteLine(str);
        Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
        {
                DisplayLogs.Add(str);
        });
    }
}

*Edit:

GetInfoString will call by a dll file.

Body:
You should really use something designed for this kind of update. I'm going to suggest Microsoft's Reactive Framework (NuGet "System.Reactive" & "System.Reacive.Windows.Threading").

Then you can do this after the _displayLogs = new ObservableCollection<string>(); line:

IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0))
        .Select(_ => GetInfoString())
        .Where(newString => !string.IsNullOrWhiteSpace(newString))
        .DistinctUntilChanged()
        .ObserveOnDispatcher()
        .Subscribe(newString =>
        {
            Debug.WriteLine(newString);
            DisplayLogs.Add(newString);
        });

That should call GetInfoString() every second and update your UI. It handles all of the threading and marshalling issues.

If you keep a reference to subscription you can stop it at any stage by calling subscription.Dispose().


问:
Is there a way to convert date which is in string(varchar) in a table to date(Date variable) without deleting data?
I Have stored the date as a string format in my database (EX:01-July-2017)
Is there a way to Change that to proper date format in sql server since I have to use Range eventually

```<code> Create table xus(Date varchar(40) )
 #my input is 01-July-2017
</code>```

I need to use Range operator so I need to convert it into proper date format without deleting data

答:
```<code>-- Add new date column
ALTER TABLE xus
ADD NewDate DATETIME

-- Migrate data
UPDATE xus
SET NewDate = CONVERT( DATETIME, OldDate )
-- If any errors at this stage, you may need to fix them individually for each problematic record.
-- ISDATE function may help with this

-- Drop current date column (which is VARCHAR)
ALTER TABLE xus
DROP COLUMN OldDate

-- Rename New column to be old column enter code here
EXEC sp_RENAME 'xus.NewDate' , 'OldDate', 'COLUMN'
</code>```

Body:
I Have stored the date as a string format in my database (EX:01-July-2017)
Is there a way to Change that to proper date format in sql server since I have to use Range eventually

 Create table xus(Date varchar(40) )
 #my input is 01-July-2017

I need to use Range operator so I need to convert it into proper date format without deleting data


问:
Variable not taking on values in C#
I have the following problem -

```<code>rec = new Record(name, age, dob, sex, country );
webservicename.function[] test = new webservicename.function[1];
test[0].name = rec.name;
test[i].age = rec.age;
test[i].dob = dob;
test[i].sex = sex;
test[i].country = country;
</code>```

When I start debugging it stops on the first test[0] line with a 'NullReferenceException was uhandled' message. When I hover mouse over the rec.Account it shows the value from the csv file that I have read from, however when I hover over test[0] its value is null. For some reason the variable array is not taking on values, How can I sort this?

Thanks for your time.

答:
Try this:</p>

```<code>rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary[] test = new webservicename.singlesummary[1];
webservicename.singlesummary result = new webservicename.singlesummary();
result.account = rec.name;
result.actualy = rec.age;
result.commitment = dob;
result.costCentre = sex;
result.internalCostCentre = country;
test[0] = result;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Variable not taking on values in C#

Body:
I have the following problem -

rec = new Record(name, age, dob, sex, country );
webservicename.function[] test = new webservicename.function[1];
test[0].name = rec.name;
test[i].age = rec.age;
test[i].dob = dob;
test[i].sex = sex;
test[i].country = country;

When I start debugging it stops on the first test[0] line with a 'NullReferenceException was uhandled' message. When I hover mouse over the rec.Account it shows the value from the csv file that I have read from, however when I hover over test[0] its value is null. For some reason the variable array is not taking on values, How can I sort this?

Thanks for your time.

Body:
Try this:

rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary[] test = new webservicename.singlesummary[1];
webservicename.singlesummary result = new webservicename.singlesummary();
result.account = rec.name;
result.actualy = rec.age;
result.commitment = dob;
result.costCentre = sex;
result.internalCostCentre = country;
test[0] = result;


问:
Read property file placed inside in package under src/test/resource in maven
My maven structure looks as below:

Have placed property file inside package under src/test/resources
And I trying to read from java class( Browser Test) under src/test/java

I am using below code to ready file, but the getting NullPointerException.

```<code>public Static Properties CONFIG
CONFIG = new Properties();
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

[31mMessage: [0m[31mjava.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
</code>```

答:
You getting NullPointerException because both BrowserTest.java and application.properties are in different packages.

Either

Move application.properties from com.philips.rs.properties to com.philips.rs.utils and read it directly.

```<code>String filename = "application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);
</code>```

Or change the filename to "/com/philips/rs/properties/application.properties"

```<code>String filename = "/com/philips/rs/properties/application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);
</code>```

Better explaination can find from https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-

Body:
My maven structure looks as below:

Have placed property file inside package under src/test/resources
And I trying to read from java class( Browser Test) under src/test/java

I am using below code to ready file, but the getting NullPointerException.

public Static Properties CONFIG
CONFIG = new Properties();
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

[31mMessage: [0m[31mjava.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)

Body:
You getting NullPointerException because both BrowserTest.java and application.properties are in different packages.

Either

Move application.properties from com.philips.rs.properties to com.philips.rs.utils and read it directly.

String filename = "application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

Or change the filename to "/com/philips/rs/properties/application.properties"

String filename = "/com/philips/rs/properties/application.properties";
InputStream inputStream = BrowserTest.class.getResourceAsStream(filename);
CONFIG.load(inputStream);

Better explaination can find from https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-


问:
Add taxonomy terms list to homepage Drupal 8
Please help me to add taxonomy terms from custom taxonomy into home page. I have no idea how to do this as I'm coming from WordPress. In WordPress it is easy as calling get_terms(). I have following file as my home page: mytheme/templates/page--front.html.twig

I have more than one taxonomy type and all of them are going to queried in the home page.

How to query the taxonomy terms?

UPDATE:

I have created a new region called home_content in my theme.info.yml and I have created a view(block) for getting the taxonomy terms, added it to region in back-end and display it as {{page.home_content}}. It works but I have few questions.

I have fields for logo and text in the taxonomy. I want to list them too.

I need to customize the html. How can I do that?

Thanks for the support.

答:
You don't really need to code anything

Create view with taxonomy terms required. Structure > Views > Create New View and add block view for taxonomy terms. User filter section to select specific terms or dictionaries. Save the view.

Go to Structure > Block Layout and insert block with your view into desired region. In visibility section, pages tab: type <front> in pages and select Show for the listed pages in order to display it on home page only.

Above steps will display your required terms on home page.

To copy and modify template(s) in your theme, follow the instructions on drupal.org: https://www.drupal.org/node/2358785


问:
Reshape array that is stored in a collection and export to CSV
I have a collection of Facebook Page Likes (titled pagelikes) that is stored in a Mongo database/JSON file. Below is an example of one entry.

```<code>{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : [
        {
            "id" : "859302873383",
            "name" : "Hotdogs"
        },
        {
            "id" : "8593683902",
            "name" : "Video Games"
        },
        {
            "id" : "849204859849028",
            "name" : "Road Bikes"
        }
    ]
}
</code>```

id = the unique Facebook Page identifier, name = the name of a Facebook page.

I would like to export this entire collection to a CSV file with three columns, user_id, page_likes.id, page_likes.name. It would look like the following:

```<code>user_id                     page_likes.id     page_likes.name
0939bf9w9804842f9f817ad100  859302873383      Hotdogs
0939bf9w9804842f9f817ad100  8593683902        Video Games
0939bf9w9804842f9f817ad100  849204859849028   Road Bikes
...                         ...               ...
</code>```

The JSON file is quite large (4GB), contains over 120K users, and there is no limit on the number of an entry has.

I have tried and failed with mongoexport, although an aggregation framework seems most useful (possibly the project and unwind functions). That said, I have little experience with Mongo.

Any advice, examples or suggestions would be very helpful.

Many thanks,

R

答:
You can deal with this in a number of ways.

Firstly if you have MongoDB 3.4 available then you could use a "View" in order to represent the collection with the array contents "un-wound". A "View" is basically an aggregation pipeline statement that appears to be a normal collection as far as most actions that would use a collection are concerned.

So presuming your source collection is called "pages" here, then you would create the "View" with:

```<code>db.createView("pageArray", "pages", [{ "$unwind": "$page_likes" }])
</code>```

Then you can query the collection as normal:

```<code>db.pageArray.find()

/* 1 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "859302873383",
        "name" : "Hotdogs"
    }
}

/* 2 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "8593683902",
        "name" : "Video Games"
    }
}

/* 3 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "849204859849028",
        "name" : "Road Bikes"
    }
}
</code>```

And subsequently issue the mongoexport as if it were a normal collection:

```<code>mongoexport -d test -c pageArray --type=csv --fields user_id,page_likes.id,page_likes.name
2017-07-05T13:14:11.588+1000    connected to: localhost
user_id,page_likes.id,page_likes.name
0939bf9w9804842f9f817ad100,859302873383,Hotdogs
0939bf9w9804842f9f817ad100,8593683902,Video Games
0939bf9w9804842f9f817ad100,849204859849028,Road Bikes
2017-07-05T13:14:11.589+1000    exported 3 records
</code>```

Of course adding --out or a standard redirect to actually output to a file.

If your MongoDB is an older version but at least has $out available ( from MongoDB 2.6 ) then write to another collection:

```<code>db.pages.aggregate([
  { "$unwind": "$page_likes" },
  { "$project": { "_id": 0 } },
  { "$out": "pagesArray" }
])
</code>```

Then you basically run the same mongoexport as above since it's also a collection that is accessible to do so.

If you really don't want to create either a "View" or "another collection", then you could simply send a short script to the mongo shell. Albeit in a very hacky way:

```<code>mongo --quiet --eval '
    print("user_id,page_likes.id,page_likes.name");
    db.pages.aggregate([
      { "$unwind": "$page_likes" },
      { "$project": { "_id": 0 } },
    ]).forEach(p => print(`${p.user_id},${p.page_likes.id},${p.page_likes.name}`))'
</code>```

Or even without aggregate() and $unwind at all:

```<code>mongo --quiet --eval '
    print("user_id,page_likes.id,page_likes.name");
    db.pages.find({},{ _id: 0 }).forEach(p =>
       p.page_likes.forEach(l => print(`${p.user_id},${l.id},${l.name}`)))'
</code>```

Which gives you the same output:

```<code>user_id,page_likes.id,page_likes.name
0939bf9w9804842f9f817ad100,859302873383,Hotdogs
0939bf9w9804842f9f817ad100,8593683902,Video Games
0939bf9w9804842f9f817ad100,849204859849028,Road Bikes
</code>```

Note also that if you want or "need" a different delimiter than comma ,here, then either of the two last approaches with the shell is probably the way to go. As this is "scheduled" for addition to mongoexport and mongoimport with TOOLS-87, but of course is "yet to be resolved". So if you want different output, then you do it yourself.

Body:
I have a collection of Facebook Page Likes (titled pagelikes) that is stored in a Mongo database/JSON file. Below is an example of one entry.

{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : [
        {
            "id" : "859302873383",
            "name" : "Hotdogs"
        },
        {
            "id" : "8593683902",
            "name" : "Video Games"
        },
        {
            "id" : "849204859849028",
            "name" : "Road Bikes"
        }
    ]
}

id = the unique Facebook Page identifier, name = the name of a Facebook page.

I would like to export this entire collection to a CSV file with three columns, user_id, page_likes.id, page_likes.name. It would look like the following:

user_id                     page_likes.id     page_likes.name
0939bf9w9804842f9f817ad100  859302873383      Hotdogs
0939bf9w9804842f9f817ad100  8593683902        Video Games
0939bf9w9804842f9f817ad100  849204859849028   Road Bikes
...                         ...               ...

The JSON file is quite large (4GB), contains over 120K users, and there is no limit on the number of an entry has.

I have tried and failed with mongoexport, although an aggregation framework seems most useful (possibly the project and unwind functions). That said, I have little experience with Mongo.

Any advice, examples or suggestions would be very helpful.

Many thanks,

R

Body:
You can deal with this in a number of ways.

Firstly if you have MongoDB 3.4 available then you could use a "View" in order to represent the collection with the array contents "un-wound". A "View" is basically an aggregation pipeline statement that appears to be a normal collection as far as most actions that would use a collection are concerned.

So presuming your source collection is called "pages" here, then you would create the "View" with:

db.createView("pageArray", "pages", [{ "$unwind": "$page_likes" }])

Then you can query the collection as normal:

db.pageArray.find()

/* 1 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "859302873383",
        "name" : "Hotdogs"
    }
}

/* 2 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "8593683902",
        "name" : "Video Games"
    }
}

/* 3 */
{
    "_id" : ObjectId("4725bf8731b8faf4c04595bb"),
    "user_id" : "0939bf9w9804842f9f817ad100",
    "page_likes" : {
        "id" : "849204859849028",
        "name" : "Road Bikes"
    }
}

And subsequently issue the mongoexport as if it were a normal collection:

mongoexport -d test -c pageArray --type=csv --fields user_id,page_likes.id,page_likes.name
2017-07-05T13:14:11.588+1000    connected to: localhost
user_id,page_likes.id,page_likes.name
0939bf9w9804842f9f817ad100,859302873383,Hotdogs
0939bf9w9804842f9f817ad100,8593683902,Video Games
0939bf9w9804842f9f817ad100,849204859849028,Road Bikes
2017-07-05T13:14:11.589+1000    exported 3 records

Of course adding --out or a standard redirect to actually output to a file.

If your MongoDB is an older version but at least has $out available ( from MongoDB 2.6 ) then write to another collection:

db.pages.aggregate([
  { "$unwind": "$page_likes" },
  { "$project": { "_id": 0 } },
  { "$out": "pagesArray" }
])

Then you basically run the same mongoexport as above since it's also a collection that is accessible to do so.

If you really don't want to create either a "View" or "another collection", then you could simply send a short script to the mongo shell. Albeit in a very hacky way:

mongo --quiet --eval '
    print("user_id,page_likes.id,page_likes.name");
    db.pages.aggregate([
      { "$unwind": "$page_likes" },
      { "$project": { "_id": 0 } },
    ]).forEach(p => print(`${p.user_id},${p.page_likes.id},${p.page_likes.name}`))'

Or even without aggregate() and $unwind at all:

mongo --quiet --eval '
    print("user_id,page_likes.id,page_likes.name");
    db.pages.find({},{ _id: 0 }).forEach(p =>
       p.page_likes.forEach(l => print(`${p.user_id},${l.id},${l.name}`)))'

Which gives you the same output:

user_id,page_likes.id,page_likes.name
0939bf9w9804842f9f817ad100,859302873383,Hotdogs
0939bf9w9804842f9f817ad100,8593683902,Video Games
0939bf9w9804842f9f817ad100,849204859849028,Road Bikes

Note also that if you want or "need" a different delimiter than comma ,here, then either of the two last approaches with the shell is probably the way to go. As this is "scheduled" for addition to mongoexport and mongoimport with TOOLS-87, but of course is "yet to be resolved". So if you want different output, then you do it yourself.


问:
Build error for SDL2-2.0.5 in Ubuntu 16.04
```<code>uranus@uranus:~/lib/SDL2-2.0.5$ make
/bin/bash build-scripts/updaterev.sh
    LTLINK build/libSDL2.la
build/.libs/SDL_mirvideo.o: In function 'MIR_InitDisplayFromOutput':
/home/uranus/lib/SDL2-2.0.5/src/video/mir/SDL_mirvideo.c:258: undefined reference to 'mir_output_get_current_mode'
collect2: error: ld returned 1 exit status
Makefile:147: recipe for target 'build/libSDL2.la' failed
make: *** [build/libSDL2.la] Error 1
</code>```

SDL2 Configure Summary:

```<code>Building Shared Libraries
Building Static Libraries
Enabled modules : atomic audio video render events joystick haptic power filesystem threads timers file loadso cpuinfo assembly
Assembly Math   : mmx 3dnow sse sse2
Audio drivers   : disk dummy oss alsa(dynamic) pulse(dynamic) sndio
Video drivers   : dummy x11(dynamic) opengl opengl_es2 mir(dynamic)
X11 libraries   : xcursor xdbe xinerama xinput2 xinput2_multitouch xrandr xscrnsaver xshape xvidmode
Input drivers   : linuxev linuxkd
Using libudev   : YES
Using dbus      : YES
Using ime       : YES
Using ibus      : NO
Using fcitx     : NO
</code>```

答:
The linker needs the name of the library where is this function.

I fixed it, adding in my Makefile file "-lmirclient".

```<code># diff  Makefile Makefile-ORG
26c26
< EXTRA_LDFLAGS =  -Wl,--no-undefined -lm -ldl  -lasound -lm -ldl -lpthread -lsndio  -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt -lmirclient
---
> EXTRA_LDFLAGS =  -Wl,--no-undefined -lm -ldl  -lasound -lm -ldl -lpthread -lsndio  -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt
#
</code>```

Body:
uranus@uranus:~/lib/SDL2-2.0.5$ make
/bin/bash build-scripts/updaterev.sh
    LTLINK build/libSDL2.la
build/.libs/SDL_mirvideo.o: In function 'MIR_InitDisplayFromOutput':
/home/uranus/lib/SDL2-2.0.5/src/video/mir/SDL_mirvideo.c:258: undefined reference to 'mir_output_get_current_mode'
collect2: error: ld returned 1 exit status
Makefile:147: recipe for target 'build/libSDL2.la' failed
make: *** [build/libSDL2.la] Error 1

SDL2 Configure Summary:

Building Shared Libraries
Building Static Libraries
Enabled modules : atomic audio video render events joystick haptic power filesystem threads timers file loadso cpuinfo assembly
Assembly Math   : mmx 3dnow sse sse2
Audio drivers   : disk dummy oss alsa(dynamic) pulse(dynamic) sndio
Video drivers   : dummy x11(dynamic) opengl opengl_es2 mir(dynamic)
X11 libraries   : xcursor xdbe xinerama xinput2 xinput2_multitouch xrandr xscrnsaver xshape xvidmode
Input drivers   : linuxev linuxkd
Using libudev   : YES
Using dbus      : YES
Using ime       : YES
Using ibus      : NO
Using fcitx     : NO

Body:
The linker needs the name of the library where is this function.

I fixed it, adding in my Makefile file "-lmirclient".

# diff  Makefile Makefile-ORG
26c26
< EXTRA_LDFLAGS =  -Wl,--no-undefined -lm -ldl  -lasound -lm -ldl -lpthread -lsndio  -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt -lmirclient
---
> EXTRA_LDFLAGS =  -Wl,--no-undefined -lm -ldl  -lasound -lm -ldl -lpthread -lsndio  -lX11 -lXext -lXcursor -lXinerama -lXi -lXrandr -lXss -lXxf86vm -lpthread -lrt
#


问:
Form not displaying "required" dialog in Angular 2
I am new to Angular 2. So, I have this form where I created with Angular 2, and bootstrap. So, when you click on the text field and move the mouse else where, the box turns red (which is good). But, when they click on submit button, it when the form is empty, it won't show the "required" dialog. So, please check my code of what I did wrong. Thank you!
I want to show this when they click on a empty form:

Here is the code.

```<code>    <div class="col-md-8 col-md-offset-2">
    <form (ngSubmit)="onSubmit(form)" #form="ngForm">
        <div class="form-group">
            <label for="content">Content</label>
            <input type="text"
                   id="content"
                   class="form-control"
                   ngModel
                   name="content"
                   required>

        </div>

        <button class="btn btn-primary" type="submit">Save</button>
    </form>
</div>
</code>```

Second Part:(TypeScript)

```<code>    import { Component } from "@angular/core";
import {MessageService} from "./message.service";
import {Message} from "./message.model";
import {NgForm} from "@angular/forms";

@Component({

selector: 'app-message-input',
    templateUrl: './message-input.component.html'

})

export class MessageInputComponent {

    constructor(private messageService: MessageService) {}

      onSubmit(form: NgForm) {

   const message = new Message(form.value.content, 'John');

     this.messageService.addMessage(message);
     form.resetForm();

}

}
</code>```

答:
I fixed my answer by enabling the default HTML validation. Becuase for some reason in Angular, the default HTML validation is disabled by Angular. So, I enabled it by doing:

```<code><div class="col-md-8 col-md-offset-2">
<form ngNativeValidate (ngSubmit)="onSubmit(f)" #f="ngForm">
    <div class="form-group">
        <label for="content">Content</label>
        <input
                type="text"
                id="content"
                class="form-control"
                ngModel
                name="content"
                required>
    </div>
    <button class="btn btn-primary" type="submit">Save</button>
</form>
</code>```

I just add ngNativeValidate in my form tags.

Body:
I am new to Angular 2. So, I have this form where I created with Angular 2, and bootstrap. So, when you click on the text field and move the mouse else where, the box turns red (which is good). But, when they click on submit button, it when the form is empty, it won't show the "required" dialog. So, please check my code of what I did wrong. Thank you!
I want to show this when they click on a empty form:

Here is the code.

    <form (ngSubmit)="onSubmit(form)" #form="ngForm">

            Content
            <input type="text"
                   id="content"
                   class="form-control"
                   ngModel
                   name="content"
                   required>

        <button class="btn btn-primary" type="submit">Save</button>
    </form>

Second Part:(TypeScript)

    import { Component } from "@angular/core";
import {MessageService} from "./message.service";
import {Message} from "./message.model";
import {NgForm} from "@angular/forms";

@Component({

selector: 'app-message-input',
    templateUrl: './message-input.component.html'

})

export class MessageInputComponent {

    constructor(private messageService: MessageService) {}

      onSubmit(form: NgForm) {

   const message = new Message(form.value.content, 'John');

     this.messageService.addMessage(message);
     form.resetForm();

}

}

Body:
I fixed my answer by enabling the default HTML validation. Becuase for some reason in Angular, the default HTML validation is disabled by Angular. So, I enabled it by doing:

<div class="col-md-8 col-md-offset-2">
<form ngNativeValidate (ngSubmit)="onSubmit(f)" #f="ngForm">
    <div class="form-group">
        <label for="content">Content</label>
        <input
                type="text"
                id="content"
                class="form-control"
                ngModel
                name="content"
                required>
    </div>
    <button class="btn btn-primary" type="submit">Save</button>
</form>

I just add ngNativeValidate in my form tags.


问:
Easiest way to deploy a Rails 3 app?
I finished my first ruby on rails application and I would like to put it up online.
What is the easiest way to go about doing this?</p>

答: You should try to use http://heroku.com/ they are by far one of the easiest ways to have an app running online in 5 mins.</p>

Title: Easiest way to deploy a Rails 3 app?


问:
Unable to use XPath to select input element based on content
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));
</code>```

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));
</code>```

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

```<code><input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">
</code>```

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

答:
You can rewrite the wait as something like

```<code> (new WebDriverWait(driver, TimeSpan.FromSeconds(timeout))).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.findElement("//input[@id='DP_NUMBER']").getText().length() != 0;
        }
    });
</code>```

I have taken this from selenium docs

Body:
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

<input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

Body:
You can rewrite the wait as something like

 (new WebDriverWait(driver, TimeSpan.FromSeconds(timeout))).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.findElement("//input[@id='DP_NUMBER']").getText().length() != 0;
        }
    });

I have taken this from selenium docs


答:
You need to initialize the instance first:

```<code>rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary[] test = new webservicename.singlesummary[1];
test[0] = new webservicename.singlesummary(); // extra line for your code
test[0].name= rec.name;
test[0].age = rec.age;
test[0].dob = dob;
test[0].sex = sex;
test[0].country = country;
</code>```

Obvously, if you need an array and you have length greater than one, you could replace all but lines one and two above inside a for...next loop and index to the ith element.

I notice though, that you're indexing into the array with [0] (and creating an array of length 1) which seems pointless to me, you might as well use a single instance:

```<code>rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary test = new webservicename.singlesummary();
test.name= rec.name;
test.age = rec.age;
test.dob = dob;
test.sex = sex;
test.country = country;
</code>```

If the reason you're using an array of length one is because the service you call only accepts an array/list of items, you can always create one during the call:

```<code>wbsvcProxy.MethodCall(new List<singlesummary>() { test });
</code>```

In my opinion, this is more readable throughout your code, since you only build the array/list when you're calling the method and removes all of the funky [0]. syntax from the rest of your code (If your method doesn't require it, then never mind this last bit)

Title: Variable not taking on values in C#

Body:
You need to initialize the instance first:

rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary[] test = new webservicename.singlesummary[1];
test[0] = new webservicename.singlesummary(); // extra line for your code
test[0].name= rec.name;
test[0].age = rec.age;
test[0].dob = dob;
test[0].sex = sex;
test[0].country = country;

Obvously, if you need an array and you have length greater than one, you could replace all but lines one and two above inside a for...next loop and index to the ith element.

I notice though, that you're indexing into the array with [0] (and creating an array of length 1) which seems pointless to me, you might as well use a single instance:

rec = new Record(name, age, dob, sex, country );
webservicename.singlesummary test = new webservicename.singlesummary();
test.name= rec.name;
test.age = rec.age;
test.dob = dob;
test.sex = sex;
test.country = country;

If the reason you're using an array of length one is because the service you call only accepts an array/list of items, you can always create one during the call:

wbsvcProxy.MethodCall(new List<singlesummary>() { test });

In my opinion, this is more readable throughout your code, since you only build the array/list when you're calling the method and removes all of the funky [0]. syntax from the rest of your code (If your method doesn't require it, then never mind this last bit)


问:
Rewrite to other server
I have application hosted in tomcat under port 8050; mydomain:8050. Now, I want to have friendly url, say mydomain.com to be used to access mydomain:8050 without the client seeing the port number in the URL. Client should always see mydomain.com that should be internally resolved to mydomain:8050.

I have IIS server running on port 80. I created a site in it just to use rewrite option that can resolve to mydomain:8050. It didn't work with the pattern I used

Pattern: ((?:[^\/\n]|\/\/)+)(.*)
Rewrite URL: {R:1}:8050{R:2}

Then I installed apache http server on port 90. Used redirection in IIS site to redirect the URL to mydomain:90$S$Q and then used rewrite in Apache to internally redirect it to mydomain:8050. This works when I have a query string in it, like mydomain.com/queryString, but doesn't work if I type just mydomain.com. I can see it redirecting to mydomain:90 and stops there without any rewrite rules being executed. This also changes the URL to mydomain:90 and is visible to client.

My requirement is that when user enters mydomain.com it should internally resolve to mydomain:8050 (with query string if any) without client seeing it. I have IIS running at port 80 and apache running on port 90. How can I achieve this? I am sure this can be handled in rewrite rule of IIS, but I am not sure how to do that.

答:
Rewriting to another server is basically proxying. What we need is a
  reverse proxy setup in IIS which basically proxy all your requests
  from http://example.com to to http://example:8050/(or better
  http://localhost:8050)

Make sure you have ARR module installed on IIS

Create a reverse proxy rule like this

```<code><rule name="ReverseProxyInboundRule1" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
    <add input="{CACHE_URL}" pattern="^(https?)://" />
   </conditions>
   <action type="Rewrite" url="{C:1}://mydomain:8050/{R:1}" />
</rule>
</code>```

Please note that since both Apcahe and IIS are in the same server,you can use localhost:8050 as backend proxy.

EDIT:

Also if you have any redirect coming back from the backend proxy and you do not want to redirect the Location header coming ,You can do that by unchecking "Reverse rewritehost in response headers" in Application Request Routing

Select the server node in IIS manager

Go to Application Request routing Cache

Click on Server proxy Settings

UnCheck "Reverse rewritehost in response headers"

Title: Rewrite to other server

Body:
Rewriting to another server is basically proxying. What we need is a
  reverse proxy setup in IIS which basically proxy all your requests
  from http://example.com to to http://example:8050/(or better
  http://localhost:8050)

Make sure you have ARR module installed on IIS

Create a reverse proxy rule like this

<rule name="ReverseProxyInboundRule1" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
    <add input="{CACHE_URL}" pattern="^(https?)://" />
   </conditions>
   <action type="Rewrite" url="{C:1}://mydomain:8050/{R:1}" />
</rule>

Please note that since both Apcahe and IIS are in the same server,you can use localhost:8050 as backend proxy.

EDIT:

Also if you have any redirect coming back from the backend proxy and you do not want to redirect the Location header coming ,You can do that by unchecking "Reverse rewritehost in response headers" in Application Request Routing

Select the server node in IIS manager

Go to Application Request routing Cache

Click on Server proxy Settings

UnCheck "Reverse rewritehost in response headers"


问:
GDX Pay IOS Error while testing
I've tried to implement GDX Pay for IOS for the application I am building.
I am using GDXPay 0.7.0 and GDX Version 1.7.1

I have signed out of the appstore in the settings and created user ids in sandbox environment on the itunesconnect to sign in when prompted for IAP.

However, the application crashes at the time of calling installIAP() without giving me a sign in prompt. The sign in prompt however does appear after the application crashes.

Would appreciate any help in this regards. Thanks in advance.

2016-01-04 15:24:30.810 IOSLauncher[3511:1011291] [info] IAP: IAP:
  gdx-pay successfully instantiated. [GdxPay/AppleIOS] Installing
  purchase observer...

[GdxPay/AppleIOS] Requesting products...

2016-01-04 15:24:30.864 IOSLauncher[3511:1011291] [debug]
  IOSApplication: resumed

[GdxPay/AppleIOS] Products successfully received!

[GdxPay/AppleIOS] Purchase observer successfully installed!

[GdxPay/AppleIOS] There are 0 unfinished transactions. Try to
  finish...

WARN: Failed to call getClassDomain() for the NSError subclass
  org.robovm.apple.foundation.NSCocoaError

WARN: Failed to call getClassDomain() for the NSError subclass
  org.robovm.apple.storekit.SKError

[GdxPay/AppleIOS] Transaction failed: Error Domain=SSServerErrorDomain
  Code=0 "You are not authorized to make purchases of this InApp in
  Sandbox at this time." UserInfo={NSLocalizedDescription=You are not
  authorized to make purchases of this InApp in Sandbox at this time.}

com.badlogic.gdx.utils.GdxRuntimeException:
  java.lang.RuntimeException: Transaction failed: Error
  Domain=SSServerErrorDomain Code=0 "You are not authorized to make
  purchases of this InApp in Sandbox at this time."
  UserInfo={NSLocalizedDescription=You are not authorized to make
  purchases of this InApp in Sandbox at this time.}      at
  com.vxxxxxxs.pxxxxxxxg.app.PxxxxLxxxg$1.handlePurchaseError(PxxxxxLxxxxg.java:70)
     at
  com.badlogic.gdx.pay.ios.apple.PurchaseManageriOSApple$AppleTransactionObserver.updatedTransactions(PurchaseManageriOSApple.java:392)
     at
  com.badlogic.gdx.pay.ios.apple.PurchaseManageriOSApple$AppleTransactionObserver.$cb$paymentQueue$updatedTransactions$(PurchaseManageriOSApple.java)
     at org.robovm.apple.uikit.UIApplication.main(Native Method)     at
  org.robovm.apple.uikit.UIApplication.main(UIApplication.java:395)      at
  com.vxxxxxs.pxxxxxxxxg.app.IOSLauncher.main(IOSLauncher.java:42)

Caused by: java.lang.RuntimeException: Transaction failed: Error
  Domain=SSServerErrorDomain Code=0 "You are not authorized to make
  purchases of this InApp in Sandbox at this time."
  UserInfo={NSLocalizedDescription=You are not authorized to make
  purchases of this InApp in Sandbox at this time.}     ... 5 more

答: Make sure your sandbox account is still valid in iTunes. I got this error once when I try to use a deleted sandbox account to purchase.

Title: GDX Pay IOS Error while testing


问:
Broadcast receiver for checking internet connection in android app
I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.

This is the broadcast receiver

```<code>public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something

            Log.d("Network Available ", "Flag No 1");
        }
    }
}
</code>```

This is the manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiverforinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

答:
CONNECTIVITY_ACTION docs:

Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

Body:
I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.

This is the broadcast receiver

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something

            Log.d("Network Available ", "Flag No 1");
        }
    }
}

This is the manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiverforinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


问:
Moving all nodes the same time including links?
in D3.js I use the force-layout to shift all nodes to the right with this code below. But when call the function, only the nodes shift, the text and links stay the same. What exactly is missing here? Is it the tick() function that has to be called inside the function?</p>

```<code>  function(){ d3.select(".nodes").attr("transform", "translate(200,0)");

                simulation.alpha(0.8).restart();

};

        simulation
                    .nodes(nodes)
                    .on("tick", function(d)
                    {

                      link
                        .attr("x1", function(d) { return d.source.x; })
                        .attr("y1", function(d) { return d.source.y; })
                        .attr("x2", function(d) { return d.target.x; })
                        .attr("y2", function(d) { return d.target.y; });

                      node
                        .attr("cx", function(d) { return d.x; })
                        .attr("cy", function(d) { return d.y; });

                     text
                        .attr("x", function(d) { return d.x; })
                        .attr("y", function(d) { return d.y; });

                    }

                    );

                simulation.force("link")
                    .links(links);

              });
</code>```

答:
As @TomShanley said in his answer, you are only translating the containing <g> elements.

Don't do that. The idiomatic way to move the nodes for a fixed position is setting fx and fy or, alternatively, using forceY and forceY (both in D3 v4).

This is a demo using forceX. First, we remove the center force, then we set forceX to a position at the right:

```<code>simulation.force("center", null)
simulation.force("toRight", d3.forceX(360).strength(0.8))
</code>```

Here is the demo, click the button to move the nodes, links and texts:

var width = 400;
var height = 300;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var nodes = [{
  name: "foo",
  color: "blue"
}, {
  name: "bar",
  color: "green"
}, {
  name: "baz",
  color: "red"
}, {
  name: "foofoo",
  color: "yellow"
}, {
  name: "foobar",
  color: "blue"
}, {
  name: "foobaz",
  color: "green"
}, {
  name: "barfoo",
  color: "red"
}, {
  name: "barbar",
  color: "yellow"
}, {
  name: "barbaz",
  color: "blue"
}];

var links = [{
  "source": 0,
  "target": 1
}, {
  "source": 0,
  "target": 2
}, {
  "source": 0,
  "target": 3
}, {
  "source": 1,
  "target": 3
}, {
  "source": 1,
  "target": 4
}, {
  "source": 2,
  "target": 5
}, {
  "source": 3,
  "target": 6
}, {
  "source": 1,
  "target": 7
}, {
  "source": 6,
  "target": 8
}, {
  "source": 0,
  "target": 7
}, {
  "source": 2,
  "target": 6
}, {
  "source": 3,
  "target": 8
}];

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink())
  .force("charge", d3.forceManyBody().strength(-50))
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("collide", d3.forceCollide(function(d) {
    return d.r + 1;
  }));

var link = svg.selectAll(null)
  .data(links)
  .enter()
  .append("line")
  .style("stroke", "#ccc")
  .style("stroke-width", 1);

var node = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("circle")
  .attr("r", function(d) {
    return d.r = 10;
  })
  .attr("stroke", "gray")
  .attr("stroke-width", "2px")
  .attr("fill", function(d) {
    return d.color
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));;

var text = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("text")
  .attr("pointer-events", "none")
  .style("fill", "black")
  .attr("dy", "-1em")
  .attr("dx", "-1em")
  .text(function(d) {
    return d.name;
  });

simulation.nodes(nodes);
simulation.force("link")
  .links(links);

simulation.on("tick", function() {

  link.attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    })

  node.attr("cx", function(d) {
    return d.x
  }).attr("cy", function(d) {
    return d.y
  });

  text.attr("x", function(d) {
    return d.x
  }).attr("y", function(d) {
    return d.y
  });

});

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

d3.select("button").on("click", function(d) {
  simulation.force("center", null)
  simulation.force("toRight", d3.forceX(360).strength(0.8))
  simulation.alpha(0.8).restart();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script>
<button>Click me</button>
<br></code>```

Body:
in D3.js I use the force-layout to shift all nodes to the right with this code below. But when call the function, only the nodes shift, the text and links stay the same. What exactly is missing here? Is it the tick() function that has to be called inside the function?

  function(){ d3.select(".nodes").attr("transform", "translate(200,0)");

                simulation.alpha(0.8).restart();

};

        simulation
                    .nodes(nodes)
                    .on("tick", function(d)
                    {

                      link
                        .attr("x1", function(d) { return d.source.x; })
                        .attr("y1", function(d) { return d.source.y; })
                        .attr("x2", function(d) { return d.target.x; })
                        .attr("y2", function(d) { return d.target.y; });

                      node
                        .attr("cx", function(d) { return d.x; })
                        .attr("cy", function(d) { return d.y; });

                     text
                        .attr("x", function(d) { return d.x; })
                        .attr("y", function(d) { return d.y; });

                    }

                    );

                simulation.force("link")
                    .links(links);

              });

Body:
As @TomShanley said in his answer, you are only translating the containing <g> elements.

Don't do that. The idiomatic way to move the nodes for a fixed position is setting fx and fy or, alternatively, using forceY and forceY (both in D3 v4).

This is a demo using forceX. First, we remove the center force, then we set forceX to a position at the right:

simulation.force("center", null)
simulation.force("toRight", d3.forceX(360).strength(0.8))

Here is the demo, click the button to move the nodes, links and texts:

var width = 400;
var height = 300;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var nodes = [{
  name: "foo",
  color: "blue"
}, {
  name: "bar",
  color: "green"
}, {
  name: "baz",
  color: "red"
}, {
  name: "foofoo",
  color: "yellow"
}, {
  name: "foobar",
  color: "blue"
}, {
  name: "foobaz",
  color: "green"
}, {
  name: "barfoo",
  color: "red"
}, {
  name: "barbar",
  color: "yellow"
}, {
  name: "barbaz",
  color: "blue"
}];

var links = [{
  "source": 0,
  "target": 1
}, {
  "source": 0,
  "target": 2
}, {
  "source": 0,
  "target": 3
}, {
  "source": 1,
  "target": 3
}, {
  "source": 1,
  "target": 4
}, {
  "source": 2,
  "target": 5
}, {
  "source": 3,
  "target": 6
}, {
  "source": 1,
  "target": 7
}, {
  "source": 6,
  "target": 8
}, {
  "source": 0,
  "target": 7
}, {
  "source": 2,
  "target": 6
}, {
  "source": 3,
  "target": 8
}];

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink())
  .force("charge", d3.forceManyBody().strength(-50))
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("collide", d3.forceCollide(function(d) {
    return d.r + 1;
  }));

var link = svg.selectAll(null)
  .data(links)
  .enter()
  .append("line")
  .style("stroke", "#ccc")
  .style("stroke-width", 1);

var node = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("circle")
  .attr("r", function(d) {
    return d.r = 10;
  })
  .attr("stroke", "gray")
  .attr("stroke-width", "2px")
  .attr("fill", function(d) {
    return d.color
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));;

var text = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("text")
  .attr("pointer-events", "none")
  .style("fill", "black")
  .attr("dy", "-1em")
  .attr("dx", "-1em")
  .text(function(d) {
    return d.name;
  });

simulation.nodes(nodes);
simulation.force("link")
  .links(links);

simulation.on("tick", function() {

  link.attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    })

  node.attr("cx", function(d) {
    return d.x
  }).attr("cy", function(d) {
    return d.y
  });

  text.attr("x", function(d) {
    return d.x
  }).attr("y", function(d) {
    return d.y
  });

});

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

d3.select("button").on("click", function(d) {
  simulation.force("center", null)
  simulation.force("toRight", d3.forceX(360).strength(0.8))
  simulation.alpha(0.8).restart();
})

<script src="https://d3js.org/d3.v4.js"></script>
<button>Click me</button>
<br>


问:
How to Install PHP IMAP Extension on AWS Elastic Beanstalk Using Configuration Files (.ebextensions)?
Does anyone know how to install and enable PHP IMAP Extension on AWS Elastic Beanstalk using configuration files (.ebextensions)?

I'm using 64bit Amazon Linux 2017.03 v2.4.0 running PHP 7.0.16

I've tried several ways as follow:

1st Way
I've tried using files in configuration file but it doesn't work, the configuration filename is phpini.config in .ebextensions directory with below setup:

```<code>files:
  "/etc/php.d/phpimap.ini":
    mode: "000755"
    owner: root
    group: root
    content: |
      extension=imap.so
</code>```

The additional .ini files parsed into phpinfo() by displaying /etc/php-7.0.d/phpimap.ini but the IMAP won't installed.

2nd Way
Using container_command to install php-imap but i'm getting error.

```<code>container_commands:
  install_php_imap:
    command: yum install php55-imap
</code>```

Error as image below:

3rd Way
Using combined commands & files, it is only success installing IMAP and the dependencies (php common) but it doesn't activate the IMAP

a. Create installdependencies.config in my .ebextensions by adding bellow script:

```<code>commands:
  install_phpcommon:
    test: '[ ! -f /etc/php.d/curl.ini ] && echo "php common not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-common-7.0.16-1.w6.x86_64.rpm
</code>```

b. Create phpini.config in my .ebextensions by adding bellow script:

```<code>commands:
  install_phpimap:
    test: '[ ! -f /etc/php.d/imap.ini ] && echo "php imap not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-imap-7.0.16-1.w6.x86_64.rpm

files:
  "/etc/php.d/imap.ini":
    mode: "000755"
    owner: root
    group: root
    content: |
      extension=imap.so
</code>```

4th Way I'm testing by adding upload_max_filesize, post_max_size and extension=imap.so to zzzphp.ini and only two values are included that are upload_max_filesize and post_max_size. The extension=imap.so not included into zzzphp.ini file.

Below are the script phpini.config in .ebextensions:

```<code>commands:
  install_phpimap:
    test: '[ ! -f /etc/php.d/imap.ini ] && echo "php imap not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-imap-7.0.16-1.w6.x86_64.rpm

files:
  "/etc/php.d/zzzphp.ini":
    mode: "644"
    content: |
      upload_max_filesize = 50M
      post_max_size = 58M
      extension=imap.so
</code>```

Any suggestions?

Thanks in advance.

答:
You’re including the php-imap extension in php’s configuration file, but that’s not sufficient to install it.

You’re going to have to pass something to your EBS provisioning method of choice telling it to install php-imap (or whatever it’s called in that environment) at the system level.

Body:
Does anyone know how to install and enable PHP IMAP Extension on AWS Elastic Beanstalk using configuration files (.ebextensions)?

I'm using 64bit Amazon Linux 2017.03 v2.4.0 running PHP 7.0.16

I've tried several ways as follow:

1st Way
I've tried using files in configuration file but it doesn't work, the configuration filename is phpini.config in .ebextensions directory with below setup:

files:
  "/etc/php.d/phpimap.ini":
    mode: "000755"
    owner: root
    group: root
    content: |
      extension=imap.so

The additional .ini files parsed into phpinfo() by displaying /etc/php-7.0.d/phpimap.ini but the IMAP won't installed.

2nd Way
Using container_command to install php-imap but i'm getting error.

container_commands:
  install_php_imap:
    command: yum install php55-imap

Error as image below:

3rd Way
Using combined commands & files, it is only success installing IMAP and the dependencies (php common) but it doesn't activate the IMAP

a. Create installdependencies.config in my .ebextensions by adding bellow script:

commands:
  install_phpcommon:
    test: '[ ! -f /etc/php.d/curl.ini ] && echo "php common not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-common-7.0.16-1.w6.x86_64.rpm

b. Create phpini.config in my .ebextensions by adding bellow script:

commands:
  install_phpimap:
    test: '[ ! -f /etc/php.d/imap.ini ] && echo "php imap not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-imap-7.0.16-1.w6.x86_64.rpm

files:
  "/etc/php.d/imap.ini":
    mode: "000755"
    owner: root
    group: root
    content: |
      extension=imap.so

4th Way I'm testing by adding upload_max_filesize, post_max_size and extension=imap.so to zzzphp.ini and only two values are included that are upload_max_filesize and post_max_size. The extension=imap.so not included into zzzphp.ini file.

Below are the script phpini.config in .ebextensions:

commands:
  install_phpimap:
    test: '[ ! -f /etc/php.d/imap.ini ] && echo "php imap not installed"'
    command:
      yum -y install https://archipelagointernational.s3.amazonaws.com/libs/php70w-imap-7.0.16-1.w6.x86_64.rpm

files:
  "/etc/php.d/zzzphp.ini":
    mode: "644"
    content: |
      upload_max_filesize = 50M
      post_max_size = 58M
      extension=imap.so

Any suggestions?

Thanks in advance.


问:
Setting up Python on Windows/ Apache?
I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed mod_python and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found, or a forbidden, or module not found errors when accessing http://localhost/myfolder/index.py). I can get mod_python.publisher to work but do I "want" this/ need this?

Can anyone help?

Thanks!

答:
AddHandler mod_python .py

Have you set 'PythonHandler'?

These days, consider using WSGI instead of native mod-python interfaces for more wide-ranging deployment options. Either through mod-python's WSGI support, or, maybe better, mod-wsgi. (CGI via eg. wsgiref will also work fine and is easy to get set up on a development environment where you don't care about its rubbish performance.)

OwnerDisplayName: Philipp Lenssen

Title: Setting up Python on Windows/ Apache?

OwnerDisplayName: bobince


问:
Is Autofac ContainerBuilder.Build an expensive operation?
I'm starting to use Autofac and I can't seem to find an answer to this question.

Also, when should I call ContainerBuilder.Build() ?

After I call the ContainerBuilder.Build() is it possible to register another type or instance?

答:
I can't tell you whether or not the Build method is expensive or not, but if you follow the Register Resolve Release pattern it doesn't matter because you should only have a single container instance per application.

You need to invoke the Build method once to get a container instance, so no matter how expensive (or not) it is, this is a cost you must pay. However, when you only use a single instance of the container, you only pay that cost once.


问:
C++ much faster than Bash script writing to text file
I wanted to test the performance of writing to a file in a bash script vs a C++ program.

Here is the bash script:

```<code>#!/bin/bash

while true; do
        echo "something" >> bash.txt
done
</code>```

This added about 2-3 KB to the text file per second.

Here is the C++ code:

```<code>#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}
</code>```

This created a ~6 GB text file in less than 10 seconds.

What makes this C++ code so much faster, and/or this bash script so much slower?

答:
As others have already pointed out, this is because you are currently opening and closing the file with each line you write in your script (and shell scripts are interpreted while C++ is compiled). You might batch the writes instead and write once, for example

```<code>MSG="something"
logfile="test.txt"
(
for i in {1..10000}; do
        echo $MSG
done
) >> $logfile
</code>```

Which will write the message 10k times but only open the log once.

Body:
I wanted to test the performance of writing to a file in a bash script vs a C++ program.

Here is the bash script:

#!/bin/bash

while true; do
        echo "something" >> bash.txt
done

This added about 2-3 KB to the text file per second.

Here is the C++ code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}

This created a ~6 GB text file in less than 10 seconds.

What makes this C++ code so much faster, and/or this bash script so much slower?

Body:
As others have already pointed out, this is because you are currently opening and closing the file with each line you write in your script (and shell scripts are interpreted while C++ is compiled). You might batch the writes instead and write once, for example

MSG="something"
logfile="test.txt"
(
for i in {1..10000}; do
        echo $MSG
done
) >> $logfile

Which will write the message 10k times but only open the log once.


问:
Deploy ServiceBus with multiple Topics and Queues at once
I'm fairly new to using the servicebus and other Azure features. After creating a servicebus manually on the Azure portal, I try to figure out how this can be achieved automatically. After a while of reading I thought that using the azure resource manager should be the way to go. Deploying just one topic is no big deal. But I can't find an example, that shows how to deploy multiple topics and queues at once. Or am I on the wrong approach?

Thanks for your answers!
Helmut

答:
Using the new azure portal (here), there is an Automation script feature.

I've created a new resource group with a service bus namespace that contains 2 topics and 1 queue:

You can see on the left panel, there is an Automation script feature.

In this section, you can find a template that represents the resources that you've created manually. you can then use this template to automate your deployment to others environment.

See also Deploy resources with Resource Manager templates and Azure PowerShell


问:
VBA/Excel - cells not recognised as blank until I select and press enter
I have a macro which generates an output sheet to drop into a purpose-built (in C#) application for processing sheets of this type.

Essentially, the code copies one of the sheets from the master sheet and then saves it using a user-generated reference.  It then copies and pastes all of the cells in the sheet as values.

Very frustratingly, in two of the columns in the output sheets, the cells with numbers in them are interspersed with supposedly non-blank cells which do not contain any characters or spaces (and are formatted as "general").  When I use an "IsBlank" formula, these return "FALSE".  However, if I manually click on the cells in question and press "enter", these suddenly return a "TRUE" value.

I am considering getting the macro to select every cell in these columns one by one to resolve this, but that seems criminally inefficient.

Is there a better solution to this problem?

答:
What you might be experiencing are zero length strings.
It may have been the result of a formula which evaluates to "" (e.g. ="") and then copied and pasted as values.

As I understand, you are using macro. If that is the case, you use AutoFilter method of Range Object to get all non-blank cells. Something like:

```<code>Dim r as Range
Set r = Sheet1.Range("Your Range") '/* from your master sheet */

'/* Filter all non-blanks */
'/* First argument 1 depends on the column you want filtered */
'/* For this example it is column 1 of your range */
r.AutoFilter 1, "<>"
r.SpecialCells(xlCellTypeVisible).Copy
Sheet2.Range("Your Destination").PasteSpecial xlPasteValues
</code>```

Hope this helps.

Body:
What you might be experiencing are zero length strings.
It may have been the result of a formula which evaluates to "" (e.g. ="") and then copied and pasted as values.

As I understand, you are using macro. If that is the case, you use AutoFilter method of Range Object to get all non-blank cells. Something like:

Dim r as Range
Set r = Sheet1.Range("Your Range") '/* from your master sheet */

'/* Filter all non-blanks */
'/* First argument 1 depends on the column you want filtered */
'/* For this example it is column 1 of your range */
r.AutoFilter 1, "<>"
r.SpecialCells(xlCellTypeVisible).Copy
Sheet2.Range("Your Destination").PasteSpecial xlPasteValues

Hope this helps.


问:
Bug in python code preventing successful recursion?
I have been working on a script to ingest a file (accounts.txt) which contains email addresses, for which each will then be verified against an API to see if they appear in a data dump.  The script appears to work, however there is a bug present whereby once it finds a positive hit, it will disregard any other match...

For example;
If my "accounts.txt" file contains the following entries:

```<code>a@a.com
b@b.com
</code>```

Even though both of those should return results, as soon as the script is run, the match on a@a.com will be found however b@b.com will not return anything.

I cannot seem to figure out why this is happening, ideally I want all of the hits outputted.

FYI, the script is querying 'haveibeenpwned' which is a site that locates email addresses found in credential dumps.

Any help finding my bug would be greatly appreciated.  Below is my current script.

```<code>#!/usr/bin/env python

import argparse
import json
import requests
import time

breaches_by_date = {}
breaches_by_account = {}
breaches_by_name = {}

class Breach(object):
    def __init__(self, e, n, d):
        self.email = e
        self.name = n
        self.date = d

    def __repr__(self):
        return "%s: %s breached on %s" % (self.email, self.name, self.date)

def accCheck(acc):
    global breaches_by_date, breaches_by_account, breaches_by_name
    r = requests.get('https://haveibeenpwned.com/api/v2/breachedaccount/%s?truncateResponse=false' % acc)
    try:
        data = json.loads(r.text)
    except ValueError:
        print("No breach information for %s" % acc)
        return
    for i in data:
        name, date = (i['Name'], i['BreachDate'])
        breach = Breach(acc, name, date)
        try: breaches_by_account[acc].append(breach)
        except: breaches_by_account[acc] = [breach]
        try: breaches_by_name[name].append(breach)
        except: breaches_by_name[name] = [breach]
        try: breaches_by_date[date].append(breach)
        except: breaches_by_date[date] = [breach]

def readFromFile(fname="accounts.txt"):
    accounts=[]
    with open(fname, "r+") as f:
        accounts = [l.strip() for l in f.readlines()]
    return accounts

if __name__ == '__main__':
    accounts = readFromFile()
    for email_addr in accounts:
        accCheck(email_addr)
    print
    print("Breaches by date")
    for date, breaches in breaches_by_date.items():
        for breach in breaches:
            print(breach)
        print

    print("Breaches by account")
    for acc, breaches in breaches_by_account.items():
        print(acc)
        for breach in breaches:
            print("%s breached on %s" % (breach.name, breach.date))
        print

    print("Breaches by name")
    for name, breaches in breaches_by_name.items():
        print("%s breached for the following accounts:" % name)
        for breach in breaches:
            print("%s on %s" % (breach.email, breach.date))
        print
</code>```

答:
I am not 100% sure to know where your problem comes from, but I would opt for a code like:</p>

```<code>emails_to_check = open("/path/to/yourfile").read().split("\n")
for email in emails_to_check:
 if is_email_blacklisted(email):
  do_something()
</code>```

Body:
I have been working on a script to ingest a file (accounts.txt) which contains email addresses, for which each will then be verified against an API to see if they appear in a data dump.  The script appears to work, however there is a bug present whereby once it finds a positive hit, it will disregard any other match...

For example;
If my "accounts.txt" file contains the following entries:

a@a.com
b@b.com

Even though both of those should return results, as soon as the script is run, the match on a@a.com will be found however b@b.com will not return anything.

I cannot seem to figure out why this is happening, ideally I want all of the hits outputted.

FYI, the script is querying 'haveibeenpwned' which is a site that locates email addresses found in credential dumps.

Any help finding my bug would be greatly appreciated.  Below is my current script.

#!/usr/bin/env python

import argparse
import json
import requests
import time

breaches_by_date = {}
breaches_by_account = {}
breaches_by_name = {}

class Breach(object):
    def __init__(self, e, n, d):
        self.email = e
        self.name = n
        self.date = d

    def __repr__(self):
        return "%s: %s breached on %s" % (self.email, self.name, self.date)

def accCheck(acc):
    global breaches_by_date, breaches_by_account, breaches_by_name
    r = requests.get('https://haveibeenpwned.com/api/v2/breachedaccount/%s?truncateResponse=false' % acc)
    try:
        data = json.loads(r.text)
    except ValueError:
        print("No breach information for %s" % acc)
        return
    for i in data:
        name, date = (i['Name'], i['BreachDate'])
        breach = Breach(acc, name, date)
        try: breaches_by_account[acc].append(breach)
        except: breaches_by_account[acc] = [breach]
        try: breaches_by_name[name].append(breach)
        except: breaches_by_name[name] = [breach]
        try: breaches_by_date[date].append(breach)
        except: breaches_by_date[date] = [breach]

def readFromFile(fname="accounts.txt"):
    accounts=[]
    with open(fname, "r+") as f:
        accounts = [l.strip() for l in f.readlines()]
    return accounts

if __name__ == '__main__':
    accounts = readFromFile()
    for email_addr in accounts:
        accCheck(email_addr)
    print
    print("Breaches by date")
    for date, breaches in breaches_by_date.items():
        for breach in breaches:
            print(breach)
        print

    print("Breaches by account")
    for acc, breaches in breaches_by_account.items():
        print(acc)
        for breach in breaches:
            print("%s breached on %s" % (breach.name, breach.date))
        print

    print("Breaches by name")
    for name, breaches in breaches_by_name.items():
        print("%s breached for the following accounts:" % name)
        for breach in breaches:
            print("%s on %s" % (breach.email, breach.date))
        print

Body:
I am not 100% sure to know where your problem comes from, but I would opt for a code like:

emails_to_check = open("/path/to/yourfile").read().split("\n")
for email in emails_to_check:
 if is_email_blacklisted(email):
  do_something()


答: see this question: https://stackoverflow.com/questions/1055682/good-ruby-on-rails-free-hosting</p>

Title: Easiest way to deploy a Rails 3 app?

Body:
I finished my first ruby on rails application and I would like to put it up online.
What is the easiest way to go about doing this?


问:
How to destroy ckeditor in Angular application?
I'm using the ckeditor4 in my Angular application. When I navigate away from the page the console gives a warning like this:

[CKEDITOR] Error code: editor-destroy-iframe.

      ckeditor.js:21 [CKEDITOR] For more information about this error go to http://docs.ckeditor.com/#!/guide/dev_errors-section-editor-destroy-iframe

How should I safely unload the ckeditor component?

答:
The details in the page referenced in the error says:

The editor's  could not be destroyed correctly because it had
  been unloaded before the editor was destroyed. Make sure to destroy
  the editor before detaching it from the DOM.

You should do your cleanup in your Angular Component's onDestroy event, that way it will be destroyed before Angular removes the surrounding HTML elements.  Here are the docs on onDestroy:

https://angular.io/guide/lifecycle-hooks#ondestroy


问:
Error to sync KSoap2
I am trying to synk my KSoap2 library but when I click on synchronize ksoap2 ... these tell me it was a successful synchronization but when I try to use this it does not show the tags and it marks in red the SoapObject

Does any body have the same problem? Or how can I fix it?

答:
Problem solved i see these tutorial an works for me

https://code.tutsplus.com/tutorials/consuming-web-services-with-ksoap--mobile-21242

Title: Error to sync KSoap2


问:
import error trying to install a package
When I try to install a package for python, the setup.py has the following lines:

```<code>import os, sys, platform
from distutils.core import setup, Extension
import subprocess
from numpy import get_include
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from Cython.Compiler.Options import get_directive_defaults
</code>```

and I tried to run python setup.py install in terminal but I received the following error:

Traceback (most recent call last):
File "setup.py", line  9, in <module>
from Cython.Compiler.Options import get_directive_defaults
ImportError: cannot import name 'get_directive_defaults'
```

I would really appreciate if you could let me know how to fix this.

答:
Try this:</p>

```<code>import Cython as cy

def gdd():
    return cy.Compiler.Options.get_directive_defaults()
</code>```

Body:
When I try to install a package for python, the setup.py has the following lines:

import os, sys, platform
from distutils.core import setup, Extension
import subprocess
from numpy import get_include
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from Cython.Compiler.Options import get_directive_defaults

and I tried to run python setup.py install in terminal but I received the following error:

Traceback (most recent call last):
File "setup.py", line  9, in <module>
from Cython.Compiler.Options import get_directive_defaults
ImportError: cannot import name 'get_directive_defaults'

I would really appreciate if you could let me know how to fix this.

Body:
Try this:

import Cython as cy

def gdd():
    return cy.Compiler.Options.get_directive_defaults()


问:
How to execute a java script with jshell?
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

```<code>#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit
</code>```

However that gives:

```<code>⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World
</code>```

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?

答:
It turns out that with a bit of trickery there is a way, although I haven't fully managed to suppress the interpreted commands but pretty close to what I want.

Change test.jsh to:

```<code>#!/usr/bin/env sh
tail -n +4 "$0" | jshell -s "$@"
exit $?
System.out.println("Hello World")
/exit
</code>```

Which gives us:

```<code>⚡ ./test.jsh
-> System.out.println("Hello World")
Hello World
-> /exit
</code>```

Body:
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit

However that gives:

⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?

Body:
It turns out that with a bit of trickery there is a way, although I haven't fully managed to suppress the interpreted commands but pretty close to what I want.

Change test.jsh to:

#!/usr/bin/env sh
tail -n +4 "$0" | jshell -s "$@"
exit $?
System.out.println("Hello World")
/exit

Which gives us:

⚡ ./test.jsh
-> System.out.println("Hello World")
Hello World
-> /exit


问:
JSON, PHP and REST Web services
I'm new with this, so please be patient... (I'll write it just like the code was given to me)... I'm working on PHP files with .js files attached (if somehow this could be helpfull), this is a CRM insertion.

I need to consume a REST web service from:

```<code>http://example.com:8080/path/to/folder
</code>```

From a PHP (POST method) form, I need to send a JSON with the data (this could be also be send with jQuery):

```<code>{
"name": "Name",
"lastname": "Last Name",
"email": "name@example.com", (need to be validated on PHP)
"phone": "19283764", (need to be validated on PHP)
"source": "eCommerce",
"credential": "no"
}
</code>```

And get this response:

```<code>{
"response":[X]{
"result":[X]{
"message": "Record(s) added successfully",
"recorddetail":[X]{
"FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
}
},
"uri": "/crm/private/xml/Leads/insertRecords"
}
}
</code>```

If someone could please give me an example of how to achive this, that would be awesome. Or instruction where and what to write in every file would be appreciated too.

Thanks for the help!

答:
In php you can make this with curl or you can send your data in the url like this.

```<code>$json = array(
    "name"=>"Name",
    "lastname"=>"Last Name",
    "email"=>"name@example.com",
    "phone"=>"19283764",
    "source"=>"eCommerce",
    "credential"=>"no"
)
$response = json_decode(file_get_contents("http://example.com:8080/path/to/folder?json=$json"));
echo $response;
</code>```

And in the other end that is receiving this

```<code>$email = $_GET["json"]["email"];
$phone = $_GET["json"]["phone"];

$json = '{
    "response":[X]{
    "result":[X]{
    "message": "Record(s) added successfully",
    "recorddetail":[X]{
    "FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
    }
    },
    "uri": "/crm/private/xml/Leads/insertRecords"
    }
    }';

echo json_encode($json);
</code>```

In jquery.

```<code>var json = {
    "name": "Name",
    "lastname": "Last Name",
    "email": "name@example.com",
    "phone": "19283764",
    "source": "eCommerce",
    "credential": "no"
}

$.ajax({
    url: "http://example.com:8080/path/to/folder",
    type: "POST",
    data: json,
    success: function(data) {
        console.log(data);
    }
)};
</code>```

if you are using this jquery method you must use $_POST["json"] instead of $_GET["json"]

Title: JSON, PHP and REST Web services

Body:
I'm new with this, so please be patient... (I'll write it just like the code was given to me)... I'm working on PHP files with .js files attached (if somehow this could be helpfull), this is a CRM insertion.

I need to consume a REST web service from:

http://example.com:8080/path/to/folder

From a PHP (POST method) form, I need to send a JSON with the data (this could be also be send with jQuery):

{
"name": "Name",
"lastname": "Last Name",
"email": "name@example.com", (need to be validated on PHP)
"phone": "19283764", (need to be validated on PHP)
"source": "eCommerce",
"credential": "no"
}

And get this response:

{
"response":[X]{
"result":[X]{
"message": "Record(s) added successfully",
"recorddetail":[X]{
"FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
}
},
"uri": "/crm/private/xml/Leads/insertRecords"
}
}

If someone could please give me an example of how to achive this, that would be awesome. Or instruction where and what to write in every file would be appreciated too.

Thanks for the help!

Body:
In php you can make this with curl or you can send your data in the url like this.

$json = array(
    "name"=>"Name",
    "lastname"=>"Last Name",
    "email"=>"name@example.com",
    "phone"=>"19283764",
    "source"=>"eCommerce",
    "credential"=>"no"
)
$response = json_decode(file_get_contents("http://example.com:8080/path/to/folder?json=$json"));
echo $response;

And in the other end that is receiving this

$email = $_GET["json"]["email"];
$phone = $_GET["json"]["phone"];

$json = '{
    "response":[X]{
    "result":[X]{
    "message": "Record(s) added successfully",
    "recorddetail":[X]{
    "FL":[ ][{"content": 5646542168321358, "val": "Id" }, {"content": "2017-06-30 11:25:17",…]
    }
    },
    "uri": "/crm/private/xml/Leads/insertRecords"
    }
    }';

echo json_encode($json);

In jquery.

var json = {
    "name": "Name",
    "lastname": "Last Name",
    "email": "name@example.com",
    "phone": "19283764",
    "source": "eCommerce",
    "credential": "no"
}

$.ajax({
    url: "http://example.com:8080/path/to/folder",
    type: "POST",
    data: json,
    success: function(data) {
        console.log(data);
    }
)};

if you are using this jquery method you must use $_POST["json"] instead of $_GET["json"]


问:
Minified code using Webpack and UglifyJsPlugin doesn't work
I'm trying do add multiple files into bundle and minify it. Webpack doesn't give me any error, code is compiled and minified but it doesn't work.

My webpack config:

```<code>const path = require('path');
var webpack = require("webpack");

module.exports = {
  entry: {
    app: [
    './js/jquery-2.1.1.min.js',
    './vendor/bootstrap4alpha/js/tether.min.js',
    './vendor/bootstrap4alpha/js/bootstrap.min.js',
    './js/ie10-viewport-bug-workaround.js',
    './vendor/chartjs/Chart.bundle.min.js',
    './vendor/chartjs/utils.js',
    './vendor/spincrement/jquery.spincrement.min.js',
    './js/adminux.js'
  ]
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.min.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      mangle: true
    })
  ]
};
</code>```

When I run my app in the browser, it doesn't work and give me an error in console:

Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be
  included before Bootstrap's JavaScript.

So it looks like jquery is not in bundle but it is. When I add jquery in html file, it outputs next error with tether.min.js

答:
bootstrap needs to use the $, it's not a global variable in webpack.

you can use bootstrap-webpack instead.

or use webpack ProvidePlugin to define a global $:

```<code>new webpack.ProvidePlugin({
    // Automtically detect jQuery and $ as free var in modules
    // and inject the jquery library
    // This is required by many jquery plugins
    jQuery: "jquery",
    $: "jquery"
})
</code>```

Body:
I'm trying do add multiple files into bundle and minify it. Webpack doesn't give me any error, code is compiled and minified but it doesn't work.

My webpack config:

const path = require('path');
var webpack = require("webpack");

module.exports = {
  entry: {
    app: [
    './js/jquery-2.1.1.min.js',
    './vendor/bootstrap4alpha/js/tether.min.js',
    './vendor/bootstrap4alpha/js/bootstrap.min.js',
    './js/ie10-viewport-bug-workaround.js',
    './vendor/chartjs/Chart.bundle.min.js',
    './vendor/chartjs/utils.js',
    './vendor/spincrement/jquery.spincrement.min.js',
    './js/adminux.js'
  ]
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.min.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      mangle: true
    })
  ]
};

When I run my app in the browser, it doesn't work and give me an error in console:

Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be
  included before Bootstrap's JavaScript.

So it looks like jquery is not in bundle but it is. When I add jquery in html file, it outputs next error with tether.min.js

Body:
bootstrap needs to use the $, it's not a global variable in webpack.

you can use bootstrap-webpack instead.

or use webpack ProvidePlugin to define a global $:

new webpack.ProvidePlugin({
    // Automtically detect jQuery and $ as free var in modules
    // and inject the jquery library
    // This is required by many jquery plugins
    jQuery: "jquery",
    $: "jquery"
})


问:
Transitioning opacity and visibility
I have an element that is visibility: hidden until hovered over, with a transition on the opacity for a nice fade. The problem is that fade only works one way, because when the element instantly becomes visibility: hidden which hides the opacity transition. How can I work around this?

Edit: To be clear, it is important that the element have visibility: hidden until the hover is activated. An element with opacity: 0 can be interacted with, while an element with visibility: hidden cannot.

Example below. Notice how the popup fades in, but not out.

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  visibility: hidden;
  opacity: 0;
  transition: opacity 3s;
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hover">
  <div class="label">Hover me</div>
  <div class="popup">I am only visible on hover</div>
</div></code>```

答:
You only applied transition on opacity, if you need the transition works several properties you have to use all or use property names.

Just change below css part

```<code>.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;
  visibility: hidden;
  opacity: 0;
  transition: all 3s; /*Change the opacity to all*/
}
</code>```

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;
  visibility: hidden;
  opacity: 0;
  transition: all 3s; /*Change the opacity to all*/
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hover">
  <div class="label">Hover me</div>
  <div class="popup">I am only visible on hover</div>
</div></code>```

Title: Transitioning opacity and visibility

Body:
I have an element that is visibility: hidden until hovered over, with a transition on the opacity for a nice fade. The problem is that fade only works one way, because when the element instantly becomes visibility: hidden which hides the opacity transition. How can I work around this?

Edit: To be clear, it is important that the element have visibility: hidden until the hover is activated. An element with opacity: 0 can be interacted with, while an element with visibility: hidden cannot.

Example below. Notice how the popup fades in, but not out.

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  visibility: hidden;
  opacity: 0;
  transition: opacity 3s;
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}

Hover me

I am only visible on hover

Body:
You only applied transition on opacity, if you need the transition works several properties you have to use all or use property names.

Just change below css part

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;
  visibility: hidden;
  opacity: 0;
  transition: all 3s; /*Change the opacity to all*/
}

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;
  visibility: hidden;
  opacity: 0;
  transition: all 3s; /*Change the opacity to all*/
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}

<div class="hover">
  <div class="label">Hover me</div>
  <div class="popup">I am only visible on hover</div>
</div>