问:
WCF URL Length Causing IIS 400 Bad Request Error
I have a wcf webHttp endpoint and noticed today that when called httpGet with a long url ~364 total characters (http:// etc counted) IIS throws a 400 bad request error.  Throwing a breakpoint in the code never gets reached.  If I remove some parameters and have a url that is 354 the web service runs as expected.

I'm not sure where the issue is since urls can be like 2k.  I'm not posting any data so I don't think I'm hitting a 4mb limit like from here

What gives?

Here's some wcf xml stuff.

```<code>    <behaviors>
        <endpointBehaviors>
            <behavior name="REST">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>

<endpoint address="" behaviorConfiguration="REST" binding="customBinding" bindingConfiguration="jsonpBinding" contract="Interface"/>

<bindings>
        <customBinding>
            <binding name="jsonpBinding">
                <jsonpMessageEncoding/>
                <httpTransport manualAddressing="true"/>
            </binding>
        </customBinding>
    </bindings>
    <extensions>
        <bindingElementExtensions>
            <add name="jsonpMessageEncoding" type="Microsoft.Ajax.Samples.JsonpBindingExtension, service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
        </bindingElementExtensions>
    </extensions>
</code>```

I just removed the callback function name which significantly reduced the size of the url and it still threw a 400 error.  This makes me think that there is a WCF size limit on the text that can be sent in as a string parameter.

here;'s some Contract stuff

```<code>    [OperationContract]
[WebGet(UriTemplate = @"{userName}/layer({layerName})returnAttributes({attributeList})where({attributeName})({op})({attributeValue})", ResponseFormat = WebMessageFormat.Json)]
[JSONPBehavior(callback = "callback")]
DojoGrouping GetAttributes(string userName, string layerName, string attributeList, string attributeName, string attributeValue);
</code>```

the issue is with attributeList which can be comma separated list.

so with a url call like

http://../demo/layer(OfficialsLookup)returnAttributes(USHOUSE,US_Photo,US_Web,US_Name,SENDIST,SEN_Name,SEN_Email,SEN_Party,SEN_Photo,REPDIST,REP_Name,REP_Email,REP_Party,REP_Web,REP_Photo)utmX(430)utmY(4502)

it busts. But if i shorten the return attribute text then it functions properly.

```<code>I've added I added the following entry into the registry:
Key Name: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters
Class Name: <NO CLASS>
Last Write Time: 1/25/2011 - 3:34 PM
Value 0
Name: UrlSegmentMaxLength
Type: REG_DWORD
Data: 0x200
</code>```

I rebooted the machine after adding it and am still receiving the same error. Is this the correct spot to be modifying the HTTP.sys settings that WCF and IIS are using? Is there a way to test that WCF is being affected by this registry value?

Here is a related post with no answer but saying that the httpsys stuff did not fix a 64 bit server which is what we are using.

Related Post

答:
WCF uses HTTP.sys to handle HTTP traffic. HTTP.sys has system wide settings to handle various restrictions around URL. You might be hitting one of them.

See the following article to find out those settings:
http://support.microsoft.com/kb/820129

You will need to restart http service and your WCF service. If it is hosted in IIS, restart IIS. UrlSegmentMaxLength seems to be an interesting for your URI template.

Body:
I have a wcf webHttp endpoint and noticed today that when called httpGet with a long url ~364 total characters (http:// etc counted) IIS throws a 400 bad request error.  Throwing a breakpoint in the code never gets reached.  If I remove some parameters and have a url that is 354 the web service runs as expected.

I'm not sure where the issue is since urls can be like 2k.  I'm not posting any data so I don't think I'm hitting a 4mb limit like from here

What gives?

Here's some wcf xml stuff.

    <behaviors>
        <endpointBehaviors>
            <behavior name="REST">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>

<endpoint address="" behaviorConfiguration="REST" binding="customBinding" bindingConfiguration="jsonpBinding" contract="Interface"/>

<bindings>
        <customBinding>
            <binding name="jsonpBinding">
                <jsonpMessageEncoding/>
                <httpTransport manualAddressing="true"/>
            </binding>
        </customBinding>
    </bindings>
    <extensions>
        <bindingElementExtensions>
            <add name="jsonpMessageEncoding" type="Microsoft.Ajax.Samples.JsonpBindingExtension, service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
        </bindingElementExtensions>
    </extensions>

I just removed the callback function name which significantly reduced the size of the url and it still threw a 400 error.  This makes me think that there is a WCF size limit on the text that can be sent in as a string parameter.

here;'s some Contract stuff

    [OperationContract]
[WebGet(UriTemplate = @"{userName}/layer({layerName})returnAttributes({attributeList})where({attributeName})({op})({attributeValue})", ResponseFormat = WebMessageFormat.Json)]
[JSONPBehavior(callback = "callback")]
DojoGrouping GetAttributes(string userName, string layerName, string attributeList, string attributeName, string attributeValue);

the issue is with attributeList which can be comma separated list.

so with a url call like

http://../demo/layer(OfficialsLookup)returnAttributes(USHOUSE,US_Photo,US_Web,US_Name,SENDIST,SEN_Name,SEN_Email,SEN_Party,SEN_Photo,REPDIST,REP_Name,REP_Email,REP_Party,REP_Web,REP_Photo)utmX(430)utmY(4502)

it busts. But if i shorten the return attribute text then it functions properly.

I've added I added the following entry into the registry:
Key Name: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters
Class Name: <NO CLASS>
Last Write Time: 1/25/2011 - 3:34 PM
Value 0
Name: UrlSegmentMaxLength
Type: REG_DWORD
Data: 0x200

I rebooted the machine after adding it and am still receiving the same error. Is this the correct spot to be modifying the HTTP.sys settings that WCF and IIS are using? Is there a way to test that WCF is being affected by this registry value?

Here is a related post with no answer but saying that the httpsys stuff did not fix a 64 bit server which is what we are using.

Related Post


来源: stackexchange

问:
How to set up node.js process.env variables for production with an Amazon EC2 instance?
I have searched and searched for a straight forward answer to this question but I have found nothing. I have my local .env file and am successfully loading it with dotenv.

The only answer I can find for setting up the process.env variables for production is to use Elastic Beanstalk.

Is there a way to set these variables up with just an EC2 instance?

答:
It's a normal server. you can always set env by</p>

```<code>EXPORT FOO=bar
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's a normal server. you can always set env by

EXPORT FOO=bar


问:
Error of using tfidf as the input of method 'model.fit()' in package lda
I was using package LDA in python to analysis the topics in documents, it's ok when I use term frequency as the input of method
 'model.fit()',however, there is always a error, saying that 'TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'******',using Tfidf as the input of method 'model.fix()' in the package LDA.
The code is as follows:(Every line in papers.txt is specific terms as the representation of each document)

```<code>corpus = []
for line in open('papers.txt','r').readlines():
  corpus.append(line.strip())
vectorizer =  CountVectorizer()
#tf-idf
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(corpus))
analyze = vectorizer.build_analyzer()
weight = tfidf.toarray()
words = vectorizer.get_feature_names()
years = getYears()
#import lda
model = lda.LDA(n_topics=30,n_iter=500,random_state = 1)
model.fit(np.asarray(weight))
topic_word = model.topic_word_
doc_topic = model.doc_topic_
</code>```

It seems that package LDA's method 'model.fit()' can only receive a matrix with the type of integer, not float? I have checked the documentation of package lda(https://pypi.python.org/pypi/lda), unfortunately, there is no specific discussion about the  detaills. Does anyone had met the same problem? How do you fix these? Thanks in advance!

答:
You need to cast the np array first

model.fit(np.asarray(weight)) should become model.fit(np.asarray(weight).astype(int))

Body:
I was using package LDA in python to analysis the topics in documents, it's ok when I use term frequency as the input of method
 'model.fit()',however, there is always a error, saying that 'TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'******',using Tfidf as the input of method 'model.fix()' in the package LDA.
The code is as follows:(Every line in papers.txt is specific terms as the representation of each document)

corpus = []
for line in open('papers.txt','r').readlines():
  corpus.append(line.strip())
vectorizer =  CountVectorizer()
#tf-idf
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(corpus))
analyze = vectorizer.build_analyzer()
weight = tfidf.toarray()
words = vectorizer.get_feature_names()
years = getYears()
#import lda
model = lda.LDA(n_topics=30,n_iter=500,random_state = 1)
model.fit(np.asarray(weight))
topic_word = model.topic_word_
doc_topic = model.doc_topic_

It seems that package LDA's method 'model.fit()' can only receive a matrix with the type of integer, not float? I have checked the documentation of package lda(https://pypi.python.org/pypi/lda), unfortunately, there is no specific discussion about the  detaills. Does anyone had met the same problem? How do you fix these? Thanks in advance!


问:
Pull stock value of last business day of a month
Need help in Pulling stock value of last business day of a month in a time series/dataframe
I am executing the fol code:

```<code>import pandas as pd
import datetime
import matplotlib
import warnings
warnings.filterwarnings('ignore')
start = datetime.datetime(2014, 3, 31)
end = datetime.datetime(2017, 9, 30)
stocks = ['AAPL', 'GOOG']
col = 'Adj Close'
df = web.get_data_yahoo(stocks,start,end)
data = df.ix[col]
dataframe = pd.DataFrame(data)
</code>```

This gives me a dataframe with all the close values.
I want to get the values only from the last business day of the month

答: Please ignore the question, I've managed to find the answer</p>

Body:
Need help in Pulling stock value of last business day of a month in a time series/dataframe
I am executing the fol code:

import pandas as pd
import datetime
import matplotlib
import warnings
warnings.filterwarnings('ignore')
start = datetime.datetime(2014, 3, 31)
end = datetime.datetime(2017, 9, 30)
stocks = ['AAPL', 'GOOG']
col = 'Adj Close'
df = web.get_data_yahoo(stocks,start,end)
data = df.ix[col]
dataframe = pd.DataFrame(data)

This gives me a dataframe with all the close values.
I want to get the values only from the last business day of the month


问:
Sum of dot products
How to transform 100 of 8 element vectors into 10 16 element vectors using 1000 different (8,16) weight matrices? Each of the 10 output vectors is a sum of 100 dot products:

```<code>A = np.random.randn(100,8)
W = np.random.randn(1000,8,16)
B = []

for i in range(10):
  sum = np.zeros((1,16))
  for j in range(100):
    sum += np.dot(A[j], W[i*100+j])
  B.append(sum)
B = np.asarray(B)     #B.shape=(10,16)
</code>```

Is there a function in Numpy or TensorFlow for that? I looked at dot, tensordot, einsum, and matmul in Numpy, and I'm still not sure which one is the right option.

EDIT: I just realized that I actually want to produce an intermediate result before summing dot products: (100,8)x(10,100,8,16) -> (10,100,16).

I'm guessing this could be done with reshaping (100,8) to (1,100,1,8) and (1000,8,16) to (10,100,8,16), and doing np.einsum('ijkl,ijlm->ijm', A, B)  But I'm not sure if it will broadcast 1 to 10 correctly.

Per @Divakar comment, np.einsum('jk,ijkl->ijl', V, W.reshape(10,100,8,16)) does the trick.

答:
You can use tensor based multiplication, np.tensordot -

```<code>def tensordot_app(A, W):
    m,n,r = W.shape
    Wr = W.reshape(-1,A.shape[0],n,r)
    return np.tensordot(A,Wr, axes=((0,1),(1,2)))
</code>```

Related post to understand tensordot.

Runtime test -

```<code>In [62]: A = np.random.randn(100,8)
    ...: W = np.random.randn(1000,8,16)

In [63]: %%timeit
    ...: B = []
    ...: for i in range(10):
    ...:   sum = np.zeros((1,16))
    ...:   for j in range(100):
    ...:     sum += np.dot(A[j], W[i*100+j])
    ...:   B.append(sum)
    ...: B = np.asarray(B)     #B.shape=(10,16)
1000 loops, best of 3: 1.81 ms per loop

# Other post's einsum soln
In [64]: %timeit np.einsum('ij,ikjl',A,np.reshape(W,(100,10,8,16), order='F'))
10000 loops, best of 3: 83.4 µs per loop

# Other post's einsum soln without fortran re-ordering
In [65]: %timeit np.einsum('jk,ijkl', A, np.reshape(W, (10, 100, 8, 16)))
10000 loops, best of 3: 83.3 µs per loop

In [66]: %timeit tensordot_app(A, W)
10000 loops, best of 3: 193 µs per loop
</code>```

Title: Sum of dot products

Body:
How to transform 100 of 8 element vectors into 10 16 element vectors using 1000 different (8,16) weight matrices? Each of the 10 output vectors is a sum of 100 dot products:

A = np.random.randn(100,8)
W = np.random.randn(1000,8,16)
B = []

for i in range(10):
  sum = np.zeros((1,16))
  for j in range(100):
    sum += np.dot(A[j], W[i*100+j])
  B.append(sum)
B = np.asarray(B)     #B.shape=(10,16)

Is there a function in Numpy or TensorFlow for that? I looked at dot, tensordot, einsum, and matmul in Numpy, and I'm still not sure which one is the right option.

EDIT: I just realized that I actually want to produce an intermediate result before summing dot products: (100,8)x(10,100,8,16) -> (10,100,16).

I'm guessing this could be done with reshaping (100,8) to (1,100,1,8) and (1000,8,16) to (10,100,8,16), and doing np.einsum('ijkl,ijlm->ijm', A, B)  But I'm not sure if it will broadcast 1 to 10 correctly.

Per @Divakar comment, np.einsum('jk,ijkl->ijl', V, W.reshape(10,100,8,16)) does the trick.

Body:
You can use tensor based multiplication, np.tensordot -

def tensordot_app(A, W):
    m,n,r = W.shape
    Wr = W.reshape(-1,A.shape[0],n,r)
    return np.tensordot(A,Wr, axes=((0,1),(1,2)))

Related post to understand tensordot.

Runtime test -

In [62]: A = np.random.randn(100,8)
    ...: W = np.random.randn(1000,8,16)

In [63]: %%timeit
    ...: B = []
    ...: for i in range(10):
    ...:   sum = np.zeros((1,16))
    ...:   for j in range(100):
    ...:     sum += np.dot(A[j], W[i*100+j])
    ...:   B.append(sum)
    ...: B = np.asarray(B)     #B.shape=(10,16)
1000 loops, best of 3: 1.81 ms per loop

# Other post's einsum soln
In [64]: %timeit np.einsum('ij,ikjl',A,np.reshape(W,(100,10,8,16), order='F'))
10000 loops, best of 3: 83.4 µs per loop

# Other post's einsum soln without fortran re-ordering
In [65]: %timeit np.einsum('jk,ijkl', A, np.reshape(W, (10, 100, 8, 16)))
10000 loops, best of 3: 83.3 µs per loop

In [66]: %timeit tensordot_app(A, W)
10000 loops, best of 3: 193 µs per loop


问:
How to capture image from webcam in python2?
The code that I have used gives the output but the image is cropped randomly and does not fit tot the size of the window. When i use  namedWindow("Image", WINDOW_NORMAL);  it gives the error as
:NameError: name 'CV_WINDOW_AUTOSIZE' is not defined

Code:

```<code>from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("Image", WINDOW_NORMAL);
    imshow("cam-test",img)
    waitKey(500)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image
</code>```

what should i do?enter image description here

答:
Try changing:

```<code>namedWindow("Image", WINDOW_NORMAL);
</code>```

to:

```<code>namedWindow("Image");
</code>```

Body:
The code that I have used gives the output but the image is cropped randomly and does not fit tot the size of the window. When i use  namedWindow("Image", WINDOW_NORMAL);  it gives the error as
:NameError: name 'CV_WINDOW_AUTOSIZE' is not defined

Code:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("Image", WINDOW_NORMAL);
    imshow("cam-test",img)
    waitKey(500)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

what should i do?enter image description here

Body:
Try changing:

namedWindow("Image", WINDOW_NORMAL);

to:

namedWindow("Image");


问:
Pandas KeyError: value not in index
I have the following code,

```<code>df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]] = p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]].astype(int)
</code>```

It has always been working until the csv file doesn't have enough coverage (of all week days). For e.g., with the following .csv file,

```<code>DOW,Hour,Changes
4Wed,01,237
3Tue,07,2533
1Sun,01,240
3Tue,12,4407
1Sun,09,2204
1Sun,01,240
1Sun,01,241
1Sun,01,241
3Tue,11,662
4Wed,01,4
2Mon,18,4737
1Sun,15,240
2Mon,02,4
6Fri,01,1
1Sun,01,240
2Mon,19,2300
2Mon,19,2532
</code>```

I'll get the following error:

```<code>KeyError: "['5Thu' '7Sat'] not in index"
</code>```

It seems to have a very easy fix, but I'm just too new to Python to know how to fix it.

答:
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:

```<code>[['Gender']]
</code>```

If it's easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())

ContentLicense: CC BY-SA 4.0

Title: Pandas KeyError: value not in index

Body:
I have the following code,

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]] = p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]].astype(int)

It has always been working until the csv file doesn't have enough coverage (of all week days). For e.g., with the following .csv file,

DOW,Hour,Changes
4Wed,01,237
3Tue,07,2533
1Sun,01,240
3Tue,12,4407
1Sun,09,2204
1Sun,01,240
1Sun,01,241
1Sun,01,241
3Tue,11,662
4Wed,01,4
2Mon,18,4737
1Sun,15,240
2Mon,02,4
6Fri,01,1
1Sun,01,240
2Mon,19,2300
2Mon,19,2532

I'll get the following error:

KeyError: "['5Thu' '7Sat'] not in index"

It seems to have a very easy fix, but I'm just too new to Python to know how to fix it.

Body:
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:

[['Gender']]

If it's easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())


问:
error :Cannot invoke an expression whose type lacks a call signature. Type 'has no compatible c ll signatures
I am trying to use https://github.com/mapbox/polylabel in my angular project and when I try to run ng server,the build fails with following error

```<code>error TS2349: Cannot invoke an expres ion whose type lacks a call signature. Type node_modules/@types/polylabel/index"'has no compatible c ll signatures.
</code>```

Following is the code for index.ts

```<code>    // Type definitions for polylabel 1.0
   // Project: https://github.com/mapbox/polylabel

    // Definitions by: Denis Carriere <https://github.com/DenisCarriere>
    // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

    /**
     * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.
     *
     * @param polygon - Given polygon coordinates in GeoJSON-like format
     * @param precision - Precision (1.0 by default)
     * @param debug - Debugging for Console
     * @example
     * var p = polylabel(polygon, 1.0);
     */
    declare function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];
    declare namespace polylabel {}
    export default polylabel;
