问:
Keras : Classification over time
I try to classify the state of my system over the time.

I have 100 training samples containing over 1218 timesteps  33 inputs parameters.

So I have X_train.shape = [100, 1218, 33].

I use the Deep Learning library Keras to predict the output Y = 0 or 1.

```<code>model = Sequential()
model.add(LSTM(4, input_shape=(1218 , 33), return_sequences=True))
model.add(TimeDistributed(Dense(1, activation = 'softmax')))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

Unfortunately I have the following error that I don't know how to resolve:

ValueError: Error when checking target: expected time_distributed_3 to have 3 dimensions, but got array with shape (100, 1)

Does someone knows how to fix this ?

Regards.

答:
The model you provided expects a target for each timestep of a sequence. If you have only one target for the whole sequence (and the shape of the targets in the error message suggests that), you need to modify the model in the following way: Set return_sequences to false and remove the TimeDistributed wrapper:

```<code>model = Sequential()
model.add(LSTM(4, input_shape=(1218 , 33), return_sequences=False))
model.add(Dense(1, activation = 'softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

Title: Keras : Classification over time

Body:
I try to classify the state of my system over the time.

I have 100 training samples containing over 1218 timesteps  33 inputs parameters.

So I have X_train.shape = [100, 1218, 33].

I use the Deep Learning library Keras to predict the output Y = 0 or 1.

model = Sequential()
model.add(LSTM(4, input_shape=(1218 , 33), return_sequences=True))
model.add(TimeDistributed(Dense(1, activation = 'softmax')))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

Unfortunately I have the following error that I don't know how to resolve:

ValueError: Error when checking target: expected time_distributed_3 to have 3 dimensions, but got array with shape (100, 1)

Does someone knows how to fix this ?

Regards.

Body:
The model you provided expects a target for each timestep of a sequence. If you have only one target for the whole sequence (and the shape of the targets in the error message suggests that), you need to modify the model in the following way: Set return_sequences to false and remove the TimeDistributed wrapper:

model = Sequential()
model.add(LSTM(4, input_shape=(1218 , 33), return_sequences=False))
model.add(Dense(1, activation = 'softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])


来源: stackexchange

问:
Howto compute the factorial of x
how to get the value of an integer x, indicated by x!, it is the product of the numbers 1 to x.

Example: 5! 1x2x3x4x5 = 120.

```<code>int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
     printf("%d x ", c);
     c++;
     d = d*a;
}
printf(" = %d", d);
</code>```

答:
My code is not good as other but it works for me:</p>

```<code>#include <iostream>
using namespace std;

unsigned int fattoriale (int n){
    if (n == 1){
        return 1;
    }
    else {
        return n * fattoriale(n-1);
    }
}

int main() {
    int tmp, num;
    cin >> num;

    tmp = fattoriale(num);

    cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Howto compute the factorial of x

Body:
how to get the value of an integer x, indicated by x!, it is the product of the numbers 1 to x.

Example: 5! 1x2x3x4x5 = 120.

int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
     printf("%d x ", c);
     c++;
     d = d*a;
}
printf(" = %d", d);

Body:
My code is not good as other but it works for me:

#include <iostream>
using namespace std;

unsigned int fattoriale (int n){
    if (n == 1){
        return 1;
    }
    else {
        return n * fattoriale(n-1);
    }
}

int main() {
    int tmp, num;
    cin >> num;

    tmp = fattoriale(num);

    cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;

}

ContentLicense: CC BY-SA 3.0


问:
Is it possible to iterate through an array list with elements of different data types and put them out?
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

答:
Sure!

The toString method is defined on the Object class. The Object class is the base class of every user-defined class. You could easily write:

```<code>for (Object item: itemList) {
    // prints all items
    System.out.println(item);
    if (item instanceof YourDesiredClass) {
        YourDesiredClass specificItem = (YourDesiredClass) item;
        //doSomethingElse(specificItem)
    }
}
</code>```

Body:
Sure!

The toString method is defined on the Object class. The Object class is the base class of every user-defined class. You could easily write:

for (Object item: itemList) {
    // prints all items
    System.out.println(item);
    if (item instanceof YourDesiredClass) {
        YourDesiredClass specificItem = (YourDesiredClass) item;
        //doSomethingElse(specificItem)
    }
}


问:
XML RSS image displaying in PHP
Im trying to pull an image URL out of an RSS link.

Here's an image of one of the items inside there.

In the image there is an tag media:thumbnail

I am using this for the title, link and discription:

```<code>$item_title = $item->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link = $item->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_desc = $item->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
</code>```

However I cannot seem to pull out the media:thumbnail.

I have tried the same as the other one's

```<code>$item_img = $item->getElementsByTagName('media:thumbnail')->item(0)->childNodes->item(0)->nodeValue;
</code>```

But this gives me this error:

Line 24 is the line that I tried. but I also tried using .attribute(url) but this also doesnt return a thing.

I hope someone can help me with this, its been 4 hours since I got this problem but after a lot of try and error there wasnt a single time I got the URL back.

Thanks in advance, and happy coding.

答:
The media: part on elements in your XML, is called a namespace prefix and represents a namespace URI. You should be able to find this URI as the value of a xmlns:media attribute on one of the media: element's ancestors. If you can't find that, you should be able to use the URI value of the xmlns attribute on the element itself (if applicable, which in this case it is).

In order to fetch certain elements from a certain namespace you should then use that namespace's URI and call DOMDocument::getElementsByTagNameNS() instead of DOMDocument::getElementsByTagName(), like so:

```<code>$item_img = $item->getElementsByTagNameNS('the namespace URI you found','thumbnail')
                 ->item(0)
                 ->childNodes
                 ->item(0)->nodeValue;
</code>```

If you don't care about what namespace a particular element is defined in, you could just keep using DOMDocument::getElementsByTagName(), but leave out the namespace prefix:

```<code>$item_img = $item->getElementsByTagName('thumbnail')
                 ->item(0)
                 ->childNodes
                 ->item(0)->nodeValue;
</code>```

Be aware though that this will fetch all <thumbnail> elements, no matter what namespace they are in.

However, in the sample XML you've shown1, the <media:thumbnail> element does not have any child nodes, so the above examples of your code that I adjusted will still fail.

Lastly, .attribute(url) is just invalid syntax. It should be ->getAttribute('url'), of course.

So, to wrap it up, you should be able to get the url attribute of the first <thumbnail> of a particular namespace with:

```<code>$item_img = $item->getElementsByTagNameNS('the namespace URI you found','thumbnail')
                 ->item(0)->getAttribute('url');
</code>```

or:

```<code>$item_img = $item->getElementsByTagName('thumbnail')
                 ->item(0)->getAttribute('url');
</code>```

if you don't care about the namespace of the element.

1) Please post actual sample XML code next time, instead of an image.

Title: XML RSS image displaying in PHP

Body:
Im trying to pull an image URL out of an RSS link.

Here's an image of one of the items inside there.

In the image there is an tag media:thumbnail

I am using this for the title, link and discription:

$item_title = $item->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link = $item->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_desc = $item->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;

However I cannot seem to pull out the media:thumbnail.

I have tried the same as the other one's

$item_img = $item->getElementsByTagName('media:thumbnail')->item(0)->childNodes->item(0)->nodeValue;

But this gives me this error:

Line 24 is the line that I tried. but I also tried using .attribute(url) but this also doesnt return a thing.

I hope someone can help me with this, its been 4 hours since I got this problem but after a lot of try and error there wasnt a single time I got the URL back.

Thanks in advance, and happy coding.

Body:
The media: part on elements in your XML, is called a namespace prefix and represents a namespace URI. You should be able to find this URI as the value of a xmlns:media attribute on one of the media: element's ancestors. If you can't find that, you should be able to use the URI value of the xmlns attribute on the element itself (if applicable, which in this case it is).

In order to fetch certain elements from a certain namespace you should then use that namespace's URI and call DOMDocument::getElementsByTagNameNS() instead of DOMDocument::getElementsByTagName(), like so:

$item_img = $item->getElementsByTagNameNS('the namespace URI you found','thumbnail')
                 ->item(0)
                 ->childNodes
                 ->item(0)->nodeValue;

If you don't care about what namespace a particular element is defined in, you could just keep using DOMDocument::getElementsByTagName(), but leave out the namespace prefix:

$item_img = $item->getElementsByTagName('thumbnail')
                 ->item(0)
                 ->childNodes
                 ->item(0)->nodeValue;

Be aware though that this will fetch all <thumbnail> elements, no matter what namespace they are in.

However, in the sample XML you've shown1, the <media:thumbnail> element does not have any child nodes, so the above examples of your code that I adjusted will still fail.

Lastly, .attribute(url) is just invalid syntax. It should be ->getAttribute('url'), of course.

So, to wrap it up, you should be able to get the url attribute of the first <thumbnail> of a particular namespace with:

$item_img = $item->getElementsByTagNameNS('the namespace URI you found','thumbnail')
                 ->item(0)->getAttribute('url');

or:

$item_img = $item->getElementsByTagName('thumbnail')
                 ->item(0)->getAttribute('url');

if you don't care about the namespace of the element.

1) Please post actual sample XML code next time, instead of an image.


问:
Accessing ListViews, RecycleViews, LinearLayouts in different paths
I have been reading for solutions for a while but this looks ambiguous to me. I am trying to access elements like ListViews,RecycleViews etc. I have a file called Main.axml in my Layout structure. Main.axml belongs to Activity1.

But now, i am trying to refer to the recycleView in the layout structure, but i get an exception (systemNullReference). My question seems a bit weird but if i cannot reach the recycleView in the Main.axml, why wouldn't the ide in the first place throw an error before i deploy onto my phone?  Below is how i am trying to access the id of the recycleview in Main.axml?

Activity2.cs

```<code>private RecycleView recycleView;

 //trying to access id in Main.axml
recycleView = FindViewById<RecycleView>(Resource.Layout.recyleView1);
</code>```

答:
In your code you have

```<code>recycleView = FindViewById<RecycleView>(Resource.Layout.recyleView1);
</code>```

and it should be:

```<code>recycleView = FindViewById<RecycleView>(Resource.Id.recyleView1);
</code>```

Note:

Your Main.axml layout file must contain a RecycleView with Id recyleView1.

Body:
I have been reading for solutions for a while but this looks ambiguous to me. I am trying to access elements like ListViews,RecycleViews etc. I have a file called Main.axml in my Layout structure. Main.axml belongs to Activity1.

But now, i am trying to refer to the recycleView in the layout structure, but i get an exception (systemNullReference). My question seems a bit weird but if i cannot reach the recycleView in the Main.axml, why wouldn't the ide in the first place throw an error before i deploy onto my phone?  Below is how i am trying to access the id of the recycleview in Main.axml?

Activity2.cs

private RecycleView recycleView;

 //trying to access id in Main.axml
recycleView = FindViewById<RecycleView>(Resource.Layout.recyleView1);

Body:
In your code you have

recycleView = FindViewById<RecycleView>(Resource.Layout.recyleView1);

and it should be:

recycleView = FindViewById<RecycleView>(Resource.Id.recyleView1);

Note:

Your Main.axml layout file must contain a RecycleView with Id recyleView1.


答:
Just object

```<code>new ArrayList<Object>().iterator().forEachRemaining(element -> {
    System.out.println(element);
});
</code>```

A specific type

```<code>new ArrayList<Object>().stream().filter(element -> element instanceof String).iterator()
        .forEachRemaining(System.out::println);
</code>```

Edit: this answer requires Java 8

Title: Is it possible to iterate through an array list with elements of different data types and put them out?

Body:
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

Body:
Just object

new ArrayList<Object>().iterator().forEachRemaining(element -> {
    System.out.println(element);
});

A specific type

new ArrayList<Object>().stream().filter(element -> element instanceof String).iterator()
        .forEachRemaining(System.out::println);

Edit: this answer requires Java 8


问:
IoC and Factory for C++ - Alternative to Microsoft Unity for c#
What is the most common use sturdy nugetpackage/library/framework for C++ that does pretty much the same as the C# library by Microsoft called Unity: http://unity.codeplex.com/ ?

The end result would look something like this:

```<code>class IProjectRepository
{
public:
    vector<Project> GetProjects() = 0;
}

class XMLProjectRepository : IProjectRepository
{
public:
    vector<Project> GetProjects()
    {
        return // implementation
    }
}

class Application
{
public:
    Application( shared_ptr<IProjectRepository> projectRepository )
    // Or however this would look...
    // projectRepository would be an instance of whatever i have registered (see below)
    {
        auto projects = this.projectRepository.GetProjects();
    }
}
</code>```

And in some startup area i would bind like this:

```<code>BinderFramework::Register<IProjectRepository, XMLProjectRepository>();What is the most common use sturdy nuget package/library for C++ that does pretty much the same as the C# library by Microsoft called Unity: http://unity.codeplex.com/
</code>```

I have been looking for a while now, but can't quite find a nice complete and simple solution.

The idea is to use a well known framework rather than write my own flaky code.

答:
I might be a bit late but you should give a look at Hypodermic.

It's header only, it comes with a pretty cool Dsl plus it's been used for years in production environments.

Body:
What is the most common use sturdy nugetpackage/library/framework for C++ that does pretty much the same as the C# library by Microsoft called Unity: http://unity.codeplex.com/ ?

The end result would look something like this:

class IProjectRepository
{
public:
    vector<Project> GetProjects() = 0;
}

class XMLProjectRepository : IProjectRepository
{
public:
    vector<Project> GetProjects()
    {
        return // implementation
    }
}

class Application
{
public:
    Application( shared_ptr<IProjectRepository> projectRepository )
    // Or however this would look...
    // projectRepository would be an instance of whatever i have registered (see below)
    {
        auto projects = this.projectRepository.GetProjects();
    }
}

And in some startup area i would bind like this:

BinderFramework::Register<IProjectRepository, XMLProjectRepository>();What is the most common use sturdy nuget package/library for C++ that does pretty much the same as the C# library by Microsoft called Unity: http://unity.codeplex.com/

I have been looking for a while now, but can't quite find a nice complete and simple solution.

The idea is to use a well known framework rather than write my own flaky code.


问:
Storing multiple integers in a char array
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

```<code>char* temp = (char)input.Z_pos_Camera_Temperature;
</code>```

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

```<code>char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;
</code>```

but that only added the values of the three chars individually. Can someone help me figure this out?

答:
You have to make the char* large enough to be able to store all the numbers.
Then you can use something like the following in order to convert the number to string:

```<code>int n[10] = {1, 2, 3, 4, 5888, 6, 7, 8, 9, 10};
char final[1000]; //adjust to acoomodate all the digits and spaces
int len = 0;
for (int i = 0; i < 10; i++) {
    char str[64];
    sprintf(str, "%d", n[i]);
    strcpy(final + len, str); //copy the ith number
    len += strlen(str); //take a note of the number of digits used
    final[len] = ' '; //add a space
    len++;

}
final[len] = '\0'; //terminate the string
</code>```

Try online

Body:
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

char* temp = (char)input.Z_pos_Camera_Temperature;

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;

but that only added the values of the three chars individually. Can someone help me figure this out?

Body:
You have to make the char* large enough to be able to store all the numbers.
Then you can use something like the following in order to convert the number to string:

int n[10] = {1, 2, 3, 4, 5888, 6, 7, 8, 9, 10};
char final[1000]; //adjust to acoomodate all the digits and spaces
int len = 0;
for (int i = 0; i < 10; i++) {
    char str[64];
    sprintf(str, "%d", n[i]);
    strcpy(final + len, str); //copy the ith number
    len += strlen(str); //take a note of the number of digits used
    final[len] = ' '; //add a space
    len++;

}
final[len] = '\0'; //terminate the string

Try online


问:
Trying to sort 2 pandas dataframe and then copy from one to another
I have two csv files I want to manipulate and then combine into one file. I first converted them to pandas. One pandas dataframe looks like this:

```<code>      Number  Quiz
0  111111145     0
1  111111108     1
2  111111123     1
3  111111114     0
4  111111132     0
</code>```

the other like this:

```<code>Last Name First Name       Number   Quiz
0  Student1      Student1  111111123
1  Student2      Student2  111111114
2  Student3      Student3  111111132
3  Student4      Student4  111111145
4  Student5      Student5  111111108
</code>```

I want to end up with something like this:

```<code>Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  1
    1  Student2      Student2  111111114  0
    2  Student3      Student3  111111123  1
    3  Student4      Student4  111111132  0
    4  Student5      Student5  111111145  0
</code>```

but when I run my code I end up getting:

```<code>Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  0
    1  Student2      Student2  111111114  1
    2  Student3      Student3  111111123  0
    3  Student4      Student4  111111132  1
    4  Student5      Student5  111111145  0
</code>```

And I am not sure why. My code is as follows:

```<code>import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname', '--c', help = 'column name to copy')
parser.add_argument('-source', '--s', help = 'source file with the column to copy')
parser.add_argument('-target', '--t', help = 'the target file with the names and UINS')
parser.add_argument('-out', '--f', help = 'output file with column copied')

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args = parser.parse_args()

sourceFile = pd.read_csv(args.s)
targetFile = pd.read_csv(args.t)
print sourceFile
print targetFile
del targetFile[args.c]
sourceFile.sort_values('UIN', ascending = True, inplace = True)
targetFile.sort_values('UIN', ascending = True, inplace = True)
print sourceFile
print targetFile
targetFile[args.c]= sourceFile[args.c]
targetFile.to_csv(args.f, index = False)
print targetFile
</code>```

答:
I changed it just a little and got it to work. I used</p>

```<code>result = pd.merge(targetFile, sourceFile, on = 'number')
</code>```

Body:
I have two csv files I want to manipulate and then combine into one file. I first converted them to pandas. One pandas dataframe looks like this:

      Number  Quiz
0  111111145     0
1  111111108     1
2  111111123     1
3  111111114     0
4  111111132     0

the other like this:

Last Name First Name       Number   Quiz
0  Student1      Student1  111111123
1  Student2      Student2  111111114
2  Student3      Student3  111111132
3  Student4      Student4  111111145
4  Student5      Student5  111111108

I want to end up with something like this:

Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  1
    1  Student2      Student2  111111114  0
    2  Student3      Student3  111111123  1
    3  Student4      Student4  111111132  0
    4  Student5      Student5  111111145  0

but when I run my code I end up getting:

Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  0
    1  Student2      Student2  111111114  1
    2  Student3      Student3  111111123  0
    3  Student4      Student4  111111132  1
    4  Student5      Student5  111111145  0

And I am not sure why. My code is as follows:

import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname', '--c', help = 'column name to copy')
parser.add_argument('-source', '--s', help = 'source file with the column to copy')
parser.add_argument('-target', '--t', help = 'the target file with the names and UINS')
parser.add_argument('-out', '--f', help = 'output file with column copied')

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args = parser.parse_args()

sourceFile = pd.read_csv(args.s)
targetFile = pd.read_csv(args.t)
print sourceFile
print targetFile
del targetFile[args.c]
sourceFile.sort_values('UIN', ascending = True, inplace = True)
targetFile.sort_values('UIN', ascending = True, inplace = True)
print sourceFile
print targetFile
targetFile[args.c]= sourceFile[args.c]
targetFile.to_csv(args.f, index = False)
print targetFile

Body:
I changed it just a little and got it to work. I used

result = pd.merge(targetFile, sourceFile, on = 'number')


问:
Create a custom Transformer In Java spark ml
I want to create a custom Spark Transformer in Java.

The Transformer is text preprocessor which acts like a Tokenizer. It takes an input column and an output column as parameters.

I looked around and I found 2 Scala Traits HasInputCol and HasOutputCol.

How can I create a class that extends Transformer and implements HasInputCol and OutputCol?

My goal is have something like this.

```<code>   // Dataset that have a String column named "text"
   DataSet<Row> dataset;

   CustomTransformer customTransformer = new CustomTransformer();
   customTransformer.setInputCol("text");
   customTransformer.setOutputCol("result");

   // result that have 2 String columns named "text" and "result"
   DataSet<Row> result = customTransformer.transform(dataset);
</code>```

答:
You probably want to inherit your CustomTransformer from org.apache.spark.ml.UnaryTransformer. You may try something like this:

```<code>import org.apache.spark.ml.UnaryTransformer;
import org.apache.spark.ml.util.Identifiable$;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import scala.Function1;
import scala.collection.JavaConversions$;
import scala.collection.immutable.Seq;

import java.util.Arrays;

public class MyCustomTransformer extends UnaryTransformer<String, scala.collection.immutable.Seq<String>, MyCustomTransformer>
{
    private final String uid = Identifiable$.MODULE$.randomUID("mycustom");

    @Override
    public String uid()
    {
        return uid;
    }

    @Override
    public Function1<String, scala.collection.immutable.Seq<String>> createTransformFunc()
    {
        // can't use labmda syntax :(
        return new scala.runtime.AbstractFunction1<String, Seq<String>>()
        {
            @Override
            public Seq<String> apply(String s)
            {
                // do the logic
                String[] split = s.toLowerCase().split("\\s");
                // convert to Scala type
                return JavaConversions$.MODULE$.iterableAsScalaIterable(Arrays.asList(split)).toList();
            }
        };
    }

    @Override
    public void validateInputType(DataType inputType)
    {
        super.validateInputType(inputType);
        if (inputType != DataTypes.StringType)
            throw new IllegalArgumentException("Input type must be string type but got " + inputType + ".");
    }

    @Override
    public DataType outputDataType()
    {
        return DataTypes.createArrayType(DataTypes.StringType, true); // or false? depends on your data
    }
}
</code>```

Body:
I want to create a custom Spark Transformer in Java.

The Transformer is text preprocessor which acts like a Tokenizer. It takes an input column and an output column as parameters.

I looked around and I found 2 Scala Traits HasInputCol and HasOutputCol.

How can I create a class that extends Transformer and implements HasInputCol and OutputCol?

My goal is have something like this.

   // Dataset that have a String column named "text"
   DataSet<Row> dataset;

   CustomTransformer customTransformer = new CustomTransformer();
   customTransformer.setInputCol("text");
   customTransformer.setOutputCol("result");

   // result that have 2 String columns named "text" and "result"
   DataSet<Row> result = customTransformer.transform(dataset);

Body:
You probably want to inherit your CustomTransformer from org.apache.spark.ml.UnaryTransformer. You may try something like this:

import org.apache.spark.ml.UnaryTransformer;
import org.apache.spark.ml.util.Identifiable$;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import scala.Function1;
import scala.collection.JavaConversions$;
import scala.collection.immutable.Seq;

import java.util.Arrays;

public class MyCustomTransformer extends UnaryTransformer<String, scala.collection.immutable.Seq<String>, MyCustomTransformer>
{
    private final String uid = Identifiable$.MODULE$.randomUID("mycustom");

    @Override
    public String uid()
    {
        return uid;
    }

    @Override
    public Function1<String, scala.collection.immutable.Seq<String>> createTransformFunc()
    {
        // can't use labmda syntax :(
        return new scala.runtime.AbstractFunction1<String, Seq<String>>()
        {
            @Override
            public Seq<String> apply(String s)
            {
                // do the logic
                String[] split = s.toLowerCase().split("\\s");
                // convert to Scala type
                return JavaConversions$.MODULE$.iterableAsScalaIterable(Arrays.asList(split)).toList();
            }
        };
    }

    @Override
    public void validateInputType(DataType inputType)
    {
        super.validateInputType(inputType);
        if (inputType != DataTypes.StringType)
            throw new IllegalArgumentException("Input type must be string type but got " + inputType + ".");
    }

    @Override
    public DataType outputDataType()
    {
        return DataTypes.createArrayType(DataTypes.StringType, true); // or false? depends on your data
    }
}


问:
Angular 4: How to correctly pass data from component to html
I have some trouble understanding a simple task, basically I have a controller like this:

app.componet.ts

```<code>import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Http } from '@angular/http';
import { FlexLayoutModule } from "@angular/flex-layout";
import * as io from "socket.io-client";
var b;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {
  freqValue = [2,3];
  myData: Array<any>;
  autoTicks = false;
  invert = false;
  max = 15;
  min = 0;
  showTicks = true;
  step = 1;
  thumbLabel = true;
  vertical = true;
  color = 'primary';
  mode = 'determinate';
  //value = 50;
  socket : any;
  prova : any;
  @Input() valueSlider: number;

  constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', function(a){
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }
}
</code>```

and a page like this:
app.component.html

```<code>...
  <div fxLayout="row wrap" class="nopad">
    <md-slider class="example-margin" [disabled]="disabled" [invert]="invert" [max]="max" [min]="min" [step]="step" [thumb-label]="thumbLabel"
      [tick-interval]="tickInterval" [value]="valueSlider" [vertical]="false" fxFlex="100%">
    </md-slider>
  </div>
...
</code>```

I'm triyng to pass valueSlider from my TS to the HTML as a property of <md-slider>but without success...does anyone can explain me?
Thanks

答:
Assuming you're using Angular Material, your general logic should work. Two thoughts though, first of all your structuring of the HTML attribute is odd... value={{valueSlider}} ignoring the fact that the quotation marks should be there, it would likely be better to structure it as such [value]="valueSlider".

Next, I'm wondering if the [disabled]="disabled" is causing you some issues. While a slider can be disabled, the documentation (and the source code) doesn't lead me to believe that it is a public attribute you can modify.

UPDATED

I think you have a scoping issue.

```<code> constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', (a) => {
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }
</code>```

Change the constructor to that above. The use of the term function rather than a lambda may prevent you from editing the valueSlider which is outside of the functions scope.

Body:
I have some trouble understanding a simple task, basically I have a controller like this:

app.componet.ts

import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Http } from '@angular/http';
import { FlexLayoutModule } from "@angular/flex-layout";
import * as io from "socket.io-client";
var b;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {
  freqValue = [2,3];
  myData: Array<any>;
  autoTicks = false;
  invert = false;
  max = 15;
  min = 0;
  showTicks = true;
  step = 1;
  thumbLabel = true;
  vertical = true;
  color = 'primary';
  mode = 'determinate';
  //value = 50;
  socket : any;
  prova : any;
  @Input() valueSlider: number;

  constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', function(a){
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }
}

and a page like this:
app.component.html

...

    <md-slider class="example-margin" [disabled]="disabled" [invert]="invert" [max]="max" [min]="min" [step]="step" [thumb-label]="thumbLabel"
      [tick-interval]="tickInterval" [value]="valueSlider" [vertical]="false" fxFlex="100%">
    </md-slider>

...

I'm triyng to pass valueSlider from my TS to the HTML as a property of <md-slider>but without success...does anyone can explain me?
Thanks

Body:
Assuming you're using Angular Material, your general logic should work. Two thoughts though, first of all your structuring of the HTML attribute is odd... value={{valueSlider}} ignoring the fact that the quotation marks should be there, it would likely be better to structure it as such [value]="valueSlider".

Next, I'm wondering if the [disabled]="disabled" is causing you some issues. While a slider can be disabled, the documentation (and the source code) doesn't lead me to believe that it is a public attribute you can modify.

UPDATED

I think you have a scoping issue.

 constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', (a) => {
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }

Change the constructor to that above. The use of the term function rather than a lambda may prevent you from editing the valueSlider which is outside of the functions scope.


问:
Get start time and end time of Flag=1, if it repeats 4 times (without using for loop)
I am new to R and stuck in getting Get start time and end time of Flag=1. The condition is, 1 should repeat (consecutively) at least 4 times then only its start and end time needs to be captured. My input looks like-

Time Stamp    Flag
00:00:00        1
00:00:10        1
00:00:20        1
00:00:30        1
00:00:40        0
00:00:50        0
00:01:00        0
00:01:10        0
00:01:20        0
00:01:30        1
00:01:40        1
00:01:50        1
00:02:00        0
00:02:10        1
00:02:20        1
00:02:30        1
00:02:40        1
00:02:50        1
00:03:00        1
00:03:10        1
00:03:20        1

and my output should look like -

Start Time End Time    Duration
00:00:00    00:00:30    00:00:30
00:02:10    00:03:20    00:01:10

I have achieved it using for loop and if else, but as the data is huge its taking lots of time. So, I need to optimize it.

Is there any inbuilt function in R that i can modify and use?

答:
First create the data using:

```<code>st <- data.frame(Time = format(seq(from=as.POSIXct("2012-1-1 00:00:00", tz="UTC"),
                                     to=as.POSIXct("2012-1-1  00:03:20", tz="UTC"),
                               by="10 secs") , "%H:%M:%S" ),
                 Flag = c(1,1,1,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1))

st$Time <- as.POSIXct(st$Time, format = "%H:%M:%S")
</code>```

Using dplyr I would approach this as:

```<code>st %>%
mutate(gr = cumsum(lag(Flag, default = Flag[1]) != Flag)) %>%
filter(Flag == 1) %>%
group_by(gr) %>%
filter(length(gr) >= 4) %>%
summarise(start.time = first(Time),
          last.time  = last(Time)) %>%
mutate(Duration = last.time - start.time)
</code>```

The result is

```<code># A tibble: 2 × 4
     gr          start.time           last.time Duration
  <int>              <dttm>              <dttm>   <time>
1     0 2017-06-08 00:00:00 2017-06-08 00:00:30  30 secs
2     4 2017-06-08 00:02:10 2017-06-08 00:03:20  70 secs
</code>```

Body:
First create the data using:

st <- data.frame(Time = format(seq(from=as.POSIXct("2012-1-1 00:00:00", tz="UTC"),
                                     to=as.POSIXct("2012-1-1  00:03:20", tz="UTC"),
                               by="10 secs") , "%H:%M:%S" ),
                 Flag = c(1,1,1,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1))

st$Time <- as.POSIXct(st$Time, format = "%H:%M:%S")

Using dplyr I would approach this as:

st %>%
mutate(gr = cumsum(lag(Flag, default = Flag[1]) != Flag)) %>%
filter(Flag == 1) %>%
group_by(gr) %>%
filter(length(gr) >= 4) %>%
summarise(start.time = first(Time),
          last.time  = last(Time)) %>%
mutate(Duration = last.time - start.time)

The result is

# A tibble: 2 × 4
     gr          start.time           last.time Duration
  <int>              <dttm>              <dttm>   <time>
1     0 2017-06-08 00:00:00 2017-06-08 00:00:30  30 secs
2     4 2017-06-08 00:02:10 2017-06-08 00:03:20  70 secs


问:
Deny access to all files in a directory unless a specific php page is referrer
We have files stored in a directory "uploads/downloads" which are accessed through a php file in the manner of https://www.example.com/request_file.php?file=123. That PHP file queries a database table and returns a file stored in the directory mentioned.

Using htaccess (I presume) how can I deny access to any files in the "uploads/downloads" directory unless the are being accessed through the request_file.php page?

答:
Try something like this:</p>

```<code>RewriteEngine On
RewriteCond %{HTTP_REFERER} !request_file.php
RewriteRule ^uploads/downloads/ - [L,R=404]
</code>```

Body:
Try something like this:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !request_file.php
RewriteRule ^uploads/downloads/ - [L,R=404]


问:
extract real link from encrypted link
Extracting a link seems easy on regular link by using:

```<code>$link = $('a:eq(1)');
var real_link = $link.attr('href');
</code>```

the hardest part is how to extract link from encrypted link like this:
https://jsfiddle.net/rm7mp8do/

if you hover to the link, on you status bar it will show you fake link like:

hxxp://this_is_fake_link

but after you click it, it will bring you to the original link:

hxxp://mg.com/ghits/xxx/xxx/xxx/xxx/x/x/?h=gdwagdjgawjhvjwhafgdjhwavwxdjhav

答:
You can try this php script using curl return transfer ... </p>

```<code>function expand_short_url($url)
{
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
    $header = curl_exec($ch);

    $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header)); // Parse information

    for($i=0;$i<count($fields);$i++)
    {
        if(strpos($fields[$i],'Location') !== false)
        {
            $url = str_replace("Location: ","",$fields[$i]);
        }
    }
    return $url;
}
</code>```

Title: extract real link from encrypted link

Body:
Extracting a link seems easy on regular link by using:

$link = $('a:eq(1)');
var real_link = $link.attr('href');

the hardest part is how to extract link from encrypted link like this:
https://jsfiddle.net/rm7mp8do/

if you hover to the link, on you status bar it will show you fake link like:

hxxp://this_is_fake_link

but after you click it, it will bring you to the original link:

hxxp://mg.com/ghits/xxx/xxx/xxx/xxx/x/x/?h=gdwagdjgawjhvjwhafgdjhwavwxdjhav

Body:
You can try this php script using curl return transfer ...

function expand_short_url($url)
{
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
    $header = curl_exec($ch);

    $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header)); // Parse information

    for($i=0;$i<count($fields);$i++)
    {
        if(strpos($fields[$i],'Location') !== false)
        {
            $url = str_replace("Location: ","",$fields[$i]);
        }
    }
    return $url;
}


问:
change the color of the doughnut chart
html

```<code><link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>

