问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
The short answer would be "because that's the way those operators are defined in the specification".

From section 8.19 of the ECMA C# spec:

Lifted forms of the == and !=
  operators consider two null values
  equal, and a null value unequal to a
  non-null value. Lifted forms of the
  <, >, <=, and >= operators
  return false if one or both operands
  are null.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?


来源: stackexchange

问:
Use custom intent action to launch activity only in specific application context
I need to specify my login activity with intent filter:

```<code>    <activity
        android:name=".view.LoginActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="com.example.sdk.LOGIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</code>```

The reason why I want to do it that way is that I am developing an SDK that I want to use in few projects and this is the best way I could figure out of how to notify the SDK which is the login activity, while it is defined only in the app module.

After I do such declaration I start the login activity like so (both in library and app):

```<code>    Intent intent = new Intent();
    intent.setAction("com.example.sdk.LOGIN");
    context.startActivity(intent);
</code>```

There is the possibility that two or more applications relying on the same SDK will be installed simultaneously on the same device. If I get it correctly, in such case in each of these applications the Activity start will launch a random login activity (with the possibility of the call in application A launching the login of application B).

Am I correct in my understanding of how custom intent filters work?

Is there a way to tell the call in application A to use only intent filter declarations in application A

Suggestions of alternative approaches to reusing the login-related logic, not relying on intent filters are also welcome.

答:
I figured out a way to achieve what I wanted.

Basically I do not hard code the package in my library, rather I start the login activity from the library using:

```<code>private static final String INTENT_ACTION_PATTERN = "%s.LOGIN";
public void startLoginActivity() {
    Intent intent = new Intent();
    String intentAction = String.format(INTENT_ACTION_PATTERN, mContext.getPackageName());
    intent.setAction(intentAction);
    mContext.startActivity(intent);
}
</code>```

And I will just use a convention that I will always define the custom intent filter to match the package of my application:

```<code><activity
    android:name=".view.LoginActivity"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="com.example.myapp.LOGIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to specify my login activity with intent filter:

    <activity
        android:name=".view.LoginActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="com.example.sdk.LOGIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

The reason why I want to do it that way is that I am developing an SDK that I want to use in few projects and this is the best way I could figure out of how to notify the SDK which is the login activity, while it is defined only in the app module.

After I do such declaration I start the login activity like so (both in library and app):

    Intent intent = new Intent();
    intent.setAction("com.example.sdk.LOGIN");
    context.startActivity(intent);

There is the possibility that two or more applications relying on the same SDK will be installed simultaneously on the same device. If I get it correctly, in such case in each of these applications the Activity start will launch a random login activity (with the possibility of the call in application A launching the login of application B).

Am I correct in my understanding of how custom intent filters work?

Is there a way to tell the call in application A to use only intent filter declarations in application A

Suggestions of alternative approaches to reusing the login-related logic, not relying on intent filters are also welcome.

Body:
I figured out a way to achieve what I wanted.

Basically I do not hard code the package in my library, rather I start the login activity from the library using:

private static final String INTENT_ACTION_PATTERN = "%s.LOGIN";
public void startLoginActivity() {
    Intent intent = new Intent();
    String intentAction = String.format(INTENT_ACTION_PATTERN, mContext.getPackageName());
    intent.setAction(intentAction);
    mContext.startActivity(intent);
}

And I will just use a convention that I will always define the custom intent filter to match the package of my application:

<activity
    android:name=".view.LoginActivity"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="com.example.myapp.LOGIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>


问:
linux kernel output in a file
I am using a program by using the linux kernel (in this case a predictor for protein localization). The output/results are printed in the linux kernel, one after each other. However, if I want to copy it to a simple textfile, the "length" of the kernel is not long enough for all the results.

instead of using smaller seperate files, I would like to print the output of the kernel to a file. I tried to google this, but it doesn't really help me futher.
1. dmesg seems to be for system-output stuff?
2. the /var/log/syslog.txt doesn't show the stuff I need, but other technical kernel stuff.
3. i saw something with printf(), but didn't quite understand the mechanics and if it was useable for my problem.

could someone explain how to do this or where to look for the right info?

答: I think i found out how to do it, by using > fileToBeNamed.txt at the end of the command, Sorry :( </p>

Title: linux kernel output in a file


问:
Can't Remotely Debug Tomcat Running on CentOS Virtual Machine from Eclipse on Host Windows 7

Setup

VMWare Virtual Machine

CentOS 5.5 64-bit

OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)

Tomcat 6.0

Host Machine

Windows 7 64-bit

Oracle/Sun JDK 1.6 64-bit

Eclipse Helios for Java EE developers

Problem

My eclipse Remote Java Application has following connection properties:

```<code>Host: 192.168.94.133
Port: 8000
</code>```

When I run the above configuration, I get:

```<code>Failed to connect to remote VM. Connection refused.
Connection refused: connect
</code>```

Nothing new comes out of tomcat's log.

But when I telnet from the windows box:

```<code>bash-3.2$ telnet 192.168.94.133 8000
Trying 192.168.94.133...
Connected to 192.168.94.133.
Escape character is '^]'.
Connection closed by foreign host.
</code>```

Every time I try the above telnet, tomcat spits this out in the log:

```<code>Debugger failed to attach: timeout during handshake
</code>```

Because of the telnet behavior, I think the issue is in Eclipse... I'd appreciate any help.

Thanks,

-Dave

答:
Settings required in Tomcat 1)Create setenv.sh file under */tomcat/bin/. The location will be same as the catalina.sh file

2)Place the below content inside it. export CATALINA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

Now start the Tomcat server. Once it is started please proceed with the below steps.

Settings required in Eclipse

3)In Eclipse go to Windows-->Preference--> General-->Network Connection --> Active Provider should be Direct. After changing to direct restart the eclipse.

4)In eclipse right click on project and debug as ->debug configuration ->Remote java application ->Create new configuration. Fill the below fields Name: as your wish Project:Select the project which you need to debug. ConnectionType: Standard socket attach Host: Localhost Port: 8000(It should be same as mentioned in point 2) Then click debug.

The debug will start at port 8000. Now you can verify by keeping breakpoints.

ContentLicense: CC BY-SA 2.5

Body:
Setup

VMWare Virtual Machine

CentOS 5.5 64-bit

OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)

Tomcat 6.0

Host Machine

Windows 7 64-bit

Oracle/Sun JDK 1.6 64-bit

Eclipse Helios for Java EE developers

Problem

My eclipse Remote Java Application has following connection properties:

Host: 192.168.94.133
Port: 8000

When I run the above configuration, I get:

Failed to connect to remote VM. Connection refused.
Connection refused: connect

Nothing new comes out of tomcat's log.

But when I telnet from the windows box:

bash-3.2$ telnet 192.168.94.133 8000
Trying 192.168.94.133...
Connected to 192.168.94.133.
Escape character is '^]'.
Connection closed by foreign host.

Every time I try the above telnet, tomcat spits this out in the log:

Debugger failed to attach: timeout during handshake

Because of the telnet behavior, I think the issue is in Eclipse... I'd appreciate any help.

Thanks,

-Dave


问:
Invalid Data Type error while casting PL/SQL Array to Table
I have a PL/SQL stored proc which needs to return a RefCursor type object as output parameter.

```<code>PROCEDURE usp_appnt_stts_driver_wraper2
( in_req_src_system_id   IN NUMBER,
  in_req_user_info       IN VARCHAR2,
  out_response_rec1      OUT SYS_REFCURSOR)
</code>```

At the end of the SP, I am able to return Hard Coded values to my front end by using a Select Statement.

```<code>OPEN out_response_rec1 FOR
SELECT 'data1', 'data2', 'data3', 'data 4' FROM DUAL;
</code>```

This works fine. But I need to send the data which I am getting from an Array.

The Array is populated like this,

```<code>FOR g_index IN g_slsnetoutbndarr.FIRST..g_slsnetoutbndarr.LAST

LOOP

  out_response_rec.EXTEND;
  IF g_SlsnetOutbndArr(g_index).Rectypdesc IS NOT NULL THEN
    out_response_rec(g_index).Rectypdesc   := g_SlsnetOutbndArr(g_index).Rectypdesc ;
    out_response_rec(g_index).Recdetltcode := g_SlsnetOutbndArr(g_index).Recdetltcode;
    out_response_rec(g_index).RecDetlDesc  := g_SlsnetOutbndArr(g_index).RecDetlDesc ;
  END IF;

 END LOOP;
</code>```

So at the end of this code, the Array Object out_response_rec has all the values I need.

But How do I transfer these values in the RefCursor output parameter?

Update 1

I have tried to create a new data type in the Package specification.

```<code>TYPE  SlsnetOutbndRec IS RECORD(
Rectypdesc    VARCHAR2(30),
Recdetltcode  NUMBER,
RecDetlDesc  VARCHAR2(130));

TYPE SlsnetOutbndTabArr IS TABLE OF SlsnetOutbndRec;
</code>```

Finally I have tried to Cast the Array to table in my SP as

```<code>OPEN out_response_rec_result FOR
SELECT * FROM TABLE (Cast(out_response_rec AS SlsnetOutbndTabArr));
</code>```

But this is throwing an Invalid Data Type error. The SP does not recognize the new data types I created.

答:
So at the end of this code, the Array Object out_response_rec has all
  the values I need.

But How do I transfer these values in the RefCursor output parameter?

As I could understand, you wanted to use a SYS_REFCUSOR to get the output of a Query plus the values that are in collection which is being populated by another Procedure.  I have come up with a solution for your requirement see below inline explaination:

```<code>--Create a Object in Place of Record since we cannot use a PLSQL scope compnenet in SQL scope in Oracle 11g and below
CREATE OR REPLACE TYPE SlsnetOutbndRec IS OBJECT
   (
      Rectypdesc     VARCHAR2 (30),
      Recdetltcode   NUMBER,
      RecDetlDesc    VARCHAR2 (130)
   );

--Create a table type of the Object
CREATE OR REPLACE  TYPE SlsnetOutbndTabArr IS TABLE OF SlsnetOutbndRec;
/

--Procedure
CREATE OR REPLACE PROCEDURE combined_rslt (var OUT SYS_REFCURSOR)
AS
   v_var   SlsnetOutbndTabArr := SlsnetOutbndTabArr ();

   l_var   SlsnetOutbndTabArr := SlsnetOutbndTabArr ();
BEGIN
   --Populating the collection
   v_var.EXTEND;
   v_var (1) := SlsnetOutbndRec ('ABC', 1, 'A');

   OPEN VAR FOR
      SELECT 'CDE', 2, 'B' FROM DUAL
      UNION ALL -- Combining the result of collection with the result of query
      SELECT *
        FROM TABLE (v_var) t;
