问:
Excel - Count unique values that match ID, optimized for 100,000+ cases
in reference to the excel screen capture below, I'm looking for a formula solution that counts the number of unique values in Column B (Colour) for each ID number in Column A.

I've imputed the desired result in Column C. So, for instance, ID 1 (A2) has only one unique colour, Grey (B2), which would return a 1 in C2. ID 2 has only one unique colour, yellow (B3, B4), and returns 1 in C3 and C4. ID 3, has two unique colours, Blue and Purple, thus returning a 2 in C5 through C8. Etc.

Because this will be run for close to 100,000 rows, many of the index and/or match based solutions I've come across take way to long to compute. I have found that the ID values, which are all in ascending order, can be used to speed things up by starting the formula with =IF(A2=A1, or something like this. Thanks in advance to anyone with some ideas about how to solve this with a lean formula.

Note: I am working with files that also have close to 100 columns. A solution that doesn't require helper columns would be ideal.

EDIT/ADDITION: In my main data file, there are instances of blank cells in column B. Is there a way to ignore the blank cells when counting for column C results?

答:
Here is a VBA routine that should run quickly for that number of entries.  We create a Class Module (User Defined Object) that consists of a collection (Dictionary) of Colors associated with each ID, and an count of that color. (Don't really need the count but it is trivial to add it in, in case you want it for some other purpose; and also as a demonstration of some of what could be done).

Then we output the results in the adjacent column, as you show in your screen shot.  The results could be output elsewhere, even on a different worksheet, with minor code changes.

Be sure to read the notes at the beginning of the modules for important information and about setting things up properly.

Class Module

```<code>Option Explicit
'RENAME this module:  cID

Private pID As String
Private pColor As String
Private pColors As Dictionary

Public Property Get ID() As String
    ID = pID
End Property
Public Property Let ID(Value As String)
    pID = Value
End Property

Public Property Get Color() As String
    Color = pColor
End Property
Public Property Let Color(Value As String)
    pColor = Value
End Property

Public Property Get Colors() As Dictionary
    Set Colors = pColors
End Property
Public Function ADDColor(Value As String)
    'Might as well also count # of times this color assigned
    If Not pColors.Exists(Value) Then
        pColors.Add Key:=Value, Item:=1
    Else
        pColors(Value) = pColors(Value) + 1
    End If
End Function

Private Sub Class_Initialize()
    Set pColors = New Dictionary
End Sub
</code>```

Regular Module

EDIT (edited to eliminate count for blank rows)

```<code>Option Explicit
'Set reference to Microsoft Scripting Runtime (Tools/References)

Sub IDColorCount()
    Dim cID As cID, dID As Dictionary
    Dim wsData As Worksheet, rData As Range
    Dim vData As Variant, vRes As Variant
    Dim I As Long

'Set the data worksheet and range
'Read the data into an array for faster calculations
Set wsData = Worksheets("sheet1")
With wsData
    Set rData = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(columnsize:=2)
    vData = rData
End With

'Go through the data and collect the information
Set dID = New Dictionary
For I = 2 To UBound(vData, 1)
  If Not vData(I, 1) = "" Then
    Set cID = New cID
    With cID
        .ID = vData(I, 1)
        .Color = vData(I, 2)
        .ADDColor .Color

        If Not dID.Exists(.ID) Then
            dID.Add Key:=.ID, Item:=cID
        Else
            dID(.ID).ADDColor .Color
        End If
    End With
  End If
Next I

'Size the results array
ReDim vRes(1 To UBound(vData), 1 To 1)
vRes(1, 1) = "Count"
For I = 2 To UBound(vData, 1)
    If Not vData(I, 1) = "" Then _
        vRes(I, 1) = dID(CStr(vData(I, 1))).Colors.Count
Next I

'The results can  be written anyplace
With rData.Offset(0, 2).Resize(columnsize:=1)
    .EntireColumn.Clear
    .Value = vRes
End With

End Sub
</code>```

Body:
Here is a VBA routine that should run quickly for that number of entries.  We create a Class Module (User Defined Object) that consists of a collection (Dictionary) of Colors associated with each ID, and an count of that color. (Don't really need the count but it is trivial to add it in, in case you want it for some other purpose; and also as a demonstration of some of what could be done).

Then we output the results in the adjacent column, as you show in your screen shot.  The results could be output elsewhere, even on a different worksheet, with minor code changes.

Be sure to read the notes at the beginning of the modules for important information and about setting things up properly.

Class Module

Option Explicit
'RENAME this module:  cID

Private pID As String
Private pColor As String
Private pColors As Dictionary

Public Property Get ID() As String
    ID = pID
End Property
Public Property Let ID(Value As String)
    pID = Value
End Property

Public Property Get Color() As String
    Color = pColor
End Property
Public Property Let Color(Value As String)
    pColor = Value
End Property

Public Property Get Colors() As Dictionary
    Set Colors = pColors
End Property
Public Function ADDColor(Value As String)
    'Might as well also count # of times this color assigned
    If Not pColors.Exists(Value) Then
        pColors.Add Key:=Value, Item:=1
    Else
        pColors(Value) = pColors(Value) + 1
    End If
End Function

Private Sub Class_Initialize()
    Set pColors = New Dictionary
End Sub

Regular Module

EDIT (edited to eliminate count for blank rows)

Option Explicit
'Set reference to Microsoft Scripting Runtime (Tools/References)

Sub IDColorCount()
    Dim cID As cID, dID As Dictionary
    Dim wsData As Worksheet, rData As Range
    Dim vData As Variant, vRes As Variant
    Dim I As Long

'Set the data worksheet and range
'Read the data into an array for faster calculations
Set wsData = Worksheets("sheet1")
With wsData
    Set rData = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(columnsize:=2)
    vData = rData
End With

'Go through the data and collect the information
Set dID = New Dictionary
For I = 2 To UBound(vData, 1)
  If Not vData(I, 1) = "" Then
    Set cID = New cID
    With cID
        .ID = vData(I, 1)
        .Color = vData(I, 2)
        .ADDColor .Color

        If Not dID.Exists(.ID) Then
            dID.Add Key:=.ID, Item:=cID
        Else
            dID(.ID).ADDColor .Color
        End If
    End With
  End If
Next I

'Size the results array
ReDim vRes(1 To UBound(vData), 1 To 1)
vRes(1, 1) = "Count"
For I = 2 To UBound(vData, 1)
    If Not vData(I, 1) = "" Then _
        vRes(I, 1) = dID(CStr(vData(I, 1))).Colors.Count
Next I

'The results can  be written anyplace
With rData.Offset(0, 2).Resize(columnsize:=1)
    .EntireColumn.Clear
    .Value = vRes
End With

End Sub


来源: stackexchange

问:
MS SQL Split a column value using delimiters and update in other field
Ex,  I have a table like this,

```<code>ID Name
1  Apple,banana
2  Grape,Orange
3  Papaya,Jackfruit
</code>```

I need to split (,) and save like this in SQL

```<code>ID Name    Name2
1  Apple   banana
2  Grape   Orange
3  Papaya  Jackfruit
</code>```

答:
The fastest, most scaleable  way to split strings before SQL Server 2016 is to write a SQLCLR method that splits strings, like this one. SQL Server 2016 introduced the STRING_SPLIT function which is even faster.

The second fastest way to split strings for versions before SQL Server 2016 is to convert the separated text into XML and use XML operators to retrieve the individual items. The typical usage, as shown in Aaron Bertrand's articles returns items as rows. It can be adapted easily to return items as columns:

```<code>declare @table table (ID int, Name nvarchar(200))
insert into @table
values
(1,'Apple,banana'),
(2,'Grape,Orange'),
(3,'Papaya,Jackfruit');

with items as (
    select
        ID,
        xmlField= cast('<item><tag>'
                        + replace(Name,',','</tag><tag>')
                        + '</tag></item>' as xml)
    from @table
)
-- Step 2: Select different tags and display them as fields
select
    y.item.value('(tag/text())[1]','nvarchar(20)') As Name1,
    y.item.value('(tag/text())[2]','nvarchar(20)') as Name2
from items outer apply xmlField.nodes('item') as y(item)
</code>```

This returns :

```<code>1   Apple   banana
2   Grape   Orange
3   Papaya  Jackfruit
</code>```

This works by first converting Name1,Name2 to <item><tag>Name1</tag><tag>Name2</tag><item> which can be cast to XML and returned as xmlField.

outer apply xmlField.nodes('item') as y(item) converts this field to a table of items named y. Only one item row exists in each field.

Finally, y.item.value('(tag/text())[1]','nvarchar(20)') extracts the text of the first tag element as Name1.

This can be extended easily to multiple entries, or to return entries as different elements.

The number of columns has to be known in advance. SQL, the language, doesn't allow an arbitrary number of columns. If different fields contain a different number of tokens, they'll have to be returned as rows.

In this case, you should use STRING_SPLIT if you target SQL Server 2016 or the original version of the XML splitting technique :

```<code>CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       nvarchar(max),
   @Delimiter  nvarchar(10)
)
RETURNS TABLE WITH SCHEMABINDING
AS
   RETURN (SELECT [value] = y.i.value('(./text())[1]', 'varchar(8000)')
      FROM (SELECT x = CONVERT(XML, '<i>'
          + REPLACE(@List, @Delimiter, '</i><i>')
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i));
</code>```

It's worth checking Performance Surprises and Assumptions : STRING_SPLIT() which compares all available string splitting techniques to find the fastest and most scaleable

ContentLicense: CC BY-SA 3.0

Body:
Ex,  I have a table like this,

ID Name
1  Apple,banana
2  Grape,Orange
3  Papaya,Jackfruit

I need to split (,) and save like this in SQL

ID Name    Name2
1  Apple   banana
2  Grape   Orange
3  Papaya  Jackfruit

Body:
The fastest, most scaleable  way to split strings before SQL Server 2016 is to write a SQLCLR method that splits strings, like this one. SQL Server 2016 introduced the STRING_SPLIT function which is even faster.

The second fastest way to split strings for versions before SQL Server 2016 is to convert the separated text into XML and use XML operators to retrieve the individual items. The typical usage, as shown in Aaron Bertrand's articles returns items as rows. It can be adapted easily to return items as columns:

declare @table table (ID int, Name nvarchar(200))
insert into @table
values
(1,'Apple,banana'),
(2,'Grape,Orange'),
(3,'Papaya,Jackfruit');

with items as (
    select
        ID,
        xmlField= cast('<item><tag>'
                        + replace(Name,',','</tag><tag>')
                        + '</tag></item>' as xml)
    from @table
)
-- Step 2: Select different tags and display them as fields
select
    y.item.value('(tag/text())[1]','nvarchar(20)') As Name1,
    y.item.value('(tag/text())[2]','nvarchar(20)') as Name2
from items outer apply xmlField.nodes('item') as y(item)

This returns :

1   Apple   banana
2   Grape   Orange
3   Papaya  Jackfruit

This works by first converting Name1,Name2 to <item><tag>Name1</tag><tag>Name2</tag><item> which can be cast to XML and returned as xmlField.

outer apply xmlField.nodes('item') as y(item) converts this field to a table of items named y. Only one item row exists in each field.

Finally, y.item.value('(tag/text())[1]','nvarchar(20)') extracts the text of the first tag element as Name1.

This can be extended easily to multiple entries, or to return entries as different elements.

The number of columns has to be known in advance. SQL, the language, doesn't allow an arbitrary number of columns. If different fields contain a different number of tokens, they'll have to be returned as rows.

In this case, you should use STRING_SPLIT if you target SQL Server 2016 or the original version of the XML splitting technique :

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       nvarchar(max),
   @Delimiter  nvarchar(10)
)
RETURNS TABLE WITH SCHEMABINDING
AS
   RETURN (SELECT [value] = y.i.value('(./text())[1]', 'varchar(8000)')
      FROM (SELECT x = CONVERT(XML, '<i>'
          + REPLACE(@List, @Delimiter, '</i><i>')
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i));

It's worth checking Performance Surprises and Assumptions : STRING_SPLIT() which compares all available string splitting techniques to find the fastest and most scaleable


问:
Can we write our own GUI instead of using kibana
In out project, we have decided to use ELK for the distributed logging mechanism. Our project has its own UI. We dont want to have 2 UIs. One for kibana and other for project.

So I would like to know,
1. if we can integrate kibana into our UI.
2. After integrating kibana into UI, can we modify the look and feel.
3. Can we write our own UI which can pick data from elasticsearch.
Does Elasticsearch exposes APIs for the same.

答:
1) Yes, you can integrate kibana in your application, using iframe embedded dashboard.

2)Yes, you can modify the look and feel.
It's not easy but it's possible, we did it in our company("webiks"), and we have a lot of experience.