</code>```

答: Apparently I didn't have polylabel installed globally. Doing npm install polylabel fixed the issue.

Body:
I am trying to use https://github.com/mapbox/polylabel in my angular project and when I try to run ng server,the build fails with following error

error TS2349: Cannot invoke an expres ion whose type lacks a call signature. Type node_modules/@types/polylabel/index"'has no compatible c ll signatures.

Following is the code for index.ts

    // Type definitions for polylabel 1.0
   // Project: https://github.com/mapbox/polylabel

    // Definitions by: Denis Carriere <https://github.com/DenisCarriere>
    // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

    /**
     * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.
     *
     * @param polygon - Given polygon coordinates in GeoJSON-like format
     * @param precision - Precision (1.0 by default)
     * @param debug - Debugging for Console
     * @example
     * var p = polylabel(polygon, 1.0);
     */
    declare function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];
    declare namespace polylabel {}
    export default polylabel;


答:
You could try this query.

I used CASE function() in the query to check which side is greater and then choose it. I also used the SUM() function to sum all the greater value

```<code>SELECT
SUM( CASE
     WHEN Side-1-Length > Side-2-Length
     THEN Side-1-Length
     ELSE Side-2-Length
     END
) as sum_of_all_greater_value
FROM `TableA`
WHERE DateEnd >='2017-11-10';
</code>```

Title: sum all of greatest value of two fields mysql

Body:
I was trying to get all the greatest value in the table. Let say i have table named TableA and here is the attributes
My Current query is below which is only display one row. So the value that i want to get is sum of all the greatest value of all data.

SELECT GREATEST(MAX(Side-1-Length), MAX(Side-2-Length)) from TableA where DateEnd >='2017-11-10';

Below is my TableA

+---------+--------------+--------------+--------------+
| Id      | Side-1-Length| Side-2-Length|    DateEnd   |
+---------+--------------+--------------+--------------+
| 64      |      22      |      21      | 2011-11-14   |
| 187     |      32      |      26      | 2011-11-15   |
| 325     |      12      |      18      | 2011-11-15   |
| 389     |      41      |      36      | 2011-11-16   |
| 495     |      62      |      41      | 2011-11-14   |
+---------+--------------+--------------+--------------+

The Query that i want to display will output something like below table

+---------+--------------+--------------+
| Id      | Side-Greates |    DateEnd   |
+---------+--------------+--------------+
| 64      |      22      | 2011-11-14   |
| 187     |      32      | 2011-11-15   |
| 325     |      18      | 2011-11-15   |
| 389     |      41      | 2011-11-16   |
| 495     |      62      | 2011-11-14   |
+---------+--------------+--------------+

And WIll sum up all the Side-Greates value

+---------+
| Sum     |
+---------+
| 175     |
+---------+

Body:
You could try this query.

I used CASE function() in the query to check which side is greater and then choose it. I also used the SUM() function to sum all the greater value

SELECT
SUM( CASE
     WHEN Side-1-Length > Side-2-Length
     THEN Side-1-Length
     ELSE Side-2-Length
     END
) as sum_of_all_greater_value
FROM `TableA`
WHERE DateEnd >='2017-11-10';


问:
Prompting user to select pen color doesn't function
I'm supposed to prompt the user to select a pen color based on ones that I've picked out. I've already included an if, else if, else stamtement plus and .equalsignorecase, but whenever I run the file, it won't let me input anything?

(Also my variable "color" is defined as a string if that helps.)

Edit: I already have a scanner class embedded into my code. It's:

```<code>Scanner cool=new Scanner(system.in)
</code>```

Hence any of my code that has "cool" in it is the name I've given my scanner.

```<code>System.out.println("Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
color=cool.nextLine();

StdDraw.setPenRadius(0.05);
StdDraw.circle(2, 2, 4);

if ("red".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.RED);}

