问:
Using Android AccessibilityService.getWindows() to get a list of View elements on screen
Is it possible to use AccessibilityService.getWindows() to get a list of View elements that are currently displayed on screen, including their Z-level, which one is the top-most element, and the package names that they belong to? If so, how?

I'm not trying to build a full blown AccessibilityService, I'm only interested in the getWindows() method to get a list of windows on screen. I tried the following code:

```<code>AccessibilityService myService = new AccessibilityService() {
  @Override
  public void onAccessibilityEvent(AccessibilityEvent event) {

  }

  @Override
  public void onInterrupt() {

  }
};
List<AccessibilityWindowInfo> windowList = myService.getWindows();
if (windowList.isEmpty()) {
  Log.d(TAG, "Window list is empty");
} else {
  Log.d(TAG, "Window list is not empty");
}
</code>```

However, the window list is always empty. I'm sure I'm doing something wrong, but I can't seem to find any documentation/example on using getWindows().

答:
You can't instantiate an accessibility service this way.  Accessibility services get intimate access to view information.  Allowing them to be started willy nilly from Activities and other classes would be a very severe security risk.  You have to register your accessibility service with the system and start it from the accessibility services settings menu. To do this you should have an entry in your manifest file that looks something like this:

```<code><application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

    <service
        android:name=".MyAccessibilityService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >

        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>

        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/service_config" />

    </service>

    <activity android:name=".MyServiceSettingsActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.accessibilityservice.SERVICE_SETTINGS" />
        </intent-filter>
    </activity>
</application>
</code>```

Along with a raw xml file called "service_config" that contains stuff like this:

```<code><accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_service_description"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canRequestTouchExplorationMode="true"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:settingsActivity="com.yourpackage.MyServiceSettingsActivity"
/>
</code>```

You then start your service from the same area that TalkBack is started, by turnning the switch on for your service.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to use AccessibilityService.getWindows() to get a list of View elements that are currently displayed on screen, including their Z-level, which one is the top-most element, and the package names that they belong to? If so, how?

I'm not trying to build a full blown AccessibilityService, I'm only interested in the getWindows() method to get a list of windows on screen. I tried the following code:

AccessibilityService myService = new AccessibilityService() {
  @Override
  public void onAccessibilityEvent(AccessibilityEvent event) {

  }

  @Override
  public void onInterrupt() {

  }
};
List<AccessibilityWindowInfo> windowList = myService.getWindows();
if (windowList.isEmpty()) {
  Log.d(TAG, "Window list is empty");
} else {
  Log.d(TAG, "Window list is not empty");
}

However, the window list is always empty. I'm sure I'm doing something wrong, but I can't seem to find any documentation/example on using getWindows().

Body:
You can't instantiate an accessibility service this way.  Accessibility services get intimate access to view information.  Allowing them to be started willy nilly from Activities and other classes would be a very severe security risk.  You have to register your accessibility service with the system and start it from the accessibility services settings menu. To do this you should have an entry in your manifest file that looks something like this:

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

    <service
        android:name=".MyAccessibilityService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >

        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>

        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/service_config" />

    </service>

    <activity android:name=".MyServiceSettingsActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.accessibilityservice.SERVICE_SETTINGS" />
        </intent-filter>
    </activity>
</application>

Along with a raw xml file called "service_config" that contains stuff like this:

<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_service_description"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canRequestTouchExplorationMode="true"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:settingsActivity="com.yourpackage.MyServiceSettingsActivity"
/>

You then start your service from the same area that TalkBack is started, by turnning the switch on for your service.


来源: stackexchange

问:
What is the COMDAT section used for?
I see the /Gy option and am wondering why I would use it? http://msdn.microsoft.com/en-us/library/xsa71f43.aspx</p>

答:
/Gy option is good to be used in release builds. 'cause every function has it's own section, linker can drop every unused piece of code.
If you do not specify /Gy option you will get something like this:
"a.cpp" defines 3 functions and compiler puts them in one code section when compiling.
"main.cpp" uses only one function from "a.cpp", but when linking all of functions from "a.cpp" will be linked (two of them as a burden). And if every function had it's own section, linker could pick up only one that contained function needed by "main.cpp".
Compiling without /Gy option is good for debug builds.
When compiling a class, all of it's methods get their own separate sections by default.</p>

ContentLicense: CC BY-SA 2.5

Title: What is the COMDAT section used for?


问:
Implementing alpha beta pruning in Prolog
I'm developing the game Teeko in Prolog and I try to implement alpha beta pruning but I do not know where to start. Could someone please guide me? I have already found the minimax algorithm.</p>

答:
I try to implement alpha beta pruning but I do not know where to start.

Could someone please guide me?

I have already found the minimax algorithm.

The short look into alpha beta pruning algorithm

Choosing a move using minimax with alpha-beta pruning

The new relation scheme is alpha_beta( Depth, Position, Alpha, Beta, Move, Value ),

which extends minimax by replacing the minimax flag with alpha and beta. The same relation holds with respect to evaluate_and_choose.

The program can be generalized by replacing the base case of alpha_beta by a test of whether the position is terminal. This is necessary in chess programs, for example, for handling incomplete piece exchanges.

evaluate_and_choose ( Moves, Position, Depth, Alpha, Beta, Record, BestMove )

Chooses the BestMove from the set of Moves from the current

Position using the minimax algorithm with alpha-beta cutoff searching

Depth ply ahead.

Alpha and Beta are the parameters of the algorithm.

Record records the current best move.