3)Yes. Elasticsearch expose API, so you can write your GUI alone, but in my opinion kibana did very good job so I think it's good tool to use.


问:
Mysql Return all values of a table where column is equal to user input
I have some sql statements that accepts a number and if that number is equal to the value of a column in a database, it should return all rows in the database that has the same value. Unfortunately the rows only return blog_post_id that has a value 0.

This is my codes below:

```<code><?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id']
: '';

$pdo=new PDO("mysql:dbname=db;host=localhost","username","password",
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id =
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
    echo $json;
else
    echo json_last_error_msg();

?>
</code>```

答:
You should do variable binding like so:

```<code>$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);
</code>```

This will also prevent 1st level SQL-Injection as described here: Are PDO prepared statements sufficient to prevent SQL injection?

Body:
I have some sql statements that accepts a number and if that number is equal to the value of a column in a database, it should return all rows in the database that has the same value. Unfortunately the rows only return blog_post_id that has a value 0.

This is my codes below:

<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id']
: '';

$pdo=new PDO("mysql:dbname=db;host=localhost","username","password",
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id =
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
    echo $json;
else
    echo json_last_error_msg();

?>

Body:
You should do variable binding like so:

$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);

This will also prevent 1st level SQL-Injection as described here: Are PDO prepared statements sufficient to prevent SQL injection?


问:
Using CSS selectors to access specific table rows with selenium
If I have the following HTML:

```<code><tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>
</code>```

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

ContentLicense: CC BY-SA 2.5

Body:
If I have the following HTML:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

Body: selenium.getText("css=table>tbody[id=items]>tr:nth-child(3)>td(3)");


问:
Convert String to ByteArray in C#
I want to convert a String to ByteArray in C# for Decrypt some data.

When I get de String from the ByteArray created, it shows question marks (?).

Example code:

```<code>        byte[] strTemp = Encoding.ASCII.GetBytes(strData);

        MessageBox.Show(strData);
        MessageBox.Show(Encoding.ASCII.GetString(strTemp));
</code>```

The string is "Ê<,,l"x¡" (With the double quotation mark) and the result to convert again to string is: ???l?x?

答:
I hope this helps you:

To Get byte array from a string

```<code>private byte[] StringToByteArray(string str)
{
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     return enc.GetBytes(str);
}
</code>```

To get a string back from byte array:

```<code>private string ByteArrayToString(byte[] arr)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetString(arr);
}
</code>```

Title: Convert String to ByteArray in C#

Body:
I want to convert a String to ByteArray in C# for Decrypt some data.

When I get de String from the ByteArray created, it shows question marks (?).

Example code:

        byte[] strTemp = Encoding.ASCII.GetBytes(strData);

        MessageBox.Show(strData);
        MessageBox.Show(Encoding.ASCII.GetString(strTemp));

The string is "Ê<,,l"x¡" (With the double quotation mark) and the result to convert again to string is: ???l?x?

Body:
I hope this helps you:

To Get byte array from a string

private byte[] StringToByteArray(string str)
{
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     return enc.GetBytes(str);
}

To get a string back from byte array:

private string ByteArrayToString(byte[] arr)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetString(arr);
}


问:
Using hierarchical blocks in redhawk
Is there a way to use hirarchical blocks in redhawk?
For example, say I want to make a digital modulator that is a composition of filters, upsamplers, etc, and I want to use it as a single block in a waveform project, that has other hierarchical components as well. How would I combine the already made filter and upsampler blocks into the digital modulator block using redhawk?</p>

答:
You currently cannot create waveforms of waveforms. A waveform can however have external ports, and external properties allowing you to chain waveforms together dynamically and treat it similar to a component from a programmatic perspective. For example in the example below I launch two waveforms on the domain and connect the two, these waveforms are the examples that come bundled with REDHAWK and have external ports and properties.</p>

```<code>>>> from ossie.utils import redhawk
>>> dom = redhawk.attach()
>>> wf1 = dom.createApplication('/waveforms/rh/FM_mono_demo/FM_mono_demo.sad.xml')
>>> wf2 = dom.createApplication('/waveforms/rh/FM_mono_demo/FM_mono_demo.sad.xml')
>>> wf1.connect(wf2)
</code>```

Title: Using hierarchical blocks in redhawk