else if ("blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BLUE);}

else if ("light blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);}

else if ("pink".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.PINK);}

else if ("green".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.GREEN);}

else if ("orange".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.ORANGE);}

else if ("magenta".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.MAGENTA);}

else if ("yellow".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.YELLOW);}

else
{
   StdDraw.setPenColor(StdDraw.CYAN);
}
</code>```

答:
You need to have a Scanner to read the input. Try this out.

```<code>public class Test {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in); // Reading from System.in
        System.out.println(
                "Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
        String color = reader.nextLine(); // Scans the next token of the input as an string.

        System.out.println(color);
        // once finished
        reader.close();

    }

}
</code>```

Body:
I'm supposed to prompt the user to select a pen color based on ones that I've picked out. I've already included an if, else if, else stamtement plus and .equalsignorecase, but whenever I run the file, it won't let me input anything?

(Also my variable "color" is defined as a string if that helps.)

Edit: I already have a scanner class embedded into my code. It's:

Scanner cool=new Scanner(system.in)

Hence any of my code that has "cool" in it is the name I've given my scanner.

System.out.println("Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
color=cool.nextLine();

StdDraw.setPenRadius(0.05);
StdDraw.circle(2, 2, 4);

if ("red".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.RED);}

else if ("blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BLUE);}

else if ("light blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);}

else if ("pink".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.PINK);}

else if ("green".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.GREEN);}

else if ("orange".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.ORANGE);}

else if ("magenta".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.MAGENTA);}

else if ("yellow".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.YELLOW);}

else
{
   StdDraw.setPenColor(StdDraw.CYAN);
}

Body:
You need to have a Scanner to read the input. Try this out.

public class Test {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in); // Reading from System.in
        System.out.println(
                "Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
        String color = reader.nextLine(); // Scans the next token of the input as an string.

        System.out.println(color);
        // once finished
        reader.close();

    }

}


问:
Android: invalid parent reference
Things get weird when I using Android Studio 3.0 to open a project which was programmed under Android Studio in an older version, after sync, this piece of code didn't work which was programmed by my friend, but I just can't figure it out that why it doesn't work.

```<code> <style name="MyActionBar.MenuTextStyle"
    parent="style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/colorLightPurple</item>
    <item name="android:textSize">14sp</item>
</style>
</code>```

This is the screenshot of the error.

Thanks in advance!

Title: Android: invalid parent reference

Body:
Things get weird when I using Android Studio 3.0 to open a project which was programmed under Android Studio in an older version, after sync, this piece of code didn't work which was programmed by my friend, but I just can't figure it out that why it doesn't work.

This is the screenshot of the error.

Thanks in advance!

Body:
change parent="style/TextAppearance.AppCompat.Widget.ActionBar.Title" to
parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"


问:
How to desgin a class for json when I use Gson in Kotlin?
I'm a beginner of Json and Gson, I know I can map json into a class, and map a class to json via Gson.

"My Json" is a json data, I try to design a class "My Class" to map, but I think that "My Class" is not good. Could you show me some sample code? Thanks!

My Class

```<code>data class Setting (
        val _id: Long,
        val Bluetooth_Stauts: Boolean,
        val WiFi_Name,String
        val WiFi_Statuse: Boolean
)
</code>```

My Json

```<code>{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}
</code>```

Updated

The following is made by Rivu Chakraborty's opinion, it can work well, but it's to complex, is there a simple way?

```<code>data class BluetoothDef(val Status:Boolean=false)

data class WiFiDef(val Name:String, val Status:Boolean=false)

data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
)

data class MDetailsList(val mListMetail: MutableList<MDetail>)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)
        var aMDetailsList=MDetailsList(mListMetail)
        val json = Gson().toJson(aMDetailsList)
</code>```

答:
As per your JSON Structure, I think below class definition should work with Gson

```<code>data class Setting (
        val id: Long,
        val Bluetooth: BluetoothDef,
        val WiFi:WiFiDef
)
data class BluetoothDef(val Status:String)
data class WiFiDef(val Name:String, val Status:String)
</code>```

Explanation -

If you're getting an object in your JSON, you should define a class for that to use with Gson.

Data types should match, use String if you're getting Strings like "ON" and "OFF". You can use Boolean if you're getting true and false (without quotes).

The JSON Element name should match the variable/property name unless you're using @SerializedName to define JSON variable name while using different variable/property name.

*Note You can rename the classes if you want

I think it'll be helpful for you

Body:
I'm a beginner of Json and Gson, I know I can map json into a class, and map a class to json via Gson.

"My Json" is a json data, I try to design a class "My Class" to map, but I think that "My Class" is not good. Could you show me some sample code? Thanks!

My Class

data class Setting (
        val _id: Long,
        val Bluetooth_Stauts: Boolean,
        val WiFi_Name,String
        val WiFi_Statuse: Boolean
)

My Json

{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}

Updated

The following is made by Rivu Chakraborty's opinion, it can work well, but it's to complex, is there a simple way?

data class BluetoothDef(val Status:Boolean=false)

data class WiFiDef(val Name:String, val Status:Boolean=false)

data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
)

data class MDetailsList(val mListMetail: MutableList<MDetail>)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)
        var aMDetailsList=MDetailsList(mListMetail)
        val json = Gson().toJson(aMDetailsList)

Body:
As per your JSON Structure, I think below class definition should work with Gson

data class Setting (
        val id: Long,
        val Bluetooth: BluetoothDef,
        val WiFi:WiFiDef
)
data class BluetoothDef(val Status:String)
data class WiFiDef(val Name:String, val Status:String)

Explanation -

If you're getting an object in your JSON, you should define a class for that to use with Gson.

Data types should match, use String if you're getting Strings like "ON" and "OFF". You can use Boolean if you're getting true and false (without quotes).

The JSON Element name should match the variable/property name unless you're using @SerializedName to define JSON variable name while using different variable/property name.

*Note You can rename the classes if you want

I think it'll be helpful for you


问:
How do I query a list of entities in a many to many relationship in JPA?
Suppose I have the following two entities:

```<code>@Entity
@Table(name="manifest")
public class Manifest extends DbTable implements Serializable {
    public Manifest() { }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(cascade=CascadeType.ALL, mappedBy="manifests",fetch= FetchType.LAZY)
    public List<Thingy> thingys;
}
</code>```

and

```<code>@Entity
@Table(name="thingy")
public class Thingy extends DbTable implements Serializable {
    public Thingy(){}

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "manifest_thingy",
            joinColumns = @JoinColumn(name = "thingy_id", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name = "manifest_id", referencedColumnName="id"))
    public List<Manifest> manifests;
}
</code>```

How can I query my thingies that belong to a given manifest? I have tried queries like

```<code>"SELECT DISTINCT d
 FROM Thingy d
 WHERE :manifest MEMBER OF d.manifests"