```<code>evaluate_and_choose([ Move | Moves ], Position, D, Alpha, Beta, Move1, BestMove ) :-
    move( Move, Position, Positionl ),
    alpha_beta( D, Positionl, Alpha, Beta, MoveX, Value ),
    Value1 is -Value,
    cutoff( Move, Value1, D, Alpha, Beta, Moves, Position, Move1, BestMove ).

evaluate_and_choose( [], Position, D, Alpha, Beta, Move, ( Move, Alpha )).

alpha_beta( 0, Position, Alpha, Beta, Move, Value ) :-
    value( Position, Value ).

alpha_beta( D, Position, Alpha, Beta, Move, Value ) :-
    findall( M, move( Position, M ), Moves ),
    Alphal is -Beta,
    Betal is -Alpha,
    D1 is D-l,
    evaluate_and_choose( Moves, Position, D1, Alphal, Betal, nil, ( Move, Value )).

cutoff( Move, Value, D, Alpha, Beta, Moves, Position, Movel, ( Move,Value )) :-
    Value > Beta.
cutoff(Move, Value, D, Alpha, Beta, Moves, Position, Movel, BestMove ) :-
    Alpha < Value, Value < Beta,
    evaluate_and_choose( Moves, Position, D, Value, Beta, Move, BestMove ).

cutoff( Move, Value, D, Alpha, Beta, Moves, Position, Movel, BestMove ) :-
    Value < Alpha,
    evaluate_and_choose( Moves, Position, D, Alpha, Beta, Move1, BestMove ).
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I try to implement alpha beta pruning but I do not know where to start.

Could someone please guide me?

I have already found the minimax algorithm.

The short look into alpha beta pruning algorithm

Choosing a move using minimax with alpha-beta pruning

The new relation scheme is alpha_beta( Depth, Position, Alpha, Beta, Move, Value ),

which extends minimax by replacing the minimax flag with alpha and beta. The same relation holds with respect to evaluate_and_choose.

The program can be generalized by replacing the base case of alpha_beta by a test of whether the position is terminal. This is necessary in chess programs, for example, for handling incomplete piece exchanges.

evaluate_and_choose ( Moves, Position, Depth, Alpha, Beta, Record, BestMove )

Chooses the BestMove from the set of Moves from the current

Position using the minimax algorithm with alpha-beta cutoff searching

Depth ply ahead.

Alpha and Beta are the parameters of the algorithm.

Record records the current best move.

evaluate_and_choose([ Move | Moves ], Position, D, Alpha, Beta, Move1, BestMove ) :-
    move( Move, Position, Positionl ),
    alpha_beta( D, Positionl, Alpha, Beta, MoveX, Value ),
    Value1 is -Value,
    cutoff( Move, Value1, D, Alpha, Beta, Moves, Position, Move1, BestMove ).

evaluate_and_choose( [], Position, D, Alpha, Beta, Move, ( Move, Alpha )).

alpha_beta( 0, Position, Alpha, Beta, Move, Value ) :-
    value( Position, Value ).

alpha_beta( D, Position, Alpha, Beta, Move, Value ) :-
    findall( M, move( Position, M ), Moves ),
    Alphal is -Beta,
    Betal is -Alpha,
    D1 is D-l,
    evaluate_and_choose( Moves, Position, D1, Alphal, Betal, nil, ( Move, Value )).

cutoff( Move, Value, D, Alpha, Beta, Moves, Position, Movel, ( Move,Value )) :-
    Value > Beta.
cutoff(Move, Value, D, Alpha, Beta, Moves, Position, Movel, BestMove ) :-
    Alpha < Value, Value < Beta,
    evaluate_and_choose( Moves, Position, D, Value, Beta, Move, BestMove ).

cutoff( Move, Value, D, Alpha, Beta, Moves, Position, Movel, BestMove ) :-
    Value < Alpha,
    evaluate_and_choose( Moves, Position, D, Alpha, Beta, Move1, BestMove ).


问:
Can't load Python modules installed via pip from site-packages directory
I am trying to install and use the Evernote module (https://github.com/evernote/evernote-sdk-python) . I ran pip install evernote and it says that the installation worked.

I can confirm that the evernote module exists in /usr/local/lib/python2.7/site-packages. However, when I try to run python -c "import evernote" I get the following error:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named evernote
</code>```

This is the contents of my .bash-profile:

```<code>[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

# Setting PATH for Python 3.3
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.3/bin:${PATH}"
export PATH
export PATH=$PATH:/usr/local/bin/
</code>```

I am having this same problem with other modules installed with pip. Help?

EDIT: I am a super newbie and have not edited that .bash-profile file.

EDIT: python -c 'import sys; print "\n".join(sys.path)' Outputs the following:

```<code>/Library/Python/2.7/site-packages/setuptools-1.3.2-py2.7.egg
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/Library/Python/2.7/site-packages
</code>```

EDIT: I seemed to have made progress towards a solution by adding export PYTHONPATH=“/usr/local/lib/python2.7/site-packages” to my .bash_profile file. However, now when I run python -c 'from evernote.api.client import EvernoteClient' it tries to import oauth2, which fails with the same error. The ouath2 module is present in the module directory.

答:
Simply just type in terminal:

```<code>sudo pip install pillow
</code>```

and type import (whatever you like) or type from (whatever you like) import (whatever you like).

Body:
I am trying to install and use the Evernote module (https://github.com/evernote/evernote-sdk-python) . I ran pip install evernote and it says that the installation worked.

I can confirm that the evernote module exists in /usr/local/lib/python2.7/site-packages. However, when I try to run python -c "import evernote" I get the following error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named evernote

This is the contents of my .bash-profile:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

# Setting PATH for Python 3.3
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.3/bin:${PATH}"
export PATH
export PATH=$PATH:/usr/local/bin/

I am having this same problem with other modules installed with pip. Help?

EDIT: I am a super newbie and have not edited that .bash-profile file.

EDIT: python -c 'import sys; print "\n".join(sys.path)' Outputs the following:

/Library/Python/2.7/site-packages/setuptools-1.3.2-py2.7.egg
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/Library/Python/2.7/site-packages

EDIT: I seemed to have made progress towards a solution by adding export PYTHONPATH=“/usr/local/lib/python2.7/site-packages” to my .bash_profile file. However, now when I run python -c 'from evernote.api.client import EvernoteClient' it tries to import oauth2, which fails with the same error. The ouath2 module is present in the module directory.

Body:
Simply just type in terminal:

sudo pip install pillow

and type import (whatever you like) or type from (whatever you like) import (whatever you like).


问:
What is the convention for organising interfaces and their implementations in a Go project?
What is the convention for organising interfaces and their implementations in a Go project?

I am new to Go and creating a small project, I currently have this folder structure:

```<code>src/
    my-repo/
        solve/
            backtracksolve.go
            permutatesolve.go
            ...
            solver.go

... (some repositories and packages omitted for brevity) ...
</code>```

backtracksolve and permutatesolve both implement the interface solver so it make sense to keep them in the same package as the interface and other implementations of that interface, coming from Java/C# this is a common convention for example, java.util contains interfaces such as Set, Map, List, while also having implementations such as HashSet, HashMap and ArrayList.

However in Go because they both implement a func Solve() and both in the package solve there is redeclared exception.

Is it the convention to create a sub directory for each implementation (below) or something completely different?

```<code>src/
    my-repo/
        solve/
            backtrack/
                backtracksolve.go
            permutation/
                permutatesolve.go

            solver.go
</code>```

答:
You would generally define different types that implement your Solver interface and then define the Solve function on those types.

```<code>func (s *BackTrackSolver) Solve() { … }
func (s *PermutateSolver) Solve() { … }
</code>```

Because the types have distinct names there is no name clash.
You can try it out online in the go playground.

About your package convention question: I think a good approach is to start with all code in a single package and only export the types and functions you actually want to expose to your callers. Then later when you your code cohesion drops you should start splitting out code into multiple packages.

Also have a look at the "Organizing Go code" article from the go blog, subsection "What to put into a package" (short read).

Body:
What is the convention for organising interfaces and their implementations in a Go project?

I am new to Go and creating a small project, I currently have this folder structure:

src/
    my-repo/
        solve/
            backtracksolve.go
            permutatesolve.go
            ...
            solver.go

... (some repositories and packages omitted for brevity) ...

backtracksolve and permutatesolve both implement the interface solver so it make sense to keep them in the same package as the interface and other implementations of that interface, coming from Java/C# this is a common convention for example, java.util contains interfaces such as Set, Map, List, while also having implementations such as HashSet, HashMap and ArrayList.

However in Go because they both implement a func Solve() and both in the package solve there is redeclared exception.

Is it the convention to create a sub directory for each implementation (below) or something completely different?

src/
    my-repo/
        solve/
            backtrack/
                backtracksolve.go
            permutation/
                permutatesolve.go

            solver.go

Body:
You would generally define different types that implement your Solver interface and then define the Solve function on those types.

func (s *BackTrackSolver) Solve() { … }
func (s *PermutateSolver) Solve() { … }

Because the types have distinct names there is no name clash.
You can try it out online in the go playground.

About your package convention question: I think a good approach is to start with all code in a single package and only export the types and functions you actually want to expose to your callers. Then later when you your code cohesion drops you should start splitting out code into multiple packages.

Also have a look at the "Organizing Go code" article from the go blog, subsection "What to put into a package" (short read).


问:
angular display ng-repeat only after clicking a button
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

```<code><div ng-controller="MyController">Files on server: {{ mydata }}
</div>

<ul ng-controller="MyController as controller">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
</code>```

JS:

```<code>app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});
</code>```

答:
Use ng-click with a button to define a function to be called on click and call your $http.get inside that function.

```<code><button ng-click="myFunction()">Click</button>
</code>```

And in your controller

```<code>vm.myFunction = function() {
    $http.get('list').then(function(result) {
        console.log(result);
        vm.mydata = result.data;
     });
});
</code>```

Body:
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

Files on server: {{ mydata }}

{{ data }}

JS:

app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});

