问:
RPI docker running ubuntu container
I recently installed docker in my raspberry pi as explained in this post. I use docker in my every day, however never before with the raspberries. It exists an image of the raspberry pi called resin/rpi-raspbian. My question comes regarding other containers with other operating systems. Let's say I run in my raspberry:

```<code>docker run --rm -it ubuntu
</code>```

It seems to run perfectly fine. My question is? Is there a problem when doing this? Since ubuntu is not meant to run with armv7l (maybe I'm mistaken) based systems as the one used in the raspberry. Is this taken into account with the kernel isolation used by docker? Are there any consequences, drawbacks or something that might not work because of this?

The question might be silly, but I'm confused about this. Thanks!

答:
In short, if it is working, then it works!

Docker isolates the image and runs it in a container, over the existing kernel (It shares some part with the existing kernel). The idea behind this is to eliminate the dependencies of OS/ kernel version for different applications. Docker provides you that environment, so that your application can freely run upon it. The same applies to all of the Operating systems you want to run on docker. It takes care of them for you. Cheers!

Title: RPI docker running ubuntu container

Body:
I recently installed docker in my raspberry pi as explained in this post. I use docker in my every day, however never before with the raspberries. It exists an image of the raspberry pi called resin/rpi-raspbian. My question comes regarding other containers with other operating systems. Let's say I run in my raspberry:

docker run --rm -it ubuntu

It seems to run perfectly fine. My question is? Is there a problem when doing this? Since ubuntu is not meant to run with armv7l (maybe I'm mistaken) based systems as the one used in the raspberry. Is this taken into account with the kernel isolation used by docker? Are there any consequences, drawbacks or something that might not work because of this?

The question might be silly, but I'm confused about this. Thanks!


来源: stackexchange

问:
How to set Authorization header in Rest API Basic Authentication
Currently I am working in REST API in Java. My RestAPI is in separate maven project, And web application is in separate maven project. I have handled Basic Authentication in RestAPI. I want to set Authorization in response header and also need to get it from HttpRequest in each request(Is this best practice?)

Once I login into the application, login Username and password will forward to API, If once login credentials are valid, need to set Authorization header in Response. Each and every time I want to check the header whether the credentials are valid.

My Question is,

How to set Authorization Header, and where to set?

Either I want to set header in every response or only once?

My Web.xml(RestAPI)

```<code><http realm="MY APP REALM">
    <csrf disabled="true" />
    <intercept-url pattern="/rest/**"
        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <http-basic entry-point-ref="basicAuthenticationEntryPoint" />

</http>
<beans:bean name="bcryptEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<beans:bean name="ser"
    class="com.test.api.config.SampleUserDetailsService" />
<beans:bean name="userService" class="com.test.api.service.impl.UserServiceImpl" />

<beans:bean name="basicAuthenticationEntryPoint"
    class="com.test.api.config.MyAppBasicAuthenticationEntryPoint" />

<authentication-manager>
    <authentication-provider user-service-ref="ser">
        <password-encoder ref="bcryptEncoder" />
    </authentication-provider>
</authentication-manager>
</code>```

REST API CONTROLLER

```<code>@RestController
@RequestMapping("/rest")
public class RestServiceController {

@Autowired
IUserService userService;

@RequestMapping(value = "/user", method = RequestMethod.GET)
public ResponseEntity<List<Users>> listAllUsers() {
    List<Users> users = userService.findAllUsers();
    if (users.isEmpty()) {
        return new ResponseEntity<List<Users>>(HttpStatus.NO_CONTENT);// You many decide to return
                                                                        // HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<List<Users>>(users, HttpStatus.OK);
}

}
</code>```

Help me to resolve this?

答:
```<code>public class MyHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      response.setHeader("Authorization", "token");

       return true;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Currently I am working in REST API in Java. My RestAPI is in separate maven project, And web application is in separate maven project. I have handled Basic Authentication in RestAPI. I want to set Authorization in response header and also need to get it from HttpRequest in each request(Is this best practice?)

Once I login into the application, login Username and password will forward to API, If once login credentials are valid, need to set Authorization header in Response. Each and every time I want to check the header whether the credentials are valid.

My Question is,

How to set Authorization Header, and where to set?

Either I want to set header in every response or only once?

My Web.xml(RestAPI)

<http realm="MY APP REALM">
    <csrf disabled="true" />
    <intercept-url pattern="/rest/**"
        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <http-basic entry-point-ref="basicAuthenticationEntryPoint" />

</http>
<beans:bean name="bcryptEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<beans:bean name="ser"
    class="com.test.api.config.SampleUserDetailsService" />
<beans:bean name="userService" class="com.test.api.service.impl.UserServiceImpl" />

<beans:bean name="basicAuthenticationEntryPoint"
    class="com.test.api.config.MyAppBasicAuthenticationEntryPoint" />

<authentication-manager>
    <authentication-provider user-service-ref="ser">
        <password-encoder ref="bcryptEncoder" />
    </authentication-provider>
</authentication-manager>

REST API CONTROLLER

@RestController
@RequestMapping("/rest")
public class RestServiceController {

@Autowired
IUserService userService;

@RequestMapping(value = "/user", method = RequestMethod.GET)
public ResponseEntity<List<Users>> listAllUsers() {
    List<Users> users = userService.findAllUsers();
    if (users.isEmpty()) {
        return new ResponseEntity<List<Users>>(HttpStatus.NO_CONTENT);// You many decide to return
                                                                        // HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<List<Users>>(users, HttpStatus.OK);
}

}

Help me to resolve this?


问:
how to make a get-form in flask
I have a form which is like

```<code><form action="{{ url_for('my_form')}}" method="get">

            <h2><td><input type="hidden" name="user_name" value="{{ user_name }}">{{ user_name }}</td></h2><br>

             <button type="submit" class="btn btn-primary btn-lg" value="Submit">Submit</button>
          </form>
</code>```

And then on flask backend

```<code>@app.route('/my_form', methods=['GET'])
def my_form():
    print request.form.items()
    user_name = request.form['user_name']
    print "exclusive request"
    print "got user name ", user_name
</code>```

But this doesnt work as the submit query becomes
http://local_host/my_form?user_name=foobar  <--- 400 error

which makes sense.. as the query url is my_form
So, the question is how to make a get form in flask?

答:
According to the flask documentation we use form attribute of request  only with POST method or PUT in your case as you are using GET try args parameters:

form A MultiDict with the parsed form data from POST or PUT requests.
  Please keep in mind that file uploads will not end up here, but
  instead in the files attribute.

args A MultiDict with the parsed contents of the query string. (The
  part in the URL after the question mark).

use this in your backend :

```<code>@app.route('/my_form', methods=['GET'])
def my_form():
    print request.args.items()
    user_name = request.args['user_name']
    print "exclusive request"
    print "got user name ", user_name
</code>```

Title: how to make a get-form in flask

Body:
I have a form which is like

<form action="{{ url_for('my_form')}}" method="get">

<input type="hidden" name="user_name" value="{{ user_name }}">{{ user_name }}

             <button type="submit" class="btn btn-primary btn-lg" value="Submit">Submit</button>
          </form>

And then on flask backend

@app.route('/my_form', methods=['GET'])
def my_form():
    print request.form.items()
    user_name = request.form['user_name']
    print "exclusive request"
    print "got user name ", user_name

But this doesnt work as the submit query becomes
http://local_host/my_form?user_name=foobar  <--- 400 error

which makes sense.. as the query url is my_form
So, the question is how to make a get form in flask?

Body:
According to the flask documentation we use form attribute of request  only with POST method or PUT in your case as you are using GET try args parameters:

form A MultiDict with the parsed form data from POST or PUT requests.
  Please keep in mind that file uploads will not end up here, but
  instead in the files attribute.

args A MultiDict with the parsed contents of the query string. (The
  part in the URL after the question mark).

use this in your backend :

@app.route('/my_form', methods=['GET'])
def my_form():
    print request.args.items()
    user_name = request.args['user_name']
    print "exclusive request"
    print "got user name ", user_name


问:
Why does the size of the same identifier differ in C and C++?
```<code>#include <stdio.h>
int T;
int main()
{
    struct T { double x; };
    printf("%zu", sizeof(T));
    return 0;
}
</code>```

If I run this code in C, the result is 4, while in C++ it is 8.

Can someone explain why the difference?

答:
In C, the T in struct T is a struct tag. Struct tags reside in a different namespace than variables and types. To get a type in C, you would have to write struct T.

sizeof() expects either a type or an expression, and a struct tag is neither. You do you however have the variable T. A variable name is a valid expression in sizeof().

In C++ however, the T in struct T is a type name since a struct in C++ is essentially just a class with all members public. Therefore sizeof(T) matches the struct type in C++.

Notable here is that the sizeof operator has two different syntax cases:

sizeof unary-expression

sizeof ( type-name )

In case of the former, sizeof only accepts expressions, but not types. In case of the latter, it excepts either expressions or types. So had you written sizeof T instead of sizeof (T), you would have gotten a compiler error in C++, since T would then have been a type and not an expression.

Body:
#include <stdio.h>
int T;
int main()
{
    struct T { double x; };
    printf("%zu", sizeof(T));
    return 0;
}

If I run this code in C, the result is 4, while in C++ it is 8.

Can someone explain why the difference?


问:
Add item to a specific column in ListView Adapter
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

```<code>public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}
</code>```

Here is what I tried but I got an error and no idea what to do next :

```<code> String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
</code>```

Error:

```<code>'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'
</code>```

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.

答:
```<code>VanzatorProduse producse = new VanzatorProduse();
producse.setProdus("add value here")
vanzatorProduseList.add(producse);
</code>```

Body:
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}

Here is what I tried but I got an error and no idea what to do next :

 String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);

Error:

'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.


问:
Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time
And the Kotlin newbie asks, "why won't the following code compile?":

```<code>var left: Node? = null

fun show() {
    if (left != null) {
        queue.add(left) // ERROR HERE
    }
}
</code>```

Smart cast to 'Node' is impossible, because 'left' is a mutable
property that could have been changed by this time

I get that left is mutable variable, but I'm explicitly checking left != null and left is of type Node so why can't it be smart-casted to that type?

How can I fix this elegantly?

答:
There is a fourth option in addition to the ones in mfulton26's answer.

By using the ?. operator it is possible to call methods as well as fields without dealing with let or using local variables.

Some code for context:

```<code>var factory: ServerSocketFactory = SSLServerSocketFactory.getDefault();
socket = factory.createServerSocket(port)
socket.close()//smartcast impossible
socket?.close()//Smartcast possible. And works when called
</code>```

It works with methods, fields and all the other things I tried to get it to work.

So in order to solve the issue, instead of having to use manual casts or using local variables, you can use ?. to call the methods.

For reference, this was tested in Kotlin 1.1.4-3, but also tested in 1.1.51 and 1.1.60. There's no guarantee it works on other versions, it could be a new feature.

Using the ?. operator can't be used in your case since it's a passed variable that's the problem. The Elvis operator can be used as an alternative, and it's probably the one that requires the least amount of code. Instead of using continue though, return could also be used.

Using manual casting could also be an option, but this isn't null safe:

```<code>queue.add(left as Node);
</code>```

Meaning if left has changed on a different thread, the program will crash.

ContentLicense: CC BY-SA 4.0

Body:
And the Kotlin newbie asks, "why won't the following code compile?":

var left: Node? = null

fun show() {
    if (left != null) {
        queue.add(left) // ERROR HERE
    }
}

Smart cast to 'Node' is impossible, because 'left' is a mutable
property that could have been changed by this time

I get that left is mutable variable, but I'm explicitly checking left != null and left is of type Node so why can't it be smart-casted to that type?

How can I fix this elegantly?

Body:
There is a fourth option in addition to the ones in mfulton26's answer.

By using the ?. operator it is possible to call methods as well as fields without dealing with let or using local variables.

Some code for context:

var factory: ServerSocketFactory = SSLServerSocketFactory.getDefault();
socket = factory.createServerSocket(port)
socket.close()//smartcast impossible
socket?.close()//Smartcast possible. And works when called

It works with methods, fields and all the other things I tried to get it to work.

So in order to solve the issue, instead of having to use manual casts or using local variables, you can use ?. to call the methods.

For reference, this was tested in Kotlin 1.1.4-3, but also tested in 1.1.51 and 1.1.60. There's no guarantee it works on other versions, it could be a new feature.

Using the ?. operator can't be used in your case since it's a passed variable that's the problem. The Elvis operator can be used as an alternative, and it's probably the one that requires the least amount of code. Instead of using continue though, return could also be used.

Using manual casting could also be an option, but this isn't null safe:

queue.add(left as Node);

Meaning if left has changed on a different thread, the program will crash.


问:
What is the best J2ME UI Library
What's the J2ME UI library you recommend?</p>

答:
I have used LWUIT in a mobile application, even for BB devices, this framework was quite good. Also, AFAIK, it supports touch screen devices.

Also, it comes with a bundled toolkit, which helps you configure framework, animations, layouts, localization and so on.

Title: What is the best J2ME UI Library

ContentLicense: CC BY-SA 2.5


问:
accessing function attributes inside decorators
Is it possible to access function attributes inside a decorator?
Consider below piece of code.

```<code>def deco(a):
    def wrap():
        print(a.status)
        a()
        print(a.status)

    return wrap

@deco
def fun1():
    fun1.status="bar"

fun1.status="foo"
fun1()
</code>```

I expected the output  to be :

```<code>foo
bar
</code>```

But I get the below error:

```<code>Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    fun1()
  File "D:\python_projects\test_suite\func_attribute.py", line 3, in wrap
    print(a.status)
AttributeError: 'function' object has no attribute 'status'
</code>```

Is there any way to make this work since

```<code>def fun1():
    fun1.status="bar"

fun1.status="foo"

a=fun1

print(a.status)
a()
print(a.status)
</code>```

Outputs:

```<code>foo
bar
</code>```

As expected.

答:
Thanks to the decorator, the global name fun1 is bound to the decoration result, so to the nested wrap() function object. Inside wrap() however,  a refers to the original, unwrapped function object.

So you have two different function objects, and each can have attributes; they are not the same objects.  fun1.status is a different attribute from a.status.

You can access the same object as fun1 in the decorator as wrap:

```<code>print(wrap.status)
</code>```

Demo:

```<code>>>> def deco(a):
...     def wrap():
...         print(wrap.status)
...         a()
...         print(wrap.status)
...     return wrap
...
>>> @deco
... def fun1():
...     fun1.status="bar"
...
>>> fun1.status="foo"
>>> fun1()
foo
bar
</code>```

Body:
Is it possible to access function attributes inside a decorator?
Consider below piece of code.

def deco(a):
    def wrap():
        print(a.status)
        a()
        print(a.status)

    return wrap

@deco
def fun1():
    fun1.status="bar"

fun1.status="foo"
fun1()

I expected the output  to be :

foo
bar

But I get the below error:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    fun1()
  File "D:\python_projects\test_suite\func_attribute.py", line 3, in wrap
    print(a.status)
AttributeError: 'function' object has no attribute 'status'

Is there any way to make this work since

def fun1():
    fun1.status="bar"

fun1.status="foo"

a=fun1

print(a.status)
a()
print(a.status)

Outputs:

foo
bar

As expected.

Body:
Thanks to the decorator, the global name fun1 is bound to the decoration result, so to the nested wrap() function object. Inside wrap() however,  a refers to the original, unwrapped function object.

So you have two different function objects, and each can have attributes; they are not the same objects.  fun1.status is a different attribute from a.status.

You can access the same object as fun1 in the decorator as wrap:

print(wrap.status)

Demo:

>>> def deco(a):
...     def wrap():
...         print(wrap.status)
...         a()
...         print(wrap.status)
...     return wrap
...
>>> @deco
... def fun1():
...     fun1.status="bar"
...
>>> fun1.status="foo"
>>> fun1()
foo
bar


问:
XAMPP - Error: MySQL shutdown unexpectedly
I have reinstalled XAMPP for some reason and MySQL is not working, giving the following error in the console:

```<code>01:56:03  [mysql]   Error: MySQL shutdown unexpectedly.
01:56:03  [mysql]   This may be due to a blocked port, missing dependencies,
01:56:03  [mysql]   improper privileges, a crash, or a shutdown by another method.
01:56:03  [mysql]   Check the "/xampp/mysql/data/mysql_error.log" file
01:56:03  [mysql]   and the Windows Event Viewer for more clues
</code>```

When checking the "/xampp/mysql/data/mysql_error.log" file I get:

```<code>130302  1:48:06  InnoDB: Waiting for the background threads to start
130302  1:48:07 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:48:07 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:48:07 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:48:07 [Note] Server socket created on IP: '0.0.0.0'.
130302  1:51:12 [Note] Plugin 'FEDERATED' is disabled.
130302  1:51:12 InnoDB: The InnoDB memory heap is disabled
130302  1:51:12 InnoDB: Mutexes and rw_locks use Windows interlocked functions
130302  1:51:12 InnoDB: Compressed tables use zlib 1.2.3
130302  1:51:12 InnoDB: Initializing buffer pool, size = 16.0M
130302  1:51:12 InnoDB: Completed initialization of buffer pool
130302  1:51:12 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130302  1:51:12  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130302  1:51:13  InnoDB: Waiting for the background threads to start
130302  1:51:14 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:51:14 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:51:14 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:51:14 [Note] Server socket created on IP: '0.0.0.0'.
130302  1:56:01 [Note] Plugin 'FEDERATED' is disabled.
130302  1:56:01 InnoDB: The InnoDB memory heap is disabled
130302  1:56:01 InnoDB: Mutexes and rw_locks use Windows interlocked functions
130302  1:56:01 InnoDB: Compressed tables use zlib 1.2.3
130302  1:56:01 InnoDB: Initializing buffer pool, size = 16.0M
130302  1:56:01 InnoDB: Completed initialization of buffer pool
130302  1:56:01 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130302  1:56:01  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130302  1:56:02  InnoDB: Waiting for the background threads to start
130302  1:56:03 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:56:03 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:56:03 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:56:03 [Note] Server socket created on IP: '0.0.0.0'.
</code>```

That is just a part of the log, the full one is a bit too big.

Help?

答: the true way is RECONFIGURE  your app.with setup of MYSQL .you can open your setup again and change port from 3306 to 3307.

Body:
I have reinstalled XAMPP for some reason and MySQL is not working, giving the following error in the console:

01:56:03  [mysql]   Error: MySQL shutdown unexpectedly.
01:56:03  [mysql]   This may be due to a blocked port, missing dependencies,
01:56:03  [mysql]   improper privileges, a crash, or a shutdown by another method.
01:56:03  [mysql]   Check the "/xampp/mysql/data/mysql_error.log" file
01:56:03  [mysql]   and the Windows Event Viewer for more clues

When checking the "/xampp/mysql/data/mysql_error.log" file I get:

130302  1:48:06  InnoDB: Waiting for the background threads to start
130302  1:48:07 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:48:07 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:48:07 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:48:07 [Note] Server socket created on IP: '0.0.0.0'.
130302  1:51:12 [Note] Plugin 'FEDERATED' is disabled.
130302  1:51:12 InnoDB: The InnoDB memory heap is disabled
130302  1:51:12 InnoDB: Mutexes and rw_locks use Windows interlocked functions
130302  1:51:12 InnoDB: Compressed tables use zlib 1.2.3
130302  1:51:12 InnoDB: Initializing buffer pool, size = 16.0M
130302  1:51:12 InnoDB: Completed initialization of buffer pool
130302  1:51:12 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130302  1:51:12  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130302  1:51:13  InnoDB: Waiting for the background threads to start
130302  1:51:14 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:51:14 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:51:14 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:51:14 [Note] Server socket created on IP: '0.0.0.0'.
130302  1:56:01 [Note] Plugin 'FEDERATED' is disabled.
130302  1:56:01 InnoDB: The InnoDB memory heap is disabled
130302  1:56:01 InnoDB: Mutexes and rw_locks use Windows interlocked functions
130302  1:56:01 InnoDB: Compressed tables use zlib 1.2.3
130302  1:56:01 InnoDB: Initializing buffer pool, size = 16.0M
130302  1:56:01 InnoDB: Completed initialization of buffer pool
130302  1:56:01 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
130302  1:56:01  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
130302  1:56:02  InnoDB: Waiting for the background threads to start
130302  1:56:03 InnoDB: 1.1.8 started; log sequence number 1600324627
130302  1:56:03 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
130302  1:56:03 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
130302  1:56:03 [Note] Server socket created on IP: '0.0.0.0'.

That is just a part of the log, the full one is a bit too big.

Help?


问:
Printing data with give start and end
Help on how to print all with in a given start and end

first this is the function in main

```<code>for (i = 0; i < 30; i++) {
    printf("%s\n", Codes[i]);
    OneStock_ManyDailyData( DS, DS[i].Nametag, "10/2/2017", "11/6/2017" );
    printf("\n\n");
}
</code>```

this calls the function

```<code>void OneStock_ManyDailyData(struct company DS[30], Symbol code, StrDate start, StrDate end) {
    int i;
    int c;
    int x;
    int y;
    int a;

    for(i=0; i<30; i++) {
        //printf("Entered Loop\n");

        if(strcmp(DS[i].Nametag, code) == 0) {
            //printf("Gotcha!\n");

            for(c=0; c<DS[i].ndd; c++){
                //printf("Entered Second Loop\n");

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

what codes should in put inside the 2nd for loop in order to get the range of start and end

this last part is displays can be inserted inside the for loop but it only display 1 start or given date

```<code>if(strcmp(DS[i].Values[c].date, date)==0){
    printf("%s \t%.2f \t%.2f \t%.2f \t%.2f \t%.0f\n", DS[i].Values[c].date, DS[i].Values[c].open, DS[i].Values[c].high, DS[i].Values[c].low, DS[i].Values[c].close, DS[i].Values[c].volume);
    printf("\n");
}
</code>```

答:
Well you have to work on functions in C.To study and follow some tutorials.
Here you write:

```<code>void OneStock_ManyDailyData(struct company DS[30], Symbol code, StrDate start, StrDate end)
</code>```

First of all you can't pass an array as a parameter in C.You have to pass a pointer of the start of the array.So

```<code>void OneStock_ManyDailyData(struct company* ds, Symbol code, StrDate start, StrDate end)
</code>```

What we do here is to pass a pointer for the first element of the array (this is what we do in C)
Now you need to iterate the ds[30].To do this we need to say to the function also the number of elements , so where the iteration knows where to stop.
We also need to know how big is the step of iteration , in this case and usually we can find it by sizeof(our_element).

Iteration goes like this:

```<code>void iterate_ds(struct company* ds , int elements , ... , ...)
{
    int i;
    for ( i = 0 , i < 30 , i ++)
    {
        do_what_you_want(ds[i]);
    }
}
</code>```

You don't provide me the structure of your struct so I can't say what you have in do_what_you_want(ds[i]); .However I think you could have another iteration alongside with checking , or whatever , by passing the parameters like we did for ds array.
I hope this helps  :)

PS:Pointers is what we pass in functions in C and pointer is just an integer that holds the address where the element we created lies to.

Title: Printing data with give start and end

Body:
Help on how to print all with in a given start and end

first this is the function in main

for (i = 0; i < 30; i++) {
    printf("%s\n", Codes[i]);
    OneStock_ManyDailyData( DS, DS[i].Nametag, "10/2/2017", "11/6/2017" );
    printf("\n\n");
}

this calls the function

void OneStock_ManyDailyData(struct company DS[30], Symbol code, StrDate start, StrDate end) {
    int i;
    int c;
    int x;
    int y;
    int a;

    for(i=0; i<30; i++) {
        //printf("Entered Loop\n");

        if(strcmp(DS[i].Nametag, code) == 0) {
            //printf("Gotcha!\n");

            for(c=0; c<DS[i].ndd; c++){
                //printf("Entered Second Loop\n");

            }
        }
    getch();
}

what codes should in put inside the 2nd for loop in order to get the range of start and end

this last part is displays can be inserted inside the for loop but it only display 1 start or given date

if(strcmp(DS[i].Values[c].date, date)==0){
    printf("%s \t%.2f \t%.2f \t%.2f \t%.2f \t%.0f\n", DS[i].Values[c].date, DS[i].Values[c].open, DS[i].Values[c].high, DS[i].Values[c].low, DS[i].Values[c].close, DS[i].Values[c].volume);
    printf("\n");
}

Body:
Well you have to work on functions in C.To study and follow some tutorials.
Here you write:

void OneStock_ManyDailyData(struct company DS[30], Symbol code, StrDate start, StrDate end)

First of all you can't pass an array as a parameter in C.You have to pass a pointer of the start of the array.So

void OneStock_ManyDailyData(struct company* ds, Symbol code, StrDate start, StrDate end)

What we do here is to pass a pointer for the first element of the array (this is what we do in C)
Now you need to iterate the ds[30].To do this we need to say to the function also the number of elements , so where the iteration knows where to stop.
We also need to know how big is the step of iteration , in this case and usually we can find it by sizeof(our_element).

Iteration goes like this:

void iterate_ds(struct company* ds , int elements , ... , ...)
{
    int i;
    for ( i = 0 , i < 30 , i ++)
    {
        do_what_you_want(ds[i]);
    }
}

You don't provide me the structure of your struct so I can't say what you have in do_what_you_want(ds[i]); .However I think you could have another iteration alongside with checking , or whatever , by passing the parameters like we did for ds array.
I hope this helps  :)

PS:Pointers is what we pass in functions in C and pointer is just an integer that holds the address where the element we created lies to.


问:
How to use angular.bind(self, fn, args)
I am new to angular js. I was gone through the angular api references,
I had seen function called angular.bind(self, fn, args).
I could not understand the usage of this function. Can anyone explain this function with one example?</p>

答:
It used in Function Currying. An example with JavaScript:

```<code>var concat = function(input1) {
  return function(input2) {
    console.log(input1 + ", " + input2);
  };
};

var externalFunction = concat("Hello");
externalFunction("World!"); // gives: "Hello, World!"
</code>```

This allows you to use only some parameters and not all, for example concant("Hello") instead of concant("Hello","World!"). You can imagine using a defined variable as one of the parameters, whereas you fill in the second one from a user input. The same concept can be used with AnuglarJS:

        <input type="number" ng-model="num" ng-change="AddValue()" />
        Adding 5: {{Add}}

```

Title: How to use angular.bind(self, fn, args)

Body:
It used in Function Currying. An example with JavaScript:

var concat = function(input1) {
  return function(input2) {
    console.log(input1 + ", " + input2);
  };
};

var externalFunction = concat("Hello");
externalFunction("World!"); // gives: "Hello, World!"

This allows you to use only some parameters and not all, for example concant("Hello") instead of concant("Hello","World!"). You can imagine using a defined variable as one of the parameters, whereas you fill in the second one from a user input. The same concept can be used with AnuglarJS:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="bindController">
        <input type="number" ng-model="num" ng-change="AddValue()" />
        Adding 5: {{Add}}
    </div>
</body>
</html>
<script>
    var app = angular.module("app", []);
    app.controller('bindController',['$scope',function($scope){
        $scope.num = 30;
        $scope.AddValue = function () {
            var addData = angular.bind(this, function (a, b) {return a + b;});
            $scope.Add = addData(5, $scope.num);
        }
        $scope.AddValue();
    }]);
</script>


问:
How to export dynamoDB table's entire records to CSV from aws console?
I am new to AWS, just working around dynamo DB for first time..

I have a table in dynamoDB with close to 100,000 records in it.
I want to export these records to CSV file.

I have tried all possible options in aws console, found that we can only export 100 records at a time, which will not scale well to 100k records,

I did some search around it, exporting to S3 is doable for larger record set.

But I cannot opt that way because of S3 & data pipeline expenses.

Please suggest any work-around (if any).

答:
This application will export the content of a DynamoDB table into CSV (comma-separated values) output. All you need to do is update config.json with your AWS credentials and region.

AWS DynamoDBtoCSV


问:
jsPlumb: fat arrow?
I want a fat arrow in jsPlumb with a pretty tip.

This is what I want:

This is what I get:

How can I change the settings?

Here's what I currently use:

```<code>PaintStyle: { stroke: "#f00", strokeWidth: 20 },
connector: ["Straight"],
connectorOverlays:[["Arrow", { location:1, width:70, length:70 } ]]
</code>```

I have been using arrows in SVG before. There, I could simply change the SVG code of the head to be moved forward so that the end of the line (the coordinates of the line end point) is inside the arrowhead triangle. I don't seem to be able to do this in jsPlumb.

I see it is difficult to convey the problem.

Here's a next try:

答:
This has no solution till date I guess by looking at github, It's still an open issue. Issue was opened in 2014.

One solution would be hacking library itself to add margin or padding kind of property to Arrow Object.

update:

I tried to figure out in library itself. See this below image where it's doing some math calculations. If you're good at it, tweak it and you're done!

And extents are being user here:

Update2:

Try Location array like below: (demo: http://jsfiddle.net/crerhawn/)

```<code>["Arrow", { location:[0.5,0.5], width:70, length:70 } ]
</code>```

Title: jsPlumb: fat arrow?

Body:
I want a fat arrow in jsPlumb with a pretty tip.

This is what I want:

This is what I get:

How can I change the settings?

Here's what I currently use:

PaintStyle: { stroke: "#f00", strokeWidth: 20 },
connector: ["Straight"],
connectorOverlays:[["Arrow", { location:1, width:70, length:70 } ]]

I have been using arrows in SVG before. There, I could simply change the SVG code of the head to be moved forward so that the end of the line (the coordinates of the line end point) is inside the arrowhead triangle. I don't seem to be able to do this in jsPlumb.

I see it is difficult to convey the problem.

Here's a next try:

Body:
This has no solution till date I guess by looking at github, It's still an open issue. Issue was opened in 2014.

One solution would be hacking library itself to add margin or padding kind of property to Arrow Object.

update:

I tried to figure out in library itself. See this below image where it's doing some math calculations. If you're good at it, tweak it and you're done!

And extents are being user here:

Update2:

Try Location array like below: (demo: http://jsfiddle.net/crerhawn/)

["Arrow", { location:[0.5,0.5], width:70, length:70 } ]


问:
Loop Through jQuery Elements Separately and Animate on Page Scroll
I've managed to get a simple stat counter running up from zero to a given value where it's only activated on page scroll, but it's not exactly as I was aiming for.

The problem is, all of the ".counter" elements are firing off at the same time as soon as the first element comes into view, as opposed to waiting until each individual element is actually visible on screen. So as soon at the window hits the containing div, all of them go off at once.

I'd like to have each individual .counter wait until it's fully visible before it fires off.

Here's what I've got so far:

HTML:

```<code><p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<div id="stats">
  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="400"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="350"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="12"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="97"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="899"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="4"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="0"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="6"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>
</div>
</code>```

And the jQuery...

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

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      $('.counter').each(function() {
        var $this = $(this);
        jQuery({
          Counter: 0
        }).animate({
          Counter: $this.attr('count')
        }, {
          duration: 3000,
          step: function() {
            $this.text(Math.ceil(this.Counter));
          }
        });
        $this.removeClass('counter').addClass('counted');
      });
    }
  }
})(jQuery);
</code>```

Fiddle here:
https://jsfiddle.net/ahfL4jxr/11/

Thanks in advance.

答:
Ah, you were so close.

You're targeting all of the elements instead of the one in the argument you pushed through.

In your animateCounter() function, $('.counter') should change to $(elem)

https://jsfiddle.net/7xsv33hf/

Body:
I've managed to get a simple stat counter running up from zero to a given value where it's only activated on page scroll, but it's not exactly as I was aiming for.

The problem is, all of the ".counter" elements are firing off at the same time as soon as the first element comes into view, as opposed to waiting until each individual element is actually visible on screen. So as soon at the window hits the containing div, all of them go off at once.

I'd like to have each individual .counter wait until it's fully visible before it fires off.

Here's what I've got so far:

HTML:

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

And the jQuery...

    (function($) {

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      $('.counter').each(function() {
        var $this = $(this);
        jQuery({
          Counter: 0
        }).animate({
          Counter: $this.attr('count')
        }, {
          duration: 3000,
          step: function() {
            $this.text(Math.ceil(this.Counter));
          }
        });
        $this.removeClass('counter').addClass('counted');
      });
    }
  }
})(jQuery);

Fiddle here:
https://jsfiddle.net/ahfL4jxr/11/

Thanks in advance.


问:
what is the SQL query to get all dates list from specific date to today date
I need to get all dates from 01-01-2016 to todays date.

Example:

```<code>01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017
</code>```

Any help would be appreciated.

答:
This is what i have understand from your requirement. Check below query.

=========================================

declare @date datetime='2016-01-01'

declare @tbl table
(alldate date)

while (@date<=GETDATE())
begin
insert into @tbl
select @date

set @date=@date+1

if @date=GETDATE()
begin
break;
end
end

select  * from @tbl

Body:
I need to get all dates from 01-01-2016 to todays date.

Example:

01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017

Any help would be appreciated.


问:
How to make Pro*C cope with #warning directives?
When I try to precompile a *.pc file that contains a #warning directive I recieve the following error:

PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).

Can I somehow convince Pro*C to ignore the thing if it doesn't know what to do with it? I can't remove the #warning directive as it's used in a header file that I can't change and must include.

答:
Modify /usr/include/standards.h.

Delete the line #warning  The -qdfp option is required to process DFP code in headers.      The proc does not support the #warning，just #else #if etc.

OwnerDisplayName: Maximilian


问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答: You haven't passed any parameters to your function day_of_year.</p>

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}