<div class="col-md-5">
    <div class="exp"></div>
</div>
</code>```

javascript into the page

```<code><script type="text/javascript">

      $( document ).ready(function() {

        function get_data() {
          var props = ["conto", "investimenti"];
          var out   = [];
          var saldo = document.getElementById('saldo').value;
          var invest = document.getElementById('invest').value;
          var totale = parseFloat(saldo)+parseFloat(invest);

          out.push({"name":props[0], "hvalue": Math.floor((parseFloat(saldo)/totale)*100)});
          out.push({"name":props[1], "hvalue": Math.floor((parseFloat(invest)/totale)*100)});
          /*
          for (var i = 0; i < props.length; i++) {
            out.push({"name":props[i], "hvalue": Math.floor(Math.random() * 100)});
          };
          */
          return out;
        }

        // init the pie
        $(".exp").donutpie();

        // update it with some fake data
        $(".exp").donutpie('update', get_data());

        // keep updating every x sec
        setInterval( function () {
          $(".exp").donutpie('update', get_data());
        }, 400);

      });

  </script>
</code>```

external js file

```<code>(function ( $ ) {

    var DonutPie = function($self, options) {
        this.$self = $self;
        this.settings = $.extend( $.fn.donutpie.defaults, options );
    };

    DonutPie.prototype.display = function() {

        var radius = this.settings.radius / 2;

        this.svg = d3.select(this.$self[0])
            .append("svg")
            .attr("width", radius * 2)
            .attr("height", radius * 2)
            .append("g");

        this.svg.append("g")
            .attr("class", "slices");

        this.pie = d3.layout.pie()
            .sort(null)
            .value(function(d){
                return d.hvalue;
            });

        this.arc = d3.svg.arc()
          .outerRadius(radius * 0.8)
          .innerRadius(radius * 0.4);

        this.outerArc = d3.svg.arc()
          .innerRadius(radius * 0.9)
          .outerRadius(radius * 0.9);

        this.svg.attr("transform", "translate(" + radius + "," + radius + ")");

        var tpClass = this.settings.tooltipClass;
        if (!$('body').hasClass( tpClass )) {
            $('.' + tpClass).remove();
            d3.select("body")
                .append("div")
                .attr('class', tpClass )
                .style("position", "absolute")
                .style("z-index", "100")
                .style("visibility", "hidden")
                .text("");
        }

    };

    DonutPie.prototype.update = function(data) {

        // check if all the items has colors.
        var colors = d3.scale.category20().range();
        for (var i = 0; i < data.length; i++) {
            if( data[i]['color'] == undefined )
                data[i]['color'] = colors[i];
        };

        var tooltip = this.settings.tooltip;
        var tpClass = "." + this.settings.tooltipClass;
        var arc = this.arc;
        var slice = this.svg.select(".slices").selectAll("path.slice")
            .data(this.pie(data));
        //roba sopra

        slice.enter()
            .insert("path")
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attr("class", "slice")

            .on("mouseover", function (d) {

            if (tooltip) {
                if (d.id != "none") {
                    $(tpClass).html( d.data.name + " " + Math.round(d.value) + "%" );
                    $(tpClass).css("visibility", "visible");
                }
            }

        });

        slice
            .transition().duration(1000)
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attrTween("d", function(d) {
              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                return arc(interpolate(t));
              };
            });

        slice.exit()
            .remove();

    };

    $.fn.donutpie = function(option) {

        var $this = $(this);
        var $donutpie = $this.data("donutpie");

        if(!$donutpie) {
            // init the object
            var options = typeof option == "object" && option;
            $donutpie   = new DonutPie($this, options);
            $this.data("donutpie", $donutpie);
        }

        if (typeof option === 'string' && $.fn.donutpie.methods[option]) {
            $donutpie[option].apply($donutpie, Array.prototype.slice.call(arguments, 1));
        } else if ( typeof option === 'object' || !option ) {
            $donutpie.display.apply( $donutpie, option);
        } else {
            $.error( 'Method ' +  option + ' does not exist in DonutPie' );
        }

    };

    $.fn.donutpie.methods = {
        'display': 1,
        'update': 1
    }

    $.fn.donutpie.defaults = {
      radius: 240,
      tooltip : true,
      tooltipClass : "donut-pie-tooltip-bubble"
    };

}( jQuery ));
</code>```

I have to change the color of the chart, but i can't do that. How I can change the two colors? I tried to modify the code, but it doesn't work. Please someone give a hand.

答:
To change the color of the chart a "color" property must be specified in the object literal you pass to the update function. In your case, this object literal is defined in the return of get_data().

To add a color property to an object literal, follow the previous property with a comma and then define the name of your property with color:"#rrggbb".

```<code>out.push({name:props[0], hvalue: Math.floor((parseFloat(saldo)/totale)*100), color:"#FF0000"}); //makes color red
</code>```

Title: change the color of the doughnut chart

Body:
html

<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">

javascript into the page

external js file

(function ( $ ) {

    var DonutPie = function($self, options) {
        this.$self = $self;
        this.settings = $.extend( $.fn.donutpie.defaults, options );
    };

    DonutPie.prototype.display = function() {

        var radius = this.settings.radius / 2;

        this.svg = d3.select(this.$self[0])
            .append("svg")
            .attr("width", radius * 2)
            .attr("height", radius * 2)
            .append("g");

        this.svg.append("g")
            .attr("class", "slices");

        this.pie = d3.layout.pie()
            .sort(null)
            .value(function(d){
                return d.hvalue;
            });

        this.arc = d3.svg.arc()
          .outerRadius(radius * 0.8)
          .innerRadius(radius * 0.4);

        this.outerArc = d3.svg.arc()
          .innerRadius(radius * 0.9)
          .outerRadius(radius * 0.9);

        this.svg.attr("transform", "translate(" + radius + "," + radius + ")");

        var tpClass = this.settings.tooltipClass;
        if (!$('body').hasClass( tpClass )) {
            $('.' + tpClass).remove();
            d3.select("body")
                .append("div")
                .attr('class', tpClass )
                .style("position", "absolute")
                .style("z-index", "100")
                .style("visibility", "hidden")
                .text("");
        }

    };

    DonutPie.prototype.update = function(data) {

        // check if all the items has colors.
        var colors = d3.scale.category20().range();
        for (var i = 0; i < data.length; i++) {
            if( data[i]['color'] == undefined )
                data[i]['color'] = colors[i];
        };

        var tooltip = this.settings.tooltip;
        var tpClass = "." + this.settings.tooltipClass;
        var arc = this.arc;
        var slice = this.svg.select(".slices").selectAll("path.slice")
            .data(this.pie(data));
        //roba sopra

        slice.enter()
            .insert("path")
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attr("class", "slice")

            .on("mouseover", function (d) {

            if (tooltip) {
                if (d.id != "none") {
                    $(tpClass).html( d.data.name + " " + Math.round(d.value) + "%" );
                    $(tpClass).css("visibility", "visible");
                }
            }

        });

        slice
            .transition().duration(1000)
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attrTween("d", function(d) {
              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                return arc(interpolate(t));
              };
            });

        slice.exit()
            .remove();

    };

    $.fn.donutpie = function(option) {

        var $this = $(this);
        var $donutpie = $this.data("donutpie");

        if(!$donutpie) {
            // init the object
            var options = typeof option == "object" && option;
            $donutpie   = new DonutPie($this, options);
            $this.data("donutpie", $donutpie);
        }

        if (typeof option === 'string' && $.fn.donutpie.methods[option]) {
            $donutpie[option].apply($donutpie, Array.prototype.slice.call(arguments, 1));
        } else if ( typeof option === 'object' || !option ) {
            $donutpie.display.apply( $donutpie, option);
        } else {
            $.error( 'Method ' +  option + ' does not exist in DonutPie' );
        }

    };

    $.fn.donutpie.methods = {
        'display': 1,
        'update': 1
    }

    $.fn.donutpie.defaults = {
      radius: 240,
      tooltip : true,
      tooltipClass : "donut-pie-tooltip-bubble"
    };

}( jQuery ));

I have to change the color of the chart, but i can't do that. How I can change the two colors? I tried to modify the code, but it doesn't work. Please someone give a hand.

Body:
To change the color of the chart a "color" property must be specified in the object literal you pass to the update function. In your case, this object literal is defined in the return of get_data().

To add a color property to an object literal, follow the previous property with a comma and then define the name of your property with color:"#rrggbb".

out.push({name:props[0], hvalue: Math.floor((parseFloat(saldo)/totale)*100), color:"#FF0000"}); //makes color red


问:
Get a HTML list to dynamically alternate between two columns
I have an html list that I need to get split into two columns. I'm curious if I can do this purely in CSS without changing the HTML code.

For example:

I have a list like this:

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

But I want to display the list as two columns with equal width, but without changing the HTML code.

I've tried using child selectors and inline display but I can't figure out how to get the second column to start evenly.

This is what I'm trying to achieve in CSS. That way if I keep adding to the list, it keeps alternating the content between columns, as well as always having the second column be even.

li {
display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul></code>```