Body:
Use ng-click with a button to define a function to be called on click and call your $http.get inside that function.

<button ng-click="myFunction()">Click</button>

And in your controller

vm.myFunction = function() {
    $http.get('list').then(function(result) {
        console.log(result);
        vm.mydata = result.data;
     });
});


问:
Difference between shell and environment variables
What are the differences between shell and environment variables?
Where are these variables stored?</p>

答:
For Bash shell:

Shell variables differ from environment variables in different ways:

♦ A shell variable is specific to the shell itself and is not inherited by child processes. For example, let's say you're running another application from the shell, that application will not inherit the shell variable:

```<code>$ SHELL_VAR=xyz
$ firefox
</code>```

SHELL_VAR will not be available in the environment of the child process (firefox).

♦ In contrast, environment variables of the parent process (the shell here) are inherited by all child processes:

```<code>$ export SHELL_VAR=xyz
$ firefox
</code>```

♦ Both shell and environment variables are local to the shell/process which defined them:

Environment variables can be persistent, whereas, for shell variables once you exit the session, they're all gone.

Note: the above examples only alter the shell that you're working on, in other words, if you logout or start a new shell/terminal you're not going to see the variables that you defined, this is per the principle of process locality.

How to make presistent shell variables:

One way to do that is by modifying the ~/.profile file:

```<code>export SHELL_VAR=xyz
</code>```

This setting is user-specific and not system-wide, for system-wide environment variables, you can add the above line to a .sh file in /etc/profile.d

I highly recommend reading this page: EnvironmentVariables

Body:
For Bash shell:

Shell variables differ from environment variables in different ways:

♦ A shell variable is specific to the shell itself and is not inherited by child processes. For example, let's say you're running another application from the shell, that application will not inherit the shell variable:

$ SHELL_VAR=xyz
$ firefox

SHELL_VAR will not be available in the environment of the child process (firefox).

♦ In contrast, environment variables of the parent process (the shell here) are inherited by all child processes:

$ export SHELL_VAR=xyz
$ firefox

♦ Both shell and environment variables are local to the shell/process which defined them:

Environment variables can be persistent, whereas, for shell variables once you exit the session, they're all gone.

Note: the above examples only alter the shell that you're working on, in other words, if you logout or start a new shell/terminal you're not going to see the variables that you defined, this is per the principle of process locality.

How to make presistent shell variables:

One way to do that is by modifying the ~/.profile file:

export SHELL_VAR=xyz

This setting is user-specific and not system-wide, for system-wide environment variables, you can add the above line to a .sh file in /etc/profile.d

I highly recommend reading this page: EnvironmentVariables


答:
Like that :

HTML

```<code>    <div ng-controller="MyController">Files on server: {{ mydata }}
</div>
<input type="button" value="Click" id="refresh"/>
<ul ng-controller="MyController as controller">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
</code>```

Java script

```<code>app.controller('MyController', function ($http) {
    var vm = this;
    vm.mydata = [];

    vm.refresh = function () {
        $http.get('list')
            .then(function (result) {
                console.log(result);
                vm.mydata = result.data;
            });
    };
});
</code>```

Title: angular display ng-repeat only after clicking a button

Body:
Like that :

HTML

    <div ng-controller="MyController">Files on server: {{ mydata }}
</div>
<input type="button" value="Click" id="refresh"/>
<ul ng-controller="MyController as controller">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>

Java script

app.controller('MyController', function ($http) {
    var vm = this;
    vm.mydata = [];

    vm.refresh = function () {
        $http.get('list')
            .then(function (result) {
                console.log(result);
                vm.mydata = result.data;
            });
    };
});


答:
i think you need to put your http call in some function activated onclik

HTML:

```<code><div ng-controller="MyController as controller">
 <ul>
   <li ng-repeat="data in controller.mydata">{{ data }}</li>
 </ul>
 <button ng-click="controller.getData()">get data</button>
</div>
</code>```

controller:

```<code>   app.controller('MyController', function($http) {
 var vm = this;
 vm.mydata = [];
 //http call is in the 'getData' function
 vm.getData = function(){
  $http.get('list')
  .then(function(result) {
    console.log(result);
    vm.mydata = result.data;
   });
}
</code>```

Body:
i think you need to put your http call in some function activated onclik

HTML:

<div ng-controller="MyController as controller">
 <ul>
   <li ng-repeat="data in controller.mydata">{{ data }}</li>
 </ul>
 <button ng-click="controller.getData()">get data</button>
</div>