Body:
You currently cannot create waveforms of waveforms. A waveform can however have external ports, and external properties allowing you to chain waveforms together dynamically and treat it similar to a component from a programmatic perspective. For example in the example below I launch two waveforms on the domain and connect the two, these waveforms are the examples that come bundled with REDHAWK and have external ports and properties.

>>> from ossie.utils import redhawk
>>> dom = redhawk.attach()
>>> wf1 = dom.createApplication('/waveforms/rh/FM_mono_demo/FM_mono_demo.sad.xml')
>>> wf2 = dom.createApplication('/waveforms/rh/FM_mono_demo/FM_mono_demo.sad.xml')
>>> wf1.connect(wf2)


问:
Apply several summary functions (sum, mean, etc.) on several variables by group in one call
I have the following data frame

```<code>x <- read.table(text = "  id1 id2 val1 val2
1   a   x    1    9
2   a   x    2    4
3   a   y    3    5
4   a   y    4    9
5   b   x    1    7
6   b   y    4    4
7   b   x    3    9
8   b   y    2    8", header = TRUE)
</code>```

I want to calculate the mean of val1 and val2 grouped by id1 and id2, and simultaneously count the number of rows for each id1-id2 combination. I can perform each calculation separately:

```<code># calculate mean
aggregate(. ~ id1 + id2, data = x, FUN = mean)

# count rows
aggregate(. ~ id1 + id2, data = x, FUN = length)
</code>```

In order to do both calculations in one call, I tried

```<code>do.call("rbind", aggregate(. ~ id1 + id2, data = x, FUN = function(x) data.frame(m = mean(x), n = length(x))))
</code>```

However, I get a garbled output along with a warning:

```<code>#     m   n
# id1 1   2
# id2 1   1
#     1.5 2
#     2   2
#     3.5 2
#     3   2
#     6.5 2
#     8   2
#     7   2
#     6   2
# Warning message:
#   In rbind(id1 = c(1L, 2L, 1L, 2L), id2 = c(1L, 1L, 2L, 2L), val1 = list( :
#   number of columns of result is not a multiple of vector length (arg 1)
</code>```

I could use the plyr package, but my data set is quite large and plyr is very slow (almost unusable) when the size of the dataset grows.

How can I use aggregate or other functions to perform several calculations in one call?

答:
You can also use the plyr::each() to introduce multiple functions:

```<code>aggregate(cbind(val1, val2) ~ id1 + id2, data = x, FUN = plyr::each(avg = mean, n = length))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following data frame

x <- read.table(text = "  id1 id2 val1 val2
1   a   x    1    9
2   a   x    2    4
3   a   y    3    5
4   a   y    4    9
5   b   x    1    7
6   b   y    4    4
7   b   x    3    9
8   b   y    2    8", header = TRUE)

I want to calculate the mean of val1 and val2 grouped by id1 and id2, and simultaneously count the number of rows for each id1-id2 combination. I can perform each calculation separately:

# calculate mean
aggregate(. ~ id1 + id2, data = x, FUN = mean)

# count rows
aggregate(. ~ id1 + id2, data = x, FUN = length)

In order to do both calculations in one call, I tried

do.call("rbind", aggregate(. ~ id1 + id2, data = x, FUN = function(x) data.frame(m = mean(x), n = length(x))))

However, I get a garbled output along with a warning:

#     m   n
# id1 1   2
# id2 1   1
#     1.5 2
#     2   2
#     3.5 2
#     3   2
#     6.5 2
#     8   2
#     7   2
#     6   2
# Warning message:
#   In rbind(id1 = c(1L, 2L, 1L, 2L), id2 = c(1L, 1L, 2L, 2L), val1 = list( :
#   number of columns of result is not a multiple of vector length (arg 1)

I could use the plyr package, but my data set is quite large and plyr is very slow (almost unusable) when the size of the dataset grows.

How can I use aggregate or other functions to perform several calculations in one call?

Body:
You can also use the plyr::each() to introduce multiple functions:

aggregate(cbind(val1, val2) ~ id1 + id2, data = x, FUN = plyr::each(avg = mean, n = length))


问:
How to create a query dynamically for an array of elements?
I have a basic query as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
</code>```

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
</code>```

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
</code>```

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

答:
```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.
</code>```

CODE UPDATED ABOVE as it is an object.

You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.

Body:
I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

Body:
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.

CODE UPDATED ABOVE as it is an object.

You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.


问:
Why does Visual Studio give you Page_Load for WebForms as a default?
When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool.  So for years, I have always put code for doing things like set properties of controls in Page_Load.  Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event).  So I started to wonder, where is the best place really to set the properties of controls, in OnLoad or Page_Load?  Or in a different method altogether?  And if not Page_Load, why does Studio add that to the code behind?

My final thought:  Although I know that putting logic in OnLoad works fine, I will probably stick with Page_Load for now because that's conventional.  I asked the question really to find out if I had been missing out on something new after I started seeing OnLoad come up in other people's code.  Thank you all for your thoughtful answers!

答: Page_Load is just the autoeventwireup for OnLoad. You would think that it doesn't make any difference which is used, but I agree with K. Scott Allen at Ode to Code that you should usually only deviate from the norm when you are trying to do something unexpected. Overriding a virtual method like OnLoad suggests that you are trying to do something different such as not calling base.Onload, which most programmers are typically not.</p>

OwnerDisplayName: Barneytron

LastEditorDisplayName: Barneytron

OwnerDisplayName: David Thomas Garcia


答:
You can use implode  to convert array to string comma delimited

like below:

```<code>$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array );

$query1="SELECT subject_code FROM subject WHERE sbranch  in ('".$branch."')";
</code>```

result:

```<code> 'subject1', 'subject2', 'subject3'
</code>```

Hope that resolve your issue

Title: How to create a query dynamically for an array of elements?

Body:
You can use implode  to convert array to string comma delimited

like below:

$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array );

$query1="SELECT subject_code FROM subject WHERE sbranch  in ('".$branch."')";

result:

 'subject1', 'subject2', 'subject3'

Hope that resolve your issue


问:
Jquery not removing row
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

```<code>var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + val + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + price + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });
</code>```

Here is the tables in my view

```<code> <table id="tblList" class="table">
        <tr>
            <th>
                Item
            </th>
            <th>
                Qty
            </th>
            <th>
                Price
            </th>
            <th>
            </th>
        </tr>
    </table>
    <br />
    <table class="table">
        <tr>
            <th>Total</th>
            <th></th>
            <th><p id="total">0</p></th>
            <th></th>
        </tr>
    </table>
</code>```

答:
You are just calling the function with id and try to remove the id.
 But what you have to do is pass the element while you are calling the function.

```<code>function remove(id,element) {
      $(element).closest('tr').remove();
    }//try something like this
</code>```

And in onclick function you have to edit code like this

```<code>onclick="remove(' + id + ',this)"
</code>```

Finally your code should look like this click here

Title: Jquery not removing row

Body:
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + val + '  	  Remove
');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + price + '  	  Remove
');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });

Here is the tables in my view

                Item

                Qty

                Price

            Total

0

Body:
You are just calling the function with id and try to remove the id.
 But what you have to do is pass the element while you are calling the function.

function remove(id,element) {
      $(element).closest('tr').remove();
    }//try something like this

And in onclick function you have to edit code like this

onclick="remove(' + id + ',this)"

Finally your code should look like this click here


问:
Is AUGraph being deprecated on iOS? If so, when?
I've heard rumblings that AUGraph is being deprecated on iOS, for example in this Twitter post:

@marcoarment Your comment on @atpfm about needing to rewrite your audio engine: b/c of the looming AUGraph deprecation, or something else?

Is AUGraph in fact being deprecated, and if so, when? Can somebody point me toward an official Apple document or announcement that clarifies this?

答:
Indeed it will be deprecated as stated in the WWDC talk

(Note: The picture is from the core audio mailing list)


问:
Android Studio 2.3.3 stucks when first run
I downloaded Android Studio 2.3.3 for Linux and unzipped the content to /usr/local
then

```<code>$ cd android-studio/bin
</code>```

Edited the file idea.properties and appended a following line to it:

```<code>disable.android.first.run=true
</code>```

Then launched Android Studio:

```<code>$ sudo sh studio.sh

Looking in classpath from com.intellij.util.lang.UrlClassLoader@1a7cec2 for /com/sun/jna/linux-x86/libjnidispatch.so
Found library resource at jar:file:/usr/local/android-studio/lib/jna.jar!/com/sun/jna/linux-x86/libjnidispatch.so
Trying /root/.AndroidStudio2.3/system/tmp/jna5562911082428971611.tmp
Found jnidispatch at /root/.AndroidStudio2.3/system/tmp/jna5562911082428971611.tmp
[  40066]   WARN - dea.updater.SdkComponentSource - File /root/.android/repositories.cfg could not be loaded.
^C[18124266]   WARN - pl.local.NativeFileWatcherImpl - Watcher terminated with exit code 130
</code>```

And it will stuck. After long waiting I termited it with Ctrl+C

答:
I've found a potientaly useful link from AskUbuntu, the guy suggested creating an empty file called repositories.cfg. And that solved it.

Ref: https://askubuntu.com/questions/885658/android-sdk-repositories-cfg-could-not-be-loaded

Body:
I downloaded Android Studio 2.3.3 for Linux and unzipped the content to /usr/local
then

$ cd android-studio/bin

Edited the file idea.properties and appended a following line to it:

disable.android.first.run=true

Then launched Android Studio:

$ sudo sh studio.sh

Looking in classpath from com.intellij.util.lang.UrlClassLoader@1a7cec2 for /com/sun/jna/linux-x86/libjnidispatch.so
Found library resource at jar:file:/usr/local/android-studio/lib/jna.jar!/com/sun/jna/linux-x86/libjnidispatch.so
Trying /root/.AndroidStudio2.3/system/tmp/jna5562911082428971611.tmp
Found jnidispatch at /root/.AndroidStudio2.3/system/tmp/jna5562911082428971611.tmp
[  40066]   WARN - dea.updater.SdkComponentSource - File /root/.android/repositories.cfg could not be loaded.
^C[18124266]   WARN - pl.local.NativeFileWatcherImpl - Watcher terminated with exit code 130

And it will stuck. After long waiting I termited it with Ctrl+C


问:
Import mp3 files through FileChooser to clickable Labels
I want to import mp3 files as clickable labels, but i have no idea how to handle it. I am doing graphical user interface through JavaFX. Image below will explain more.

答:
You can get all Files from a directory by doing something like this:

```<code>File myfolder = new File("path/to/directory");
File[] allFiles = folder.listFiles();

for (int i = 0; i < all.length; i++) {
  if (allFiles[i].isFile()) {
    System.out.println("File " + allFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + allFiles[i].getName());
  }
}
</code>```

But instead of printing it to the output you can add Labels with the file.

Maybe something like this is what you want:

```<code>File myfolder = new File("your/path");
File[] allFiles = folder.listFiles();
VBox yourBox = new VBox();

for (int i = 0; i < all.length; i++) {
  if (allFiles[i].isFile()) {
    yourBox.getChildren().add(new Label(allFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    //Do whatever you want to do with subfolders.
  }
}
</code>```

Edit: for selecting a folder at runtime you can use:

DirectoryChooser
https://docs.oracle.com/javase/8/javafx/api/javafx/stage/DirectoryChooser.html
Or a FileChooser, which allows selecting multiple Files.

Edit full code (tested):

```<code>import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class test extends Application {

    @Override
    public void start(final Stage stage) {
        stage.setTitle("File Chooser");

        final FileChooser fileChooser = new FileChooser();
        final Button openMultipleButton = new Button("Open Files...");

        VBox yourBox = new VBox();

        openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(final ActionEvent e) {
                List<File> list = fileChooser.showOpenMultipleDialog(stage);
                if (list != null) {
                    for (File file : list) {

                        yourBox.getChildren().add(new Label(file.getName()));

                    }
                }
            }
        });

        HBox all = new HBox();
        all.getChildren().addAll(openMultipleButton, yourBox);

        final Pane rootGroup = new VBox(12);
        rootGroup.getChildren().addAll(all);
        rootGroup.setPrefSize(400, 400);

        stage.setScene(new Scene(rootGroup));
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    }
</code>```

Hope this helped,
Steffi

Body:
You can get all Files from a directory by doing something like this:

File myfolder = new File("path/to/directory");
File[] allFiles = folder.listFiles();

for (int i = 0; i < all.length; i++) {
  if (allFiles[i].isFile()) {
    System.out.println("File " + allFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + allFiles[i].getName());
  }
}

But instead of printing it to the output you can add Labels with the file.

Maybe something like this is what you want:

File myfolder = new File("your/path");
File[] allFiles = folder.listFiles();
VBox yourBox = new VBox();

for (int i = 0; i < all.length; i++) {
  if (allFiles[i].isFile()) {
    yourBox.getChildren().add(new Label(allFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    //Do whatever you want to do with subfolders.
  }
}

Edit: for selecting a folder at runtime you can use:

DirectoryChooser
https://docs.oracle.com/javase/8/javafx/api/javafx/stage/DirectoryChooser.html
Or a FileChooser, which allows selecting multiple Files.

Edit full code (tested):

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class test extends Application {

    @Override
    public void start(final Stage stage) {
        stage.setTitle("File Chooser");

        final FileChooser fileChooser = new FileChooser();
        final Button openMultipleButton = new Button("Open Files...");

        VBox yourBox = new VBox();

        openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(final ActionEvent e) {
                List<File> list = fileChooser.showOpenMultipleDialog(stage);
                if (list != null) {
                    for (File file : list) {

                        yourBox.getChildren().add(new Label(file.getName()));

                    }
                }
            }
        });

        HBox all = new HBox();
        all.getChildren().addAll(openMultipleButton, yourBox);

        final Pane rootGroup = new VBox(12);
        rootGroup.getChildren().addAll(all);
        rootGroup.setPrefSize(400, 400);

        stage.setScene(new Scene(rootGroup));
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    }

Hope this helped,
Steffi


问:
Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries
I am trying to execute my tests in nodejs using protractor.

Example protractor protractor.conf
When I run protractor protractor.conf, I get error  Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries

I ran the following command but still get the above error message

```<code>webdriver-manager update -- proxy http://
</code>```

protractor.conf.js

```<code>/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'chrome',
    /*'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']*/
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};
</code>```

答:
I'm not 100% sure (and cannot it check now), but shouldn't command look like that:

webdriver-manager update --proxy http:// (without space between -- and proxy)?

Body:
I am trying to execute my tests in nodejs using protractor.

Example protractor protractor.conf
When I run protractor protractor.conf, I get error  Error code 135, Error message Could not fingd update-config.json. Run webdriver-manager update to download the binaries

I ran the following command but still get the above error message

webdriver-manager update -- proxy http://

protractor.conf.js

/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
var TfsReporter = require('jasmine-tfs-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/tests/*spec.js'
  ],
  capabilities: {
    'browserName': 'chrome',
    /*'browserName': 'phantomjs',
    'phantomjs.binary.path': require('phantomjs-prebuilt').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']*/
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: false,
  beforeLaunch: function() {
    require('ts-node').register({
      project: '../PartyAndIndustryDataMigration'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new SpecReporter());
    jasmine.getEnv().addReporter(new TfsReporter());
  }
};


问:
Url.Action is throwing error CS1026: ) expected
This is hopefully just a syntax error as I'm new to MVC and trying to edit something that already exists without having much experience. Having spent ages trying different syntax I'm obviously missing something.

My issue is that I have this:

```<code>var url = '<%= Url.Action("List") %>?page=' + pageNo;
</code>```

which is fine, but its not passing in all the required parameters as part of pager functionality.

What I want to use is something like:

```<code>var url = '<%= Html.RenderAction("List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new { Domain = "Placement",
                     Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                     agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                     Page = Model.PageNo
                });
           %>';
</code>```

But it always complains about error CS1026: ) expected

Same with trying

```<code><%= Url.Action("List", "PlacementAgreementAgencyPlacementAgreementsPlacement",
        new { Domain = "Placement",
              Id = ViewData.Model.AgencyPlacementAgreement.PlacementAgreement.PlacementAgreementId,
              agencyPlacementAgreementId = ViewData.Model.AgencyPlacementAgreement.AgencyPlacementAgreementId,
              Page = Model.PageNo }
    )%>
</code>```

If someone could point out what I'm doing wrong that would be great.  Basically I'm trying to call controller PlacementAgreementAgencyPlacementAgreementsPlacement with action List passing in all parameters Id, agencyPlacementAgreementId and Page.  It's being done in javascript so that I can use this:

```<code>    function loadAgreementPlacementPage(pageNo) {

        var url = '<%= Url.Action("List") %>?page=' + pageNo;
        $.get(url, function(data) {
            $("#agreementplacement_list_holder").html(data);
        });
</code>```