https://jsfiddle.net/u85avecb/

答:
You can use columns like this without changing your html code :

ul {
  -webkit-column-count: 2; /* Chrome, Safari, Opera */
    -moz-column-count: 2; /* Firefox */
    column-count: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul></code>```

Body:
I have an html list that I need to get split into two columns. I'm curious if I can do this purely in CSS without changing the HTML code.

For example:

I have a list like this:

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

But I want to display the list as two columns with equal width, but without changing the HTML code.

I've tried using child selectors and inline display but I can't figure out how to get the second column to start evenly.

This is what I'm trying to achieve in CSS. That way if I keep adding to the list, it keeps alternating the content between columns, as well as always having the second column be even.

li {
display: inline;
}

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

https://jsfiddle.net/u85avecb/

Body:
You can use columns like this without changing your html code :

ul {
  -webkit-column-count: 2; /* Chrome, Safari, Opera */
    -moz-column-count: 2; /* Firefox */
    column-count: 2;
}

<ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul>


问:
Dynamically Create Collection/Array in VBA
I'm struggling with this, I'm doing some stuff in Access with VBA and I need to dynamically create N collections/lists/arrays of records and add them to my dictionary.

```<code>//Some pseudo code
Dim dict as object
Set dict = CreateObject("Scripting.Dictionary")

for record in myRecordSetObject
    if dict.exists(keyfromrecord)
         dict(keyfromrecord) = array.add(record)
    else
         newarray = [record]
         dict.add key:="keyfromrecord" item:=array
</code>```

If it can't be done I might just do a string of primary keys and grow it as needed, then call string split.

Edit

So I have my records and I need to divide them into subgroups based on a few common fields that they may or may not share. If two records have the same pieces of information in these select fields they're in a subgroup. A subgroup may have 1 - N records.

Instead of getting all possible combinations and filtering my query I want to create a dictionary that defines it's key as a string generated from these fields. If a key exists then there's a member of that subgroup, if it doesn't it's a new subgroup.

The value was going to be an array of records.

Afterwards I was going to go through my dictionary and do stuff with these records.

```<code>Field1     Field2     Field3    Field4
Fruit      Skinned    Sliced    Baked
Apples     True       True      True
Bananas    True       True      True
Oranges    True       False     False
</code>```

Using this example above subgroup would be when Field2,3 and 4 have the same value. (Apples, Bananas) and the other would be (Oranges)

I want a dictionary with Key being

```<code>dictionary{
           "True-True-True": [Apples, Bananas],
           "True-False-True": [Oranges]
}
</code>```

答:
Not sure if this is what you are after, but this puts a recordset of each combination in at each dictionary key.

Based on your table, it gives keys of

FALSE-FALSE-FALSE-,FALSE-FALSE-TRUE-,FALSE-TRUE-FALSE-,FALSE-TRUE-TRUE-,TRUE-FALSE-FALSE-,TRUE-FALSE-TRUE-,TRUE-TRUE-FALSE-,TRUE-TRUE-TRUE-

where ? dicOutput("TRUE-TRUE-TRUE-").recordcount returns 2 records
 and GroupTable("0fruits")("TRUE-TRUE-TRUE-").recordcount the same 2

Hope this helps

```<code>Function GroupTable(strTableName As String) As Scripting.Dictionary

Dim strKey As String
Dim diccols As New Scripting.Dictionary
Dim dicOutput As Scripting.Dictionary
Dim dicTruth As Scripting.Dictionary
Dim rst As ADODB.Recordset
Dim rcols As ADODB.Recordset

Set rcols = New ADODB.Recordset
Set rcols = CurrentProject.Connection.OpenSchema(adSchemaColumns, Array(Empty, Empty, strTableName, Empty))

While Not rcols.EOF

    If rcols.Fields("COLUMN_NAME").Value <> "Fruit" Then
        diccols.Add CStr(diccols.Count), rcols.Fields("COLUMN_NAME").Value
    End If

    rcols.MoveNext
Wend

Set dicTruth = maketruthtable(2 ^ diccols.Count - 1, diccols.Count)
Set dicOutput = New Scripting.Dictionary

For l = 0 To dicTruth.Count - 1
    strSQL = "select [fruit] from [" & strTableName & "] where " & Join(diccols.Items(), "&") & "='" & dicTruth.Items()(l) & "'"
    Set rst = New ADODB.Recordset
    rst.Open strSQL, CurrentProject.Connection, adOpenStatic
    dicOutput.Add Replace(Replace(dicTruth.Items()(l), "-1", "TRUE-"), "0", "FALSE-"), rst
Next l

Set GroupTable = dicOutput

End Function

Function maketruthtable(intMax As Integer, intOptions As Integer) As Scripting.Dictionary

Dim d As New Scripting.Dictionary
Dim j As Integer

For j = 0 To intMax
    d.Add CStr(j), Replace(Right(DecToBin(j), intOptions), "1", "-1")
Next j

Set maketruthtable = d

End Function

Public Function DecToBin(ByVal lngDec As Long) As String

 Const MAXLEN = 5
 Dim strBin As String
 Dim n As Long

 If lngDec < 0 Then
    strBin = "1"
 Else
    strBin = "0"
 End If

 For n = MAXLEN To 0 Step -1
 If lngDec And (2 ^ n) Then
    strBin = strBin & "1"
 Else
    strBin = strBin & "0"
 End If
 Next

 DecToBin = strBin

 End Function
</code>```

EDIT

Another solution would be to use SQL to do it, so if you have a table with just TRUE in 1 row and False in another, called tblLogicOptions for example, like so

Then you can use the following SQL on a table called 0Fruits

Using the following SQL

```<code>select LOGICTABLE.*,Data.Fruit FROM (select ((x1.a) & (x2.a) & (x3.a)) as Logic from tblLogicOptions  as x1, tblLogicOptions  as x2, tblLogicOptions  as x3) AS LOGICTABLE
LEFT JOIN
(SELECT F1.Fruit, [skinned] & [sliced] & [baked] AS LogicCompare
FROM 0fruits as F1) AS DATA ON LOGICTABLE.Logic=DATA.LogicCompare
</code>```

Which gives the results

Looping through this to build the dictionary, or even using the resultant recordset perhaps, would be easier I think.

Body:
I'm struggling with this, I'm doing some stuff in Access with VBA and I need to dynamically create N collections/lists/arrays of records and add them to my dictionary.

//Some pseudo code
Dim dict as object
Set dict = CreateObject("Scripting.Dictionary")

for record in myRecordSetObject
    if dict.exists(keyfromrecord)
         dict(keyfromrecord) = array.add(record)
    else
         newarray = [record]
         dict.add key:="keyfromrecord" item:=array

If it can't be done I might just do a string of primary keys and grow it as needed, then call string split.

Edit

So I have my records and I need to divide them into subgroups based on a few common fields that they may or may not share. If two records have the same pieces of information in these select fields they're in a subgroup. A subgroup may have 1 - N records.

Instead of getting all possible combinations and filtering my query I want to create a dictionary that defines it's key as a string generated from these fields. If a key exists then there's a member of that subgroup, if it doesn't it's a new subgroup.

The value was going to be an array of records.

Afterwards I was going to go through my dictionary and do stuff with these records.

Field1     Field2     Field3    Field4
Fruit      Skinned    Sliced    Baked
Apples     True       True      True
Bananas    True       True      True
Oranges    True       False     False

Using this example above subgroup would be when Field2,3 and 4 have the same value. (Apples, Bananas) and the other would be (Oranges)

I want a dictionary with Key being

dictionary{
           "True-True-True": [Apples, Bananas],
           "True-False-True": [Oranges]
}

Body:
Not sure if this is what you are after, but this puts a recordset of each combination in at each dictionary key.

Based on your table, it gives keys of

FALSE-FALSE-FALSE-,FALSE-FALSE-TRUE-,FALSE-TRUE-FALSE-,FALSE-TRUE-TRUE-,TRUE-FALSE-FALSE-,TRUE-FALSE-TRUE-,TRUE-TRUE-FALSE-,TRUE-TRUE-TRUE-

where ? dicOutput("TRUE-TRUE-TRUE-").recordcount returns 2 records
 and GroupTable("0fruits")("TRUE-TRUE-TRUE-").recordcount the same 2

Hope this helps

Function GroupTable(strTableName As String) As Scripting.Dictionary

Dim strKey As String
Dim diccols As New Scripting.Dictionary
Dim dicOutput As Scripting.Dictionary
Dim dicTruth As Scripting.Dictionary
Dim rst As ADODB.Recordset
Dim rcols As ADODB.Recordset

Set rcols = New ADODB.Recordset
Set rcols = CurrentProject.Connection.OpenSchema(adSchemaColumns, Array(Empty, Empty, strTableName, Empty))

While Not rcols.EOF

    If rcols.Fields("COLUMN_NAME").Value <> "Fruit" Then
        diccols.Add CStr(diccols.Count), rcols.Fields("COLUMN_NAME").Value
    End If

    rcols.MoveNext
Wend

Set dicTruth = maketruthtable(2 ^ diccols.Count - 1, diccols.Count)
Set dicOutput = New Scripting.Dictionary

For l = 0 To dicTruth.Count - 1
    strSQL = "select [fruit] from [" & strTableName & "] where " & Join(diccols.Items(), "&") & "='" & dicTruth.Items()(l) & "'"
    Set rst = New ADODB.Recordset
    rst.Open strSQL, CurrentProject.Connection, adOpenStatic
    dicOutput.Add Replace(Replace(dicTruth.Items()(l), "-1", "TRUE-"), "0", "FALSE-"), rst
Next l

Set GroupTable = dicOutput

End Function

Function maketruthtable(intMax As Integer, intOptions As Integer) As Scripting.Dictionary

Dim d As New Scripting.Dictionary
Dim j As Integer

For j = 0 To intMax
    d.Add CStr(j), Replace(Right(DecToBin(j), intOptions), "1", "-1")
Next j

Set maketruthtable = d

End Function

Public Function DecToBin(ByVal lngDec As Long) As String

 Const MAXLEN = 5
 Dim strBin As String
 Dim n As Long

 If lngDec < 0 Then
    strBin = "1"
 Else
    strBin = "0"
 End If

 For n = MAXLEN To 0 Step -1
 If lngDec And (2 ^ n) Then
    strBin = strBin & "1"
 Else
    strBin = strBin & "0"
 End If
 Next

 DecToBin = strBin

 End Function

EDIT

Another solution would be to use SQL to do it, so if you have a table with just TRUE in 1 row and False in another, called tblLogicOptions for example, like so

Then you can use the following SQL on a table called 0Fruits

Using the following SQL

select LOGICTABLE.*,Data.Fruit FROM (select ((x1.a) & (x2.a) & (x3.a)) as Logic from tblLogicOptions  as x1, tblLogicOptions  as x2, tblLogicOptions  as x3) AS LOGICTABLE
LEFT JOIN
(SELECT F1.Fruit, [skinned] & [sliced] & [baked] AS LogicCompare
FROM 0fruits as F1) AS DATA ON LOGICTABLE.Logic=DATA.LogicCompare

Which gives the results

Looping through this to build the dictionary, or even using the resultant recordset perhaps, would be easier I think.


问:
Why does unordered_map take two values?
I'm just not getting it - why does this initialize a 2 parameter value?

I know there's a key and value...but do I need to specifically give the key every time? Doesn't this have an internal hashing function?

I have a question that's : "Given 2 arrays, find common numbers + different numbers". Simple enough. Though my issue is actually implementing the STL container "unordered_map" because I can't find anything explicitly explaining why it takes two parameters.

What I wanna' do:

```<code>unordered_map<int> hash;
hash.insert(5);

if ( hash.find(5) == true)
{
  cout << "Okay, got it. It's in the hash table." << endl;
}
</code>```

So something like that so you can get the gist. Just not sure why there are two values like:

```<code>unordered_map<int, int> hash;
</code>```

Thanks for the help!

答:
[...] but do I need to specifically give the key every time?

Yes! Thats what a map is about. If you dont care about the key, then you probably dont want a map, but a std::set or std::unordered_set.

Title: Why does unordered_map take two values?

Body:
I'm just not getting it - why does this initialize a 2 parameter value?

I know there's a key and value...but do I need to specifically give the key every time? Doesn't this have an internal hashing function?

I have a question that's : "Given 2 arrays, find common numbers + different numbers". Simple enough. Though my issue is actually implementing the STL container "unordered_map" because I can't find anything explicitly explaining why it takes two parameters.

What I wanna' do:

unordered_map<int> hash;
hash.insert(5);

if ( hash.find(5) == true)
{
  cout << "Okay, got it. It's in the hash table." << endl;
}

So something like that so you can get the gist. Just not sure why there are two values like:

unordered_map<int, int> hash;

Thanks for the help!


问:
python - convert UTC timestamp to unixtime
I'm trying to convert my timestamp to unixtime paying attention to it not being UTC however the unixtime is incorrect.

```<code>import time
import datetime
from dateutil.parser import parse

time_str = '2017-03-09T15:44:40.000-05:00'

time_obj = parse(time_str)

print time_obj

unixtime = time.mktime(time_obj.timetuple())

print unixtime
</code>```

The unixtime it returns is 1489092280.0 which represents to 03/09/2017 @ 8:44pm (UTC) when what I want is 1489074280.

答: I believe your result was correct. 15:44 in -05:00 timezone is 20:44 (ie. 8:44 pm) in UTC. </p>

Body:
I'm trying to convert my timestamp to unixtime paying attention to it not being UTC however the unixtime is incorrect.

import time
import datetime
from dateutil.parser import parse

time_str = '2017-03-09T15:44:40.000-05:00'

time_obj = parse(time_str)

print time_obj

unixtime = time.mktime(time_obj.timetuple())

print unixtime

The unixtime it returns is 1489092280.0 which represents to 03/09/2017 @ 8:44pm (UTC) when what I want is 1489074280.


问:
Read-Only ADO.NET Connection String for Excel
I'm trying to prevent the following from coming up when reading an Excel file using ADO.NET:

The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data.

I know it is happening because another user has the file open, but I can't get rid of it.  I've tried adding Read Only=True; to my connection string, but that doesn't work.  I've also tried to set the Mode of the connection to read-only, but I can't figure out how to in C#.

Here is my connection string:

```<code>Provider=Microsoft.Jet.OLEDB.4.0; data source=test.xls; Extended Properties="Excel 8.0;HDR=No;IMEX=1"
</code>```

Thanks for the help!

答:
Well, you said you tried changing the mode to read only, how exactly did you do that?

As per MSDN, by default, the OLE DB Provider for Microsoft Jet opens Microsoft Jet databases in read/write mode. To open a database in read-only mode, set the Mode property on the ADO Connection object to adModeRead.

So in C# it should have looked like:

```<code>ADODB.Connection myConn = new new ADODB.Connection();
myConn.Mode = adModeRead; //1
myConn.Open(strConectionString, null, null, -1);
</code>```

Body:
I'm trying to prevent the following from coming up when reading an Excel file using ADO.NET:

The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data.

I know it is happening because another user has the file open, but I can't get rid of it.  I've tried adding Read Only=True; to my connection string, but that doesn't work.  I've also tried to set the Mode of the connection to read-only, but I can't figure out how to in C#.

Here is my connection string:

Provider=Microsoft.Jet.OLEDB.4.0; data source=test.xls; Extended Properties="Excel 8.0;HDR=No;IMEX=1"

Thanks for the help!

Body:
Well, you said you tried changing the mode to read only, how exactly did you do that?

As per MSDN, by default, the OLE DB Provider for Microsoft Jet opens Microsoft Jet databases in read/write mode. To open a database in read-only mode, set the Mode property on the ADO Connection object to adModeRead.

So in C# it should have looked like:

ADODB.Connection myConn = new new ADODB.Connection();
myConn.Mode = adModeRead; //1
myConn.Open(strConectionString, null, null, -1);


问:
C# Docusign API - Getting Remote Signing View URL
After running the console app, our users get an email with the signing link to Docusign making them remote signers.

What I want to be able to do is get those links from their emails.

I did some research and this is what each url is made of

https://demo.docusign.net/Member/EmailStart.aspx?

a=65d11cf7-d3b7-49a1-8000-6192b6227d71& <<< Unique Activity ID? Always different in all URLs

acct=a0e816ac-3919-475e-a826-34c2c33f90e7& <<< Some kind of role ID (stays same between envelopes and users of the same role, I have it
for my roles..just don't know how to get it programmatically

er=62378ec0-39ce-495e-84e4-e0e598fab3cc& <<<< envelopesApi.ListRecipients(.....) .Signers[n].RecipientIdGuid, able to get it

espei=30cec285-39cd-45a3-bb8e-7bd0560dcd80 <<<< ENVELOPE ID, able to get it

The first parameter is the main focus of my question - it is a total mistery what is it and how to get it

The second parameter looks like a role_id, but I don't know how to get it other than hard-coding values for each of my roles

The other two parameters aren't a concern.

Does anybody know how to get ahold of the first two parameters using the C# Docusign API?

Or even better, is there a way to get the recipients signing url links using the same API?

答:
To obtain the signing URL you will have to set the recipient as an embedded recipient.

After the envelope is created, use the createRecipient:EnvelopeViews api to retrieve the Signing URL.

You have to set the recipient clientUserId parameter to mark a recipient as an embedded recipient.

Request

```<code>{
  "userName": "name",
  "email": "examble@email.com",
  "clientUserId": "clientUserId",
  "authenticationMethod": "email",
  "returnUrl": "your app url"
}
</code>```

Body:
To obtain the signing URL you will have to set the recipient as an embedded recipient.

After the envelope is created, use the createRecipient:EnvelopeViews api to retrieve the Signing URL.

You have to set the recipient clientUserId parameter to mark a recipient as an embedded recipient.

Request

{
  "userName": "name",
  "email": "examble@email.com",
  "clientUserId": "clientUserId",
  "authenticationMethod": "email",
  "returnUrl": "your app url"
}


问:
variables are not working in rand range statement in bubble sort program
I attempted to add a user input for the rand range statement and the total numbers in the list that it will sort through, I've tried everything I can to counter this but nothing seems to be working correctly.</p>

```<code>import time
import random
def create_random_values():
    totalsortnum = (eval("Please enter the amount of numbers you wish to sort: "))

    rng1 = (eval("Please enter the maximum number range: "))
    randomList=[]
    for i in range (totalsortnum):
        randomList.append(random.randrange(1,rng1))
    return randomList, totalsortnum, rng1

def main():
    numList = create_random_values()
    print()
    print("Here is a random list of 20 numbers between 1 and 1000:")
    print(numList)

    pause = input("Hit <Enter> to start sorting")

    timeInitial = time.time()
    l = len(numList)
    for lastitem in range(l-1,0,-1):
        sorted = True
        for i in range(lastitem):
            if numList[i] > numList[i+1]:
                numList[i],numList[i+1] = numList[i+1],numList[i]
                sorted = False
            #print(numList)
            #pause = input("Hit <Enter> to start sorting")
        if sorted == True:
            break
    timeFinal = time.time()
    print(numList)

    print("the selection sort of",len(numList),"items took:")
    print(timeFinal - timeInitial,"seconds.")
</code>```

答:
There's a couple problems with your code:

Inside of create_random_values() you're trying to use eval() for user input.

eval() is not the function you want, you want input().

Inside of main() your numList variable is a 3-tuple, (randomList, totalsortnum, rng1), I think you meant to reference just randomList.

This should work for you:

```<code>import time
import random
def create_random_values():
    totalsortnum = int(input("Please enter the amount of numbers you wish to sort: "))

    rng1 = int(input("Please enter the maximum number range: "))
    randomList=[]
    for i in range (totalsortnum):
        randomList.append(random.randrange(1,rng1))
    return randomList, totalsortnum, rng1

def main():
    numList, totalsortnum, rng1 = create_random_values()
    print()
    print("Here is a random list of {0} numbers between 1 and {1}:".format(totalsortnum, rng1))
    print(numList)

    pause = input("Hit <Enter> to start sorting")

    timeInitial = time.time()
    l = len(numList)
    for lastitem in range(l-1,0,-1):
        sorted = True
        for i in range(lastitem):
            if numList[i] > numList[i+1]:
                numList[i],numList[i+1] = numList[i+1],numList[i]
                sorted = False
            print(numList)
            #pause = input("Hit <Enter> to start sorting")
        if sorted == True:
            break
    timeFinal = time.time()
    print(numList)

    print("the selection sort of",len(numList),"items took:")
    print(timeFinal - timeInitial,"seconds.")
</code>```

Body:
I attempted to add a user input for the rand range statement and the total numbers in the list that it will sort through, I've tried everything I can to counter this but nothing seems to be working correctly.

import time
import random
def create_random_values():
    totalsortnum = (eval("Please enter the amount of numbers you wish to sort: "))

    rng1 = (eval("Please enter the maximum number range: "))
    randomList=[]
    for i in range (totalsortnum):
        randomList.append(random.randrange(1,rng1))
    return randomList, totalsortnum, rng1

def main():
    numList = create_random_values()
    print()
    print("Here is a random list of 20 numbers between 1 and 1000:")
    print(numList)

    pause = input("Hit <Enter> to start sorting")

    timeInitial = time.time()
    l = len(numList)
    for lastitem in range(l-1,0,-1):
        sorted = True
        for i in range(lastitem):
            if numList[i] > numList[i+1]:
                numList[i],numList[i+1] = numList[i+1],numList[i]
                sorted = False
            #print(numList)
            #pause = input("Hit <Enter> to start sorting")
        if sorted == True:
            break
    timeFinal = time.time()
    print(numList)

    print("the selection sort of",len(numList),"items took:")
    print(timeFinal - timeInitial,"seconds.")

Body:
There's a couple problems with your code:

Inside of create_random_values() you're trying to use eval() for user input.

eval() is not the function you want, you want input().

Inside of main() your numList variable is a 3-tuple, (randomList, totalsortnum, rng1), I think you meant to reference just randomList.

This should work for you:

import time
import random
def create_random_values():
    totalsortnum = int(input("Please enter the amount of numbers you wish to sort: "))

    rng1 = int(input("Please enter the maximum number range: "))
    randomList=[]
    for i in range (totalsortnum):
        randomList.append(random.randrange(1,rng1))
    return randomList, totalsortnum, rng1

def main():
    numList, totalsortnum, rng1 = create_random_values()
    print()
    print("Here is a random list of {0} numbers between 1 and {1}:".format(totalsortnum, rng1))
    print(numList)

    pause = input("Hit <Enter> to start sorting")

    timeInitial = time.time()
    l = len(numList)
    for lastitem in range(l-1,0,-1):
        sorted = True
        for i in range(lastitem):
            if numList[i] > numList[i+1]:
                numList[i],numList[i+1] = numList[i+1],numList[i]
                sorted = False
            print(numList)
            #pause = input("Hit <Enter> to start sorting")
        if sorted == True:
            break
    timeFinal = time.time()
    print(numList)

    print("the selection sort of",len(numList),"items took:")
    print(timeFinal - timeInitial,"seconds.")


问:
How to remove all double spaces from the text
I'm struggeling a bit with my homework. In one task we have to correct a text. We have to remove multiple spaces from the text and turn that into one space. And if there is the space at the beginning or at the end we have to do the same. I have created this function:

```<code>function clean(word) {
  var output = "";
  for (var x = 0; x < word.length; x++)
  {
      if (word.charAt(x) !== " " || word.charAt(x + 1) !== " ") {
        output = output + word.charAt(x);
      }
  }

  return output;
}
console.log("test = " + clean(" test  word  testing   more"));
</code>```

This works for all the spaces in the text but not at the begionning and end. Also it would be better if I do not use the number of the character directly (x) but I can do it if I don't find another way...

答:
You can simply use String.prototype.replace:

function clean(str) {
  // remove double spaces
  while (str.indexOf("  ") > -1) {
    str = str.replace("  ", " ");
  }

  // remove spaces in the beginning and end (it is called "trim")
  return str.trim();
}

console.log(clean(" This is    the    text  with double   spaces!  "));```

This can be solved in many other ways like using regular expression, but I have decided to demonstrate the easiest and understandable solution.

Body:
I'm struggeling a bit with my homework. In one task we have to correct a text. We have to remove multiple spaces from the text and turn that into one space. And if there is the space at the beginning or at the end we have to do the same. I have created this function:

function clean(word) {
  var output = "";
  for (var x = 0; x < word.length; x++)
  {
      if (word.charAt(x) !== " " || word.charAt(x + 1) !== " ") {
        output = output + word.charAt(x);
      }
  }

  return output;
}
console.log("test = " + clean(" test  word  testing   more"));

This works for all the spaces in the text but not at the begionning and end. Also it would be better if I do not use the number of the character directly (x) but I can do it if I don't find another way...

Body:
You can simply use String.prototype.replace:

function clean(str) {
  // remove double spaces
  while (str.indexOf("  ") > -1) {
    str = str.replace("  ", " ");
  }

  // remove spaces in the beginning and end (it is called "trim")
  return str.trim();
}

console.log(clean(" This is    the    text  with double   spaces!  "));

This can be solved in many other ways like using regular expression, but I have decided to demonstrate the easiest and understandable solution.


问:
Seeing if a column value is updated
I have a complex user model with a validation method

```<code>before_validation_on_update :geocode_places
</code>```

This validation geocodes the "places" column in my user table each time an update occurs.

The problem is that this validation takes quite a long time. Is there any way to only call this validation when the places column is updated? Sort of like a "before_validation_on_column_update" so to speak..

答:
There's a whole set of methods available for that. E.g., self.places_changed? should work.

Check the docs for more.

Title: Seeing if a column value is updated

Body:
I have a complex user model with a validation method

before_validation_on_update :geocode_places

This validation geocodes the "places" column in my user table each time an update occurs.

The problem is that this validation takes quite a long time. Is there any way to only call this validation when the places column is updated? Sort of like a "before_validation_on_column_update" so to speak..


问:
Where to store values calculated from props in React
What is the best place to store the result of an expensive calculation from the React props which I use in render() but do not want to execute at each render() ?

```<code>constructor(props) {
    super(props)
    const result = this.doExpensiveCalculation(props)
}

componentWillReceiveProps(nextProps) {
    // if nextProps differ from props
    const result = this.doExpensiveCalculation(nextProps)
}

doExpensiveCalculation(props) {
   // Some expensive stuff
}

render(){
    // Use doExpensiveCalculation(this.props) here
}
</code>```

The options are this and state but both I see rather unsatisfying. Is there a ready solution which uses memoisation?

On the other hand, should I worry about optimizing this ? I read that React can rerender component even if the props have not changed but does this happen often ?

答:
If all you want to do is perform the expensive calculation whenever you get new props, instead of on every render, you probably want componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component receives new props.

As far as where to store them, you can either store them in state, or as a property directly on the component instance. Either will work just as well.

You want to make sure compare values though, to avoid unnecessarily recomputing.

For example:

```<code>componentWillReceiveProps(nextProps) {
    if (nextProps.someValue !== this.props.someValue) {
        this.someResult = this.performExpensiveCalculation(nextProps.someValue);
    }
}
</code>```

Body:
What is the best place to store the result of an expensive calculation from the React props which I use in render() but do not want to execute at each render() ?

constructor(props) {
    super(props)
    const result = this.doExpensiveCalculation(props)
}

componentWillReceiveProps(nextProps) {
    // if nextProps differ from props
    const result = this.doExpensiveCalculation(nextProps)
}

doExpensiveCalculation(props) {
   // Some expensive stuff
}

render(){
    // Use doExpensiveCalculation(this.props) here
}

The options are this and state but both I see rather unsatisfying. Is there a ready solution which uses memoisation?

On the other hand, should I worry about optimizing this ? I read that React can rerender component even if the props have not changed but does this happen often ?

Body:
If all you want to do is perform the expensive calculation whenever you get new props, instead of on every render, you probably want componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component receives new props.

As far as where to store them, you can either store them in state, or as a property directly on the component instance. Either will work just as well.

You want to make sure compare values though, to avoid unnecessarily recomputing.

For example:

componentWillReceiveProps(nextProps) {
    if (nextProps.someValue !== this.props.someValue) {
        this.someResult = this.performExpensiveCalculation(nextProps.someValue);
    }
}


问:
calculate frequency using sql
I have a table in MySQL:

```<code>Col1 | Col2
 a       A
 a       B
 c       C
 a       B
</code>```

i want to create a table like this:

```<code>col1 | col2 |    freq
 a        A      0.33
 a        B      0.67
</code>```

col1 is a specified item in Col1. col2 is distinct item that has occured with the specified item(i.e. a). freq column is the frequency of appearence of item in col2.

Can someone give me a hint of how to create such a query? Thanks a lot.

答:
You can also use this which is coded in SQL server

```<code>  DECLARE @Count INT;
  SELECT @Count = COUNT(1) FROM YourTableName   WHERE Col1 = 'a'

  SELECT Col1, Col2, CAST(COUNT(1)* 1.00 /@Count AS DECIMAL(4,2) ) AS Frequency
  FROM YourTableName
  WHERE Col1 = 'a'
  GROUP BY Col1, Col2
</code>```

this way you have a better performance

Title: calculate frequency using sql

Body:
I have a table in MySQL:

Col1 | Col2
 a       A
 a       B
 c       C
 a       B

i want to create a table like this:

col1 | col2 |    freq
 a        A      0.33
 a        B      0.67

col1 is a specified item in Col1. col2 is distinct item that has occured with the specified item(i.e. a). freq column is the frequency of appearence of item in col2.

Can someone give me a hint of how to create such a query? Thanks a lot.

Body:
You can also use this which is coded in SQL server

  DECLARE @Count INT;
  SELECT @Count = COUNT(1) FROM YourTableName   WHERE Col1 = 'a'

  SELECT Col1, Col2, CAST(COUNT(1)* 1.00 /@Count AS DECIMAL(4,2) ) AS Frequency
  FROM YourTableName
  WHERE Col1 = 'a'
  GROUP BY Col1, Col2

this way you have a better performance


问:
lightbox doesn't want to open image from folder
I'm trying to setup lightbox plugin to load images from folder, but it don't want to open image.
When I click on image and it trying open with lightbox, in terminal I get Routing error, no route matches.
Lightbox is working, tried with external image link, but it not working with images from folder.

This is what I have so far.

index.html.erb

```<code><div class="container">
  <id class="gallery">
    <div class="row">
      <% @images.each do |image| %>
        <div class="col-md-2">
          <a href="<%= image %>" class="img-responsive" data-lightbox="my-images">
            <%= image_tag image, class: "img-responsive" %>
          </a>
        </div>
      <% end %>
    </div>
  </id>
</div>
</code>```

controller.rb

```<code>  def gallery
    @images = Dir.chdir(Rails.root.join('app/assets/images')) do
      Dir.glob("galleria/landscape/*.jpg")
    end
  end
</code>```

application.js

```<code>//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require lightbox
//= require_tree .
</code>```

application.css

```<code> @import "lightbox";
</code>```

Source code:

```<code><a href="galleria/portrait/17-min.jpg" class="photo-hover img-responsive" data-lightbox="my-images"">
    <img class="img-responsive" src="/assets/galleria/portrait/17-min-ec4c03d557eb21edfdb115aaf9a69eab86e27b247385b8af3bb88a87cb398fd5.jpg" alt="17 min" />
</a>
</code>```

答:
Correct example

Problem was with a href url.

```<code><% @images.each do |image| %>
  <div class="col-md-3 portrait">
    <a href='<%= "/images/#{image}" %>' data-lightbox="my-images">
      <%= image_tag image, class: "img-responsive" %>
    </a>
  </div>
<% end %>
</code>```

Body:
I'm trying to setup lightbox plugin to load images from folder, but it don't want to open image.
When I click on image and it trying open with lightbox, in terminal I get Routing error, no route matches.
Lightbox is working, tried with external image link, but it not working with images from folder.

This is what I have so far.

index.html.erb

  <id class="gallery">

      <% @images.each do |image| %>

          <a href="<%= image %>" class="img-responsive" data-lightbox="my-images">
            <%= image_tag image, class: "img-responsive" %>

      <% end %>

  </id>

controller.rb

  def gallery
    @images = Dir.chdir(Rails.root.join('app/assets/images')) do
      Dir.glob("galleria/landscape/*.jpg")
    end
  end

application.js

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require lightbox
//= require_tree .

application.css

 @import "lightbox";

Source code:

Body:
Correct example

Problem was with a href url.

<% @images.each do |image| %>
  <div class="col-md-3 portrait">
    <a href='<%= "/images/#{image}" %>' data-lightbox="my-images">
      <%= image_tag image, class: "img-responsive" %>
    </a>
  </div>
<% end %>


问:
Low-level caching with Django
Instead of caching the whole site, or whole views, I've decided to cache only a few heavy queries, using the low level caching API.

I'm doing something like this

```<code>key = ...
value = cache.get(key)
if value is None:
    value = ...
    cache.set(key, value, CACHE_TIMEOUT)
</code>```

It works almost as expected (question 01: is there a better way to do it?),

but if I set CACHE_TIMEOUT to a big value (86400: the db is updated once a day),
it looks that CACHE_TIMEOUT is being overrided by something else, and the value is cached just for a few minutes...

(question 02:) What am I doing wrong?

Is my timeout too long?
Or maybe I'm caching too much information? (value contains ~ 500-1000 objects, and it's evaluated in 50-60 different pages/keys)