EXCEPTION
   WHEN OTHERS
   THEN
      DBMS_OUTPUT.put_line (SQLERRM);
END;
</code>```

Execution :

```<code>DECLARE
   x   SYS_REFCURSOR;
   a   VARCHAR2 (30);
   b   NUMBER;
   c   VARCHAR2 (130);
BEGIN
   combined_rslt (var => x);

   LOOP
      FETCH x INTO a, b, c;

      EXIT WHEN x%NOTFOUND;
      DBMS_OUTPUT.put_line (a || ' ' || b || '  ' || c);
   END LOOP;
END;
</code>```

Results:

```<code>SQL> /
CDE 2  B
ABC 1  A

PL/SQL procedure successfully completed.
</code>```

Body:
I have a PL/SQL stored proc which needs to return a RefCursor type object as output parameter.

PROCEDURE usp_appnt_stts_driver_wraper2
( in_req_src_system_id   IN NUMBER,
  in_req_user_info       IN VARCHAR2,
  out_response_rec1      OUT SYS_REFCURSOR)

At the end of the SP, I am able to return Hard Coded values to my front end by using a Select Statement.

OPEN out_response_rec1 FOR
SELECT 'data1', 'data2', 'data3', 'data 4' FROM DUAL;

This works fine. But I need to send the data which I am getting from an Array.

The Array is populated like this,

FOR g_index IN g_slsnetoutbndarr.FIRST..g_slsnetoutbndarr.LAST

LOOP

  out_response_rec.EXTEND;
  IF g_SlsnetOutbndArr(g_index).Rectypdesc IS NOT NULL THEN
    out_response_rec(g_index).Rectypdesc   := g_SlsnetOutbndArr(g_index).Rectypdesc ;
    out_response_rec(g_index).Recdetltcode := g_SlsnetOutbndArr(g_index).Recdetltcode;
    out_response_rec(g_index).RecDetlDesc  := g_SlsnetOutbndArr(g_index).RecDetlDesc ;
  END IF;

 END LOOP;

So at the end of this code, the Array Object out_response_rec has all the values I need.

But How do I transfer these values in the RefCursor output parameter?

Update 1

I have tried to create a new data type in the Package specification.

TYPE  SlsnetOutbndRec IS RECORD(
Rectypdesc    VARCHAR2(30),
Recdetltcode  NUMBER,
RecDetlDesc  VARCHAR2(130));

TYPE SlsnetOutbndTabArr IS TABLE OF SlsnetOutbndRec;

Finally I have tried to Cast the Array to table in my SP as

OPEN out_response_rec_result FOR
SELECT * FROM TABLE (Cast(out_response_rec AS SlsnetOutbndTabArr));

But this is throwing an Invalid Data Type error. The SP does not recognize the new data types I created.

Body:
So at the end of this code, the Array Object out_response_rec has all
  the values I need.

But How do I transfer these values in the RefCursor output parameter?

As I could understand, you wanted to use a SYS_REFCUSOR to get the output of a Query plus the values that are in collection which is being populated by another Procedure.  I have come up with a solution for your requirement see below inline explaination:

--Create a Object in Place of Record since we cannot use a PLSQL scope compnenet in SQL scope in Oracle 11g and below
CREATE OR REPLACE TYPE SlsnetOutbndRec IS OBJECT
   (
      Rectypdesc     VARCHAR2 (30),
      Recdetltcode   NUMBER,
      RecDetlDesc    VARCHAR2 (130)
   );

--Create a table type of the Object
CREATE OR REPLACE  TYPE SlsnetOutbndTabArr IS TABLE OF SlsnetOutbndRec;
/

--Procedure
CREATE OR REPLACE PROCEDURE combined_rslt (var OUT SYS_REFCURSOR)
AS
   v_var   SlsnetOutbndTabArr := SlsnetOutbndTabArr ();

   l_var   SlsnetOutbndTabArr := SlsnetOutbndTabArr ();
BEGIN
   --Populating the collection
   v_var.EXTEND;
   v_var (1) := SlsnetOutbndRec ('ABC', 1, 'A');

   OPEN VAR FOR
      SELECT 'CDE', 2, 'B' FROM DUAL
      UNION ALL -- Combining the result of collection with the result of query
      SELECT *
        FROM TABLE (v_var) t;
EXCEPTION
   WHEN OTHERS
   THEN
      DBMS_OUTPUT.put_line (SQLERRM);
END;

Execution :

DECLARE
   x   SYS_REFCURSOR;
   a   VARCHAR2 (30);
   b   NUMBER;
   c   VARCHAR2 (130);
BEGIN
   combined_rslt (var => x);

   LOOP
      FETCH x INTO a, b, c;

      EXIT WHEN x%NOTFOUND;
      DBMS_OUTPUT.put_line (a || ' ' || b || '  ' || c);
   END LOOP;
END;

Results:

SQL> /
CDE 2  B
ABC 1  A

PL/SQL procedure successfully completed.


问:
How to use Rcpp in Code::Blocks IDE
I am trying to use Rcpp package in Code::Blocks IDE but when I try to compile a script with #include<Rcpp.h> I get an error saying that the file or repository does not exists.

I have the library Rcpp installed, so in RStudio I can run .cpp files.

The thing is I want to use Rcpp classes in a c++ script in Code::Blocks IDE.

How can I do this?

答:
You need to configure the build of your IDE so that you can:

access headers from R and Rcpp

link against librairies from R and Rcpp

You may use sourceCpp( , verbose = TRUE) to have some examples:

For example, when sourceCpp this file:

```<code>#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int zero(){
  return 0 ;
}
</code>```

on my machine, I get this:

```<code>// ... lots of stuff irrelevant here ...
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/3.4/Resources/library/Rcpp/include" -I"/Users/romain/Desktop" -I/usr/local/include   -fPIC  -O3 -c test.cpp -o test.o
clang++ -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/usr/local/lib -o sourceCpp_28.so test.o -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
</code>```

You can get some of these from R CMD config i.e.

```<code>$ R CMD config DYLIB_LDFLAGS
-dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -fopenmp
</code>```

Title: How to use Rcpp in Code::Blocks IDE

Body:
You need to configure the build of your IDE so that you can:

access headers from R and Rcpp

link against librairies from R and Rcpp

You may use sourceCpp( , verbose = TRUE) to have some examples:

For example, when sourceCpp this file:

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int zero(){
  return 0 ;
}

on my machine, I get this:

// ... lots of stuff irrelevant here ...
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/3.4/Resources/library/Rcpp/include" -I"/Users/romain/Desktop" -I/usr/local/include   -fPIC  -O3 -c test.cpp -o test.o
clang++ -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/usr/local/lib -o sourceCpp_28.so test.o -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation

You can get some of these from R CMD config i.e.

$ R CMD config DYLIB_LDFLAGS
-dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -fopenmp


问:
How do I access information about a cascading dynamic prompt via Crystal Report API?
I am using the CR 2008 RAS API (but could also use an older API if needed). Any idea how to access information about the settings for dynamic prompts in a report?

I can access the PromptField objects with

```<code>dataDefController.ParameterFieldController.
    GetPromptParameterFields(new PropertyBagClass());
</code>```

but can't seem to find any options for its dynamic prompt settings (such as fields used to fill the default values, cascading prompt settings, etc.).

答:
Here are two links that are helpful for the RAS API.

API reference:
http://help.sap.com/businessobject/product_guides/boexir31/en/rassdk_net_apiRef_12_en.chm

Dev Guide:
http://help.sap.com/businessobject/product_guides/boexir31/en/rassdk_net_dg_12_en.chm

Unfortunately they don't seem to completely answer your question, but maybe they'll help.

OwnerDisplayName: CrystalReportsGuy

Body:
I am using the CR 2008 RAS API (but could also use an older API if needed). Any idea how to access information about the settings for dynamic prompts in a report?

I can access the PromptField objects with

dataDefController.ParameterFieldController.
    GetPromptParameterFields(new PropertyBagClass());

but can't seem to find any options for its dynamic prompt settings (such as fields used to fill the default values, cascading prompt settings, etc.).

OwnerDisplayName: Epaga


问:
Using Executer service in multithreaded program
I am using executer service for using multithreading. I have a large number of tasks. When I am submitting those tasks one by one using executer.submit() the heap space increasing and slowly slowly the java process becomes slow. How should I approach this problem?

For example: After getting all the data

```<code>while(resultset.hasnext())
{
I am thread objects here //
RunnableObject o = new RunnableObject(data);
executer.submit(o);
}
</code>```

答:
As per your code, I understood that, you are retrieving results from database and assigning each recode to a thread, right ?

In this scenario, if you get 10 records, you will create 10 thread, but in the long run, if you get 1000 records, you can create 1000 threads right. this will make your application slower.

My solution is go for thread pools like this.

Body:
I am using executer service for using multithreading. I have a large number of tasks. When I am submitting those tasks one by one using executer.submit() the heap space increasing and slowly slowly the java process becomes slow. How should I approach this problem?

For example: After getting all the data

while(resultset.hasnext())
{
I am thread objects here //
RunnableObject o = new RunnableObject(data);
executer.submit(o);
}


问:
SQL multiple group by, aggregate by first group
I Currently have written an sql query like this:

```<code>SELECT   a, b, count(id) / ????
FROM     X
group by a, b
</code>```

Please pay attention to the ????? in the code above.
There are two groups in group by. Namely by columns a and b.

What I intend to do is to divide the (1) count of items in the second group (b) to the (2) count of items in the first group (a).

count(id) accomplishes (1). But I don't know what to write for (2).

P.S.: However I know It is possible to replace "????" with another complex select query, but I want to learn if there is a simpler way to aggregate items of first Group by.

Update:
Sample data:

```<code>id       a           b
______________________
1       'A'         'G'
2       'A'         'H'
3       'A'         'H'
4       'B'         'G'
5       'B'         'G'
6       'B'         'K'
7       'B'         'K'
</code>```

results:

```<code>a           b          [unnamed]
________________________________
'A'         'G'        0.33333
'A'         'H'        0.66667
'B'         'G'        0.5
'B'         'K'        0.5
</code>```

The third column is the percentage of columns with values as in column b relative to values in column a.

Thank you.

答:
Maybe this works if you are using SQL Server</p>

```<code>SELECT  DISTINCT  a, b, (COUNT(*)OVER(PARTITION BY a, b)* 1.0/COUNT(*)OVER(PARTITION BY a)) as unnamed
FROM Sample
</code>```

Body:
I Currently have written an sql query like this:

SELECT   a, b, count(id) / ????
FROM     X
group by a, b

Please pay attention to the ????? in the code above.
There are two groups in group by. Namely by columns a and b.

What I intend to do is to divide the (1) count of items in the second group (b) to the (2) count of items in the first group (a).

count(id) accomplishes (1). But I don't know what to write for (2).

P.S.: However I know It is possible to replace "????" with another complex select query, but I want to learn if there is a simpler way to aggregate items of first Group by.

Update:
Sample data:

id       a           b
______________________
1       'A'         'G'
2       'A'         'H'
3       'A'         'H'
4       'B'         'G'
5       'B'         'G'
6       'B'         'K'
7       'B'         'K'

results:

a           b          [unnamed]
________________________________
'A'         'G'        0.33333
'A'         'H'        0.66667
'B'         'G'        0.5
'B'         'K'        0.5

The third column is the percentage of columns with values as in column b relative to values in column a.

Thank you.

Body:
Maybe this works if you are using SQL Server

SELECT  DISTINCT  a, b, (COUNT(*)OVER(PARTITION BY a, b)* 1.0/COUNT(*)OVER(PARTITION BY a)) as unnamed
FROM Sample


问:
extracting right hand side vector from JuMP model
Is there a way to extract the right hand side vector from a JuMP model similar to the one used to extract the coefficients matrix (getconstrmatrix())? if there is no way to do so, how could i extract said information? </p>

答:
getconstrLB() and getconstrUB() return the upper and lower bounds on the constraints, with equal values when the constraints are equalities. They take the same argument as getconstmatrix().

The documentation Google found is here


问:
Django OAuthToolkit Scopes per specific method
I'm using Django Rest Framework and OAuthTookit.

I want that the scope provided by the token should be HTTP Method specific. For eg:- GET, PUT, DELETE of the same APIView should have different scopes.

Following are my APIs.

```<code>class MyView(RetrieveUpdateDestroyAPIView):
    permission_classes = [TokenHasScope]
    required_scopes = ['scope1']
    serializer_class = ModelSerializer
    queryset = Model.objects.all()