controller:

   app.controller('MyController', function($http) {
 var vm = this;
 vm.mydata = [];
 //http call is in the 'getData' function
 vm.getData = function(){
  $http.get('list')
  .then(function(result) {
    console.log(result);
    vm.mydata = result.data;
   });
}


问:
Does it matter if we specify 'super' in an overridable method
Does it matter if we do specify the keyword "super" when overriding methods?

If yes, under what condition it does matter?

```<code>1.
@Override
public void foo() {
super.foo();
}

2.
@Override
public void foo() {
}
</code>```

答:
Does it matter if we do specify the keyword "super" when overriding
  methods?

Invoking super.methodName() has a meaning : it invokes the method implemented in the parent class of the current instance.

So, yes it matters.

When we override a method from a parent class, we want to define a specific behavior for this subclass. This specific behavior has two flavors :

most of time, the subclass needs also to inherit from the parent behavior (addition of parent behavior and current class behavior) : in the overrided method, we call so super.methodName() and we do the specific behavior.

but in some specific cases, the subclass needs to define a specific behavior without inheriting from the behavior of the parent class : in the overrided method, we don't call super.methodName() and we do only the specific behavior.

Body:
Does it matter if we do specify the keyword "super" when overriding methods?

If yes, under what condition it does matter?

1.
@Override
public void foo() {
super.foo();
}

2.
@Override
public void foo() {
}


答:
It all depends on what you want to happen. If the parent class (super) has functionality that you still want to be executed, then calling super.foo() is needed. That would be a method that might need the parent class to perform its function, and then the child class adds some more logic after the parent did its thing.

Otherwise, if you want to completely replace what the parent class is doing, you do not want to call super.foo(). This will make sure that whatever the parent class would have done by calling the function DOES NOT get executed. Here's an example:

```<code>public class Parent {
    public void printSomething() {
        System.out.println("I'm a Parent!");
    }
}

public class Child extends Parent {
    @Override
    public void printSomething() {
        super.printSomething();
        System.out.println("I'm a Child!");
    }
}
</code>```

Calling Child printSomething would result in this:

```<code>I'm a Parent!
I'm a Child!
</code>```

If you did not call super.printSomething(), you would see this:

```<code>I'm a Child!
</code>```

Title: Does it matter if we specify 'super' in an overridable method

Body:
It all depends on what you want to happen. If the parent class (super) has functionality that you still want to be executed, then calling super.foo() is needed. That would be a method that might need the parent class to perform its function, and then the child class adds some more logic after the parent did its thing.

Otherwise, if you want to completely replace what the parent class is doing, you do not want to call super.foo(). This will make sure that whatever the parent class would have done by calling the function DOES NOT get executed. Here's an example:

public class Parent {
    public void printSomething() {
        System.out.println("I'm a Parent!");
    }
}

public class Child extends Parent {
    @Override
    public void printSomething() {
        super.printSomething();
        System.out.println("I'm a Child!");
    }
}

Calling Child printSomething would result in this:

I'm a Parent!
I'm a Child!

If you did not call super.printSomething(), you would see this:

I'm a Child!


问:
Passing a text `prop` to an `option` element
I'm trying to render a very generic <option/> tag, i want to pass it some props and just spread them as attributes.

<option {...props}>{props.text}</option>

As you can see, i'm using the text property of my object to set... well the text property of the element.

Consider this object passed in as props:

{
  value: "someValue",
  text: "some text",
  "data-something": "something"
}

With this object passed in, i will have the value and data-something set correctly, though text will set but will through a nice warning of:

Unknown prop text on <option> tag...

I don't want to force the consumers to use the label attribute instead of the text.

Keep in mind that the consumer can pass any attributes to this option including data-*.
Is there a way to spread an object and excluding properties in an elegant way?

Or maybe there's a different way to set the text property of a DOM element?

const cities = [
    {
        value: "nyc",
        text: "New York",
        'data-type': "city"
    },
    {
        value: "lnd",
        text: "London",
        'data-type': "city"
    },
    {
        value: "TLV",
        text: "Tel Aviv",
        'data-type': "city"
    }
]

const Option = (props) => {
    return (
        <option {...props}>{props.text}</option>
    )
}

class Selector extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            selectedObject: props.selectedObject || {
                value: "defualt",
                text: "Select...",
                'data-type': "default"
            }
        }
        this.onChange = this.onChange.bind(this);
    }

    onChange(e) {
        const { onChange } = this.props;
        const { selectedObject } = this.state;
        const selectedOption = e.target.selectedOptions[0];
        const nextSelectedObject = {
            value: selectedOption.value,
            text: selectedOption.text,
            'data-type': selectedOption.dataset.type
        };
        const nextState = Object.assign({}, ...selectedObject, ...nextSelectedObject);
        this.setState({
            selectedObject: nextState
        }, onChange && onChange(nextSelectedObject));
    }

    render() {
        const { selectedObject } = this.state;
        const { options } = this.props;
        return (

                <select name="" id="" value={selectedObject.value} onChange={this.onChange}>
                    {options.map((o,i) => <Option key={i} {...o} />)}
                </select>

        )
    }
}