答:
I do not know which cache backend you are using nor how you exactly set the timeout, but maybe you're doing wrong (from the django documentation on caching):

Each cache backend may take arguments. They're given in
    query-string style on the
    CACHE_BACKEND setting. Valid arguments
    are as follows:

timeout: The default timeout, in seconds, to use for the cache. This
argument defaults to 300 seconds (5

...

CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=60

Title: Low-level caching with Django

Body:
Instead of caching the whole site, or whole views, I've decided to cache only a few heavy queries, using the low level caching API.

I'm doing something like this

key = ...
value = cache.get(key)
if value is None:
    value = ...
    cache.set(key, value, CACHE_TIMEOUT)

It works almost as expected (question 01: is there a better way to do it?),

but if I set CACHE_TIMEOUT to a big value (86400: the db is updated once a day),
it looks that CACHE_TIMEOUT is being overrided by something else, and the value is cached just for a few minutes...

(question 02:) What am I doing wrong?

Is my timeout too long?
Or maybe I'm caching too much information? (value contains ~ 500-1000 objects, and it's evaluated in 50-60 different pages/keys)


问:
How to pass property value into init method in SAPUI5?
Let's imagine I have a class

```<code>sap.ui.core.Control.extend("sap.my.MyButton", {
    metadata: {
        properties: {
            "isButtonWithMenu": {
                type: "boolean",
                defaultValue: true
            }
        }
    }
},

init: function () {
    if (this.getIsButtonWithMenu()) {
         this.myButton = this._createMenuButton();
    } else {
         this.myButton = this._createNormalButton();
    }
    var baseBox = new sap.m.FlexBox();
    baseBox.addItem(this.myButton);
    this.setLayout(baseBox);
}
</code>```