问:
Angular, TypeError: Cannot read property 'toLowerCase' of undefined
i'm trying to make a custom filter pipe by following this link, but i got error that said Angular, TypeError: Cannot read property 'toLowerCase' of undefined. I already imported the pipe to app.module.ts and also declared it in declaration. Can anyone help me with this error?

<form id="filter">
  <input type="text" class="form-control" name="term" [(ngModel)]="term" placeholder="filter by name" />
</form>

  {{product.prdName}}
  {{product.prdCat}}
  {{product.prdSup}}

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@Pipe({
  name: 'filter'
})

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

    return prdName.filter(function(Product) {
      return Product.name.toLowerCase().includes(term.toLowerCase());
    })</code>```

答:
try like this :</p>

```<code>transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(Product) {
        return Product.prdName.toLowerCase().includes(term.toLowerCase());
    })
}
</code>```

Body:
i'm trying to make a custom filter pipe by following this link, but i got error that said Angular, TypeError: Cannot read property 'toLowerCase' of undefined. I already imported the pipe to app.module.ts and also declared it in declaration. Can anyone help me with this error?

<form id="filter">
  <input type="text" class="form-control" name="term" [(ngModel)]="term" placeholder="filter by name" />
</form>

  {{product.prdName}}
  {{product.prdCat}}
  {{product.prdSup}}

@Pipe({
  name: 'filter'
})

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

    return prdName.filter(function(Product) {
      return Product.name.toLowerCase().includes(term.toLowerCase());
    })

Body:
try like this :

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

    return items.filter(function(Product) {
        return Product.prdName.toLowerCase().includes(term.toLowerCase());
    })
}


问:
How to put an image to the right of a radio button, Android
I am trying to make a radio button list of 4 items. Each item needs to have text to it's right, but also an image to the right of the text. The image is not the radio button itself, it's an image describing the option.
I have no luck so far, the designer seems to be useless to put things in place. You have to know how to code this in XML.
My XML looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:weightSum="1" android:baselineAligned="true" android:orientation="horizontal">
    <RadioGroup android:layout_weight="0.50" android:layout_height="wrap_content" android:id="@+id/radioGroup1" android:layout_width="0dp">
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:checked="true" android:text="A" android:id="@+id/radio0"></RadioButton>
        <ImageView android:layout_toRightOf="@id/radio0" android:layout_height="wrap_content" android:src="@drawable/A2" android:layout_width="wrap_content" android:id="@+id/imageView1"></ImageView>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="B" android:id="@+id/radio1"></RadioButton>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="C" android:id="@+id/radio2"></RadioButton>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="D" android:id="@+id/radio3"></RadioButton>
    </RadioGroup>

</LinearLayout>
</code>```