ReactDOM.render(<Selector options={cities} />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

答:
What you want to do is pull the text out of the property to pass to the object</p>

```<code>const Option = (props) => {
    const toExtendProps = Object.assign({}, props);
    delete toExtendProps.text;
    return (
        <option {...toExtendProps }>{props.text}</option>
    )
}
</code>```

Body:
What you want to do is pull the text out of the property to pass to the object

const Option = (props) => {
    const toExtendProps = Object.assign({}, props);
    delete toExtendProps.text;
    return (
        <option {...toExtendProps }>{props.text}</option>
    )
}


问:
How can I pass HTML form information to javascript?
Alright, so I am working on a button that when clicked will display information from my RESTAPI - all without refreshing/reloading the page.

How it will work:
HTML button calls javascript function onClick -> javascript makes call to my API and displays the given information from my API.

Now, my API requires a "bet" parameter; which is a integer. The user provides this in a HTML input form.

```<code>        <form>
            Bet<br>
            <input onchange="checkBet" value="0.00001" type="text" name="bet"><br>
            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
        </form>
</code>```

So, assuming the user typed in a number in <input onchange="checkBet" value="0.00001" type="text" name="bet">
, how can I pass that to my javascript function "prepareRoll()"?

答:
You can use .previousElementSibling to reference the previous element, .value to get element .value

```<code><button type="button" id="dicebutton" onclick="prepareRoll(`${this.previousElementSibling.name}=${this.previousElementSibling.value}`)" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</code>```

Body:
Alright, so I am working on a button that when clicked will display information from my RESTAPI - all without refreshing/reloading the page.

How it will work:
HTML button calls javascript function onClick -> javascript makes call to my API and displays the given information from my API.

Now, my API requires a "bet" parameter; which is a integer. The user provides this in a HTML input form.

        <form>
            Bet

            <input onchange="checkBet" value="0.00001" type="text" name="bet">

            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"> Roll dice!</button>
        </form>

So, assuming the user typed in a number in <input onchange="checkBet" value="0.00001" type="text" name="bet">
, how can I pass that to my javascript function "prepareRoll()"?

Body:
You can use .previousElementSibling to reference the previous element, .value to get element .value

<button type="button" id="dicebutton" onclick="prepareRoll(`${this.previousElementSibling.name}=${this.previousElementSibling.value}`)" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>


问:
uiautomator - button is not getting selected
I have the following piece of code in my test:

```<code>    device.findObject(By.text("Widgets")).click();
    device.wait(Until.hasObject(By.text("Widgets").selected(true)), LAUNCH_TIMEOUT);
    device.waitForIdle(LAUNCH_TIMEOUT);
    assertTrue("Widgets button is selected after the click",
               device.findObject(By.text("Widgets")).isSelected());
</code>```

Where "Widgets" is the component of TabWidget. This works when I run it on emulator on my computer, but assertion fails when the test is performed on Travis. Here's the link to the failed build: https://travis-ci.org/aragaer/jtt_android/builds/239115606

How do I fix that?

答:
It appears that it is the problem that I have already encountered two years ago - Disabling first-run greeter on fresh android emulator

The combination of uiautomator and travis-ci hinted me that it was something I've encountered earlier.

Body:
I have the following piece of code in my test:

    device.findObject(By.text("Widgets")).click();
    device.wait(Until.hasObject(By.text("Widgets").selected(true)), LAUNCH_TIMEOUT);
    device.waitForIdle(LAUNCH_TIMEOUT);
    assertTrue("Widgets button is selected after the click",
               device.findObject(By.text("Widgets")).isSelected());

Where "Widgets" is the component of TabWidget. This works when I run it on emulator on my computer, but assertion fails when the test is performed on Travis. Here's the link to the failed build: https://travis-ci.org/aragaer/jtt_android/builds/239115606

How do I fix that?


问:
Spring @Scheduled timer accuracy
I'm using spring-boot @Scheduled annotation with fixedDelay in milliseconds as documented in javadoc:

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

Code:

```<code>@Scheduled(fixedDelay=1000)
public void task() {
    LOG.info("START: " + System.currentTimeInMillis());
    ....do some work here...
    LOG.info("END: " + System.currentTimeInMillis());
}
</code>```

And sometimes I get such output that time between previous task end and next task starts is less than 1000ms for about 2-30 milliseconds.

Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?

答: Obviously it cannot be guaranteed since you're most likely not on a real time system. Depending on what the CPU(s) do at the moment it can vary like that. It's quite hard to do something like that actually on most PC's due to the OS scheduling calls and so on (unless you have direct access to the CPU/GPU but even then)</p>

Title: Spring @Scheduled timer accuracy

Body:
I'm using spring-boot @Scheduled annotation with fixedDelay in milliseconds as documented in javadoc:

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

Code:

@Scheduled(fixedDelay=1000)
public void task() {
    LOG.info("START: " + System.currentTimeInMillis());
    ....do some work here...
    LOG.info("END: " + System.currentTimeInMillis());
}

And sometimes I get such output that time between previous task end and next task starts is less than 1000ms for about 2-30 milliseconds.

Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?


问:
When do I have to use interfaces instead of abstract classes?
I was wondering when I should use interfaces.

Lets think about the following:

```<code>public abstract class Vehicle {
   abstract float getSpeed();
}
</code>```

and :

```<code>public interface IVehicle {
  float getSpeed();
}
</code>```

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

What is the reason to use interfaces?

Thanks!

EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

答: The answer of this question is very simple,Whatever we can do with interface can be done with abstract class Agree...so when to use interfaces,the answer lies in C# restriction of multiple inheritance. When you have only contracts(abstracts) to declare and want your sub-classes implement it go with interfaces, because if you use abstract class in this case, you can not inherit from one more class and you are stuck if want to inherit from one more class,but you can implement as many interfaces.</p>

Body:
I was wondering when I should use interfaces.

Lets think about the following:

public abstract class Vehicle {
   abstract float getSpeed();
}

and :

public interface IVehicle {
  float getSpeed();
}

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

What is the reason to use interfaces?

Thanks!

EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces


问:
What's the HTML character entity for the # sign?
What's the HTML character entity for the # sign?  I've looked around for "pound" (which keeps returning the currency), and "hash" and "number", but what I try doesn't seem to turn into the right character.</p>

答:
# is the best option because it is the only one that doesn't include the # (hash) in it. Supported by old browsers or not, it is the best practice going forward.

(What is the point of encoding something using the same symbol you are encoding?)

LastEditorDisplayName: anon


问:
Show special hidden Files/Directories from Windows 7 in Java
Since Windows 7 the directory windows/system32/drivers/etc is specially hidden. Windows 7 itself doesn't show it, but it is there if I open it manually.

Today I was playing around with a Java JFace Eclipse example (http://www.ibm.com/developerworks/library/os-ecgui1/) and was wondering that java also doesn't show the etc directory.

So how can I get all directories/Files, when using file.listFiles() ?
Any ideas?

答:
The File.listFiles() method should include normal "hidden" files in the result.  If it does not, it is because of something going on at the operating system level to hide the files from the application (and not just the user).

I could not find anything in either java.io.File or the Java 7 java.nio.* extensions that mention accessing "specially hidden" files.

It could be a privilege related thing ... and if that's the case the solution is to execute the Java application with elevated privileges.

But the simple solution is for your application to keep its nose out of the Windows drivers directory tree.


问:
GameObject following another GameObject smooth Java
So in my game i have a player, which holds a bulb in his hand.(The bulb is an own GameObject like that player) Right now I am setting the Bulb position to the Player position so that the bulb lays in the players hand. What i want to do is that, when the player moves the bulb follows the player, with a bit of delay.

```<code>public void tick() {
    bulbX = playerX + 20;
    bulbY = playerY - 3;
}
</code>```

Any ideas??

Many thanks, Maxi

答:
Set it up so the bulb is always moving towards the player.

```<code>public void tick() {
    bulbX += (playerX - bulbX)/2;
    bulbY += (playerY - bulbY)/2;
}
</code>```

This way, the bulb will be moving towards the player faster if it's further away. You might need to tune the 1/2 parameter.

I also like to add time differences to my code, so the game won't slow down with the framerate.

```<code>long time1 = System.currentTimeMillis();
while(running){
    long time2 = System.currentTimeMillis();
    float timeDiff = (time2-time1)/1000f;
    time1 = time2;
    tick(timeDiff);
}
</code>```

and the tick method:

```<code>public void tick(float timeDiff){
    float factor = 2;
    bulbX += (playerX - bulbX)*factor*timeDiff;
    bulbY += (playerY - bulbY)*factor*timeDiff;
}
</code>```

This way, with a high enough framerate, the bulb will aproach the player exponentially.

Body:
So in my game i have a player, which holds a bulb in his hand.(The bulb is an own GameObject like that player) Right now I am setting the Bulb position to the Player position so that the bulb lays in the players hand. What i want to do is that, when the player moves the bulb follows the player, with a bit of delay.

public void tick() {
    bulbX = playerX + 20;
    bulbY = playerY - 3;
}

Any ideas??

Many thanks, Maxi

Body:
Set it up so the bulb is always moving towards the player.

public void tick() {
    bulbX += (playerX - bulbX)/2;
    bulbY += (playerY - bulbY)/2;
}

This way, the bulb will be moving towards the player faster if it's further away. You might need to tune the 1/2 parameter.

I also like to add time differences to my code, so the game won't slow down with the framerate.

long time1 = System.currentTimeMillis();
while(running){
    long time2 = System.currentTimeMillis();
    float timeDiff = (time2-time1)/1000f;
    time1 = time2;
    tick(timeDiff);
}

and the tick method:

public void tick(float timeDiff){
    float factor = 2;
    bulbX += (playerX - bulbX)*factor*timeDiff;
    bulbY += (playerY - bulbY)*factor*timeDiff;
}

This way, with a high enough framerate, the bulb will aproach the player exponentially.


问:
Failing inversion of control principle - single concrete class
I have a single concrete class: Validator that does a single thing.

I have no need to create an interface as there is only a single implementation of this.

Does this fail dependency of inversion principle when injecting instances of Validator into higher level classes?

If i am to use an interface for this class it causes a naming problem

答:
We use interfaces because they help for swapping implementations, mocking during unit testing and of course abstraction.

Does this fail dependency of inversion principle when injecting
  instances of Validator into higher level classes?

According to DIP, Validator should implement IValidator and classes needing it should just know about IValidator contract, not Validator definition itself. However, IOC containers (ex. Unity) allow you to register class types instead of interface.

It's just a principle and there could be valid exception to not follow it as-is. In cases like you, I would focus more on the core intention of DIP, IOC and DI; and that is to have loosely coupled code. I would hesitate to create interface if I am sure there's going to be just one implementation.

I would just make sure that nothing except my IOC container instantiates Validator.


问:
Adb install failure: INSTALL_CANCELED_BY_USER
I try to install app via adb and get a error:

```<code>$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]
</code>```

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

```<code>06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload
</code>```

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

```<code>06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
</code>```

but this is not error strings, just warning and debug.
Also strange line:

```<code>06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
</code>```

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.

答:
On Xiaomi Mi5s with MIUI8.3 (Android 6) Xiaomi.EU Rom:

Settings/ Other Settings / Developer Options /
Switch on: Allow USB Debug, Allow USB install and Allow USB Debug (Security options)

{Sorry for the translation, my device has spanish}

Body:
I try to install app via adb and get a error:

$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk

but this is not error strings, just warning and debug.
Also strange line:

06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.


问:
Running an echo statement within a return statement
I'm trying to create a dynamic footer, where the year is automatically updated. In PHP, this can be done using the following snippet:

```<code><?php echo date("Y"); ?>
</code>```

My site is on Wordpress, and because of the way the footer is structured in the theme, I am inputting the copyright notice in place of the generic Wordpress "powered by" statement, using the following filter:

```<code><?php
add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 );
function wpse_245817_esc_html( $safe_text, $text ) {
    if ( $safe_text == 'Powered by %2$s' ) {
        return '© Company';
    }
    return $safe_text;
</code>```

This outputs the copyright symbol as well as the company name (©Company), but not the date, as I cannot place the PHP snippet directly within the return statement as is.

What would be the appropriate way to add the snippet within the scope of the filter? The final output I am trying to show is:
©2017 Company.

答:
Try this, it will append the date to the return string.</p>

```<code>if ( $safe_text == 'Powered by %2$s' ) {
    return '© ' . date("Y") . ' Company';
}
</code>```

Body:
I'm trying to create a dynamic footer, where the year is automatically updated. In PHP, this can be done using the following snippet:

<?php echo date("Y"); ?>

My site is on Wordpress, and because of the way the footer is structured in the theme, I am inputting the copyright notice in place of the generic Wordpress "powered by" statement, using the following filter:

<?php
add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 );
function wpse_245817_esc_html( $safe_text, $text ) {
    if ( $safe_text == 'Powered by %2$s' ) {
        return '© Company';
    }
    return $safe_text;

This outputs the copyright symbol as well as the company name (©Company), but not the date, as I cannot place the PHP snippet directly within the return statement as is.

What would be the appropriate way to add the snippet within the scope of the filter? The final output I am trying to show is:
©2017 Company.

Body:
Try this, it will append the date to the return string.

if ( $safe_text == 'Powered by %2$s' ) {
    return '&copy; ' . date("Y") . ' Company';
}


问:
nested delete/sql statements
the following statement returns this:

```<code>select rowid,name,compound,COUNT(*) from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
group by rowid,name,compound
having COUNT(*)>1

rowid   name    compound    (No column name)
19300   QC1 ETG 2
20379   QC4 ETS 2
20686   QC2 ETG 2
19402   QC1 ETG 2
23605   QC1 ETG 2
21705   QC3 ETS 2
23678   QC1 ETG 2
18480   QC2 ETG 2
</code>```

.....
......
.....

i have another table called qvalues:

```<code>rid name    compound    rt  response    finalConc   qvalue  rowid
229263  QC3 Hydromorphone   0.69    6228.00 82.53   98  4695
229264  QC3 Morphine    0.51    3168.00 119.89  99  4695
229265  QC3 Oxymorphone 0.57    2472.00 83.89   99  4695
229266  QC3 Benzoylecgonine 2.17    20439.25    85.99   95  4695
229267  QC3 Codeine 1.34    4829.00 82.85   96  4695
229268  QC3 Hydrocodone 1.58    12416.00    84.99   94  4695
229269  QC3 Oxycodone   1.47    5430.00 78.44   94  4695
229270  QC3 Buprenorphine   2.54    366.13  10.41   98  4695
229271  QC3 Mepbrobamate    2.50    1330.34 95.56   92  4695
229272  QC3 Methadone   2.68    85897.27    86.77   92  4695
</code>```

what i need to do is take the combination of the ROWID,NAME,COMPOUND from the first set and keep only the first occurrence of it in the second set. i need to delete all other rows that have the combination of ROWID, NAME, and COMPOUND from the compound. i need to keep this combination where the RID is the smallest.

please let me know if i need to clarify anything

答:
I'd create a table alias on the second set, grouping by Name, Compound, having MIN(rowid) and then join that to the first set.

Then delete everything not in that set using NOT IN.

Title: nested delete/sql statements

Body:
the following statement returns this:

select rowid,name,compound,COUNT(*) from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
group by rowid,name,compound
having COUNT(*)>1

rowid   name    compound    (No column name)
19300   QC1 ETG 2
20379   QC4 ETS 2
20686   QC2 ETG 2
19402   QC1 ETG 2
23605   QC1 ETG 2
21705   QC3 ETS 2
23678   QC1 ETG 2
18480   QC2 ETG 2

.....
......
.....

i have another table called qvalues:

rid name    compound    rt  response    finalConc   qvalue  rowid
229263  QC3 Hydromorphone   0.69    6228.00 82.53   98  4695
229264  QC3 Morphine    0.51    3168.00 119.89  99  4695
229265  QC3 Oxymorphone 0.57    2472.00 83.89   99  4695
229266  QC3 Benzoylecgonine 2.17    20439.25    85.99   95  4695
229267  QC3 Codeine 1.34    4829.00 82.85   96  4695
229268  QC3 Hydrocodone 1.58    12416.00    84.99   94  4695
229269  QC3 Oxycodone   1.47    5430.00 78.44   94  4695
229270  QC3 Buprenorphine   2.54    366.13  10.41   98  4695
229271  QC3 Mepbrobamate    2.50    1330.34 95.56   92  4695
229272  QC3 Methadone   2.68    85897.27    86.77   92  4695

what i need to do is take the combination of the ROWID,NAME,COMPOUND from the first set and keep only the first occurrence of it in the second set. i need to delete all other rows that have the combination of ROWID, NAME, and COMPOUND from the compound. i need to keep this combination where the RID is the smallest.

please let me know if i need to clarify anything


问:
Vagrant stuck trying to start up: No valid rapl domains found
I am running Homestead via Vagrant, I have just updated my box and tried to start it. I get the following log:

```<code>==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
</code>```

I have enabled the GUI to see if its waiting for some sort of prompt and I see this message:

intel_repl: no valid rapl domains found in package 0.

Can someone advise how I can fix this?

EDIT: I am using Mac OS Yosemite.

答:
I am posting this here, because I can't add a comment (only 47 rep atm).

I had a problem very similar to yours (if not the same) 2 years ago. I discovered that the reason I had that problem with vagrant, was because I used CCleaner to clear all the temp files from my computer. I'm afraid my problem didn't have a fix, so I had to start all over again. I really hope this is not your case, but I'm just saying, this might have happened.

Body:
I am running Homestead via Vagrant, I have just updated my box and tried to start it. I get the following log:

==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...

I have enabled the GUI to see if its waiting for some sort of prompt and I see this message:

intel_repl: no valid rapl domains found in package 0.

Can someone advise how I can fix this?

EDIT: I am using Mac OS Yosemite.


问:
Modifying os.stat object
Is there a way to edit the object returned by os.stat?  At this point I'd like to be able to add a value for the filename to the object in order to identify the originating file easier.

At this point the only way I can figure out is to something like subclassing the posix.stat_result object and adding the value (though I haven't tried that to find out how doable that is).  Will that work? Is there a better way?

答:
You could convert it to a dict this way:

```<code>import os
s = os.stat('.')
d = dict(zip('mode ino dev nlink uid gid size atime mtime ctime'.split(), s))
</code>```

...and then add further entries to the dict.

Note that I included only the core 10 fields there.  If you want to cover all the possible fields then you could do something like:

```<code>import os
fields = 'mode ino dev nlink uid gid size atime mtime ctime blocks blksize rdev flags gen birthtime ftype attrs obtype'

s = os.stat('.')
d = dict((field,getattr(s,'st_'+field, None)) for field in fields.split())
</code>```

Title: Modifying os.stat object

Body:
You could convert it to a dict this way:

import os
s = os.stat('.')
d = dict(zip('mode ino dev nlink uid gid size atime mtime ctime'.split(), s))

...and then add further entries to the dict.

Note that I included only the core 10 fields there.  If you want to cover all the possible fields then you could do something like:

import os
fields = 'mode ino dev nlink uid gid size atime mtime ctime blocks blksize rdev flags gen birthtime ftype attrs obtype'

s = os.stat('.')
d = dict((field,getattr(s,'st_'+field, None)) for field in fields.split())


问:
How to reverse modified string back into MD5 hash given the method used to modify the string?
I am working with some MD5 hashes that have been turned into number sequences using the methods shown below. Given the code and example hash below, how can I "reverse" the effect of the getString() method and turn a numerical sequence back into an MD5 hash?

For example, encrypt("umadbro"); returns "1518918615824625494170109603025017352201241" because the MD5 hash is passed through the getString() method. The MD5 hash for "umadbro" is 9759ba9ef6fe5eaa6d3c1efaad34c9f1. I need a method that takes a string of numbers modified by the getString() method and converts it into its MD5 hash. For example: reverseMethod("1518918615824625494170109603025017352201241"); should output "9759ba9ef6fe5eaa6d3c1efaad34c9f1" (The input parameter is the modified string of numbers and the output is the MD5 hash of the original string). NOTE: I am not looking for a method to crack the MD5 hash. I only need a method that reverses the effect of the getString() method shown below.

```<code>    public String encrypt(String source)
        {
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] bytes = md.digest(source.getBytes());
                return getString(bytes);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

    private String getString(byte[] bytes) //this takes an md5 hash and turns it into a string of numbers.
    // How can I reverse the effect of this method?
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++)
        {
            byte b = bytes[i];
            sb.append(0xFF & b);
        }
        return sb.toString();
}
</code>```

答:
This is not possible without trying all combinations and comparing. The problem is that getString doesn't return a number that is unique for the given hash value as bytes.

For instance if the bytes are valued 0216 hex then 02 becomes "2" in decimals string encoding and 16 becomes "22". So your method would return "222" as the concatenation of both. Now if we do the same thing for 1602 then it will result in "22" and "2", and concatenation will still result in "222". And this can happen for each and every byte combination in the byte array.

So although the result is likely to still be relatively secure hash, the chance of finding a collision is much higher. What you can do is to return a large set of hashes of which 1 will result in a match, but it would take a lot of calculations; if you want to compare you're better off putting your result through getString and compare the much less secure hashes (even less secure than MD5 already is).

Body:
I am working with some MD5 hashes that have been turned into number sequences using the methods shown below. Given the code and example hash below, how can I "reverse" the effect of the getString() method and turn a numerical sequence back into an MD5 hash?

For example, encrypt("umadbro"); returns "1518918615824625494170109603025017352201241" because the MD5 hash is passed through the getString() method. The MD5 hash for "umadbro" is 9759ba9ef6fe5eaa6d3c1efaad34c9f1. I need a method that takes a string of numbers modified by the getString() method and converts it into its MD5 hash. For example: reverseMethod("1518918615824625494170109603025017352201241"); should output "9759ba9ef6fe5eaa6d3c1efaad34c9f1" (The input parameter is the modified string of numbers and the output is the MD5 hash of the original string). NOTE: I am not looking for a method to crack the MD5 hash. I only need a method that reverses the effect of the getString() method shown below.

    public String encrypt(String source)
        {
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] bytes = md.digest(source.getBytes());
                return getString(bytes);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

    private String getString(byte[] bytes) //this takes an md5 hash and turns it into a string of numbers.
    // How can I reverse the effect of this method?
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++)
        {
            byte b = bytes[i];
            sb.append(0xFF & b);
        }
        return sb.toString();
}


问:
How to iterate over an array that's inside an object in React JS
Imagine I have an array of objects like so:

```<code>const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]
</code>```

And I'm wanting to assign each of the images inside of the images array to a React component called CarrouselItem using props:

```<code>class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}
</code>```

Which is then placed into a parent component called Carrousel, where I loop over the object and return the images inside, to be placed inside of the CarrouselItem component:

```<code>class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}
      </div>
    )
  }
}
</code>```

What I expect to happen

The map function should iterate over all of the objects (in this case, just one of them) which then creates X number of CarrouselItem components, each with an  that's taken from the images array.

What actually happens

Unfortunately I'm only getting the first item in the array (in this case, 'http://lorempixel.com/400/400/sports/').

Could someone be so kind to explain where I'm going wrong here?

Link to CodePen.

答:
First you need to iterate over chefs array, and then individual images.

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

class Carrousel extends React.Component {
  render() {
    return (

Slide image

        {chefs.map((chef, i)=>(

            {chef.images.map((image,index)=>(
              <CarrouselItem imageUrl={image} key={index} />
            ))}

        ))}
        ))

    )
  }
}