</code>```

or

```<code>"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m = :manifest"
</code>```

or

```<code>"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m.id = :manifestId"
</code>```

the latter of those three being basically the only suggestion I could find searching around for this, but to no avail. For all 3 of those I think what I'm getting is an empty list (rather than an error). The query is being fed through something like this (parameters set as appropriate):

```<code>myEntityManager
    .createQuery(giantQueryStringGoesHere, Thingy.class)
    .setParameter("manifest", myManifestObject)
    .getResultList();
</code>```

答:
If you know the specific manifest ID couldn't you just retrieve that manifest and get the list of thingys from it?</p>

```<code>Manifest m = em.find(Manifest.class, manifestId);
List<Thingy> thingys = m.thingys;
</code>```

Body:
Suppose I have the following two entities:

@Entity
@Table(name="manifest")
public class Manifest extends DbTable implements Serializable {
    public Manifest() { }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(cascade=CascadeType.ALL, mappedBy="manifests",fetch= FetchType.LAZY)
    public List<Thingy> thingys;
}

and

@Entity
@Table(name="thingy")
public class Thingy extends DbTable implements Serializable {
    public Thingy(){}

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long id;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "manifest_thingy",
            joinColumns = @JoinColumn(name = "thingy_id", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name = "manifest_id", referencedColumnName="id"))
    public List<Manifest> manifests;
}

How can I query my thingies that belong to a given manifest? I have tried queries like

"SELECT DISTINCT d
 FROM Thingy d
 WHERE :manifest MEMBER OF d.manifests"

or

"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m = :manifest"

or

"SELECT DISTINCT d
 FROM Thingy d
 JOIN d.manifests m
 WHERE m.id = :manifestId"

the latter of those three being basically the only suggestion I could find searching around for this, but to no avail. For all 3 of those I think what I'm getting is an empty list (rather than an error). The query is being fed through something like this (parameters set as appropriate):

myEntityManager
    .createQuery(giantQueryStringGoesHere, Thingy.class)
    .setParameter("manifest", myManifestObject)
    .getResultList();

Body:
If you know the specific manifest ID couldn't you just retrieve that manifest and get the list of thingys from it?

Manifest m = em.find(Manifest.class, manifestId);
List<Thingy> thingys = m.thingys;


问:
Read value of Hidden Field inside ng-repeat in html table binding
I have a html table and data is binding from angular js.
The structure is like that

```<code><tr ng-repeat="item in List| filter: { MachineType: 'Physical' }">

     <td>{{item.MachineType}}</td>

</tr>
</code>```

I want to pass the filter value dynamically from html hidden field which is set dynamically.

How I read the Html hidden field value here and pass in filter..

Thanks

答:
You can do set ng-model on the hidden element and then pass it to the filter. Below is one of the simplest way you can do it.

```<code><input type="hidden" ng-model="myMachineTypw" />

<tr ng-repeat="item in List| filter: { MachineType: myMachineTypw }">
     <td>{{item.MachineType}}</td>
</tr>
</code>```

Another way is, you said you are setting the value of hidden dynamically right? Then you don't even need the hidden element, just update the value of $scope.myMachineType and use that myMachineType as shown in above example and remove the hidden element.

```<code><script type="text/javascript">
    angular
        .module('myApp')
        .controller('myCtrl', myCtrl);

    myCtrl.$inject = ['$scope'];

    function myCtrl ($scope) {
        $scope.myMachineType = "anyValue";
    }
</script>

<tr ng-repeat="item in List| filter: { MachineType: myMachineType }">
     <td>{{item.MachineType}}</td>
</tr>
</code>```

Here is working example:

angular.module('myApp', []);

angular
    .module('myApp')
    .controller('myAppController', myAppController);

myAppController.$inject = ['$scope'];

function myAppController ($scope) {

    $scope.processing = true;

    $scope.init = init;

    function init () {
        $scope.List = [
          {'name':'Item 1', 'MachineType': 'Type1'},
          {'name':'Item 2', 'MachineType': 'Type2'},
          {'name':'Item 3', 'MachineType': 'Type3'},
          {'name':'Item 4', 'MachineType': 'Type2'},
          {'name':'Item 5', 'MachineType': 'Type1'},
          {'name':'Item 6', 'MachineType': 'Type1'},
          {'name':'Item 7', 'MachineType': 'Type3'},
          {'name':'Item 8', 'MachineType': 'Type1'},
          {'name':'Item 9', 'MachineType': 'Type3'},
          {'name':'Item 10', 'MachineType': 'Type3'}
        ];

        $scope.setType = function (x) {
            if ( x ) {
                $scope.myMachineType = "Type"+x;
            } else {
                $scope.myMachineType = "";
            }
        }

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myAppController" ng-init="init();">
    <button ng-click="setType();">Show All</button>
    <button ng-click="setType(1);">Type 1</button>
    <button ng-click="setType(2);">Type 2</button>
    <button ng-click="setType(3);">Type 3</button>
    <table>
        <tr ng-repeat="i in List | filter: { MachineType: myMachineType }">
             <td>{{i.name}} : {{i.MachineType}}</td>
        </tr>
    </table>
</div>
  </code>```

Body:
I have a html table and data is binding from angular js.
The structure is like that

     {{item.MachineType}}

I want to pass the filter value dynamically from html hidden field which is set dynamically.

How I read the Html hidden field value here and pass in filter..

Thanks

Body:
You can do set ng-model on the hidden element and then pass it to the filter. Below is one of the simplest way you can do it.

<input type="hidden" ng-model="myMachineTypw" />

<tr ng-repeat="item in List| filter: { MachineType: myMachineTypw }">
     <td>{{item.MachineType}}</td>
</tr>

Another way is, you said you are setting the value of hidden dynamically right? Then you don't even need the hidden element, just update the value of $scope.myMachineType and use that myMachineType as shown in above example and remove the hidden element.

<script type="text/javascript">
    angular
        .module('myApp')
        .controller('myCtrl', myCtrl);

    myCtrl.$inject = ['$scope'];

    function myCtrl ($scope) {
        $scope.myMachineType = "anyValue";
    }
</script>

<tr ng-repeat="item in List| filter: { MachineType: myMachineType }">
     <td>{{item.MachineType}}</td>
</tr>

Here is working example:

angular.module('myApp', []);

angular
    .module('myApp')
    .controller('myAppController', myAppController);

myAppController.$inject = ['$scope'];

function myAppController ($scope) {

    $scope.processing = true;

    $scope.init = init;

    function init () {
        $scope.List = [
          {'name':'Item 1', 'MachineType': 'Type1'},
          {'name':'Item 2', 'MachineType': 'Type2'},
          {'name':'Item 3', 'MachineType': 'Type3'},
          {'name':'Item 4', 'MachineType': 'Type2'},
          {'name':'Item 5', 'MachineType': 'Type1'},
          {'name':'Item 6', 'MachineType': 'Type1'},
          {'name':'Item 7', 'MachineType': 'Type3'},
          {'name':'Item 8', 'MachineType': 'Type1'},
          {'name':'Item 9', 'MachineType': 'Type3'},
          {'name':'Item 10', 'MachineType': 'Type3'}
        ];

        $scope.setType = function (x) {
            if ( x ) {
                $scope.myMachineType = "Type"+x;
            } else {
                $scope.myMachineType = "";
            }
        }

    }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myAppController" ng-init="init();">
    <button ng-click="setType();">Show All</button>
    <button ng-click="setType(1);">Type 1</button>
    <button ng-click="setType(2);">Type 2</button>
    <button ng-click="setType(3);">Type 3</button>
    <table>
        <tr ng-repeat="i in List | filter: { MachineType: myMachineType }">
             <td>{{i.name}} : {{i.MachineType}}</td>
        </tr>
    </table>
</div>


问:
Photon Unity Networking or Bolt or ...?
I am not able to decide whether to use PUN or Bolt in my Unity based multiplayer game. The game must have LAN and over the internet playing options.

According to documentation on photon website, PUN is meant for multiplayer games over the internet. Master Server is hosted either in the photon cloud or dedicated servers running Photon Server.

Bolt, on the other hand, is meant for LAN games. One of the clients becomes the server.

My game needs both, LAN and Internet. Should I use both the SDKs? Can't there be common code for both options?

答:
Photon made a comparison here:
https://doc.photonengine.com/en-us/pun/current/reference/pun-vs-bolt

The major difference to me is the Host Migration, Bolt and UNet are not support Host Migration yet (UNet support LAN but not Internet)...

If your game is really fast pace (~30s per game) and don't care about Host Migration (Master client disconnected), then PUN or own dedicated server (which I wouldn't consider) are the only choices.

Title: Photon Unity Networking or Bolt or ...?


问:
Inline style using asset pipeline in rails