</code>```

Currently, the scope is set at the class level, which means to access all the GET, PUT & DELETE method, the token should have scope1.

I want that there should be different scope for different HTTP methods. How can I set different scope for different methods?

答:
To handle this case, I think you need to implement a new permission class, something like this:

```<code>class TokenHasScopeForMethod(TokenHasScope):

     def has_permission(self, request, view):
         token = request.auth

         if not token:
             return False

         if hasattr(token, "scope"):
             # Get the scopes required for the current method from the view
             required_scopes = view.required_scopes_per_method[request.method]

             return token.is_valid(required_scopes)
</code>```

And use it in your view like this:

```<code>class MyView(RetrieveUpdateDestroyAPIView):
     permission_classes = [TokenHasScopeForMethod]
     required_scopes_per_method = {'POST': ['post_scope'], 'GET': ['get_scope']}
     serializer_class = ModelSerializer
     queryset = Model.objects.all()
</code>```

Body:
I'm using Django Rest Framework and OAuthTookit.

I want that the scope provided by the token should be HTTP Method specific. For eg:- GET, PUT, DELETE of the same APIView should have different scopes.

Following are my APIs.

class MyView(RetrieveUpdateDestroyAPIView):
    permission_classes = [TokenHasScope]
    required_scopes = ['scope1']
    serializer_class = ModelSerializer
    queryset = Model.objects.all()

Currently, the scope is set at the class level, which means to access all the GET, PUT & DELETE method, the token should have scope1.

I want that there should be different scope for different HTTP methods. How can I set different scope for different methods?

Body:
To handle this case, I think you need to implement a new permission class, something like this:

class TokenHasScopeForMethod(TokenHasScope):

     def has_permission(self, request, view):
         token = request.auth

         if not token:
             return False

         if hasattr(token, "scope"):
             # Get the scopes required for the current method from the view
             required_scopes = view.required_scopes_per_method[request.method]

             return token.is_valid(required_scopes)

And use it in your view like this:

class MyView(RetrieveUpdateDestroyAPIView):
     permission_classes = [TokenHasScopeForMethod]
     required_scopes_per_method = {'POST': ['post_scope'], 'GET': ['get_scope']}
     serializer_class = ModelSerializer
     queryset = Model.objects.all()


问:
SetId() and then findviewById in java programmatically issue
Hi i am trying to setId programmatically, but the issue is how to find that id after setting it in java. i am working in fragments (Viewpager)and here is my code below.

```<code>property=new SearchableSpinner(getActivity());
city.setId(R.id.citybuy);
town.setId(R.id.townbuy);
property.setId(R.id.propertybuy);

 city = (SearchableSpinner) this.view.findViewById(R.id.citybuy);
  town = (SearchableSpinner) this.view.findViewById(R.id.townbuy);
 property = (SearchableSpinner) this.view.findViewById(R.id.propertybuy);
</code>```

and it didn't find id and shows NullPointerException
and if i set id through XML then it shows this error:

java.lang.IllegalArgumentException: Wrong state class, expecting View
  State but received class
  gr.escsoft.michaelprimez.searchablespinner.SearchableSpinner$SavedState
  instead. This usually happens when two views of different type have
  the same id in the same hierarchy..This view's id is id/city_wanted.
  Make sure other views do not use the same id

Though id's are different in all fragments XML

答: what I believe you are setting id to the view in xml and also now you are setting the same id again to the same view. </p>

Body:
Hi i am trying to setId programmatically, but the issue is how to find that id after setting it in java. i am working in fragments (Viewpager)and here is my code below.

property=new SearchableSpinner(getActivity());
city.setId(R.id.citybuy);
town.setId(R.id.townbuy);
property.setId(R.id.propertybuy);

 city = (SearchableSpinner) this.view.findViewById(R.id.citybuy);
  town = (SearchableSpinner) this.view.findViewById(R.id.townbuy);
 property = (SearchableSpinner) this.view.findViewById(R.id.propertybuy);

and it didn't find id and shows NullPointerException
and if i set id through XML then it shows this error:

java.lang.IllegalArgumentException: Wrong state class, expecting View
  State but received class
  gr.escsoft.michaelprimez.searchablespinner.SearchableSpinner$SavedState
  instead. This usually happens when two views of different type have
  the same id in the same hierarchy..This view's id is id/city_wanted.
  Make sure other views do not use the same id

Though id's are different in all fragments XML


问:
Drop down button is not responding with selenium in java
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

```<code>driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/
</code>```

答:
To click on Dropdown button and Select the Option with text as Analytics you can use the following code block :

```<code>driver.findElement(By.xpath("//div[@id='homepages']/button/span[@id='homepages_dropdown']")).click();
List<WebElement> allElements = driver.findElements(By.xpath("//div[@id='homepages']/ul/li/a"));
for (WebElement element : allElements)
  if(element.getAttribute("innerHTML").contains("Analytics"))
  {
      element.click();
      break;
  }
System.out.println("Option with text as Analytics is selected");
</code>```

Body:
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/

Body:
To click on Dropdown button and Select the Option with text as Analytics you can use the following code block :

driver.findElement(By.xpath("//div[@id='homepages']/button/span[@id='homepages_dropdown']")).click();
List<WebElement> allElements = driver.findElements(By.xpath("//div[@id='homepages']/ul/li/a"));
for (WebElement element : allElements)
  if(element.getAttribute("innerHTML").contains("Analytics"))
  {
      element.click();
      break;
  }
System.out.println("Option with text as Analytics is selected");


问:
Bootstrap navbar-right not working on fix-top
I want the nav links aligned right of the nav bar. However my nav links are showing up next to the logo on the left. Any ideas?

Here is my code:

```<code><nav class="navbar navbar-expand-md navbar-light fixed-top bg-light white-bg purple-top-strip">
    <div class="container">
      <a class="navbar-brand" href="#"><img src="images/presitskillsbank-logo.png" width="102" height="40" alt=""/></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse navbar-right" id="navbarCollapse">
        <ul class="nav navbar-nav navbar-right">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled" href="#">Disabled</a>
          </li>
        </ul>

      </div>
    </div>
    </nav>
</code>```

答:
Here is the working code for your quick reference.

Updated fiddle: https://jsfiddle.net/DTcHh/39316/

.navbar-toggler {
  float: right;
  margin-top: 10px;;
  position: relative;
  z-index: 3;
}
.navbar-right {
  float: right;
}
.navbar-nav {
  margin-top: 20px;
}
.navbar-nav li {
  width: 100%;
}```

Body:
I want the nav links aligned right of the nav bar. However my nav links are showing up next to the logo on the left. Any ideas?

Here is my code:

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home (current)

            Link

            Disabled


问:
Leading slashes in JSON from Google Finance API call
I've been using the Google Finance API to successfully gather some stock info.  The problem is that after a call to http://www.google.com/finance/info?infotype=infoquoteall&q=[$tickerSymbol], the JSON that Google returns has // added before it and therefore the string cannot be encoded using PHP's json_encode().  The JSONLint JSON Validator confirms that the //s are not valid. The obvious workaround is to strip the slashes from the beginning of the JSON.  None-the-less, I am left wondering why Google is adding slashes to the JSON it is returning.  Is there a purpose behind the extra slashes? Is this a quirk with PHP's json_encode() when other languages would simply ignore the extra characters? Am I doing something incorrectly?

Here is an example of the result of a request for http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL with the leading slashes.

```<code>// [ {
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "340.65"
,"l_cur" : "340.65"
,"ltt":"4:00PM EST"
,"lt" : "Jan 18, 4:00PM EST"
,"c" : "-7.83"
,"cp" : "-2.25"
,"ccol" : "chr"
,"el": "345.20"
,"el_cur": "345.20"
,"elt" : "Jan 18, 5:45PM EST"
,"ec" : "+4.55"
,"ecp" : "1.34"
,"eccol" : "chg"
,"div" : ""
,"yld" : ""
,"eo" : ""
,"delay": ""
,"op" : "327.05"
,"hi" : "344.76"
,"lo" : "326.00"
,"vo" : "66.34M"
,"avvo" : "11.28M"
,"hi52" : "348.48"
,"lo52" : "190.25"
,"mc" : "313.75B"
,"pe" : "22.49"
,"fwpe" : ""
,"beta" : "1.38"
,"eps" : "15.15"
,"name" : "Apple Inc."
,"type" : "Company"
}
]
</code>```

答: I guess it's because google don't want you to work with that JSON, they  recommend to use the Google Data API.</p>