Here I am trying to put one image to the right of the first radio button, with no success.
How do I put images to the right of the radio buttons?

答:
```<code><RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/ic_launcher"/>
</code>```

RadioButton itself contains a TextView as default.. so you can do all the operations those are present for any TextView.

BONUS: If you want to change the circular dot that shows check status, just update the android:button tag to refer your own drawable.

Body:
I am trying to make a radio button list of 4 items. Each item needs to have text to it's right, but also an image to the right of the text. The image is not the radio button itself, it's an image describing the option.
I have no luck so far, the designer seems to be useless to put things in place. You have to know how to code this in XML.
My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:weightSum="1" android:baselineAligned="true" android:orientation="horizontal">
    <RadioGroup android:layout_weight="0.50" android:layout_height="wrap_content" android:id="@+id/radioGroup1" android:layout_width="0dp">
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:checked="true" android:text="A" android:id="@+id/radio0"></RadioButton>
        <ImageView android:layout_toRightOf="@id/radio0" android:layout_height="wrap_content" android:src="@drawable/A2" android:layout_width="wrap_content" android:id="@+id/imageView1"></ImageView>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="B" android:id="@+id/radio1"></RadioButton>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="C" android:id="@+id/radio2"></RadioButton>
        <RadioButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="D" android:id="@+id/radio3"></RadioButton>
    </RadioGroup>