<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>```

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

答:
If you decide to use non-inline style, then you can also use image-path  at .scss.

At html.erb

```<code><div class="custom-background"></div>
</code>```

At .scss

```<code>.custom-background {
 background-image: image-path('image1.png');
}
</code>```

Body:
<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

Body:
If you decide to use non-inline style, then you can also use image-path  at .scss.

At html.erb

<div class="custom-background"></div>

At .scss

.custom-background {
 background-image: image-path('image1.png');
}


问:
What is it called when JS is used to show only a certain part of a png?
Let's say you have a png and it contains all of the icons that are to be used on one page, what is the process of using JS to select and display on a certain icon in that image? I've always seen it being done, but it seems to evade me what it is, and how to do it.

答: I guess you are referring to sprite image.  js or css can be used to select images.</p>

ContentLicense: CC BY-SA 2.5


问:
Abaqus Surface getSequenceFromMask
I am writing script in Abaqus, where I crush circle and square with cut circle (like cheese). I need to put Contact between parts so I need Surface.

macro manager generates:

```<code>s1 = a.instances['kolo-1'].edges
side1Edges1 = s1.getSequenceFromMask(mask=('[#1 ]', ), )
a.Surface(side1Edges=side1Edges1 , name='kolkoSurf')
</code>```

The problem is: getSequenceFromMask(mask=('[#1 ]', ), )
How to get this #1? Can I replace it? I searched little and there were some ideas to use: 'find', 'face', 'COORDS' but I cannot manage it.
Please help me. I dream to get an simple example how to extract this Surface using X, Y or anyway.

BR,
Wonman

答:
I suppose you are creating an edge based surface. There are many ways to do it, easiest one is

Create an assembly based set ("setName") of those edges for which you want to create surface.

```<code>instance=mdb.rootAssembly.instances["InstanceName"]
set_for_surface=instance.sets["setName"].edges
assembly.Surface(side1Edges=set_for_surface, name="surf_name")
</code>```

Have look at findAt() or selecting region by bounding box "getBoundingBox()". See this SO answer, which is somewhat similar.

Edit: If the set is an assembly based set, access it directly from assembly not instance. Then, use the same procedure.

```<code>mdb.rootAssembly.sets['Set_name'].edges
</code>```

Title: Abaqus Surface getSequenceFromMask

Body:
I am writing script in Abaqus, where I crush circle and square with cut circle (like cheese). I need to put Contact between parts so I need Surface.

macro manager generates:

s1 = a.instances['kolo-1'].edges
side1Edges1 = s1.getSequenceFromMask(mask=('[#1 ]', ), )
a.Surface(side1Edges=side1Edges1 , name='kolkoSurf')

The problem is: getSequenceFromMask(mask=('[#1 ]', ), )
How to get this #1? Can I replace it? I searched little and there were some ideas to use: 'find', 'face', 'COORDS' but I cannot manage it.
Please help me. I dream to get an simple example how to extract this Surface using X, Y or anyway.

BR,
Wonman

Body:
I suppose you are creating an edge based surface. There are many ways to do it, easiest one is

Create an assembly based set ("setName") of those edges for which you want to create surface.

instance=mdb.rootAssembly.instances["InstanceName"]
set_for_surface=instance.sets["setName"].edges
assembly.Surface(side1Edges=set_for_surface, name="surf_name")

Have look at findAt() or selecting region by bounding box "getBoundingBox()". See this SO answer, which is somewhat similar.

Edit: If the set is an assembly based set, access it directly from assembly not instance. Then, use the same procedure.

mdb.rootAssembly.sets['Set_name'].edges


问:
What's the default regex engine in C++11?
Having seen a regex from one of my colleagues of <.*?> for stripping HTML tags, it didn't make sense to me to have zero-or-one occurrences (?) of zero-or-more characters (.*). Additionally, it appeared that it wouldn't work since.* is greedy so would strip out data between tags as well.

But on testing this in an online regex, it appeared my colleague was correct in his assertion that it makes it non-greedy so I decided to go and check why.

In any case, that's just the background. Looking at the C++11 standard, I finally found out that there were multiple possible regex engines that were allowed, as per 28.5.2 and table 128, and that:

A valid value of type syntax_option_type shall have exactly one of the
  elements ECMAScript, basic, extended, awk, grep, egrep, set.

However, that same section shows that the default used if not specified, match_default, is defined as zero, which clearly does not have one of the bits set.

Nowhere in the standard can I find where the default engine is specified so I'm wondering whether that's implementation defined or whether I've just missed it.

答:
Okay, based on a comment, I looked more deeply into the standard and what the class hierarchy is.

I believe this is covered by the basic_regex constructors, in C++11 28.8.2, which are used by the higher levels. All of those constructors, such as:

```<code>basic_regex(const charT* p, flag_type f = regex_constants::ECMAScript);
</code>```

use ECMAScript as the default engine.

And, for what it's worth, the ECMAScript syntax explicitly calls out the .*? behaviour that sent me on this quest in the first place. The ? is treated differently (i.e., is not the zero-or-one quantifier) when it immediately follows a quantifier (*, +, ?, {exact}, {min,} and {min,max}) in that it makes the matching non-greedy:

By default, all these quantifiers are greedy (i.e., they take as many characters that meet the condition as possible). This behavior can be overridden to ungreedy (i.e., take as few characters that meet the condition as possible) by adding a question mark, ?, after the quantifier.

For example, matching "(a+).*" against "aardvark" succeeds and yields aa as the first submatch, while matching "(a+?).*" against it also succeeds, but yields a as the first submatch.

Body:
Okay, based on a comment, I looked more deeply into the standard and what the class hierarchy is.

I believe this is covered by the basic_regex constructors, in C++11 28.8.2, which are used by the higher levels. All of those constructors, such as:

basic_regex(const charT* p, flag_type f = regex_constants::ECMAScript);

use ECMAScript as the default engine.

And, for what it's worth, the ECMAScript syntax explicitly calls out the .*? behaviour that sent me on this quest in the first place. The ? is treated differently (i.e., is not the zero-or-one quantifier) when it immediately follows a quantifier (*, +, ?, {exact}, {min,} and {min,max}) in that it makes the matching non-greedy:

By default, all these quantifiers are greedy (i.e., they take as many characters that meet the condition as possible). This behavior can be overridden to ungreedy (i.e., take as few characters that meet the condition as possible) by adding a question mark, ?, after the quantifier.

For example, matching "(a+).*" against "aardvark" succeeds and yields aa as the first submatch, while matching "(a+?).*" against it also succeeds, but yields a as the first submatch.


问:
wso2 cep Siddhiql
I have multiple sensors sending measurement events to a stream. An event consists of {parameter, value, timestamp}. I want to observe these values for a time window of few days and check the trends and make diagnostics about the equipment being monitored by these different sensors.

Divide the streams by parameter.

```
    from inputStream[parameter='A']
    select *
    insert into Astream;
```

and so on for each parameter being received.

for the timewindow, say 60 seconds, compute linear regression to find the change.

```
    from Astream#timeseries:lengthTimeRegress(60000, value, timestamp)
    select beta1 * 100 as AChange
    insert into AChangeStream;
```

This I do for each metric stream.
3. Once I have trend for each stream, I collect the changed values for each stream and check if they meet the condition.

```
    from every e1=AChangeStream[e1.AChangeStream > 0.5], e2=BChangeStream[e2.BChangeStream  0.15]
    select 'condition 1 alarm' as message
    insert into alertStream;
```

Will the above siddhi ql detect the changes in 6 parameters in the time window?

答:
The gist of the query you have provided is correct except for few minor things you have missed. When you say 6 parameters, I believe that you have something similar to Parameters A, B, C, D, E and F. Eventually you seem to want to find a sequence of events that match the given condition [1].

Considering only 2 Parameters A and B, you could write the queries in Siddhi language as follows, to achieve your requirement.

```

@Import('input:1.0.0')
define stream inputStream (parameter string, value double, timestamp long);

from inputStream[parameter=='A']
select *
insert into Astream;

from inputStream[parameter=='B']
select *
insert into Bstream;

from Astream#timeseries:lengthTimeRegress(60000, 10000, value, timestamp)
select beta1*100 as AChange
insert into AChangeStream;

from Bstream#timeseries:lengthTimeRegress(60000, 10000, value, timestamp)
select beta1*100 as BChange
insert into BChangeStream;

from every e1=AChangeStream[e1.AChange > 0.5], e2=BChangeStream[e2.BChange > 0.15]
select 'condition 1 alarm' as message
insert into alertStream;