Body:
I've been using the Google Finance API to successfully gather some stock info.  The problem is that after a call to http://www.google.com/finance/info?infotype=infoquoteall&q=[$tickerSymbol], the JSON that Google returns has // added before it and therefore the string cannot be encoded using PHP's json_encode().  The JSONLint JSON Validator confirms that the //s are not valid. The obvious workaround is to strip the slashes from the beginning of the JSON.  None-the-less, I am left wondering why Google is adding slashes to the JSON it is returning.  Is there a purpose behind the extra slashes? Is this a quirk with PHP's json_encode() when other languages would simply ignore the extra characters? Am I doing something incorrectly?

Here is an example of the result of a request for http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL with the leading slashes.

// [ {
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "340.65"
,"l_cur" : "340.65"
,"ltt":"4:00PM EST"
,"lt" : "Jan 18, 4:00PM EST"
,"c" : "-7.83"
,"cp" : "-2.25"
,"ccol" : "chr"
,"el": "345.20"
,"el_cur": "345.20"
,"elt" : "Jan 18, 5:45PM EST"
,"ec" : "+4.55"
,"ecp" : "1.34"
,"eccol" : "chg"
,"div" : ""
,"yld" : ""
,"eo" : ""
,"delay": ""
,"op" : "327.05"
,"hi" : "344.76"
,"lo" : "326.00"
,"vo" : "66.34M"
,"avvo" : "11.28M"
,"hi52" : "348.48"
,"lo52" : "190.25"
,"mc" : "313.75B"
,"pe" : "22.49"
,"fwpe" : ""
,"beta" : "1.38"
,"eps" : "15.15"
,"name" : "Apple Inc."
,"type" : "Company"
}
]


问:
npm script section "clean:dist" vs "clean"
I am trying to figure out the role of "clean:dist" or "clean:js" vs "clean" inside package.json scripts section? I've searched the web and looked at NPM documentation but couldn't find any clue. So can someone please help by explaining the role as well as the use of "clean:dist" or "clean:js" vs "clean"? Thanks</p>

```<code> "scripts": {
    "clean:dist"   : "rimraf dist",
    "clean:js"     : "rimraf public/js/main*.js && rimraf public/js/app.js && rimraf public/js/plugins.js && rimraf public/js/*.map",
    "clean:css"    : "rimraf public/css/main*.css && rimraf public/css/app*.css && rimraf public/css/*.map",
    "clean:fonts"  : "rimraf public/fonts/*",
    "clean:server" : "rimraf server.js && rimraf server.js.map",
    "clean:tmp"    : "rimraf tmp",
    "clean"        : "run-s clean:dist clean:tmp clean:server clean:css clean:js clean:fonts",
    "update:schema": "babel-node tools/update-schema.js",
    "admin-check"  : "cross-env NODE_ENV=development babel-node tools/check-admin-user.js",
    "hot:server"   : "cross-env NODE_ENV=development webpack --colors --display-    "start": "node server.js"
}
</code>```

答:
You can specify any task you want in the package.json file.

Here the clean:dist task calls rimraf which a quick google search got me here (it's a shorthand for rm -rf);

The clean:js task deletes files from the public dir.

The clean task seems to be using this library to run multiple clean tasks at once.

For more information on npm scripts/tasks, just go here

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out the role of "clean:dist" or "clean:js" vs "clean" inside package.json scripts section? I've searched the web and looked at NPM documentation but couldn't find any clue. So can someone please help by explaining the role as well as the use of "clean:dist" or "clean:js" vs "clean"? Thanks

 "scripts": {
    "clean:dist"   : "rimraf dist",
    "clean:js"     : "rimraf public/js/main*.js && rimraf public/js/app.js && rimraf public/js/plugins.js && rimraf public/js/*.map",
    "clean:css"    : "rimraf public/css/main*.css && rimraf public/css/app*.css && rimraf public/css/*.map",
    "clean:fonts"  : "rimraf public/fonts/*",
    "clean:server" : "rimraf server.js && rimraf server.js.map",
    "clean:tmp"    : "rimraf tmp",
    "clean"        : "run-s clean:dist clean:tmp clean:server clean:css clean:js clean:fonts",
    "update:schema": "babel-node tools/update-schema.js",
    "admin-check"  : "cross-env NODE_ENV=development babel-node tools/check-admin-user.js",
    "hot:server"   : "cross-env NODE_ENV=development webpack --colors --display-    "start": "node server.js"
}


问:
Algorithm for finding number of squares in a given circle
Here is my drawing: CLICK

I need to write a program, that will find the number of squares(1x1), that we can draw into a circle of given radius.The squares can only by drawn fully and placed like lego blocks- one on another. In some cases, vertexes of squares can lie on the circle.

Examples: for 1- it makes 0, for 2- it gives four, for 3- 16 squares, for 4-32, for 5-52.

I have written something, but it doesn't work fine for 5+ (I mean- radius bigger than 5). Here it goes: CLICK. In my code- r is radius of the circle, sum is the sum of all squares and height is the height of triangles I try to "draw" into the circle (using Pythagorean theorem).

Now- any help? Is my algorithm even correct? Should I change something?

答:
First off - circle with a radius of 5 fits 60 1x1 squares, not 52. My bet would be someone didn't count the points {[3,4],[3,-4],[4,3],[4,-3],[-4,3],[-4,-3],[-3,4],[-3,-4]} when drawing that on paper and counting by hand, being unsure whether they are right on the circle or just outside of it. They are exactly on the circle.

Second - MBo's answer brought me here - I sometimes search StackOverflow for Gauss Circle Problem to see if someone suggested some new, fun algorithm.

Third - here's the code:

```<code>int     allSquares=0,
        squaredRadius=radius*radius,
        sideOfQuarterOfInscribedSquare=(int)(long)(radius/sqrt(2));
for(int x=sideOfQuarterOfInscribedSquare+1;
        x<radius;
        x++){
    allSquares+=(long)sqrt(squaredRadius-x*x);
}
allSquares= allSquares*8+4*sideOfQuarterOfInscribedSquare*sideOfQuarterOfInscribedSquare;
return allSquares;
</code>```

What it does is just count the squares inside one-eighth of the circle, outside an inscribed square. Sorry for my hipster formatting and overly verbose variable names.

Body:
First off - circle with a radius of 5 fits 60 1x1 squares, not 52. My bet would be someone didn't count the points {[3,4],[3,-4],[4,3],[4,-3],[-4,3],[-4,-3],[-3,4],[-3,-4]} when drawing that on paper and counting by hand, being unsure whether they are right on the circle or just outside of it. They are exactly on the circle.

Second - MBo's answer brought me here - I sometimes search StackOverflow for Gauss Circle Problem to see if someone suggested some new, fun algorithm.

Third - here's the code:

int     allSquares=0,
        squaredRadius=radius*radius,
        sideOfQuarterOfInscribedSquare=(int)(long)(radius/sqrt(2));
for(int x=sideOfQuarterOfInscribedSquare+1;
        x<radius;
        x++){
    allSquares+=(long)sqrt(squaredRadius-x*x);
}
allSquares= allSquares*8+4*sideOfQuarterOfInscribedSquare*sideOfQuarterOfInscribedSquare;
return allSquares;

What it does is just count the squares inside one-eighth of the circle, outside an inscribed square. Sorry for my hipster formatting and overly verbose variable names.


问:
Shading a region under a PDF
I've used the following to plot a Weibull distribution W(2,3):

```<code>Weibull=function(x){
(2*x/9)*exp(-(x^2)/9)
}
xx=seq(from=0,to=10,length.out=1000)
xx1=Weibull(xx)
plot(xx,xx1,type="l")
polygon(xx, xx1, col = "red", border = NA)
</code>```

PDF plot

I want to shade the region between (4,10) only. How would I go about doing this?

答:
```<code>xx2=seq(from=4,to=10,length.out=1000)
yy2=c(Weibull(xx2),0)
xx2=c(xx2,4)
plot(xx,xx1,type="l")
polygon(xx2, yy2, col = "red", border = NA)
</code>```

Title: Shading a region under a PDF

Body:
I've used the following to plot a Weibull distribution W(2,3):

Weibull=function(x){
(2*x/9)*exp(-(x^2)/9)
}
xx=seq(from=0,to=10,length.out=1000)
xx1=Weibull(xx)
plot(xx,xx1,type="l")
polygon(xx, xx1, col = "red", border = NA)

PDF plot

I want to shade the region between (4,10) only. How would I go about doing this?


问:
Linear Regression Model in R
I am a total novice to R, I have an assignment using Linear regression, where we have to produce 2 different models, to see which one is a better predictor of pain. The first model is just to contain age and gender. The second model is to include extra variables; The State Trait Anxiety Inventory scores, The Pain Catastrophizing Scale, The Mindful Attention Awareness Scale, and measures of cortisol levels in both salivia and serum (blood).

The research question states that we need to conduct a hierarchical regression, by building a model containing age and sex as predictors of pain (model 1), then building a new model with the predictors: age, sex, STAI, pain catastrophizing, mindfulness, and cortisol measures (model 2). Hence, the predictors used in model 1 are a subset of the predictors used in model 2. After completion of both models, need comparison to assess whether substantial new information was gained about pain in model 2 compared to model 1.

I am having a lot of problems with "sex" as a variable, someone had coded a "3" instead of male and female and although I have excluded the score, "3" is still coming up as a level in the data set, is there a way to remove this?

Furthermore how can I convert "sex" into a "factor" type vector instead of "character" vector? Can categorical variables be predictors in a model? I have attempted to do this using the following command, but it continues to return in errors.

```<code>sex_vector <- c("female", "male") etc.
factor.sex.vector <- factor(sex.vector)
</code>```

Below is an excerpt of the data set:

```<code>data.frame': 156 obs. of 10 variables:
$ sex : Factor w/ 3 levels "3","female","male": 2 2 3 3 3 3 3 2 2 2 ...
</code>```

答:
Eliminate the unwanted value and then, as suggested by mt1022 apply factor again:</p>

```<code>factor.sex.vector <- subset(factor.sex.vector, factor.sex.vector != 3)
factor.sex.vector <- factor(factor.sex.vector)
</code>```

Title: Linear Regression Model in R

Body:
I am a total novice to R, I have an assignment using Linear regression, where we have to produce 2 different models, to see which one is a better predictor of pain. The first model is just to contain age and gender. The second model is to include extra variables; The State Trait Anxiety Inventory scores, The Pain Catastrophizing Scale, The Mindful Attention Awareness Scale, and measures of cortisol levels in both salivia and serum (blood).

The research question states that we need to conduct a hierarchical regression, by building a model containing age and sex as predictors of pain (model 1), then building a new model with the predictors: age, sex, STAI, pain catastrophizing, mindfulness, and cortisol measures (model 2). Hence, the predictors used in model 1 are a subset of the predictors used in model 2. After completion of both models, need comparison to assess whether substantial new information was gained about pain in model 2 compared to model 1.

I am having a lot of problems with "sex" as a variable, someone had coded a "3" instead of male and female and although I have excluded the score, "3" is still coming up as a level in the data set, is there a way to remove this?

Furthermore how can I convert "sex" into a "factor" type vector instead of "character" vector? Can categorical variables be predictors in a model? I have attempted to do this using the following command, but it continues to return in errors.

sex_vector <- c("female", "male") etc.
factor.sex.vector <- factor(sex.vector)

Below is an excerpt of the data set:

data.frame': 156 obs. of 10 variables:
$ sex : Factor w/ 3 levels "3","female","male": 2 2 3 3 3 3 3 2 2 2 ...

Body:
Eliminate the unwanted value and then, as suggested by mt1022 apply factor again:

factor.sex.vector <- subset(factor.sex.vector, factor.sex.vector != 3)
factor.sex.vector <- factor(factor.sex.vector)


问:
Search Only One Field Using Pipe In Angular
I have this project lists in my JSON and I only want to search the project name and disregard the other fields. My problem now is that it also searches other fields. How can i do searching using the project name only in my pipe  without other fields affecting it. Here's what I've done below.

JSON

```<code>{
  "token": "ejsk0e",
  "projects": [
    {
      "id": 5,
      "name": "Store",
      "description": "Small",
      "organization_id": 1,
      "created_at": "2017-10-29 10:31:50",
      "updated_at": "2017-11-14 06:27:03",
      "material_projects": [
        {
          "id": 18,
          "material_id": 40,
          "project_id": 5,
          "quantity": 10,
          "unit": "pcs",
          "created_at": "2017-11-02 09:57:14",
          "updated_at": "2017-11-02 09:57:14",
          "material": {
            "id": 40,
            "sku": "ACWNAIL",
            "name": "Banana",
            "created_at": "2017-10-26 03:19:54",
            "updated_at": "2017-10-26 03:23:21"
          },
          "categories": [
            {
              "id": 8,
              "name": "Fruits",
              "created_at": "2017-10-26 07:36:48",
              "updated_at": "2017-11-10 02:06:07",
              "pivot": {
                "material_proj_id": 18,
                "category_id": 8
              }
            }
          ],
          "material_name": "Banana",
          "material_sku": "ACWNAIL",
          "category_name": "Fruits"
        }
  ]
}
</code>```

TS

```<code> getAllProjects() {
    this.subscription = this.projectsService.getAll()
      .subscribe(
        (data:any) => {
          this.projects = data.projects;
        },
        error => {
          console.log(error);
        });
  }
</code>```

HTML

```<code><div class="container-fluid">
  <input placeholder="Search..."" type="text" [(ngModel)]="searchProj">
  <div class="row" *ngFor="let project of projects | search : searchProj">
    <div class="card-block">
      <h2 class="proj-name">{{ project.name }}</h2>
    </div>
  </div>
</div>
</code>```

PIPE.ts

```<code>export class SearchPipe implements PipeTransform {

      transform(items: any, term: any): any {
        if (term === undefined) return items;

        return items.filter(function(item) {
          for(let property in item){
            if (item[property] === null){
              continue;
            }
            if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
              return true;
            }
          }
          return false;
        });
      }
    }
</code>```

答:
Solution to your problem is to just feed the property as variable into your pipe:

```<code>transform(items: any, term: any, prop: string): any {
    if (!term || !prop) return items;

    return items.filter((item) =>
        item[prop].toString().toLowerCase().includes(term.toLowerCase()));
  }

<div class="row" *ngFor="let project of projects | search : searchProj : 'name'">
</code>```

HOWEVER...

You should never do things like sorting and filtering in a pipe transform.  Pipe transforms trigger on every single change detection cycle, which is extremely frequent, and this leads to sorting and filtering being reapplied on every change detection cycle whether they are needed or not, this results in extremely poor app performance.  In fact, angularJS included a filter pipe, but it was removed due to wide spread abuse that led to poor application performance.  The better method is to build in the logic of when you need to trigger sorting or filtering yourself instead of relying on change detection to do it for you.

this is easier with reactive forms instead of ngModel, so my sample will use that.

TS:

```<code>this.projects$ = this.projectsService.getAll();
this.searchProj = new FormControl('');
this.search$ = this.searchProj.valueChanges.startWith('').debounce(300).distinctUntilChanged();
this.filteredProjects$= Observable.combineLatest(this.projects$, this.search$)
                                  .map(([projects, searchTerm]) => (searchTerm) ? projects.filter(p => p.name.toString().toLowerCase().includes(searchTerm.toLowerCase()) : projects);
</code>```

then your html:

```<code><div class="container-fluid">
  <input placeholder="Search..."" type="text" [formControl]="searchProj">
  <div class="row" *ngFor="let project of filteredProjects$ | async">
    <div class="card-block">
      <h2 class="proj-name">{{ project.name }}</h2>
    </div>
  </div>
</div>
</code>```

to walk you through this code, first you store your service method for retrieving the projects in an observable, then you make a form control for your search term, then you store it's value changes method in an observable, telling it to first start with an empty value and then debounce it and only get distnct values (this is a minor optimization so that if a user quickly types you only actually search every couple of characters and don't research if they quickly enter and remove a character).  Then you combine those two in a new observable, and map them together into your filter function, so that the projects get filtered each time either item changes.