class CarrouselItem extends React.Component {
  render() {

    return (

    )
  }
}

ReactDOM.render(<Carrousel />,document.getElementById("app"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
Imagine I have an array of objects like so:

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

And I'm wanting to assign each of the images inside of the images array to a React component called CarrouselItem using props:

class CarrouselItem extends React.Component {
  render() {

    return (

    )
  }
}

Which is then placed into a parent component called Carrousel, where I loop over the object and return the images inside, to be placed inside of the CarrouselItem component:

class Carrousel extends React.Component {
  render() {
    return (

Slide image

        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}

    )
  }
}

What I expect to happen

The map function should iterate over all of the objects (in this case, just one of them) which then creates X number of CarrouselItem components, each with an  that's taken from the images array.

What actually happens

Unfortunately I'm only getting the first item in the array (in this case, 'http://lorempixel.com/400/400/sports/').

Could someone be so kind to explain where I'm going wrong here?

Link to CodePen.

Body:
First you need to iterate over chefs array, and then individual images.

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, i)=>(
          <div key={i}>
            {chef.images.map((image,index)=>(
              <CarrouselItem imageUrl={image} key={index} />
            ))}
          </div>
        ))}
        ))
      </div>
    )
  }
}

class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}

ReactDOM.render(<Carrousel />,document.getElementById("app"))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
How to convert XML to a custom object in c#
XML File below.  Looking to be able to read from and write to the below file.