</LinearLayout>

Here I am trying to put one image to the right of the first radio button, with no success.
How do I put images to the right of the radio buttons?

Body:
<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/ic_launcher"/>

RadioButton itself contains a TextView as default.. so you can do all the operations those are present for any TextView.

BONUS: If you want to change the circular dot that shows check status, just update the android:button tag to refer your own drawable.


问:
Why does this "Slow network detected..." log appear in Chrome?
I noticed this info log began to appear in Google Chrome Dev (Version 55.0.2883.18 dev) and I can't imagine why.

Slow network is detected. Fallback font will be used while loading: http://font-path.extension`

It appears on all websites that use font-face, even on local pages and Chrome extensions.

答:
Goto chrome://flags/#enable-webfonts-intervention-v2 and set it to disabled

It’s due to a bug in Chrome with their latest API for ‘network speed’. Hope it will be fixed in the next version


问:
Jquery Fullcalendar (arshaw's) pass selected month
hey i'm using the great full calendar,
i want to pass to a aspx page the selected month in the calendar
my code is:

```<code>$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
**var MONTH = m;**
//alert(new Date(y, m, 1).toString());

var calendar = $('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    selectable: false,
    selectHelper: true,
    select: function (start, end, allDay) {
        var title = prompt('Event Title:');
        if (title) {
            calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allDay: allDay
                    },
                    true // make the event "stick"
                );
    }

        calendar.fullCalendar('unselect');
    },
    editable: false,
    events: 'eventsList.aspx?d=' + MONTH // **I would like to send the MONTH HERE**
});
</code>```

any ideas?

答:
I needed the same thing as you did and so I did it like the following...

I put a textbox(with id="start_date") to my aspx page

```<code><input type="text" class="textbox" size="19" name="start_date" id="start_date">
</code>```

Then during select function, I sent the selected day, month(+1 is needed because fullCalendar start counting from 0) and year to my textbox with javascript(just above 'unselect')

```<code>document.getElementById('start_date').value = start.getDate() + ' - ' + (start.getMonth()+1) + ' - ' + start.getFullYear();

calendar.fullCalendar('unselect');
</code>```

Body:
hey i'm using the great full calendar,
i want to pass to a aspx page the selected month in the calendar
my code is:

$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
**var MONTH = m;**
//alert(new Date(y, m, 1).toString());

var calendar = $('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    selectable: false,
    selectHelper: true,
    select: function (start, end, allDay) {
        var title = prompt('Event Title:');
        if (title) {
            calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allDay: allDay
                    },
                    true // make the event "stick"
                );
    }

        calendar.fullCalendar('unselect');
    },
    editable: false,
    events: 'eventsList.aspx?d=' + MONTH // **I would like to send the MONTH HERE**
});