as for your original problem... this is now a non factor since you're not using something as generic as a pipe, you can just explicitly filter on the name property, or you could just take the transform function above and use it in your map operator to not repeat the filtering logic if you use it frequently.

Body:
I have this project lists in my JSON and I only want to search the project name and disregard the other fields. My problem now is that it also searches other fields. How can i do searching using the project name only in my pipe  without other fields affecting it. Here's what I've done below.

JSON

{
  "token": "ejsk0e",
  "projects": [
    {
      "id": 5,
      "name": "Store",
      "description": "Small",
      "organization_id": 1,
      "created_at": "2017-10-29 10:31:50",
      "updated_at": "2017-11-14 06:27:03",
      "material_projects": [
        {
          "id": 18,
          "material_id": 40,
          "project_id": 5,
          "quantity": 10,
          "unit": "pcs",
          "created_at": "2017-11-02 09:57:14",
          "updated_at": "2017-11-02 09:57:14",
          "material": {
            "id": 40,
            "sku": "ACWNAIL",
            "name": "Banana",
            "created_at": "2017-10-26 03:19:54",
            "updated_at": "2017-10-26 03:23:21"
          },
          "categories": [
            {
              "id": 8,
              "name": "Fruits",
              "created_at": "2017-10-26 07:36:48",
              "updated_at": "2017-11-10 02:06:07",
              "pivot": {
                "material_proj_id": 18,
                "category_id": 8
              }
            }
          ],
          "material_name": "Banana",
          "material_sku": "ACWNAIL",
          "category_name": "Fruits"
        }
  ]
}

TS

 getAllProjects() {
    this.subscription = this.projectsService.getAll()
      .subscribe(
        (data:any) => {
          this.projects = data.projects;
        },
        error => {
          console.log(error);
        });
  }

HTML

  <input placeholder="Search..."" type="text" [(ngModel)]="searchProj">

{{ project.name }}

PIPE.ts

export class SearchPipe implements PipeTransform {

      transform(items: any, term: any): any {
        if (term === undefined) return items;

        return items.filter(function(item) {
          for(let property in item){
            if (item[property] === null){
              continue;
            }
            if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
              return true;
            }
          }
          return false;
        });
      }
    }

Body:
Solution to your problem is to just feed the property as variable into your pipe:

transform(items: any, term: any, prop: string): any {
    if (!term || !prop) return items;

    return items.filter((item) =>
        item[prop].toString().toLowerCase().includes(term.toLowerCase()));
  }

<div class="row" *ngFor="let project of projects | search : searchProj : 'name'">

HOWEVER...

You should never do things like sorting and filtering in a pipe transform.  Pipe transforms trigger on every single change detection cycle, which is extremely frequent, and this leads to sorting and filtering being reapplied on every change detection cycle whether they are needed or not, this results in extremely poor app performance.  In fact, angularJS included a filter pipe, but it was removed due to wide spread abuse that led to poor application performance.  The better method is to build in the logic of when you need to trigger sorting or filtering yourself instead of relying on change detection to do it for you.

this is easier with reactive forms instead of ngModel, so my sample will use that.

TS:

this.projects$ = this.projectsService.getAll();
this.searchProj = new FormControl('');
this.search$ = this.searchProj.valueChanges.startWith('').debounce(300).distinctUntilChanged();
this.filteredProjects$= Observable.combineLatest(this.projects$, this.search$)
                                  .map(([projects, searchTerm]) => (searchTerm) ? projects.filter(p => p.name.toString().toLowerCase().includes(searchTerm.toLowerCase()) : projects);

then your html:

<div class="container-fluid">
  <input placeholder="Search..."" type="text" [formControl]="searchProj">
  <div class="row" *ngFor="let project of filteredProjects$ | async">
    <div class="card-block">
      <h2 class="proj-name">{{ project.name }}</h2>
    </div>
  </div>
</div>

to walk you through this code, first you store your service method for retrieving the projects in an observable, then you make a form control for your search term, then you store it's value changes method in an observable, telling it to first start with an empty value and then debounce it and only get distnct values (this is a minor optimization so that if a user quickly types you only actually search every couple of characters and don't research if they quickly enter and remove a character).  Then you combine those two in a new observable, and map them together into your filter function, so that the projects get filtered each time either item changes.

as for your original problem... this is now a non factor since you're not using something as generic as a pipe, you can just explicitly filter on the name property, or you could just take the transform function above and use it in your map operator to not repeat the filtering logic if you use it frequently.


问:
cocoa core data not saving both fields
Iam trying to save a date field + a text field into a core-data stoagemodel. I have used the "Core Data Entity" assists in interface builder but i can't get it to save both fiels when i press save.

It only saves the text field (but if i change the date it also saves that) - it feels like it is only "sends" or "take" the fiels i actually edit..

Why is that?

Ive uploaded a SS of the app, maybe it gives you a better understanding: http://img801.imageshack.us/content_round.php?page=done&l=img801/6577/skrmbillede20110118kl12.png&via=mupload

Thanks alot

答: Im not sure I completely understand your question but if its not saving a certain field you can manually save it by doing something like this: [myArrayController setValue:valueOfTheFieldHere forKeyPath:@"selection.keyName"];

Title: cocoa core data not saving both fields


问:
How to Start/Stop/Delete the user define services from MS-CONFIG
I am running the Spring-Boot application as a Windows service.I can see my services is listed in the MSCONFIG

I wanted to know how can I

Stop

Start

Delete

The Service.

答: You can't perform those operations from MSCONFIG. Use the services control panel application (services.msc) to start, stop and generally manage your service. Use the SC command line utility to delete your service ("SC DELETE service-name").</p>


问:
Using "like" wildcard in prepared statement
I am using prepared statements to execute mysql database queries. And I want to implement a search functionality based on a keyword of sorts.

For that I need to use LIKE keyword, that much I know. And I have also used prepared statements before, but I do not know how to use it with LIKE because from the following code where would I add the 'keyword%'?

Can I directly use it in the pstmt.setString(1, notes) as (1, notes+"%") or something like that. I see a lot of posts on this on the web but no good answer anywhere.

```<code>PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
</code>```

答:
```<code>String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);
</code>```

Body:
I am using prepared statements to execute mysql database queries. And I want to implement a search functionality based on a keyword of sorts.

For that I need to use LIKE keyword, that much I know. And I have also used prepared statements before, but I do not know how to use it with LIKE because from the following code where would I add the 'keyword%'?

Can I directly use it in the pstmt.setString(1, notes) as (1, notes+"%") or something like that. I see a lot of posts on this on the web but no good answer anywhere.

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();


问:
W3 Modal opens and closes immediately
I've noticed some odd behaviour with the W3.css modal class. After hours and hours of searching and attempting to debug, i discovered that using the "base" tag in a css file will cause W3 modal boxes to open and then close immediately, and then redirect to the directory defined in the "base" tag. Seems very odd to me.

I haven't been able to discover WHY this is happening, or to find a sensible work around other than omitting the "base" tag.

I did try defining the "base" with and without the "https:". The only difference this made was that WITH the "https:" the modals would open, but the browser gave an "INSECURE WEBSITE..." warning, and attempted to block (and the modals would open, albeit with blocked content). WITHOUT the "https:" the modals would open but then close immediately and redirect to the "base" dir.

I would like to stress that i am not using bootstrap or any other way of opening the modals - it is purely W3 classes (but obviously using javascript within the modal to get.ElementById etc).

Has anyone else come across this? Has anyone managed to find a sensible workaround?

Here's the css tag:

```<code><base href="//www.<subdomain>.<domain>" />
</code>```

Here's the calling code:

```<code><div class="w3-container">
    <a href="#"   onclick="document.getElementById('example-modal').style.display='inline'">
       <span class="ca-icon">$</span>
       <div class="ca-content">
           <h2 class="ca-main">Example</h2>
       </div>
    </a>
</div>
</code>```

And here is the modal definition:

```<code><div id="example-modal" class="w3-modal">
   <div class="w3-modal-content w3-card-8 w3-animate-zoom" style="max-width:600px">
      <h2>EXAMPLE MODAL BOX...</h2>
      <div class="w3-center"><br>
         <span onclick="document.getElementById('example-modal').style.display='none'" class="w3-closebtn w3-hover-red w3-container w3-padding-8 w3-display-topright" title="Close Modal">x</span>
         <i class="fa fa-spinner fa-spin" style="font-size:64px"></i>
      </div>
      <form class="w3-container" action="" >
         <div class="w3-section">
            ...some text here.
         </div>
      </form>
      <div class="w3-container w3-border-top w3-padding-16 w3-light-grey" align="center">
         <button onclick="document.getElementById('example-modal').style.display='none'" type="button" class="w3-btn w3-red">OK</button>
      </div>
   </div>
</div>
</code>```

答:
I was having the same issue, it was due to the modal being within a form, so when you clicked the <button> it submitted the page, hence clearing the modal.
Changed it to  and it cured the issue.

I used this:

```<code><span onclick=""document.getElementById('idembim').style.display='block'"" class=""w3-button w3-blue w3-small w3-padding-small"">Select Image</span>
</code>```

Instead of this:

```<code><button onclick=""document.getElementById('idembim').style.display='block'"" class=""w3-button w3-blue w3-small w3-padding-small"">Select Image</button>
</code>```

Title: W3 Modal opens and closes immediately

Body:
I've noticed some odd behaviour with the W3.css modal class. After hours and hours of searching and attempting to debug, i discovered that using the "base" tag in a css file will cause W3 modal boxes to open and then close immediately, and then redirect to the directory defined in the "base" tag. Seems very odd to me.

I haven't been able to discover WHY this is happening, or to find a sensible work around other than omitting the "base" tag.

I did try defining the "base" with and without the "https:". The only difference this made was that WITH the "https:" the modals would open, but the browser gave an "INSECURE WEBSITE..." warning, and attempted to block (and the modals would open, albeit with blocked content). WITHOUT the "https:" the modals would open but then close immediately and redirect to the "base" dir.

I would like to stress that i am not using bootstrap or any other way of opening the modals - it is purely W3 classes (but obviously using javascript within the modal to get.ElementById etc).

Has anyone else come across this? Has anyone managed to find a sensible workaround?

Here's the css tag:

<base href="//www.<subdomain>.<domain>" />

Here's the calling code:

       $

Example

And here is the modal definition:

EXAMPLE MODAL BOX...

         x

      <form class="w3-container" action="" >

            ...some text here.

      </form>

         <button onclick="document.getElementById('example-modal').style.display='none'" type="button" class="w3-btn w3-red">OK</button>

Body:
I was having the same issue, it was due to the modal being within a form, so when you clicked the <button> it submitted the page, hence clearing the modal.
Changed it to  and it cured the issue.

I used this:

<span onclick=""document.getElementById('idembim').style.display='block'"" class=""w3-button w3-blue w3-small w3-padding-small"">Select Image</span>

Instead of this:

<button onclick=""document.getElementById('idembim').style.display='block'"" class=""w3-button w3-blue w3-small w3-padding-small"">Select Image</button>


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
Use your custom submit via ajax. i.e., </p>

```<code><form id="form-customer-attr-new" actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
    $('#form-customer-attr-new').submit(function(e) {
        var value = $("#autocompleteform").val();
        value = value.substr(0, value.indexOf(' '));
        var urlPost = 'http://test.com/'
        if (!isNan(value) && !empty(value)) {
            $("#autocompleteform").val(value);
            alert($("#autocompleteform").val());
            $.ajax({
                   type: "GET",
                   url: urlPost+'?test='+value  ,
                   data: '',
                   dataType: "text",
                   success: function(resultData){
                            alert("Save Complete");
                   }
        } else {
            alert("Invalid Postcode");
            //return false;
        }
    });
</script>
</code>```

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";

Body:
Use your custom submit via ajax. i.e.,

<form id="form-customer-attr-new" actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
    $('#form-customer-attr-new').submit(function(e) {
        var value = $("#autocompleteform").val();
        value = value.substr(0, value.indexOf(' '));
        var urlPost = 'http://test.com/'
        if (!isNan(value) && !empty(value)) {
            $("#autocompleteform").val(value);
            alert($("#autocompleteform").val());
            $.ajax({
                   type: "GET",
                   url: urlPost+'?test='+value  ,
                   data: '',
                   dataType: "text",
                   success: function(resultData){
                            alert("Save Complete");
                   }
        } else {
            alert("Invalid Postcode");
            //return false;
        }
    });
</script>


问:
Why does Heroku fail to detect Node.js buildpack?
I git cloned a Node.js application (the version specified in the package.json being 4.1.2 and that of my local machine being 6.2.2) and tried to  git push on Heroku. But it failed to build and gave this error:

Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz

Now I set the buildpack to heroku/nodejs and I get this message:

```<code>Buildpack set. Next release on lit-badlands-92088 will use heroku/nodejs.
Run git push heroku master to create a new release using this buildpack.
</code>```

Now when I run git push heroku master, I am again told:

```<code>remote: -----> Failed to detect set buildpack
        https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz

remote: More info:
https://devcenter.heroku.com/articles/buildpacks#detection-failure

remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to lit-badlands-92088.
</code>```

What could be the possible reasons for the Node.js buildpack not being detected even if I set it?

答:
Most apps have at least one of these signatures present, so if you see this error, it usually means an important file isn't checked into your git repository:

Java: pom.xml

Ruby: Gemfile

Node.js: package.json

Python: requirements.txt / setup.py / Pipfile

PHP: composer.json / index.php

You should:

```<code>git add {file}
git commit -am 'added {file}
git push heroku master
</code>```

Body:
I git cloned a Node.js application (the version specified in the package.json being 4.1.2 and that of my local machine being 6.2.2) and tried to  git push on Heroku. But it failed to build and gave this error:

Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz

Now I set the buildpack to heroku/nodejs and I get this message:

Buildpack set. Next release on lit-badlands-92088 will use heroku/nodejs.
Run git push heroku master to create a new release using this buildpack.

Now when I run git push heroku master, I am again told:

remote: -----> Failed to detect set buildpack
        https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz

remote: More info:
https://devcenter.heroku.com/articles/buildpacks#detection-failure

remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to lit-badlands-92088.

What could be the possible reasons for the Node.js buildpack not being detected even if I set it?

Body:
Most apps have at least one of these signatures present, so if you see this error, it usually means an important file isn't checked into your git repository:

Java: pom.xml

Ruby: Gemfile

Node.js: package.json

Python: requirements.txt / setup.py / Pipfile

PHP: composer.json / index.php

You should:

git add {file}
git commit -am 'added {file}
git push heroku master


问:
How to use libssh in Borland Cbuilder project?
A while ago I used the libssh on a Visual Studio project. So far so good.

Now I want to use that library on another project, a Borland Cbuilder project. But now I get a lot of compiler errors.

I started by putting the following includes in the header:

```<code>#include <libssh/libssh.h>
#include <libssh/sftp.h>
</code>```

But this gives the following error:

```<code>[C++ Error] libssh.h(59): E2209 Unable to open include file 'unistd.h'
</code>```

This refers to a unix file, so that isn't good.
In the file libssh.h I see the following code:

```<code>#ifdef _MSC_VER
  /* Visual Studio hasn't inttypes.h so it doesn't know uint32_t */
  typedef int int32_t;
  typedef unsigned int uint32_t;
  typedef unsigned short uint16_t;
  typedef unsigned char uint8_t;
  typedef unsigned long uint64_t;
  typedef int mode_t;
#else /* _MSC_VER */
  #include <unistd.h>
  #include <inttypes.h>
#endif /* _MSC_VER */
</code>```

So I tried to include the following line in my header file as a workaround:

```<code>#define _MSC_VER   1
</code>```

But then I get another error:

```<code>[C++ Error] types.h(47): E2238 Multiple declaration for 'mode_t'
[C++ Error] libssh.h(57): E2344 Earlier declaration of 'mode_t'
</code>```

Long story short: whatever next workarounds I try, I always get compiler errors.

Can this be fixed? Or can libssh only be used with Microsoft compilers?

[Edit:]
I tried another thing: include the typedefs from the libbssh header into my own header. Then i get the next error:

```<code>[C++ Error] sftp.h(50): E2238 Multiple declaration for 'uid_t'
</code>```

for the following piece from sftp.h:

```<code>#ifndef uid_t
  typedef uint32_t uid_t;
#endif /* uid_t */
</code>```

I'm flabbergasted....

BTW, I'm using Borland C++builder 5.0. (I know it's ancient)

答:
Well, eventually I fixed the header files in the following way:

```<code>#ifdef _MSC_VER
  // Do MSVC specific stuff
#else
#ifdef __BCPLUSPLUS__
  // Do Borland specific stuff
#else /* __BCPLUSPLUS__ */
  // Do unix stuff
#endif /* __BCPLUSPLUS__ */
#endif /* _MSC_VER */
</code>```

I copied the MSVC stuff to the Borland section and after some tweaking it compiled.

Body:
A while ago I used the libssh on a Visual Studio project. So far so good.

Now I want to use that library on another project, a Borland Cbuilder project. But now I get a lot of compiler errors.

I started by putting the following includes in the header:

#include <libssh/libssh.h>
#include <libssh/sftp.h>

But this gives the following error:

[C++ Error] libssh.h(59): E2209 Unable to open include file 'unistd.h'

This refers to a unix file, so that isn't good.
In the file libssh.h I see the following code:

#ifdef _MSC_VER
  /* Visual Studio hasn't inttypes.h so it doesn't know uint32_t */
  typedef int int32_t;
  typedef unsigned int uint32_t;
  typedef unsigned short uint16_t;
  typedef unsigned char uint8_t;
  typedef unsigned long uint64_t;
  typedef int mode_t;
#else /* _MSC_VER */
  #include <unistd.h>
  #include <inttypes.h>
#endif /* _MSC_VER */

So I tried to include the following line in my header file as a workaround:

#define _MSC_VER   1

But then I get another error:

[C++ Error] types.h(47): E2238 Multiple declaration for 'mode_t'
[C++ Error] libssh.h(57): E2344 Earlier declaration of 'mode_t'

Long story short: whatever next workarounds I try, I always get compiler errors.

Can this be fixed? Or can libssh only be used with Microsoft compilers?

[Edit:]
I tried another thing: include the typedefs from the libbssh header into my own header. Then i get the next error:

[C++ Error] sftp.h(50): E2238 Multiple declaration for 'uid_t'

for the following piece from sftp.h:

#ifndef uid_t
  typedef uint32_t uid_t;
#endif /* uid_t */

I'm flabbergasted....

BTW, I'm using Borland C++builder 5.0. (I know it's ancient)

Body:
Well, eventually I fixed the header files in the following way:

#ifdef _MSC_VER
  // Do MSVC specific stuff
#else
#ifdef __BCPLUSPLUS__
  // Do Borland specific stuff
#else /* __BCPLUSPLUS__ */
  // Do unix stuff
#endif /* __BCPLUSPLUS__ */
#endif /* _MSC_VER */

I copied the MSVC stuff to the Borland section and after some tweaking it compiled.


问:
How to use Microsoft.Extensions.DependencyInjection in Http Handler Sitecore?
I am using Microsoft extension dependency injection in Sitecore 8.2 update 4 with Helix Framework, below is my code:

public class TestTextHandler : IHttpHandler
{
    private readonly ITest _test;

    public TestTextHandler(Test test)
    {
        _test = test;
    }
}

public interface ITest
{
}

public class Test : ITest
{
}

public class RegisterContainer : IServicesConfigurator
{
    public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<ITest, Test>();
    }
}
```

<p>One patch file:</p>

<pre class="lang-xml prettyprint-override"><code><configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <services>
      <configurator type="XX.XX.RegisterContainer, XX.XX" />
    </services>
  </sitecore>
</configuration>
</code>```