Using the below code I am able to SEARCH for a specific pagename node

```<code>`XDocument xmldoc = XDocument.Load(path);
 metadata m = new metadata();
 XElement emp = xmldoc.Descendants("data").FirstOrDefault(p => p.Element("pagename").Value == pagename);

        if (emp != null)
        {
           //How to populate each child node
           // dctermscreator.en = this
           // dctermscreator.fr = this

           //so on
        }`

 `<?xml version="1.0" encoding="UTF-8" ?>
 <root>
 <data>
  <pagename>default</pagename>
  <metadata>
    <desc>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </desc>
    <dctermscreator>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </dctermscreator>
    <dctermssubject>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </dctermssubject>
  </metadata>
 </data>
 </root>`
</code>```

答: I think XmlSerializer is what you need just call deserialize and it will do all work for you. You can also use CreateReader  to get xml reader from XElement</p>

Body:
XML File below.  Looking to be able to read from and write to the below file.

Using the below code I am able to SEARCH for a specific pagename node

`XDocument xmldoc = XDocument.Load(path);
 metadata m = new metadata();
 XElement emp = xmldoc.Descendants("data").FirstOrDefault(p => p.Element("pagename").Value == pagename);

        if (emp != null)
        {
           //How to populate each child node
           // dctermscreator.en = this
           // dctermscreator.fr = this

           //so on
        }`

 `<?xml version="1.0" encoding="UTF-8" ?>
 <root>
 <data>
  <pagename>default</pagename>
  <metadata>
    <desc>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </desc>
    <dctermscreator>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </dctermscreator>
    <dctermssubject>
      <en>eng desc</en>
      <fr>desc fra</fr>
    </dctermssubject>
  </metadata>
 </data>
 </root>`