```

Please note the following.

In lengthTimeRegress function, you need to provide 4 mandatory parametrs, as specified in [2]. You have missed the batch size in the query you have written. The maximum number of events to be used for a regression calculation is specified by the batch size.

In the sequence condition, you need to use a parameter. Not the stream name. What you have mistakenly written as e1.AChangeStream > 0.5 must change as e1.AChange > 0.5

[1] https://docs.wso2.com/display/CEP420/SiddhiQL+Guide+3.1#SiddhiQLGuide3.1-Sequence

[2] https://docs.wso2.com/display/SIDDHIEXTENSIONS/Regression

Title: wso2 cep Siddhiql

Body:
I have multiple sensors sending measurement events to a stream. An event consists of {parameter, value, timestamp}. I want to observe these values for a time window of few days and check the trends and make diagnostics about the equipment being monitored by these different sensors.

Divide the streams by parameter.

    from inputStream[parameter='A']
    select *
    insert into Astream;

and so on for each parameter being received.

for the timewindow, say 60 seconds, compute linear regression to find the change.

    from Astream#timeseries:lengthTimeRegress(60000, value, timestamp)
    select beta1 * 100 as AChange
    insert into AChangeStream;

This I do for each metric stream.
3. Once I have trend for each stream, I collect the changed values for each stream and check if they meet the condition.

    from every e1=AChangeStream[e1.AChangeStream > 0.5], e2=BChangeStream[e2.BChangeStream  0.15]
    select 'condition 1 alarm' as message
    insert into alertStream;

Will the above siddhi ql detect the changes in 6 parameters in the time window?

Body:
The gist of the query you have provided is correct except for few minor things you have missed. When you say 6 parameters, I believe that you have something similar to Parameters A, B, C, D, E and F. Eventually you seem to want to find a sequence of events that match the given condition [1].

Considering only 2 Parameters A and B, you could write the queries in Siddhi language as follows, to achieve your requirement.

@Import('input:1.0.0')
define stream inputStream (parameter string, value double, timestamp long);

from inputStream[parameter=='A']
select *
insert into Astream;

from inputStream[parameter=='B']
select *
insert into Bstream;

from Astream#timeseries:lengthTimeRegress(60000, 10000, value, timestamp)
select beta1*100 as AChange
insert into AChangeStream;

from Bstream#timeseries:lengthTimeRegress(60000, 10000, value, timestamp)
select beta1*100 as BChange
insert into BChangeStream;

from every e1=AChangeStream[e1.AChange > 0.5], e2=BChangeStream[e2.BChange > 0.15]
select 'condition 1 alarm' as message
insert into alertStream;

Please note the following.

In lengthTimeRegress function, you need to provide 4 mandatory parametrs, as specified in [2]. You have missed the batch size in the query you have written. The maximum number of events to be used for a regression calculation is specified by the batch size.

In the sequence condition, you need to use a parameter. Not the stream name. What you have mistakenly written as e1.AChangeStream > 0.5 must change as e1.AChange > 0.5

[1] https://docs.wso2.com/display/CEP420/SiddhiQL+Guide+3.1#SiddhiQLGuide3.1-Sequence

[2] https://docs.wso2.com/display/SIDDHIEXTENSIONS/Regression


问:
sending mail in asp.net core 2.0 to Amazon SES
I've made a simple form that when it's submitted, I want it to send a mail to my SES Provider in amazon.
How can I achieve this and is there a library in .NET Core 2.0 that allows sending mails?

BTW: I'm using angular in the front end, and for the backend I'm using a WebAPI.

答:
Yes, you can achieve this very easily, since AWSSDK fully supports .net Core 2.0.

Install AWSSDK.SimpleEmail.

Then:

```<code>    public async Task<bool> SendEmail(string from, string to, string subject, string html){
    // might want to provide credentials
    using(var ses = new AmazonSimpleEmailServiceClient(RegionEndpoint.USEast1))

       {
    var sendResult = await ses.SendEmailAsync(new SendEmailRequest
            {
                  Source = from,
                  Destination = new Destination(to) { CcAddresses = "if you need them", BccAddresses = "or these" },
                  Message = new Message
                     {
                       Subject = new Content(subject),
                       Body = new Body
                       {
                          Html = new Content(html)
                       }
                     }
                 });
         return sendResult.HttpStatusCode == HttpStatusCode.OK;
       }
}
</code>```

Body:
Yes, you can achieve this very easily, since AWSSDK fully supports .net Core 2.0.

Install AWSSDK.SimpleEmail.

Then:

    public async Task<bool> SendEmail(string from, string to, string subject, string html){
    // might want to provide credentials
    using(var ses = new AmazonSimpleEmailServiceClient(RegionEndpoint.USEast1))

       {
    var sendResult = await ses.SendEmailAsync(new SendEmailRequest
            {
                  Source = from,
                  Destination = new Destination(to) { CcAddresses = "if you need them", BccAddresses = "or these" },
                  Message = new Message
                     {
                       Subject = new Content(subject),
                       Body = new Body
                       {
                          Html = new Content(html)
                       }
                     }
                 });
         return sendResult.HttpStatusCode == HttpStatusCode.OK;
       }
}


问:
order array of objects based on array of IDs
if I have an array of

```<code>const users = [
  { id: 2, name: 'User 2' },
  { id: 5, name: 'User 5' },
  { id: 3, name: 'User 3' },
]
</code>```

how can I order them based on this array

```<code>const ids = [5, 2, 3]
</code>```

so that the result would be something like

```<code>const users = [
  { id: 5, name: 'User 5' },
  { id: 2, name: 'User 2' },
  { id: 3, name: 'User 3' },
]
</code>```

I tried ids.map(id => users.find(u => u.id === id)) but I think that is not optimised because we keep doing find() to same collection for every id

答:
You can create a Map object that contains the sort index for each value.  Then, use that sort index to actually sort the array:

```<code>const ids = [5,2,3];

// Create sorting index using a Map object
// The id value is the key, the the index in that array is the value
//   in the map and is used as the sort index
const mapIndex = new Map();
for (let [i, id] of ids.entries()) {
   mapIndex.set(id, i);
}

const users = [
  { id: 2, name: 'User 2' },
  { id: 5, name: 'User 5' },
  { id: 3, name: 'User 3' },
];

// sort using the mapIndex
users.sort((a, b) => {
    return mapIndex.get(a.id) - mapIndex.get(b.id);
});
</code>```

This assumes there are no .id values that are not in your ids array.  If that is a possibility, then you need to define what the sort position is for id values not in your ids array and add protection for that in your sort callback.

Body:
if I have an array of

const users = [
  { id: 2, name: 'User 2' },
  { id: 5, name: 'User 5' },
  { id: 3, name: 'User 3' },
]

how can I order them based on this array

const ids = [5, 2, 3]

so that the result would be something like

const users = [
  { id: 5, name: 'User 5' },
  { id: 2, name: 'User 2' },
  { id: 3, name: 'User 3' },
]

I tried ids.map(id => users.find(u => u.id === id)) but I think that is not optimised because we keep doing find() to same collection for every id

Body:
You can create a Map object that contains the sort index for each value.  Then, use that sort index to actually sort the array:

const ids = [5,2,3];

// Create sorting index using a Map object
// The id value is the key, the the index in that array is the value
//   in the map and is used as the sort index
const mapIndex = new Map();
for (let [i, id] of ids.entries()) {
   mapIndex.set(id, i);
}

const users = [
  { id: 2, name: 'User 2' },
  { id: 5, name: 'User 5' },
  { id: 3, name: 'User 3' },
];

// sort using the mapIndex
users.sort((a, b) => {
    return mapIndex.get(a.id) - mapIndex.get(b.id);
});

This assumes there are no .id values that are not in your ids array.  If that is a possibility, then you need to define what the sort position is for id values not in your ids array and add protection for that in your sort callback.


问:
Generate random String in PostgreSQL
I'm using this SQL query to generate random value in PostgreSQL

```<code>chr(ascii('B') + (random() * 25)::integer)
</code>```

How I can generate 15 characters random String using the same query?

答:
Here is my contrib

```<code>postgres=# SELECT array_to_string(array(select substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',((random()*(36-1)+1)::integer),1) from generate_series(1,50)),'');
                  array_to_string
----------------------------------------------------
 4XOS6TQG5JORLF3D1RPXUWR2FQKON9HIXV0UGH0CQFT1LN5D4L