I am getting error Constructor on type 'XX.XX.TestTextHandler' not found.

答:
You are getting the error because you have configured your TestTextHandler to take a concrete Test object instead of an object that inherits your ITest interface.

You need to change your constructor declaration to:
public TestTextHandler(ITest test)

Body:
I am using Microsoft extension dependency injection in Sitecore 8.2 update 4 with Helix Framework, below is my code:

public class TestTextHandler : IHttpHandler
{
    private readonly ITest _test;

    public TestTextHandler(Test test)
    {
        _test = test;
    }
}

public interface ITest
{
}

public class Test : ITest
{
}

public class RegisterContainer : IServicesConfigurator
{
    public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<ITest, Test>();
    }
}

One patch file:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <services>
      <configurator type="XX.XX.RegisterContainer, XX.XX" />
    </services>
  </sitecore>
</configuration>

I am getting error Constructor on type 'XX.XX.TestTextHandler' not found.


问:
Hamburger icon changes on Back Arrow icon after closing the previous Activity
I am opening an About page from the Navigation drawer of an application. It creates an intent and starts a new Activity. In the AboutActivity I show a Back Arrow and when I close this activity on my MainActivity the Hamburger icon changes to Back Arrow icon.

Here is MainActivity:

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDrawerToggle = new ActionBarDrawerToggle(
            this, mDrawer, mToolbar, R.string.drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            LogUtils.d(TAG, "onDrawerOpened() ");

            KeyboardUtils.hideKeyboard(getBaseContext(), drawerView);

            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            LogUtils.d(TAG, "onDrawerClosed: " + getTitle());
            invalidateOptionsMenu();
        }
    };
    //calling sync state is necessary or else your hamburger icon wont show up
    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerToggle.syncState();

    /* res/menu/drawer_menu.xml */
    mNavigationView.setNavigationItemSelectedListener(this);

    setContentView(R.layout.activity_main);
}