any ideas?

Body:
I needed the same thing as you did and so I did it like the following...

I put a textbox(with id="start_date") to my aspx page

<input type="text" class="textbox" size="19" name="start_date" id="start_date">

Then during select function, I sent the selected day, month(+1 is needed because fullCalendar start counting from 0) and year to my textbox with javascript(just above 'unselect')

document.getElementById('start_date').value = start.getDate() + ' - ' + (start.getMonth()+1) + ' - ' + start.getFullYear();

calendar.fullCalendar('unselect');


问:
parSapply with 2 arguments
Is there any posibility to pass 2 arguments throught parSapply parallel function, using library parallel in R?

I have tried with:

```<code>var2 <- c(10,20,30)
myfunction<-function(var1,var2){
mean(rnorm(1000,var1,var2))
}
parSapply(cl,1:10,FUN=myfunction,var2=var2)
</code>```

Thanks!
Jesús

答:
That has to work... Have you initialized cl and var2?</p>

```<code>myfunction<-function(var1,var2){
mean(rnorm(1000,var1,var2))
}
n_cores <- 2 # number of cores for parallel processing
cl <- makeCluster(n_cores)
var2 <- 3
parSapply(cl,1:10,FUN=myfunction,var2=var2)
stopCluster(cl)
</code>```