Thanks!!!

PS. Using MVC 1.0.

答: Remove the semicolon before the closing tag</p>

Body:
This is hopefully just a syntax error as I'm new to MVC and trying to edit something that already exists without having much experience. Having spent ages trying different syntax I'm obviously missing something.

My issue is that I have this:

var url = '<%= Url.Action("List") %>?page=' + pageNo;

which is fine, but its not passing in all the required parameters as part of pager functionality.

What I want to use is something like:

var url = '<%= Html.RenderAction("List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new { Domain = "Placement",
                     Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                     agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                     Page = Model.PageNo
                });
           %>';

But it always complains about error CS1026: ) expected

Same with trying

<%= Url.Action("List", "PlacementAgreementAgencyPlacementAgreementsPlacement",
        new { Domain = "Placement",
              Id = ViewData.Model.AgencyPlacementAgreement.PlacementAgreement.PlacementAgreementId,
              agencyPlacementAgreementId = ViewData.Model.AgencyPlacementAgreement.AgencyPlacementAgreementId,
              Page = Model.PageNo }
    )%>

If someone could point out what I'm doing wrong that would be great.  Basically I'm trying to call controller PlacementAgreementAgencyPlacementAgreementsPlacement with action List passing in all parameters Id, agencyPlacementAgreementId and Page.  It's being done in javascript so that I can use this:

    function loadAgreementPlacementPage(pageNo) {

        var url = '<%= Url.Action("List") %>?page=' + pageNo;
        $.get(url, function(data) {
            $("#agreementplacement_list_holder").html(data);
        });

Thanks!!!

PS. Using MVC 1.0.


问:
"You have included the Google Maps API multiple times on this page" Error
I have the following in my html page:

```<code>    <script type="text/javascript"
            src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false">
    </script>
    <script
        async defer
        src="https://maps.googleapis.com/maps/api/js?key=hUnDAdjYG_Wz7u2qL6unHqfBOmvaZ0H1Mg&callback=initMap">
    </script>
</code>```

First link is for Google's API Geometry Library , and the second initialises and draws the map.

I'm getting the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

I know that this can be fixed by calling just one script, and changing the parameters, see Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." I don't know how to replicate the answer for my problem though.

答:
You can include one link:

```<code><script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false&key=AIzaSyBSsKUzYG_Wz7u2qL6unHqfBOmvaZ0H1Mg&callback=initMap">
</script>
</code>```

Basically merging the url parameters in both the links.

Body:
I have the following in my html page:

First link is for Google's API Geometry Library , and the second initialises and draws the map.

I'm getting the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

I know that this can be fixed by calling just one script, and changing the parameters, see Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." I don't know how to replicate the answer for my problem though.

Body:
You can include one link:

<script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false&key=AIzaSyBSsKUzYG_Wz7u2qL6unHqfBOmvaZ0H1Mg&callback=initMap">
</script>

Basically merging the url parameters in both the links.


问:
UILongPressGestureRecognizer over UITextField in swift
Is there away to use a UILongPressGestureRecognizer over a UITextField without triggering field edit while still being able to edit the textfield on a regular tap?

I have tried adding a long press gesture recognizer to the UITextField but the long press seems to only work a fraction of the time.

```<code>init(frame: CGRect, userCompany: WLUserCompany) {
    super.init(frame: frame)

    var textField: UITextField?

    var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(gesture:)))
    textField?.addGestureRecognizer(longPress)

    self.addSubview(textField!)
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}
</code>```

答:
Create subclass of UIGestureRecognizer

```<code>import UIKit.UIGestureRecognizerSubclass

class TouchGestureRecognizer: UIGestureRecognizer {

    var isLongPress: Bool = false
    fileprivate var startDateInterval: TimeInterval = 0

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        state = .began
        self.startDateInterval = Date().timeIntervalSince1970
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)
        state = .ended
        self.isLongPress = (Date().timeIntervalSince1970 - self.startDateInterval) > 1.0
    }
}
</code>```

Add gesture recognizer to your textField

```<code>let gesture = TouchGestureRecognizer(target: self, action: #selector(ViewController.textFiledPressed(gesture:)))
        self.textField?.addGestureRecognizer(gesture)
</code>```

And now you can check in textFiledPressed(gesture:) function if it's long press or not

```<code>func textFiledPressed(gesture: TouchGestureRecognizer) {
    switch gesture.state {
    case .ended:
        if gesture.isLongPress {
            //Do whatever you need
        } else {
            self.textField?.becomeFirstResponder()
        }

    default: break
    }

}
</code>```

Body:
Is there away to use a UILongPressGestureRecognizer over a UITextField without triggering field edit while still being able to edit the textfield on a regular tap?

I have tried adding a long press gesture recognizer to the UITextField but the long press seems to only work a fraction of the time.

init(frame: CGRect, userCompany: WLUserCompany) {
    super.init(frame: frame)

    var textField: UITextField?

    var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(gesture:)))
    textField?.addGestureRecognizer(longPress)

    self.addSubview(textField!)
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}

Body:
Create subclass of UIGestureRecognizer

import UIKit.UIGestureRecognizerSubclass

class TouchGestureRecognizer: UIGestureRecognizer {

    var isLongPress: Bool = false
    fileprivate var startDateInterval: TimeInterval = 0

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        state = .began
        self.startDateInterval = Date().timeIntervalSince1970
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesEnded(touches, with: event)
        state = .ended
        self.isLongPress = (Date().timeIntervalSince1970 - self.startDateInterval) > 1.0
    }
}

Add gesture recognizer to your textField