@Override
protected void onResume() {
    super.onResume();

    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }
    mDrawerToggle.syncState();
}
</code>```

Here is About activity:

```<code>public class AboutActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final String version = getString(R.string.about_version, BuildConfig.VERSION_NAME, String.valueOf(BuildConfig.VERSION_CODE));
    final View aboutPage = new AboutPage(this)
            .isRTL(false)
            .setDescription(version)
            .addGroup("Connect with us")
            .addEmail("log@lunni.fi")
            .addPlayStore("fi.lunni.mobileadvisor")
            .addYoutube("UCubK_NmfkAGPzo5UfiStsVQ")
            .addWebsite("https://lunni.fi/")
            .create();

    final ImageView image = (ImageView) aboutPage.findViewById(mehdi.sakout.aboutpage.R.id.image);
    image.setImageDrawable(ImgUtils.changeColor(this, R.drawable.lunni_logo_icon_white, R.color.lunni_blue));
    setContentView(aboutPage);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}
}
</code>```

And in the Manifest.xml

```<code>    <activity android:name=".ui.activities.AboutActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".ui.activities.MainActivity" />
    </activity>
</code>```

答:
Remove this line from onResume():

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(false);
</code>```

Body:
I am opening an About page from the Navigation drawer of an application. It creates an intent and starts a new Activity. In the AboutActivity I show a Back Arrow and when I close this activity on my MainActivity the Hamburger icon changes to Back Arrow icon.

Here is MainActivity:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDrawerToggle = new ActionBarDrawerToggle(
            this, mDrawer, mToolbar, R.string.drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            LogUtils.d(TAG, "onDrawerOpened() ");

            KeyboardUtils.hideKeyboard(getBaseContext(), drawerView);

            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            LogUtils.d(TAG, "onDrawerClosed: " + getTitle());
            invalidateOptionsMenu();
        }
    };
    //calling sync state is necessary or else your hamburger icon wont show up
    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerToggle.syncState();

    /* res/menu/drawer_menu.xml */
    mNavigationView.setNavigationItemSelectedListener(this);

    setContentView(R.layout.activity_main);
}

@Override
protected void onResume() {
    super.onResume();

    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }
    mDrawerToggle.syncState();
}

Here is About activity:

public class AboutActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final String version = getString(R.string.about_version, BuildConfig.VERSION_NAME, String.valueOf(BuildConfig.VERSION_CODE));
    final View aboutPage = new AboutPage(this)
            .isRTL(false)
            .setDescription(version)
            .addGroup("Connect with us")
            .addEmail("log@lunni.fi")
            .addPlayStore("fi.lunni.mobileadvisor")
            .addYoutube("UCubK_NmfkAGPzo5UfiStsVQ")
            .addWebsite("https://lunni.fi/")
            .create();

    final ImageView image = (ImageView) aboutPage.findViewById(mehdi.sakout.aboutpage.R.id.image);
    image.setImageDrawable(ImgUtils.changeColor(this, R.drawable.lunni_logo_icon_white, R.color.lunni_blue));
    setContentView(aboutPage);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}
}

And in the Manifest.xml

    <activity android:name=".ui.activities.AboutActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".ui.activities.MainActivity" />
    </activity>

Body:
Remove this line from onResume():

getSupportActionBar().setDisplayHomeAsUpEnabled(false);


问:
The "main" div around the options html element does not allow to insert them into parent component

I have 2 dropdowns as below:

```<code> <div class="row">
      <div class="col-4 offset-3 text-center">
          <select v-model="animation1">
            <option selected hidden>In Animation</option>
            <app-dropdown-options></app-dropdown-options>
          </select>
      </div>
    </div>

    <br>

    <div class="row">
      <div class="col-4 offset-3 text-center">
        <select v-model="animation2">
          <option selected hidden>Out Animation</option>
          <app-dropdown-options></app-dropdown-options>
        </select>
      </div>
    </div>
</code>```

Because i dont want to repeat myself i have create a component which has these options as below :

```<code><template>

        <div>
          <option value="animated bounce">bounce</option>
          <option value="animated wobble">wobble</option>
          <option value="animated bounceInLeft">bounceInLeft</option>
          <option value="animated bounceOutDown">bounceOutDown</option>
          <option value="animated fadeIn">fadeIn</option>
          <option value="animated fadeInLeftBig">fadeInLeftBig</option>
          <option value="animated fadeInUpBig">fadeInUpBig</option>
          <option value="animated fadeOutLeft">fadeOutLeft</option>
        </div>
    </template>
</code>```