Title: parSapply with 2 arguments

Body:
Is there any posibility to pass 2 arguments throught parSapply parallel function, using library parallel in R?

I have tried with:

var2 <- c(10,20,30)
myfunction<-function(var1,var2){
mean(rnorm(1000,var1,var2))
}
parSapply(cl,1:10,FUN=myfunction,var2=var2)

Thanks!
Jesús

Body:
That has to work... Have you initialized cl and var2?

myfunction<-function(var1,var2){
mean(rnorm(1000,var1,var2))
}
n_cores <- 2 # number of cores for parallel processing
cl <- makeCluster(n_cores)
var2 <- 3
parSapply(cl,1:10,FUN=myfunction,var2=var2)
stopCluster(cl)


问:
Should BufferedReader and InputStreamReader be closed explicitly?
I want to read the content of a InputStream into a String:

```<code>private String readToString(InputStream stream) {
    return new BufferedReader(new InputStreamReader(stream))
            .lines().collect(Collectors.joining("\n"));
}
</code>```

The stream comes from java.lang.Process.

Question: Do I have to explicitly close any of the InputStream, InputStreamReader or BufferedReader in this case?

Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!

答:
You only need to close the outer wrapper, but don't do that explicitly either way - there is try-with-resource that will make your life easier:

```<code>public String readToString(InputStream stream) {

    try (InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader br = new BufferedReader(reader)) {

        return br.lines().collect(Collectors.joining("\n"));

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
</code>```

There is also a much easier way to do that and way more clear:

```<code>Files.readAllLines(YourPath)
</code>```

Body:
I want to read the content of a InputStream into a String:

private String readToString(InputStream stream) {
    return new BufferedReader(new InputStreamReader(stream))
            .lines().collect(Collectors.joining("\n"));
}

The stream comes from java.lang.Process.

Question: Do I have to explicitly close any of the InputStream, InputStreamReader or BufferedReader in this case?

Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!

Body:
You only need to close the outer wrapper, but don't do that explicitly either way - there is try-with-resource that will make your life easier:

public String readToString(InputStream stream) {

    try (InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader br = new BufferedReader(reader)) {

        return br.lines().collect(Collectors.joining("\n"));

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

There is also a much easier way to do that and way more clear:

Files.readAllLines(YourPath)


问:
List distinct names Big Query
I have the following table in Big Query:

```<code>|event  |count
|event1 |1
|event2 |2
|event1 |2
|event2 |1
|event3 |4
|event1 |3
|event3 |5
|event4 |5
|event5 |4
|event1 |3
|event6 |5
|event4 |5
</code>```

That contains 6 different events:

```<code>COUNT(DISTINCT event) AS Dist_event_Count = 6
</code>```

Now I want to list the different events. What query should I do to obtain the following output?

```<code>|event1
|event2
|event3
|event4
|event5
|event6
</code>```

答:
SELECT DISTINCT event FROM event_dataset.event_dataLIMIT 1000;

     With standard SQL, you would use backticks  event_dataset.event_data

Title: List distinct names Big Query

Body:
I have the following table in Big Query:

|event  |count
|event1 |1
|event2 |2
|event1 |2
|event2 |1
|event3 |4
|event1 |3
|event3 |5
|event4 |5
|event5 |4
|event1 |3
|event6 |5
|event4 |5

That contains 6 different events:

COUNT(DISTINCT event) AS Dist_event_Count = 6

Now I want to list the different events. What query should I do to obtain the following output?

|event1
|event2
|event3
|event4
|event5
|event6


问:
Add item to a specific column in ListView Adapter
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

```<code>public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}
</code>```

Here is what I tried but I got an error and no idea what to do next :

```<code> String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
</code>```

Error:

```<code>'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'
</code>```

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.

答:
As stated in earlier answers by @jibrahim:

You are trying to add String type into List vanzatorProduseList. You can add only VanzatorProduse type into vanzatorProduseList list. So, the cause of the problem is:

```<code>String num = elegantNumberButton.getNumber();
vanzatorProduseList.add(num);
</code>```

You need to do something like this Create Object of your Custom class and assign value to that:

```<code> String num = elegantNumberButton.getNumber();
    VanzatorProduse numVanProObject = new VanzatorProduse();
    numVanProObject .setNumber(num );
    vanzatorProduseList.add(numVanProObject );
</code>```

But your custom call should have method to cater this type issue

Edit: Do not forget to call notifyDataSetChanged() method to refresh the list

Body:
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}

Here is what I tried but I got an error and no idea what to do next :

 String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);