答:
You can give id to the input tag and access the value of the input in the code.

```<code><form>
        Bet<br>
        <input id="betField" onchange="checkBet" value="0.00001" type="text" name="bet"><br>
        <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
    </form>
</code>```

JS CODE

```<code>function prepareRoll(){
    var input = document.getElementById('betField')
    var bet = input.value;

    //Make API call
}
</code>```

You can use jQuery library to make api call, it is quick and simple to use. If do not wish to use then you can still go with XMLHttpRequest.

Title: How can I pass HTML form information to javascript?

Body:
Alright, so I am working on a button that when clicked will display information from my RESTAPI - all without refreshing/reloading the page.

How it will work:
HTML button calls javascript function onClick -> javascript makes call to my API and displays the given information from my API.

Now, my API requires a "bet" parameter; which is a integer. The user provides this in a HTML input form.

        <form>
            Bet

            <input onchange="checkBet" value="0.00001" type="text" name="bet">

            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"> Roll dice!</button>
        </form>

So, assuming the user typed in a number in <input onchange="checkBet" value="0.00001" type="text" name="bet">
, how can I pass that to my javascript function "prepareRoll()"?

Body:
You can give id to the input tag and access the value of the input in the code.

<form>
        Bet<br>
        <input id="betField" onchange="checkBet" value="0.00001" type="text" name="bet"><br>
        <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
    </form>

JS CODE

function prepareRoll(){
    var input = document.getElementById('betField')
    var bet = input.value;

    //Make API call
}

You can use jQuery library to make api call, it is quick and simple to use. If do not wish to use then you can still go with XMLHttpRequest.


问:
ionic start myapp --v2 is not working
I am using ubuntu 14.04. Installed ionic and cordova. used command ionic start myapp --v2
error thrown is

```<code>[ERROR] Sorry! The --v1 and --v2 flags have been removed.
        Use the --type option. (ionic start --help)

        For Ionic Angular projects, try ionic start ionreddit --type=ionic-angular
</code>```

Used ionic start myapp blank --type=ionic2
Error

```<code>Unable to find starter type for ionic2
</code>```

答:
actually if u already install the ionic, the default is ionic v2, so that's mean u only need type

ionic start myApp blank
 but if u wanted to install ionic v1, u must adding --type ionic1 like this ionic start myApp blank --type ionic1

Title: ionic start myapp --v2 is not working

Body:
I am using ubuntu 14.04. Installed ionic and cordova. used command ionic start myapp --v2
error thrown is

[ERROR] Sorry! The --v1 and --v2 flags have been removed.
        Use the --type option. (ionic start --help)

        For Ionic Angular projects, try ionic start ionreddit --type=ionic-angular

Used ionic start myapp blank --type=ionic2
Error

Unable to find starter type for ionic2


问:
Git: How to "undo" a merge
The situation:
Starting with the Master at A I branched and made some changes at B then merged that branch back in (C). After making some more changes I was at D but found I needed to deploy the code without the changes that happened in the branch. If I hand't merged it that would have been fine.

```<code>A_______C___D
 \     /
  \_B_/
</code>```

Firstly I'd like to know what I should have done from here to deploy the code as if the merge never happened. Note: none of the same files that were edited in the branch have been edited in the master.

Secondly...

I didn't have time to work out the best method to deal with this, so I deleted the files which the branch added, and manually reverted a few edits made in the branch then commited the result for deployment (F)

```<code>A_______C___D___F
 \     /
  \_B_/
</code>```

I want to be able to keep developing the branch and merge any changes from the master into it to keep it up to date, but if I do that the stuff I did to create F will be merged in and cause the files to be deleted and the edits to be reverted. What is the best way to deal with this?

答:
The obvious solution is to reset to A, reapply all patches manually and resolve conflicts (which you won't have).

Alternatively you can just git revert patch B but that will create a new commit.

Although Gauthier's answer is better.

Title: Git: How to "undo" a merge

Body:
The situation:
Starting with the Master at A I branched and made some changes at B then merged that branch back in (C). After making some more changes I was at D but found I needed to deploy the code without the changes that happened in the branch. If I hand't merged it that would have been fine.

A_______C___D
 \     /
  \_B_/

Firstly I'd like to know what I should have done from here to deploy the code as if the merge never happened. Note: none of the same files that were edited in the branch have been edited in the master.

Secondly...

I didn't have time to work out the best method to deal with this, so I deleted the files which the branch added, and manually reverted a few edits made in the branch then commited the result for deployment (F)

A_______C___D___F
 \     /
  \_B_/

I want to be able to keep developing the branch and merge any changes from the master into it to keep it up to date, but if I do that the stuff I did to create F will be merged in and cause the files to be deleted and the edits to be reverted. What is the best way to deal with this?