After that,i use the child component on selects.The only problem is on child component in which the main div,around the options cause problem.
  I have try a lot to find a solution but i can't so i decided to publish my problem

答:
Another solution would be to have the whole select inside of child component and pass to it "animation in" and "animation out" where these are the text of two selects respectively,with props.Even if is the same component,Vue treat for the component as unique for each select

Parent component:

```<code><div class="row">
  <div class="col-4 offset-3 text-center">
      <app-dropdown-options passedInOrOut="In Animation" @optionWasChanged="firstAnimation($event)"></app-dropdown-options>
  </div>
</div>

<br>

<div class="row">
  <div class="col-4 offset-3 text-center">
      <app-dropdown-options passedInOrOut="Out Animation" @optionWasChanged="secondAnimation($event)"></app-dropdown-options>
  </div>
</div>
</code>```

Child Component:

```<code><template>
  <select v-model="optionSelected">
    <option selected hidden>{{anim}}</option>
    <option value="animated bounce">bounce</option>
    <option value="animated wobble">wobble</option>
    <option value="animated bounceInLeft">bounceInLeft</option>
    <option value="animated bounceOutDown">bounceOutDown</option>
    <option value="animated fadeIn">fadeIn</option>
    <option value="animated fadeInLeftBig">fadeInLeftBig</option>
    <option value="animated fadeInUpBig">fadeInUpBig</option>
    <option value="animated fadeOutLeft">fadeOutLeft</option>
  </select>
</template>
</code>```

For those who want to see the scripts of parent and child component:

Js of parent Component:

```<code><script>
import Options from './dropdownOptions.vue';
  export default{
    components:{
      'app-dropdown-options':Options
    },
    data(){
      return{
        show:true,
        animation1:'empty',
        animation2:'empty',
        animate:'animated bounce',
        inOrOut:'In'
      }
    },
    methods:{
      firstAnimation(animation){
        this.animation1 = animation;
      },
      secondAnimation(animation){
        this.animation2 = animation;
      }
    }
  }
</script>
</code>```

JS for child Component:

```<code><script>
    export default{
    props:['passedInOrOut'],
    data(){
      return{
        anim:this.passedInOrOut,
        option:''
      }
    },
    computed:{
      optionSelected:{
        get(){
          return this.option = this.anim;
        },
        set(option){
          this.option = option;
          this.$emit('optionWasChanged',this.option);
        }
      }
    }
    }
</script>
</code>```

Body:
I have 2 dropdowns as below:

          <select v-model="animation1">
            <option selected hidden>In Animation</option>
            <app-dropdown-options></app-dropdown-options>
          </select>

        <select v-model="animation2">
          <option selected hidden>Out Animation</option>
          <app-dropdown-options></app-dropdown-options>
        </select>

Because i dont want to repeat myself i have create a component which has these options as below :

<template>

          <option value="animated bounce">bounce</option>
          <option value="animated wobble">wobble</option>
          <option value="animated bounceInLeft">bounceInLeft</option>
          <option value="animated bounceOutDown">bounceOutDown</option>
          <option value="animated fadeIn">fadeIn</option>
          <option value="animated fadeInLeftBig">fadeInLeftBig</option>
          <option value="animated fadeInUpBig">fadeInUpBig</option>
          <option value="animated fadeOutLeft">fadeOutLeft</option>

    </template>

After that,i use the child component on selects.The only problem is on child component in which the main div,around the options cause problem.
  I have try a lot to find a solution but i can't so i decided to publish my problem

Body:
Another solution would be to have the whole select inside of child component and pass to it "animation in" and "animation out" where these are the text of two selects respectively,with props.Even if is the same component,Vue treat for the component as unique for each select

Parent component:

<div class="row">
  <div class="col-4 offset-3 text-center">
      <app-dropdown-options passedInOrOut="In Animation" @optionWasChanged="firstAnimation($event)"></app-dropdown-options>
  </div>
</div>

<br>

<div class="row">
  <div class="col-4 offset-3 text-center">
      <app-dropdown-options passedInOrOut="Out Animation" @optionWasChanged="secondAnimation($event)"></app-dropdown-options>
  </div>
</div>

Child Component:

<template>
  <select v-model="optionSelected">
    <option selected hidden>{{anim}}</option>
    <option value="animated bounce">bounce</option>
    <option value="animated wobble">wobble</option>
    <option value="animated bounceInLeft">bounceInLeft</option>
    <option value="animated bounceOutDown">bounceOutDown</option>
    <option value="animated fadeIn">fadeIn</option>
    <option value="animated fadeInLeftBig">fadeInLeftBig</option>
    <option value="animated fadeInUpBig">fadeInUpBig</option>
    <option value="animated fadeOutLeft">fadeOutLeft</option>
  </select>
</template>

For those who want to see the scripts of parent and child component:

Js of parent Component:

<script>
import Options from './dropdownOptions.vue';
  export default{
    components:{
      'app-dropdown-options':Options
    },
    data(){
      return{
        show:true,
        animation1:'empty',
        animation2:'empty',
        animate:'animated bounce',
        inOrOut:'In'
      }
    },
    methods:{
      firstAnimation(animation){
        this.animation1 = animation;
      },
      secondAnimation(animation){
        this.animation2 = animation;
      }
    }
  }
</script>

JS for child Component:

<script>
    export default{
    props:['passedInOrOut'],
    data(){
      return{
        anim:this.passedInOrOut,
        option:''
      }
    },
    computed:{
      optionSelected:{
        get(){
          return this.option = this.anim;
        },
        set(option){
          this.option = option;
          this.$emit('optionWasChanged',this.option);
        }
      }
    }
    }
</script>


问:
In Mogoose i found my document with find, but using update not
I'm using nodejs and mongo (with mongooose) to build a simple aplication, but i have this little problem.

If i search my documento using a find method, i found the document (and yes, i can update in this), but if i use a update method, o cant find it. Why?

My controller method

```<code>var query = {
        _id: ObjectId(req.params.runner_id)
    };

    Runner.find(query, function(e,o) {
        console.log(o); //here i found
    })

    Runner.update(query, req.body, function (err, qtd) {
        console.log(qtd); //here note

        if (err) {
            ...
        } else {
            ...
        }
    })
</code>```

My Schema

```<code>module.exports = mongoose.model("Runner", new Schema({
    cellphone: {
        type: String,
        require: "qual o telefone?",
        unique: true,
        validate: {
            validator: function (v) {
                var re = /^\d{11}$/;
                return (v == null || v.trim().length < 1) || re.test(v);
            },
            message: "telefone inválido"
        }
    },
    created_at: {
        type: Date,
        default: Date.now
    },
    advisors: [{
        name: {
            type: String,
            require: "entre com o nome"
        },
        email: {
            type: String,
            require: "entre com o e-mail"
        },
        advisor: {
            type: ObjectId,
            require: "qual a assessoria?"
        }
    }]
}));
</code>```

My output

with update -> { ok: 0, n: 0, nModified: 0 }
with find -> [ { _id: 5a0b99a9328fec0e4111ca52,
    cellphone: '85999981114',
    __v: 0,
    advisors: [ [Object] ],
    created_at: Wed Nov 15 2017 01:34:33 GMT+0000 (UTC) } ]

答:
```<code>app.get('/', function(req, res){
   var query = {
        _id: ObjectId(req.params.id)
    };

    Runner.find(query, function(e,o) {
        console.log(o); //here i found
    })
}
app.put('/:id', function(req, res){
    var Id=req.params.id;
 Runner.findById(Id, function (err, qtd) {
        console.log(qtd); //here qtd will found

        if (err) {
            ...
        } else {
            ...
        }
}
</code>```

Body:
I'm using nodejs and mongo (with mongooose) to build a simple aplication, but i have this little problem.

If i search my documento using a find method, i found the document (and yes, i can update in this), but if i use a update method, o cant find it. Why?

My controller method

var query = {
        _id: ObjectId(req.params.runner_id)
    };

    Runner.find(query, function(e,o) {
        console.log(o); //here i found
    })

    Runner.update(query, req.body, function (err, qtd) {
        console.log(qtd); //here note

        if (err) {
            ...
        } else {
            ...
        }
    })

My Schema

module.exports = mongoose.model("Runner", new Schema({
    cellphone: {
        type: String,
        require: "qual o telefone?",
        unique: true,
        validate: {
            validator: function (v) {
                var re = /^\d{11}$/;
                return (v == null || v.trim().length < 1) || re.test(v);
            },
            message: "telefone inválido"
        }
    },
    created_at: {
        type: Date,
        default: Date.now
    },
    advisors: [{
        name: {
            type: String,
            require: "entre com o nome"
        },
        email: {
            type: String,
            require: "entre com o e-mail"
        },
        advisor: {
            type: ObjectId,
            require: "qual a assessoria?"
        }
    }]
}));

My output

with update -> { ok: 0, n: 0, nModified: 0 }
with find -> [ { _id: 5a0b99a9328fec0e4111ca52,
    cellphone: '85999981114',
    __v: 0,
    advisors: [ [Object] ],
    created_at: Wed Nov 15 2017 01:34:33 GMT+0000 (UTC) } ]


问:
Add a dot after a number in R
I have the following list c(1.23,1,0.9) which Shows in the console[1] 1.23 1 0.9  , I would like to transform it to:
[1] 1.23,1.,.9 .
As you can see the first numebr remains the same but 1 become 1. and 0.9 become .9.

Is there is an elegant way to have this Format ?

Regards

答:
This a matter of printing, or representations.

What you might want to do is transform it as a character:

```<code>res <- as.character(c(1.23,1,0.9))
</code>```

And then use regexp:

```<code>res <- gsub("^0", "", res) # delete leading 0s
res[!grepl("\\.", res)] <- paste0(res[!grepl("\\.", res)], ".") # Add a "." at the end where there are no 0s
</code>```

And the result is:

```<code>res
[1] "1.23" "1."   ".9"
</code>```

Title: Add a dot after a number in R

Body:
This a matter of printing, or representations.

What you might want to do is transform it as a character:

res <- as.character(c(1.23,1,0.9))

And then use regexp:

res <- gsub("^0", "", res) # delete leading 0s
res[!grepl("\\.", res)] <- paste0(res[!grepl("\\.", res)], ".") # Add a "." at the end where there are no 0s

And the result is:

res
[1] "1.23" "1."   ".9"