Error:

'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.

Body:
As stated in earlier answers by @jibrahim:

You are trying to add String type into List vanzatorProduseList. You can add only VanzatorProduse type into vanzatorProduseList list. So, the cause of the problem is:

String num = elegantNumberButton.getNumber();
vanzatorProduseList.add(num);

You need to do something like this Create Object of your Custom class and assign value to that:

 String num = elegantNumberButton.getNumber();
    VanzatorProduse numVanProObject = new VanzatorProduse();
    numVanProObject .setNumber(num );
    vanzatorProduseList.add(numVanProObject );

But your custom call should have method to cater this type issue

Edit: Do not forget to call notifyDataSetChanged() method to refresh the list


问:
xslt timezone conversion with daylight saving
I am working with xslt and using the fn:current-dateTime( ) to get the current date time (https://www.w3.org/TR/xpath-functions/#func-current-dateTime). The time returned is in UTC. I need to convert this to PST. I see that the fn:adjust-dateTime-to-timezone (http://www.xqueryfunctions.com/xq/fn_adjust-datetime-to-timezone.html) can be used to perform the timezone conversion. But i see that this function accepts the timeZone argument in the form of offset, i.e -PT8H for Pacific timezone while it is -PT5H for US Eastern Standard Time. When timezone is passed in terms of offset, its subject to modifications when Daylight Savings Time (DST) starts and ends right? Is there a better way for performing timezone conversion in xslt, a method that requires no modification periodically? or is there a recommendation when using fn:adjust-dateTime-to-timezone to handle this better?</p>

答:
The XPath functions for manipulating timezone offsets work entirely in terms of numeric (duration) offsets, e.g UTC -5 hours or UTC +10 hours. They have no knowledge of civil timezone names or of daylight savings adjustments.

The one exception is the format-date[Time] function, where the fifth argument can be used to force conversion to the local timezone of a particular place, for example "America/New_York" - but it's somewhat implementation-defined whether such names are recognized. From the spec:

If the $place argument is supplied in the form of an IANA timezone
  name that is recognized by the implementation, then the date or time
  being formatted is adjusted to the timezone offset applicable in that
  timezone. For example, if the xs:dateTime value 2010-02-15T12:00:00Z
  is formatted with the $place argument set to America/New_York, then
  the output will be as if the value 2010-02-15T07:00:00-05:00 had been
  supplied. This adjustment takes daylight savings time into account
  where possible; if the date in question falls during daylight savings
  time in New York, then it is adjusted to timezone offset -PT4H rather
  than -PT5H. Adjustment using daylight savings time is only possible
  where the value includes a date, and where the date is within the
  range covered by the timezone database.


问:
How to loop through cookie's lengths that starts with a specific word?
I have used this method on PHP in the past, but cant figure out how to do it in javascript.

Basically I want to loop through a list of cookie that starts with the word "order" each cookie order contains the word "order" plus a unique number to it. the unique number is unknown which is why i need a loop to find out a specific "order".

So the idea is i need to some how check if word "order" exist in a cookie once I find out how many then I can loop that many times.

This is what I have in PHP I would need something like this in javascript.

```<code>foreach ($_COOKIE as $name=>$value){
    if(strpos($name, 'order') !== false){
    //do something amazing!!!!
    }
}
</code>```

答:
var x = document.cookie.split(';'); // your array of cookies

x.foreach(item => {
//to make sure that your item contains "cookie"
if (item.indexOf('cookie')>-1){
//do your computation
}})
```

Body:
I have used this method on PHP in the past, but cant figure out how to do it in javascript.

Basically I want to loop through a list of cookie that starts with the word "order" each cookie order contains the word "order" plus a unique number to it. the unique number is unknown which is why i need a loop to find out a specific "order".

So the idea is i need to some how check if word "order" exist in a cookie once I find out how many then I can loop that many times.

This is what I have in PHP I would need something like this in javascript.

foreach ($_COOKIE as $name=>$value){
    if(strpos($name, 'order') !== false){
    //do something amazing!!!!
    }
}


问:
requestPermissions prompt not showing
I have an activity that extends AppCompatActivity. For this activity to run I need to grant the app with ACCESS_COARSE_LOCATION and WRITE_EXTERNAL_STORAGE permissions. Everything was working well until I updated to Android Studio 3.0.

Now, the prompt for requesting WRITE_EXTERNAL_STORAGE permissions is not showing, and the function

```<code>public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults)
</code>```

is returning -1 at grantResults without even asking.

This behavior is not happening if I request the permission ACCESS_COARSE_LOCATION, which works as it should. Below, the code invoking both checks:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect beacons.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                    }
                });

                builder.show();
            }
        }
</code>```

And the other:

```<code>        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs sd access");
                builder.setMessage("Please grant sd access so this app can save files.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });

                builder.show();
            }
        }
</code>```

The corresponding section in my manifest looks like this:

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

I've read many things, but this is pretty strange, when some type of permissions are showing up the request dialog, while others aren't.
By the way, there is no SD card in the device (always used internal storage), but that was never a problem.

Both my targetSdkVersion and compileSdkVersion are 26.

EDIT

Other relevant permissions, such as READ_EXTERNAL_STORAGE, are also working correctly. It's just an issue with the write permission.
Tested on two android devices and emulator