(1 row)
</code>```

It lets you specify the set of allowed characters and the length of the string.

Title: Generate random String in PostgreSQL

Body:
I'm using this SQL query to generate random value in PostgreSQL

chr(ascii('B') + (random() * 25)::integer)

How I can generate 15 characters random String using the same query?

Body:
Here is my contrib

postgres=# SELECT array_to_string(array(select substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',((random()*(36-1)+1)::integer),1) from generate_series(1,50)),'');
                  array_to_string
----------------------------------------------------
 4XOS6TQG5JORLF3D1RPXUWR2FQKON9HIXV0UGH0CQFT1LN5D4L
(1 row)

It lets you specify the set of allowed characters and the length of the string.


问:
Swift: Add Action to a Table View Cell when value entered
I have a Table View Cell and have added an action to it that I want to execute when a value is changed.

I have added the action method in the viewController

```<code>@IBAction func valueEntered(sender: NSTextFieldCell)
{

    print("valueEntered")

}
</code>```

I can edit the Table View Cell by double clicking on it, but my method is never called.

I know I have done this before but I must be missing a step.

答:
You have to hook up the NSTableView delegate.

In your case, control-click and drag from Reseller Table up to File's Owner and choose delegate.

Body:
I have a Table View Cell and have added an action to it that I want to execute when a value is changed.

I have added the action method in the viewController

@IBAction func valueEntered(sender: NSTextFieldCell)
{

    print("valueEntered")

}

I can edit the Table View Cell by double clicking on it, but my method is never called.

I know I have done this before but I must be missing a step.


问:
Simplest way to negate $all in mongoDB
I am running the following query on mongoDB 3.4 using through my application. Basically, I want to find the documents, which the attributes array has elements which match with the specified criteria using $elemMatch

```<code>db.collectionName.find({
    attributes: {
        $all: [{
            $elemMatch: {
                "name": "manufacturer",
                "value": "val1",
                "status": 1
            }
        }, {
            $elemMatch: {
                "name": "model",
                "value": "val2",
                "status": 1
            }
        }]
    }
})
</code>```

But, concurrent to this, I want to run another find query to find the records for which the above find conditions fail, that is even one $elemMatch fails

How can I acheive this?

If possible, I'd rather not change the array I'm passing to $all

答:
Using $not operator as suggessted by @nullpointer in the comments, I was able to do it this way:

```<code>db.collectionName.find({
    attributes: {
        $not: {
            $all: [{
                $elemMatch: {
                    "name": "manufacturer",
                    "value": "val1",
                    "status": 1
                }
            }, {
                $elemMatch: {
                    "name": "model",
                    "value": "val2",
                    "status": 1
                }
            }]
        }
    }
})
</code>```

Another alternative I was trying to avoid but can be used is the De-Morgan's theorems, accoring to which:

NOT (A AND B AND C) = NOT A OR NOT B OR NOT C, which would make the query

```<code>db.collectionName.find({
    attributes: {
        $or: [{
            $elemMatch: {
                "name": "manufacturer",
                "value": {"$ne": "val1"},
                "status": 1
            }
        }, {
            $elemMatch: {
                "name": "model",
                "value": {"$ne": "val2"},
                "status": 1
            }
        }]
    }

})
</code>```

Title: Simplest way to negate $all in mongoDB

Body:
I am running the following query on mongoDB 3.4 using through my application. Basically, I want to find the documents, which the attributes array has elements which match with the specified criteria using $elemMatch

db.collectionName.find({
    attributes: {
        $all: [{
            $elemMatch: {
                "name": "manufacturer",
                "value": "val1",
                "status": 1
            }
        }, {
            $elemMatch: {
                "name": "model",
                "value": "val2",
                "status": 1
            }
        }]
    }
})

But, concurrent to this, I want to run another find query to find the records for which the above find conditions fail, that is even one $elemMatch fails

How can I acheive this?

If possible, I'd rather not change the array I'm passing to $all

Body:
Using $not operator as suggessted by @nullpointer in the comments, I was able to do it this way:

db.collectionName.find({
    attributes: {
        $not: {
            $all: [{
                $elemMatch: {
                    "name": "manufacturer",
                    "value": "val1",
                    "status": 1
                }
            }, {
                $elemMatch: {
                    "name": "model",
                    "value": "val2",
                    "status": 1
                }
            }]
        }
    }
})

Another alternative I was trying to avoid but can be used is the De-Morgan's theorems, accoring to which:

NOT (A AND B AND C) = NOT A OR NOT B OR NOT C, which would make the query

db.collectionName.find({
    attributes: {
        $or: [{
            $elemMatch: {
                "name": "manufacturer",
                "value": {"$ne": "val1"},
                "status": 1
            }
        }, {
            $elemMatch: {
                "name": "model",
                "value": {"$ne": "val2"},
                "status": 1
            }
        }]
    }

})


问:
Django, full state name from USStateField
When I try and access the variable initialized to a USStateField in Django, it gives me the two letter normalization.  I realize this is the behavior that Django intends but there must be some way to access the full name since Django can populate the menu with the full state names</p>

答:
```<code> >>>from django.contrib.localflavor.us.us_states import US_STATES
 >>>dict(US_STATES)['AL']
 'Alabama'
</code>```


问:
Using styled-components with props from React component
I'm using styled components in my react js project.
when constructing my styled component img, I want the background to be dependent on the props the component gets.
If i'm building a functional component I just use:

```<code>  const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props.imageUrl});
  background-position: center center;
  background-repeat: no-repeat;`;
</code>```

inside the component and it works.
but how can I achieve the same with class components? since I can't declare a const var inside the class itself, and out side of it, there is no this.props

Thanks!

答:
You need to pass in a function to access props when defined outside the scope of the component. So in your case:

```<code>const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props => props.imageUrl}); //use a function here instead
  background-position: center center;
  background-repeat: no-repeat;
`;
</code>```

When styled-components encounters a function in the CSS template, it'll call it with the props assigned to the component.

Remember though this is refers to props assigned to the FramedImage component, so if you want to pass in props from it's parent component, you need to spread them in as such:

```<code>class Parent extends React.Component {
  render() {
    return <FramedImage {...this.props} />
  }
}
</code>```

Body:
I'm using styled components in my react js project.
when constructing my styled component img, I want the background to be dependent on the props the component gets.
If i'm building a functional component I just use:

  const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props.imageUrl});
  background-position: center center;
  background-repeat: no-repeat;`;

inside the component and it works.
but how can I achieve the same with class components? since I can't declare a const var inside the class itself, and out side of it, there is no this.props

Thanks!

Body:
You need to pass in a function to access props when defined outside the scope of the component. So in your case:

const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props => props.imageUrl}); //use a function here instead
  background-position: center center;
  background-repeat: no-repeat;
`;

When styled-components encounters a function in the CSS template, it'll call it with the props assigned to the component.

Remember though this is refers to props assigned to the FramedImage component, so if you want to pass in props from it's parent component, you need to spread them in as such:

class Parent extends React.Component {
  render() {
    return <FramedImage {...this.props} />
  }
}


问:
Appium/Selenium TestNG Gradle DexArchiveBulderException Build Errors
I am an intermediate level tester who is currently exploring options for mobile automation. I am familiar with Appium/Selenium and am now attempting to introduce TestNG to manage test suites.

I have run into an error when attempting to build a simple project to begin mobile testing using TestNG and Appium/Selenium. I am unable to figure out how to fix this error.

Here is my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.mikejohnson.testngtest"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' // added this to resolve initial build conflict
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'org.testng:testng:6.11' //added this
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'org.seleniumhq.selenium:selenium-java:3.7.1' //added this
    implementation 'io.appium:java-client:5.0.4' //added this
}
</code>```

Here is the error:

```<code>Information:Gradle tasks [clean, :app:assembleDebug]
Warning:Ignoring InnerClasses attribute for an anonymous inner class
Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing org/openqa/selenium/firefox/FirefoxBinary.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Information:BUILD FAILED in 10s
Information:4 errors
Information:1 warning
Information:See complete output in console
</code>```

To get to this point all I have done is create a basic android project and attempted to add the required dependencies for TestNG and Appium/Selenium to build.gradle

The errors are introduced when combining the dependencies for TestNG and Appium/Selenium. The project is able to successfully build with just TestNG dependencies, or just Appium/Selenium dependencies. As soon as I combine TestNG along with Appium/Selenium, errors begin to appear.

I have searched and tried many possible solutions, however it always ends with a DexArchiveBulderException. I  do not have the experience to deduce what is going wrong with the dependencies, and there is very little information available on 'DexArchiveBuilderException' when searching.

If there is any other information I can provide, please let me know. Thank you for the assistance in advance.

答: Problem fixed - recreated project in Intellij IDEA as a basic gradle/java project.</p>

Body:
I am an intermediate level tester who is currently exploring options for mobile automation. I am familiar with Appium/Selenium and am now attempting to introduce TestNG to manage test suites.

I have run into an error when attempting to build a simple project to begin mobile testing using TestNG and Appium/Selenium. I am unable to figure out how to fix this error.

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.mikejohnson.testngtest"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' // added this to resolve initial build conflict
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'org.testng:testng:6.11' //added this
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'org.seleniumhq.selenium:selenium-java:3.7.1' //added this
    implementation 'io.appium:java-client:5.0.4' //added this
}

Here is the error:

Information:Gradle tasks [clean, :app:assembleDebug]
Warning:Ignoring InnerClasses attribute for an anonymous inner class
Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing org/openqa/selenium/firefox/FirefoxBinary.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Information:BUILD FAILED in 10s
Information:4 errors
Information:1 warning
Information:See complete output in console

To get to this point all I have done is create a basic android project and attempted to add the required dependencies for TestNG and Appium/Selenium to build.gradle

The errors are introduced when combining the dependencies for TestNG and Appium/Selenium. The project is able to successfully build with just TestNG dependencies, or just Appium/Selenium dependencies. As soon as I combine TestNG along with Appium/Selenium, errors begin to appear.

I have searched and tried many possible solutions, however it always ends with a DexArchiveBulderException. I  do not have the experience to deduce what is going wrong with the dependencies, and there is very little information available on 'DexArchiveBuilderException' when searching.

If there is any other information I can provide, please let me know. Thank you for the assistance in advance.


问:
Local repository directories disappeared?
I'm pretty new to Git, and recently started to use branches, but I don't think I have the concepts down, and now I'm running into problems.

Basically, I created a devel branch, and am creating feature branches to merge small changes into devel. I deleted some files in the feature branches, and thus in devel, but now I realized I want them again. They presumably are still in master, as I can see them online on GitHub, but when I ran the command "git checkout master", many directories and files have disappeared. I really have no clue why this has happened. How do I fix the problem?

EDIT: Is it possible for changes in other branches to cause problems when I switch back to the master branch? I feel like the master branch should have remained the same as before.

EDIT 2: It looks like the deletions happened when I was working on a feature branch and did "git checkout devel" - I was in a deep subdirectory when I ran this command, and for whatever reason there were a bunch of "D ... file" lines outputted, ending with "Switched to branch 'devel'" In fact, this continues to happen as I switch between branches.

答:
If your current checkout of master appears to be corrupt, you can try to reset it to either HEAD, or a specific commit, using the following:

git reset --hard HEAD

This will do a hard reset to the last known commit, and any working copy changes in your branch (which it does not appear you have) will be lost.

If it still does not fix your issue, you may have to look into doing a new clone into a new directory.


问:
java - All possible combinations of an array into one method
I am looking a way to put the method static void combinationUtil() function into public static void main (String[] args).

I mean to remove the method static void combinationUtil() then the whole class only got one method public static void main (String[] args), or How can I print array data[] in public static void main (String[] args)

```<code>class permutation {

    static void combinationUtil(int arr[], int data[], int start, int end, int index, int r){
    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
}

public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;
    combinationUtil(arr, data, start, end, index, r);
    }
}
</code>```