let gesture = TouchGestureRecognizer(target: self, action: #selector(ViewController.textFiledPressed(gesture:)))
        self.textField?.addGestureRecognizer(gesture)

And now you can check in textFiledPressed(gesture:) function if it's long press or not

func textFiledPressed(gesture: TouchGestureRecognizer) {
    switch gesture.state {
    case .ended:
        if gesture.isLongPress {
            //Do whatever you need
        } else {
            self.textField?.becomeFirstResponder()
        }

    default: break
    }

}


问:
ImportError: No module named tensorflow
Please help me with this error

I have installed the tensorflow module on my server and below is it's information

```<code>15IT60R19@cpusrv-gpu-109:~$ pip show tensorflow
Name: tensorflow
Version: 1.0.0
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: opensource@google.com
License: Apache 2.0
Location: /home/other/15IT60R19/anaconda2/lib/python2.7/site-packages
Requires: mock, numpy, protobuf, wheel, six
</code>```

But when I try to import tensorflow I get following error

```<code>>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named tensorflow
</code>```

My python version is as following

```<code>Python 2.7.12 |Anaconda 2.5.0 (64-bit)| (default, Jul  2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
</code>```

I have tried the solutions given in
sol1

Sol2

I do not have sudo access to the server
I can only use pip to install any module

答:
Check if Tensorflow was installed successfully using:

```<code> pip3 show tensorflow
</code>```

If you get something like

```<code>Name: tensorflow
Version: 1.2.1
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: opensource@google.com
License: Apache 2.0
Location: /usr/local/lib/python3.5/dist-packages
Requires: bleach, markdown, html5lib, backports.weakref, werkzeug, numpy, protobuf, wheel, six
</code>```

You may try adding the path of your tensorflow location by:

```<code>export PYTHONPATH=/your/tensorflow/path:$PYTHONPATH.
</code>```

Title: ImportError: No module named tensorflow

Body:
Please help me with this error

I have installed the tensorflow module on my server and below is it's information

15IT60R19@cpusrv-gpu-109:~$ pip show tensorflow
Name: tensorflow
Version: 1.0.0
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: opensource@google.com
License: Apache 2.0
Location: /home/other/15IT60R19/anaconda2/lib/python2.7/site-packages
Requires: mock, numpy, protobuf, wheel, six

But when I try to import tensorflow I get following error

>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named tensorflow

My python version is as following

Python 2.7.12 |Anaconda 2.5.0 (64-bit)| (default, Jul  2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org

I have tried the solutions given in
sol1

Sol2

I do not have sudo access to the server
I can only use pip to install any module

Body:
Check if Tensorflow was installed successfully using:

 pip3 show tensorflow

If you get something like

Name: tensorflow
Version: 1.2.1
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: opensource@google.com
License: Apache 2.0
Location: /usr/local/lib/python3.5/dist-packages
Requires: bleach, markdown, html5lib, backports.weakref, werkzeug, numpy, protobuf, wheel, six

You may try adding the path of your tensorflow location by:

export PYTHONPATH=/your/tensorflow/path:$PYTHONPATH.


问:
mod_rewrite in a subdirectory: assets not found
This is my .htaccess file

```<code><IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /focas/

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/?$ index.php?slug=$1 [QSA,NC]
    RewriteRule editoria/([^/]+)/?$ editoria.php?editoria=$1 [QSA,NC]
    RewriteRule tag/([^/]+)/?$ tag.php?tag=$1 [QSA,NC]

</IfModule>
</code>```

I also include <base> meta tag:

```<code><base href="http://website.com/focas">
</code>```

But all my assets return 404

答:
Change your <base ... tag to this:

```<code><base href="/focas/">
</code>```

and make sure it placed just below your  tag in the page.

Body:
This is my .htaccess file

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /focas/

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/?$ index.php?slug=$1 [QSA,NC]
    RewriteRule editoria/([^/]+)/?$ editoria.php?editoria=$1 [QSA,NC]
    RewriteRule tag/([^/]+)/?$ tag.php?tag=$1 [QSA,NC]

</IfModule>

I also include <base> meta tag:

<base href="http://website.com/focas">

But all my assets return 404

Body:
Change your <base ... tag to this:

<base href="/focas/">

and make sure it placed just below your <head> tag in the page.


问:
@Umbraco.TypedMedia(MyProperty) is null in Umbraco 7.6.1
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

```<code>@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}
</code>```

But bannerMediaItem is always null even though I know it exists. If I do this..

```<code>@Model.Content.Image
</code>```

It returns the id of the image e.g. 1086

答:
In Umbraco v7.6 and above, there is now a new thing called UDI. Find out more about UDI here. https://our.umbraco.org/documentation/reference/querying/Udi

So instead of your media item having a numeric id, by default it will have an id like this: umb://media/39d3ac707d634953ab52642d5037855c

Here is how you get the media url when the id is one of the new type:

```<code>string imageUrl = Model.Content.GetPropertyValue<IPublishedContent>("headerImage").Url;
</code>```

Body:
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}

But bannerMediaItem is always null even though I know it exists. If I do this..

@Model.Content.Image

It returns the id of the image e.g. 1086

Body:
In Umbraco v7.6 and above, there is now a new thing called UDI. Find out more about UDI here. https://our.umbraco.org/documentation/reference/querying/Udi

So instead of your media item having a numeric id, by default it will have an id like this: umb://media/39d3ac707d634953ab52642d5037855c

Here is how you get the media url when the id is one of the new type:

string imageUrl = Model.Content.GetPropertyValue<IPublishedContent>("headerImage").Url;


问:
Excel Macro Query: Hiding Rows based on cell value
Hi I've tried the below code but it doesn't seem to be working can anybody help me. I just want to hide rows 3 & 4 when B1 has the text Delete. But I want this to run automatically when Delete is entered into B1.

Thanks

答:
Something like this should work

```<code>Option Explicit 'Very first line to ensure that variables are declared

Private Sub Worksheet_Change(ByVal Target As Range)
    'check if target address is B1
    If Target.Address(RowAbsolute:=False, ColumnAbsolute:=False) = "B1" Then
        ShowHideRows
    End If
End Sub

Public Sub ShowHideRows()
    If Range("B1").Value = "Delete" Then
        Rows("3:4").EntireRow.Hidden = True
        Rows("7:8").EntireRow.Hidden = False
    ElseIf Range("B1").Value = "Open" Then 'use ElseIf if possible like here
        Rows("3:4").EntireRow.Hidden = False
        Rows("7:8").EntireRow.Hidden = True
    End If
End Sub
</code>```

Note: This is case sensitive. So if you type in B1 delete instead of Delete it will not run. To make it non case sensitive use LCase() like:

```<code>LCase(Range("B1").Value) = "delete" 'string delete must be lower case!
</code>```

Body:
Something like this should work

Option Explicit 'Very first line to ensure that variables are declared

Private Sub Worksheet_Change(ByVal Target As Range)
    'check if target address is B1
    If Target.Address(RowAbsolute:=False, ColumnAbsolute:=False) = "B1" Then
        ShowHideRows
    End If
End Sub

Public Sub ShowHideRows()
    If Range("B1").Value = "Delete" Then
        Rows("3:4").EntireRow.Hidden = True
        Rows("7:8").EntireRow.Hidden = False
    ElseIf Range("B1").Value = "Open" Then 'use ElseIf if possible like here
        Rows("3:4").EntireRow.Hidden = False
        Rows("7:8").EntireRow.Hidden = True
    End If
End Sub

Note: This is case sensitive. So if you type in B1 delete instead of Delete it will not run. To make it non case sensitive use LCase() like:

LCase(Range("B1").Value) = "delete" 'string delete must be lower case!


问:
Website which can make a call to a given phone number
Is there any website/server through which I can do a tie-up for doing following:

I will pass my user Id and a phone number.

Using my user Id, it will know who I am and what is my phone number.

3.1 It will make a call to the phone number which I have passed and to me and get both of us connected?

3.2 It will make a call to the phone number which I have passed and it should display my number in his mobile.

Please let me know whether any of these 3.1 or 3.2 is possible?

答: I'm not sure if this is exactly that you're looking for, but have a look at the Ribbit API.</p>


问:
Found input variables with inconsistent numbers of samples when fitting LogisticRegression
I am creating LogisticRegression classifier with the following code:

```<code>regressor = LogisticRegression()
regressor.fit(x_train, y_train)
</code>```

Both x_train and y_train shapes are

```<code><class 'tuple'>: (32383,)
</code>```

x_train contains values around range [0..1], and y_train contains only 0s and 1s.

Unfortunately, fit fails with error

```<code>ValueError: Found input variables with inconsistent numbers of samples: [1, 32383]
</code>```

Adding transpose to arguments doesn't help.

答:
To continue the solution that I proposed in my comment:
The problem is the shape of the x_train. So we need to reshape it:

From the documentation:

X : {array-like, sparse matrix}, shape (n_samples, n_features)

y : array-like, shape (n_samples,)

Example using scikit-learn and numpy:

```<code>from sklearn.linear_model import LogisticRegression
import numpy as np

# create the tuple data
x_train = tuple(range(32383))
x_train = np.asarray(x_train)

#same for y_train
y_train=tuple(range(32383))
y_train = np.asarray(y_train)

#convert tuples to nparray and reshape the x_train
x_train = x_train.reshape(32383,1)

#check if shape if (32383,)
y_train.shape

#create the model
lg = LogisticRegression()

#Fit the model
lg.fit(x_train, y_train)
</code>```

This should work fine.
Hope it helps

Body:
I am creating LogisticRegression classifier with the following code:

regressor = LogisticRegression()
regressor.fit(x_train, y_train)

Both x_train and y_train shapes are

<class 'tuple'>: (32383,)

x_train contains values around range [0..1], and y_train contains only 0s and 1s.

Unfortunately, fit fails with error

ValueError: Found input variables with inconsistent numbers of samples: [1, 32383]

Adding transpose to arguments doesn't help.

Body:
To continue the solution that I proposed in my comment:
The problem is the shape of the x_train. So we need to reshape it:

From the documentation:

X : {array-like, sparse matrix}, shape (n_samples, n_features)

y : array-like, shape (n_samples,)

Example using scikit-learn and numpy:

from sklearn.linear_model import LogisticRegression
import numpy as np

# create the tuple data
x_train = tuple(range(32383))
x_train = np.asarray(x_train)

#same for y_train
y_train=tuple(range(32383))
y_train = np.asarray(y_train)

#convert tuples to nparray and reshape the x_train
x_train = x_train.reshape(32383,1)

#check if shape if (32383,)
y_train.shape

#create the model
lg = LogisticRegression()

#Fit the model
lg.fit(x_train, y_train)

This should work fine.
Hope it helps


问:
Redirect to the same page with retrieved values from database in laravel?
View Code:

```<code> <li class="active"><a href="#tab_1" data-toggle="tab"  id="versiontab"
onclick="window.location='{{ url("versiondb") }}'" >Version
 Database</a></li>
</code>```

This is my view code.This is also a tab .Onclicking the tab the url redirection works.

Route Code:

```<code>Route::get('versiondb','versiondbController@select');
</code>```

Controllercode:

```<code>public function select()
{

    $users=debModel::all();
    return redirect()->back()->with($users);

}
</code>```

Here it should fetches the values from db and redirecting back to the same page and display the retreived values in table .But i am getting an error here as $users undefined

Inside the Same view (specified above):

```<code> <table class="table" id="table">
      @foreach($users as $users)
        <thead>
          <tr class="header">
              <th valign="middle" width="3%">Versions</th>
              <th valign="middle" width="2%">Supported versions</th>
              <th valign="middle" width="10%">Release Date</th>
              <th valign="middle" width="3%">Type</th>
              <th valign="middle" width="10%">Description</th>
              <th valign="middle" width="3%">Actions</th>
              <th valign="middle" width="3%">Downloader</th>
              <!--<th valign="middle" width="3%">Beta code</th>-->

            </tr>
            </thead>
            <tbody>
            <tr>
            <td>{{$users->versions}}</td>
            <td></td>

            </tr>
          @endforeach
            </tbody>

                </table>
</code>```

I think this is the place where error occurs.

答:
Use ($users as $user) instead ($users as $users) here

```<code>@foreach($users as $user)
</code>```

And in your template

```<code><td>{{$user->versions}}</td>
</code>```

Also change in your controller

```<code>return view('haghwayUpdate')->with('users',$users);
</code>```

Body:
View Code:

Version
 Database

This is my view code.This is also a tab .Onclicking the tab the url redirection works.

Route Code:

Route::get('versiondb','versiondbController@select');

Controllercode:

public function select()
{

    $users=debModel::all();
    return redirect()->back()->with($users);

}

Here it should fetches the values from db and redirecting back to the same page and display the retreived values in table .But i am getting an error here as $users undefined

Inside the Same view (specified above):

      @foreach($users as $users)

              Versions
              Supported versions
              Release Date
              Type
              Description
              Actions
              Downloader

            {{$users->versions}}

          @endforeach

I think this is the place where error occurs.

Body:
Use ($users as $user) instead ($users as $users) here

@foreach($users as $user)

And in your template

<td>{{$user->versions}}</td>

Also change in your controller

return view('haghwayUpdate')->with('users',$users);


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
A pointer variable holds an address, or 'location' of something.  Thus, the pointer holds a value that is a memory address.  When you say:

```<code>int *q = 6;
</code>```

you are creating a pointer variable that intends to point to an int, and telling it to point to the int value stored in the address 6, which is (probably) not what you really intended.

A pointer variable should point to some memory address that contains some actual data you want to access.  For example:

```<code>int x = 5;
int *q = &x;
</code>```

This creates a variable (x) that contains the value 5.
the next line creates a pointer variable that contains the address of x.  You have set the pointer variable 'q' to the address of the int variable 'x'.

Now you can see what is at 'x' by doing this:

```<code>int y;
y = *q;
</code>```

This says "take what is pointed to by q, and store it in y".  The end effect is that y will be set to 5.

```<code>int x = 5;     // create variable x and set it to 5
int *q = &x;   // create int pointer variable, set it to the address of x
int y;         // create variable y
y = *q;        // take the value pointed to by q, and store it in y
</code>```

If, for example the variable x is at memory location 1234, and you looked at the value stored in 'q', it would be 1234, which is the address of x.
When you say "y = *q", you are saying "take the value stored in the address 1234, and puts that value in y".  Since the memory location 1234 is 'x', and 'x' was assigned the value 5, the value 5 will be what is stored at the address 1234.

```<code>y = *q;
</code>```

will take the value stored in the address 1234 and assign y to that value, thus making y 5, which was the value stored in x, which is what q 'points' to.

This could be shortened to:

```<code>int x = 5;
int *q = &x;
int y = *q;
</code>```

Body:
A pointer variable holds an address, or 'location' of something.  Thus, the pointer holds a value that is a memory address.  When you say:

int *q = 6;

you are creating a pointer variable that intends to point to an int, and telling it to point to the int value stored in the address 6, which is (probably) not what you really intended.

A pointer variable should point to some memory address that contains some actual data you want to access.  For example:

int x = 5;
int *q = &x;

This creates a variable (x) that contains the value 5.
the next line creates a pointer variable that contains the address of x.  You have set the pointer variable 'q' to the address of the int variable 'x'.

Now you can see what is at 'x' by doing this:

int y;
y = *q;

This says "take what is pointed to by q, and store it in y".  The end effect is that y will be set to 5.

int x = 5;     // create variable x and set it to 5
int *q = &x;   // create int pointer variable, set it to the address of x
int y;         // create variable y
y = *q;        // take the value pointed to by q, and store it in y

If, for example the variable x is at memory location 1234, and you looked at the value stored in 'q', it would be 1234, which is the address of x.
When you say "y = *q", you are saying "take the value stored in the address 1234, and puts that value in y".  Since the memory location 1234 is 'x', and 'x' was assigned the value 5, the value 5 will be what is stored at the address 1234.

y = *q;

will take the value stored in the address 1234 and assign y to that value, thus making y 5, which was the value stored in x, which is what q 'points' to.

This could be shortened to:

int x = 5;
int *q = &x;
int y = *q;


问:
get latest record from table using postgresql
I have table employee as below,

```<code>id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102
</code>```

I am using jpa with eclipselink implementation and database is postgresql.
Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always.
Thanks,

答:
You can use the below query for getting the appropriate result from mysql</p>

```<code>select * from employee order by id desc limit 1
</code>```

Body:
I have table employee as below,

id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102

I am using jpa with eclipselink implementation and database is postgresql.
Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always.
Thanks,

Body:
You can use the below query for getting the appropriate result from mysql

select * from employee order by id desc limit 1


问:
How Google App Engine limit Python?
Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.

Shared hosting also do it in some way?

答:
The sandbox "internally works" by them having a special version of the Python interpreter. You aren't running the standard Python executable, but one especially modified to run on Google App engine.

Update:

And no it's not a virtual machine in the ordinary sense. Each application does not have a complete virtual PC. There may be some virtualization going on, but Google isn't saying exactly how much or what.

A process has normally in an operating system already limited access to the rest of the OS and the hardware. Google have limited this even more and you get an environment where you are only allowed to read the very specific parts of the file system, and not write to it at all, you are not allowed to open sockets and not allowed to make system calls etc.

I don't know at which level OS/Filesystem/Interpreter each limitation is implemented, though.

Title: How Google App Engine limit Python?


问:
What is a good naming convention for Rails custom controller actions regarding formulation (noun vs verb)?
When defining new actions in controllers I often find myself asking how should I formulate the name of the action correctly. Rails default CRUD actions all seem to follow the pattern of verb (new, create, edit, update, destroy, index) but is it a bad habit to use a noun? For ex. payment_history?

I found a lot of information describing the naming conventions for different files and classes and regarding the proper syntax but none about controller#actions from formulation part.

EDIT: I am asking about custom-defined actions not renaming the Rails default CRUD actions.

答:
Controllers In rails acoording to my reading and experience

Controller class names use CamelCase and have Controller as a suffix. The Controller suffix is always singular. The name of the resource is usually plural.

Controller actions use snake_case and usually match the standard route names Rails defines (index, show, new, create, edit, update, delete).

Controller files go in app/controllers/#{resource_name}_controller.rb.

Example:

```<code># app/controllers/bigfoot_sightings_controller.rb
BigfootSightingsController < ApplicationController
  def index
    # ...
  end
  def show
    # ...
  end
  # etc
end
# app/controllers/profiles_controller.rb
ProfilesController < ApplicationController
  def show
    # ...
  end
  # etc
end
</code>```

Body:
Controllers In rails acoording to my reading and experience

Controller class names use CamelCase and have Controller as a suffix. The Controller suffix is always singular. The name of the resource is usually plural.

Controller actions use snake_case and usually match the standard route names Rails defines (index, show, new, create, edit, update, delete).

Controller files go in app/controllers/#{resource_name}_controller.rb.

Example:

# app/controllers/bigfoot_sightings_controller.rb
BigfootSightingsController < ApplicationController
  def index
    # ...
  end
  def show
    # ...
  end
  # etc
end
# app/controllers/profiles_controller.rb
ProfilesController < ApplicationController
  def show
    # ...
  end
  # etc
end


问:
How can one display images side by side in a GitHub README.md?
I'm trying to show a comparison between two photos in my README.md which is why I want to display them side-by-side. Here is how the two images are placed currently. I want to show the two Solarized color schemes side by side instead of top and bottom. Help would be much appreciated, thanks!</p>

答:
If, like me, you found that @wiggin answer didn't work and images still did not appear in-line, you can use the 'align' property of the html image tag and some breaks to achieve the desired effect, for example:

```<code># Title

<img align="left" src="./documentation/images/A.jpg" alt="Made with Angular" title="Angular" hspace="20"/>
<img align="left" src="./documentation/images/B.png" alt="Made with Bootstrap" title="Bootstrap" hspace="20"/>
<img align="left" src="./documentation/images/C.png" alt="Developed using Browsersync" title="Browsersync" hspace="20"/>
<br/><br/><br/><br/><br/>

## Table of Contents...
</code>```

Obviously, you have to use more breaks depending on how big the images are: awful yes, but it worked for me so I thought I'd share.

Body:
If, like me, you found that @wiggin answer didn't work and images still did not appear in-line, you can use the 'align' property of the html image tag and some breaks to achieve the desired effect, for example:

# Title

<img align="left" src="./documentation/images/A.jpg" alt="Made with Angular" title="Angular" hspace="20"/>
<img align="left" src="./documentation/images/B.png" alt="Made with Bootstrap" title="Bootstrap" hspace="20"/>
<img align="left" src="./documentation/images/C.png" alt="Developed using Browsersync" title="Browsersync" hspace="20"/>
<br/><br/><br/><br/><br/>

## Table of Contents...

Obviously, you have to use more breaks depending on how big the images are: awful yes, but it worked for me so I thought I'd share.


问:
CalendarDatePicker Binding Null Value
I´m using a CalendarDatePicker

```<code><CalendarDatePicker x:Name="DatePick" DisplayMode="Decade" Date="{Binding DisplayValue, Mode=TwoWay}"/>
</code>```

The Problem is when i bind the Date Property the Picker doesn't display the default Placeholder Text(select a date) anymore, instead it now displays 01.01.1916 if the property is null(The Property is always set null).

```<code>public DateTimeOffset? DisplayValue {get;set;}
</code>```

if i manually put null as a value for Date, it now displays the PlaceholderText again.

```<code>DatePick.Date=null;
</code>```

And the binding still works/i`m getting the desired values back when picking a date.
So is there an possibility to display the placeholder text without the using the codebehind?

答:
Seems that the calendardatepicker "min value" is always the current year less 100, I've modified your code in my side to:

```<code>  public class CalendarDatePickerEx : CalendarDatePicker
  {
    public DateTimeOffset? DefaultValue { get; set; }

    public static readonly DependencyProperty DefaultValueProperty =
      DependencyProperty.Register("DefaultValue", typeof(DateTimeOffset), typeof(CalendarDatePickerEx), new PropertyMetadata(null, (sender, e) =>
      {
        if ((DateTimeOffset?)e.NewValue != null && ((CalendarDatePickerEx)sender).Date.Value.Date.Year == DateTime.Today.Year - 100)
        {
          ((CalendarDatePickerEx)sender).SetDisplayDate((DateTimeOffset)e.NewValue);
          ((CalendarDatePickerEx)sender).Date = null;
        }
        else if ((DateTimeOffset?)e.NewValue == null && ((CalendarDatePickerEx)sender).Date.Value.Date.Year == DateTime.Today.Year - 100)
        {
          {
            ((CalendarDatePickerEx)sender).SetDisplayDate(DateTimeOffset.Now);
            ((CalendarDatePickerEx)sender).Date = null;
          }
        }
      }));
  }
</code>```

Preferred solution

If you use x:Bind instead of Binding all works as expected and you can see the placeholder if the binded date value is null.

Directly in the XAML page:

```<code><CalendarDatePicker Date="{x:Bind DataContext.DisplayValue, Mode=TwoWay}"/>
</code>```

or inside a DataTemplate:

```<code><DataTemplate x:Key="DateFieldItemTemplate"
              x:DataType="DataModel:ObjectTypeWithDate">
    <Grid>
        <CalendarDatePicker Date="{x:Bind DateField, Mode=TwoWay}"/>
    </Grid>
</DataTemplate>
</code>```

Title: CalendarDatePicker Binding Null Value

Body:
I´m using a CalendarDatePicker

<CalendarDatePicker x:Name="DatePick" DisplayMode="Decade" Date="{Binding DisplayValue, Mode=TwoWay}"/>

The Problem is when i bind the Date Property the Picker doesn't display the default Placeholder Text(select a date) anymore, instead it now displays 01.01.1916 if the property is null(The Property is always set null).

public DateTimeOffset? DisplayValue {get;set;}

if i manually put null as a value for Date, it now displays the PlaceholderText again.

DatePick.Date=null;

And the binding still works/i`m getting the desired values back when picking a date.
So is there an possibility to display the placeholder text without the using the codebehind?

Body:
Seems that the calendardatepicker "min value" is always the current year less 100, I've modified your code in my side to:

  public class CalendarDatePickerEx : CalendarDatePicker
  {
    public DateTimeOffset? DefaultValue { get; set; }

    public static readonly DependencyProperty DefaultValueProperty =
      DependencyProperty.Register("DefaultValue", typeof(DateTimeOffset), typeof(CalendarDatePickerEx), new PropertyMetadata(null, (sender, e) =>
      {
        if ((DateTimeOffset?)e.NewValue != null && ((CalendarDatePickerEx)sender).Date.Value.Date.Year == DateTime.Today.Year - 100)
        {
          ((CalendarDatePickerEx)sender).SetDisplayDate((DateTimeOffset)e.NewValue);
          ((CalendarDatePickerEx)sender).Date = null;
        }
        else if ((DateTimeOffset?)e.NewValue == null && ((CalendarDatePickerEx)sender).Date.Value.Date.Year == DateTime.Today.Year - 100)
        {
          {
            ((CalendarDatePickerEx)sender).SetDisplayDate(DateTimeOffset.Now);
            ((CalendarDatePickerEx)sender).Date = null;
          }
        }
      }));
  }

Preferred solution

If you use x:Bind instead of Binding all works as expected and you can see the placeholder if the binded date value is null.

Directly in the XAML page:

<CalendarDatePicker Date="{x:Bind DataContext.DisplayValue, Mode=TwoWay}"/>

or inside a DataTemplate:

<DataTemplate x:Key="DateFieldItemTemplate"
              x:DataType="DataModel:ObjectTypeWithDate">
    <Grid>
        <CalendarDatePicker Date="{x:Bind DateField, Mode=TwoWay}"/>
    </Grid>
</DataTemplate>


问:
how to access redux store from custom javascript
I'm trying to implement an external API library in a redux application.
I'm fresh new in redux so I don't know exactly how it works.

In my javascript using the API library, I wan't to access info from a container (the user firstanme if he's logged).