Now I want to pass the value for isButtonWithMenu into my init method and I do the following:

```<code>var myButton = new sap.my.MyButton({isButtonWithMenu: false});
</code>```

but this doesn't work which means that I don't get passed value inside the class. However, when I change defaultValue it does work, so, what is wrong in here and how I can achieve my target?

答:
Your problem is caused by the code here in the ManagedObject's constructor. This class is a superclass of any control (ManagedObject <-- Element <-- Control). If you look into the code you will notice the the following steps occur:

An empty property bag is constructed (actually with your default values).

The control's init method is called.

The mSettings property bag is applied to your control. This property bag is the one that you (or the XML view parser) pass in the controls constructor.

This is the designed behavior for UI5. Because the init function should bring the control in an initialized state and only afterwards will the properties (passed to the constructor) be applied to your control. This ensures that whatever setters you have redefined are always called after the control was initialized (well, at least except the situation in which you call them inside the initialization code).

To get around this you have two options that I can think about:

Use the 0 delayed call trick (see What is setTimeout doing when set to 0 milliseconds? for explanations). Basically you can do: jQuery.sap.delayedCall(0, this, function() { this.myButton = ... }) to ensure that the settings were already applied to your control.

Define a constructor method for your control. Something along the lines of:

 sap.ui.core.Control.extend("sap.my.MyButton", {

    metadata: { /* same as before */},

    constructor: function () {
        sap.ui.core.Control.apply(this, arguments);

        // the init function was already called by this point
        // also the settings should have been applied

        if (this.getIsButtonWithMenu()) {
             this.myButton = this._createMenuButton();
        } else {
             this.myButton = this._createNormalButton();
        }
        var baseBox = new sap.m.FlexBox();
        baseBox.addItem(this.myButton);
        this.setLayout(baseBox);

    }
})
```

You can also put your code before the super constructor call (not really correct from an OOP perspective), but then you cannot use the getter and should look inside the mSettings constructor parameter (2nd param) instead.

Body:
Let's imagine I have a class

sap.ui.core.Control.extend("sap.my.MyButton", {
    metadata: {
        properties: {
            "isButtonWithMenu": {
                type: "boolean",
                defaultValue: true
            }
        }
    }
},

init: function () {
    if (this.getIsButtonWithMenu()) {
         this.myButton = this._createMenuButton();
    } else {
         this.myButton = this._createNormalButton();
    }
    var baseBox = new sap.m.FlexBox();
    baseBox.addItem(this.myButton);
    this.setLayout(baseBox);
}

Now I want to pass the value for isButtonWithMenu into my init method and I do the following:

var myButton = new sap.my.MyButton({isButtonWithMenu: false});

but this doesn't work which means that I don't get passed value inside the class. However, when I change defaultValue it does work, so, what is wrong in here and how I can achieve my target?

Body:
Your problem is caused by the code here in the ManagedObject's constructor. This class is a superclass of any control (ManagedObject <-- Element <-- Control). If you look into the code you will notice the the following steps occur:

An empty property bag is constructed (actually with your default values).

The control's init method is called.

The mSettings property bag is applied to your control. This property bag is the one that you (or the XML view parser) pass in the controls constructor.

This is the designed behavior for UI5. Because the init function should bring the control in an initialized state and only afterwards will the properties (passed to the constructor) be applied to your control. This ensures that whatever setters you have redefined are always called after the control was initialized (well, at least except the situation in which you call them inside the initialization code).

To get around this you have two options that I can think about:

Use the 0 delayed call trick (see What is setTimeout doing when set to 0 milliseconds? for explanations). Basically you can do: jQuery.sap.delayedCall(0, this, function() { this.myButton = ... }) to ensure that the settings were already applied to your control.

Define a constructor method for your control. Something along the lines of:

 sap.ui.core.Control.extend("sap.my.MyButton", {

    metadata: { /* same as before */},

    constructor: function () {
        sap.ui.core.Control.apply(this, arguments);

        // the init function was already called by this point
        // also the settings should have been applied

        if (this.getIsButtonWithMenu()) {
             this.myButton = this._createMenuButton();
        } else {
             this.myButton = this._createNormalButton();
        }
        var baseBox = new sap.m.FlexBox();
        baseBox.addItem(this.myButton);
        this.setLayout(baseBox);

    }
})

You can also put your code before the super constructor call (not really correct from an OOP perspective), but then you cannot use the getter and should look inside the mSettings constructor parameter (2nd param) instead.