Complete onCreate Method:

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

    setContentView(R.layout.activity_device_discovery);

    context = this;
    wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    intent = getIntent();

    if(intent.getBooleanExtra("LOCAL_NETWORK", true) == true){
        ipAddress = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        port = DEFAULT_LIGHT_PORT;
    }
    else{
         ipAddress = intent.getStringExtra("TRACK_IP");
         port = intent.getIntExtra("TRACK_PORT", DEFAULT_GATEWAY_PORT);
    }

    font = Typeface.createFromAsset(MainActivity.mainActivity.getAssets(), "RepRg.ttf");
    mHandler = new Handler();

    deviceArrayList = new ArrayList<>();
    devicesBufferList = new ArrayList<>();

    lightListAdapter = new LightListAdapter(this, deviceArrayList, intent);

    discoveredListView = (ListView) findViewById(R.id.paired_devices);
    discoveredListView.setAdapter(lightListAdapter);

    listAllCheckBox = (CheckBox) findViewById(R.id.listAllCheckBox);
    refreshButton = (ImageButton) findViewById(R.id.refreshButton);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs sd access");
            builder.setMessage("Please grant sd access so this app can save files.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
            });

            builder.show();
        }
    }

    listAllCheckBox.setTypeface(font);
    listAllCheckBox.setTextSize(18);
    listAllCheckBox.setTextColor(Color.parseColor("#202020"));
    listAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            lightListAdapter.clear();
            processDeviceListing();
        }
    });

    refreshButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    refreshButton.setImageResource(R.drawable.refresh_down);
                    break;
                case MotionEvent.ACTION_UP:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    refreshDevicesList();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    break;
            }
            return false;
        }
    });

}
</code>```

Thanks in advance.

答:
Turns out that the issue is due to the new version of HockeyApp. HockeySDK is integrated in my application. Now, since version 5.0.0, the docs say:

To be ready for Android O, HockeySDK-Android now limits the
  WRITE_EXTERNAL_STORAGE permission with the maxSdkVersion filter. In
  some use cases, e.g. where an app contains a dependency that requires
  this permission, maxSdkVersion makes it impossible for those
  dependencies to grant or request the permission. The solution for
  those cases is to declare the tools:node="replace" manifest merging
  strategy later in the dependency tree

Thus, after adding tools:node="replace" to the WRITE permission in the manifest, the problem is solved.

```<code>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>
</code>```

Source here

I hope this is useful for somebody else

Title: requestPermissions prompt not showing

Body:
I have an activity that extends AppCompatActivity. For this activity to run I need to grant the app with ACCESS_COARSE_LOCATION and WRITE_EXTERNAL_STORAGE permissions. Everything was working well until I updated to Android Studio 3.0.

Now, the prompt for requesting WRITE_EXTERNAL_STORAGE permissions is not showing, and the function

public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults)

is returning -1 at grantResults without even asking.

This behavior is not happening if I request the permission ACCESS_COARSE_LOCATION, which works as it should. Below, the code invoking both checks:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect beacons.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                    }
                });

                builder.show();
            }
        }

And the other:

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs sd access");
                builder.setMessage("Please grant sd access so this app can save files.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });

                builder.show();
            }
        }

The corresponding section in my manifest looks like this:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I've read many things, but this is pretty strange, when some type of permissions are showing up the request dialog, while others aren't.
By the way, there is no SD card in the device (always used internal storage), but that was never a problem.

Both my targetSdkVersion and compileSdkVersion are 26.

EDIT

Other relevant permissions, such as READ_EXTERNAL_STORAGE, are also working correctly. It's just an issue with the write permission.
Tested on two android devices and emulator

Complete onCreate Method:

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

    setContentView(R.layout.activity_device_discovery);

    context = this;
    wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    intent = getIntent();

    if(intent.getBooleanExtra("LOCAL_NETWORK", true) == true){
        ipAddress = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        port = DEFAULT_LIGHT_PORT;
    }
    else{
         ipAddress = intent.getStringExtra("TRACK_IP");
         port = intent.getIntExtra("TRACK_PORT", DEFAULT_GATEWAY_PORT);
    }

    font = Typeface.createFromAsset(MainActivity.mainActivity.getAssets(), "RepRg.ttf");
    mHandler = new Handler();

    deviceArrayList = new ArrayList<>();
    devicesBufferList = new ArrayList<>();

    lightListAdapter = new LightListAdapter(this, deviceArrayList, intent);

    discoveredListView = (ListView) findViewById(R.id.paired_devices);
    discoveredListView.setAdapter(lightListAdapter);

    listAllCheckBox = (CheckBox) findViewById(R.id.listAllCheckBox);
    refreshButton = (ImageButton) findViewById(R.id.refreshButton);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs sd access");
            builder.setMessage("Please grant sd access so this app can save files.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
            });

            builder.show();
        }
    }

    listAllCheckBox.setTypeface(font);
    listAllCheckBox.setTextSize(18);
    listAllCheckBox.setTextColor(Color.parseColor("#202020"));
    listAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            lightListAdapter.clear();
            processDeviceListing();
        }
    });

    refreshButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    refreshButton.setImageResource(R.drawable.refresh_down);
                    break;
                case MotionEvent.ACTION_UP:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    refreshDevicesList();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    break;
            }
            return false;
        }
    });

}

Thanks in advance.

Body:
Turns out that the issue is due to the new version of HockeyApp. HockeySDK is integrated in my application. Now, since version 5.0.0, the docs say:

To be ready for Android O, HockeySDK-Android now limits the
  WRITE_EXTERNAL_STORAGE permission with the maxSdkVersion filter. In
  some use cases, e.g. where an app contains a dependency that requires
  this permission, maxSdkVersion makes it impossible for those
  dependencies to grant or request the permission. The solution for
  those cases is to declare the tools:node="replace" manifest merging
  strategy later in the dependency tree

Thus, after adding tools:node="replace" to the WRITE permission in the manifest, the problem is solved.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>

Source here

I hope this is useful for somebody else


问:
Why is the result of "SELECT ISNULL(LEFT(NULL, 8), '1234567890')" returned as '1' instead of '1234567890'?
I have this query

```<code>SELECT ISNULL(LEFT(NULL, 8), '1234567890')
</code>```

The result I got is '1' instead of '1234567890'. What am I missing?

I'm using SQL Server 2014.

答:
To limit the length of the result to 8 characters you need

```<code>SELECT ISNULL(cast(NULL as varchar(8)), '1234567890') ;
</code>```

datatype of ISNULL result is inferred using the first argument.

Body:
I have this query

SELECT ISNULL(LEFT(NULL, 8), '1234567890')

The result I got is '1' instead of '1234567890'. What am I missing?

I'm using SQL Server 2014.

Body:
To limit the length of the result to 8 characters you need

SELECT ISNULL(cast(NULL as varchar(8)), '1234567890') ;

datatype of ISNULL result is inferred using the first argument.


问:
Visual Studio Team Services (VSTS): write release information to file?
I've created a release definition in VSTS. After I deploy my application to the app service, I want to have the information about the release shown in my application. My application currently reads a file releaseinfo.json from the app_data folder which needs to be filled during the release process in VSTS.

Does anybody know how to get this information (like the release number and description) into the file from VSTS? Or is there another way to get this info into my application?

答:
You can get all the release related info from the environment variables. You can read it in a powershell/bash task and write it back in the required format

See the variables documentation for more info


问:
Google Analytics not loading in Macbook
When I try to login to Google Analytics from MAC, the page doesn't load. It is showing a blank page. When I open the Analytics same account on another desktop (DELL, HP) it is opening fine.

答:
It could be your adblock or your browser or if have activated JavaScript or not.

Have you try to access the website from an other browser (Firefox, Chrome, Opera, ...) ?

Have you try to deactivate Adblock and reload the page ? Once it happens to me, because the add-on was updated and I could not reach analytics.google.com anymore.

Javascript also must be activated on your browser to make it work.

Have a nice day

A.

Title: Google Analytics not loading in Macbook


问:
entity framework does not map more than one list in model C#
I have a class "Project" that hat two lists one for "Employee" and one for "tool", when i build my project with only one of the lists the database updates with corrrect relation, if add the second list to the class entity framework can not figureout how to create the relation.

```<code> public class Project
{
    public Guid Id { get; set; }
    public List<Employee> RequiredEmployees {get;set;}
    public List<Tools> RequiredTools {get;set;}
}

Public class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Project Project { get; set; }
    public Guid ProjectId { get; set; }
}
</code>```

I get the error "There are no primary or candidate keys in the referenced table"
i hve tryed to map in ModelBuilder without success

```<code> modelBuilder.Entity<Employee>()
    .HasRequired<Project>(s => s.Project)
    .WithMany(g => g.Employee)
    .HasForeignKey<Guid>(s => s.ProjectId);
</code>```

any ideas ?

答:
To be sure we would need to see your Tools class, but I think that the problem is that Entity Framework can't find a property to use as Primary Key in it.

The Entity Framework convention establishes that the Primary Key of a class is named Id or <ClassName>Id (in this case ToolsId). If you want a property with a name different from this ones to be the PK, you have to specify it explicitly, with the [Key] attribute or with the Fluent API.

Body:
I have a class "Project" that hat two lists one for "Employee" and one for "tool", when i build my project with only one of the lists the database updates with corrrect relation, if add the second list to the class entity framework can not figureout how to create the relation.

 public class Project
{
    public Guid Id { get; set; }
    public List<Employee> RequiredEmployees {get;set;}
    public List<Tools> RequiredTools {get;set;}
}

Public class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Project Project { get; set; }
    public Guid ProjectId { get; set; }
}

I get the error "There are no primary or candidate keys in the referenced table"
i hve tryed to map in ModelBuilder without success

 modelBuilder.Entity<Employee>()
    .HasRequired<Project>(s => s.Project)
    .WithMany(g => g.Employee)
    .HasForeignKey<Guid>(s => s.ProjectId);

any ideas ?