After reading some doc, I tried to import the store in my js file, to get the state of the user, but I can't reach the info I need.

Here's the code I tried :

```<code>import configureStore from '../store/configureStore';

const store = configureStore();
const state = store.getState();
</code>```

I get many info in state, but not the one I need. Any help ?

答:
First of all it looks like configureStore creates new store every time you call it. But you need the very that store that your components will use and populate. So you need to somehow access the store you are passing your Provider.

Then since store state is "changing" you can't simply read it once. So your user data might be initially empty but available some time later.

In this case you could make it a Promise

```<code>const once = selector => available => new Promise(resolve => {
   store.subscribe(() => {
      const value = selector(value)
      if(available(value)) resolve(value)
   })
})
</code>```

And usage

```<code> const user = once(state => state.user)(user => user && user.fullName)

 user.then(user => console.log(`User name is ${user.fullName}`)
</code>```

Or if your data might be changing more than once during application lifecycle you might want to wrap it with something that represent changing data (observable). RX examle

Body:
I'm trying to implement an external API library in a redux application.
I'm fresh new in redux so I don't know exactly how it works.

In my javascript using the API library, I wan't to access info from a container (the user firstanme if he's logged).

After reading some doc, I tried to import the store in my js file, to get the state of the user, but I can't reach the info I need.

Here's the code I tried :

import configureStore from '../store/configureStore';

const store = configureStore();
const state = store.getState();

I get many info in state, but not the one I need. Any help ?

Body:
First of all it looks like configureStore creates new store every time you call it. But you need the very that store that your components will use and populate. So you need to somehow access the store you are passing your Provider.

Then since store state is "changing" you can't simply read it once. So your user data might be initially empty but available some time later.

In this case you could make it a Promise

const once = selector => available => new Promise(resolve => {
   store.subscribe(() => {
      const value = selector(value)
      if(available(value)) resolve(value)
   })
})

And usage

 const user = once(state => state.user)(user => user && user.fullName)

 user.then(user => console.log(`User name is ${user.fullName}`)

Or if your data might be changing more than once during application lifecycle you might want to wrap it with something that represent changing data (observable). RX examle