答:
Like this (just removed the function combinationUtil and put it's content in
main method):</p>

```<code>class permutation {

    public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;

    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
    }
}
</code>```

Body:
I am looking a way to put the method static void combinationUtil() function into public static void main (String[] args).

I mean to remove the method static void combinationUtil() then the whole class only got one method public static void main (String[] args), or How can I print array data[] in public static void main (String[] args)

class permutation {

    static void combinationUtil(int arr[], int data[], int start, int end, int index, int r){
    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
}

public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;
    combinationUtil(arr, data, start, end, index, r);
    }
}

Body:
Like this (just removed the function combinationUtil and put it's content in
main method):

class permutation {

    public static void main (String[] args) {
    int arr[] = {1, 2, 3, 4, 5,6,7};
    int r = 5;
    int n = arr.length;
    int data[]=new int[r];
    int start=0,end=n-1,index=0;

    if (index == r){
        for (int j=0; j<r; j++){
            System.out.print(data[j]+" ");
        }
        System.out.println("");
        return;
    }

    for (int i=start; i<=end && end-i+1 >= r-index; i++){
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
    }
}


问:
Get Current Activity in Espresso android
In case of a test that crosses multiple activities, is there a way to get current activity?

getActivtiy() method just gives one activity that was used to start the test.

I tried something like below,

```<code>public Activity getCurrentActivity() {
    Activity activity = null;
    ActivityManager am = (ActivityManager) this.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    try {
        Class<?> myClass = taskInfo.get(0).topActivity.getClass();
        activity = (Activity) myClass.newInstance();
    }
    catch (Exception e) {

    }
    return activity;
}
</code>```

but I get null object.

答:
The accepted answer may not work in many espresso tests. The following works with espresso version 2.2.2 and Android compile/target SDK 27 running on API 25 devices:</p>

```<code>@Nullable
private Activity getActivity() {
    Activity currentActivity = null;

    Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED);
    if (resumedActivities.iterator().hasNext()){
        currentActivity = (Activity) resumedActivities.iterator().next();
    }
    return currentActivity;
}
</code>```

Body:
In case of a test that crosses multiple activities, is there a way to get current activity?

getActivtiy() method just gives one activity that was used to start the test.

I tried something like below,

public Activity getCurrentActivity() {
    Activity activity = null;
    ActivityManager am = (ActivityManager) this.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    try {
        Class<?> myClass = taskInfo.get(0).topActivity.getClass();
        activity = (Activity) myClass.newInstance();
    }
    catch (Exception e) {

    }
    return activity;
}

but I get null object.

Body:
The accepted answer may not work in many espresso tests. The following works with espresso version 2.2.2 and Android compile/target SDK 27 running on API 25 devices:

@Nullable
private Activity getActivity() {
    Activity currentActivity = null;

    Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED);
    if (resumedActivities.iterator().hasNext()){
        currentActivity = (Activity) resumedActivities.iterator().next();
    }
    return currentActivity;
}


问:
React Native Debug Menu does not open - Android CMD + M
React native debug menu does not work in Android.

Command 'RR' does work.
CMD + M does not work.

It was working previously. Keyboard input is enabled in AVD Manager.

答:
There is an obscure setting only available after opening the emulator.

Toggle Send keyboard shortcuts to: Emulator Controls (default)

I have no idea why this was so hard to find. Hopefully you reap the benefits of my stress and heartache.

I wish you the best Christmas in 2017 and that 2018 is great for you.


问:
How do I set the minimum size of a JFrame and get it to adjust for frame thickness?
I am building a program and working on it on multiple operating systems. Windows 10 and Windows 7. When I set the minimum size correctly for one either Windows 10 or Windows 7 it works for that OS but messes up the other OS. Is there a way to get the setMinimumSize to adjust for border thickness? Or is there a way to get the thickness of the border on that OS? Or is there a way to get set the minimum size of the JFrame to the size it is when it opens? Any help is appreciated. Thanks.</p>

答:
I just ran into a problem like this on macOS using Java 8. I wanted the user to be able to resize the window but obey the minimum size computed by the layout manager. Unfortunately, the AWT code that controls the window size only looks at the minimum size if it has been explicitly set.

Here is the solution I came up with. I override the doLayout() method on the frame:

```<code>@Override
public void doLayout()
{
    super.doLayout();

    LayoutManager m = getLayout();
    if (m != null) {
        Dimension d = m.minimumLayoutSize(this);
        setMinimumSize(d);
    }
}
</code>```

Now, every time the layout is recomputed, the new minimum size is cached as an explicitly set value, so that AWT will pay attention to it.

Body:
I just ran into a problem like this on macOS using Java 8. I wanted the user to be able to resize the window but obey the minimum size computed by the layout manager. Unfortunately, the AWT code that controls the window size only looks at the minimum size if it has been explicitly set.

Here is the solution I came up with. I override the doLayout() method on the frame:

@Override
public void doLayout()
{
    super.doLayout();

    LayoutManager m = getLayout();
    if (m != null) {
        Dimension d = m.minimumLayoutSize(this);
        setMinimumSize(d);
    }
}

Now, every time the layout is recomputed, the new minimum size is cached as an explicitly set value, so that AWT will pay attention to it.


问:
Make floating child visible outside an overflow:hidden parent
In CSS the overflow:hidden is set on parent containers in order to allow it to expand with the height of their floating children.

But it also has another interesting feature when combined with margin: auto...

If PREVIOUS sibling is a floating element, it will actually appear juxtapose to it. That is if the sibling is float:left then the container with float:none overflow:hidden will appear to the right of the sibling, no newline - just as if it was floating in the normal flow. If the previous sibling is float:right then the container will appear to the left of the sibling. Resizing this container will accurately show it centered inbetween the floating elements. Say if you have two previous siblings, one float:left the other float:right, the container will appear centered inbetween the two.

So here's the problem...

How do I maintain that type of layout WITHOUT masking children?

Googling all over the web gives me ways on how to clear:both and expand a container... but I can't find any alternative solution to maintaining the left/right previous-child centering. If you make the container overflow:visible then the container suddenly ignores the layout flow of the floating elements and appears layered ontop of the floating element.

So question:

I have to have the container overflow:hidden to preserve layout...

how can I make it so the children aren't masked? I need to have the child absolutely positioned relative to the parent outside the container.

OR

How do I overflow:visible so I can absolutely position a child relative to the parent outside the container... YET preserve the sibling float-like-layout-flow?

答:
This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed.   This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

```<code><div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>
</code>```

Body:
This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed.   This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>


问:
Sharepoint 2013 Workflow Split String
I am trying to create an email that contains a list of requested items all on their own line. The problems is in that each of these items are stored in a separate list and are outputted as a single line of text and in share point 2013 there appears to be no split function. Does any one know of an easy way to go through a string (each item will be separated by a #) and output each one on it's own line. This only needs to happen inside the email and does not need to be saved elsewhere (although this could be a solution). Please see screenshots below for more details. The only solutions I could find online look like they either only work in SP2011 or require parsing through via iterators.

-----Here is what the current email looks like-----:

-----Here is the template I am using-----:

-----And here is what it looks like when creating a new request-----:

Again the goal is to simply put each requested item into its own line. The items that are available for request are saved in a separate workflow.

Any help is greatly appreciated and if you require any additional info please let me know.

答:
Have you ever tried to set the 'Return field as' of requested items field to Lookup Values in your email workflow. I succeed in having the lookup values without a #.
Lookup Values</p>

Title: Sharepoint 2013 Workflow Split String


问:
Coldfusion Websocket Channel Listeners
I'm playing around with the Coldfusion Websockets and have been trying to follow this tutorial.  However, I can't seem to get the channel listener part working for: "HelloWorld – Version 2: Using a channel listener".

I have the code in the application correct, but I think it can't find the cfclistener.

```<code>this.wschannels = [ {name="world", cfclistener="myChannelListener" }];
</code>```

I have the cfc made with the beforePublish to append the time but it's not working.
I'm using CFWheels and just put the channel listener cfc in the controllers folder. I tried the above code with different variations such as:

controllers/myChannelListener

/controllers/myChannelListener

controllers.myChannelListener

.controllers.myChannelListener

.. even trying the path from the C drive:

C:/Projects/myproject/controllers/myChannelListener

but they all do not work. I'm pretty sure it's a path problem. Does anyone know how to specify the cfclistener path?

答:
Although I'm not using CFWHEELS, I had issues as well getting the second example to work as well. The last two changes I made before it worked:

Opened CF administrator. services > web sockets
(checked "Enable WebSocket Service", checked "use built in websocket server")

Restarted CF using cfstart.bat (located in CF_install_directory/cfusion/bin)

At the very least I can confirm that the example provided in the article works with some fiddling.

Title: Coldfusion Websocket Channel Listeners

Body:
I'm playing around with the Coldfusion Websockets and have been trying to follow this tutorial.  However, I can't seem to get the channel listener part working for: "HelloWorld – Version 2: Using a channel listener".

I have the code in the application correct, but I think it can't find the cfclistener.

this.wschannels = [ {name="world", cfclistener="myChannelListener" }];

I have the cfc made with the beforePublish to append the time but it's not working.
I'm using CFWheels and just put the channel listener cfc in the controllers folder. I tried the above code with different variations such as:

controllers/myChannelListener

/controllers/myChannelListener

controllers.myChannelListener

.controllers.myChannelListener

.. even trying the path from the C drive:

C:/Projects/myproject/controllers/myChannelListener

but they all do not work. I'm pretty sure it's a path problem. Does anyone know how to specify the cfclistener path?