问:
Verifying firebase custom token to get token ID fails when using jsonwebtoken
On the backend a custom token is generated via firebase's admin SDK thusly:

```<code>router.use('/get-token', (req, res) => {
    var uid = "big-secret";
    admin.auth().createCustomToken(uid)
      .then(function(customToken) {
        res.json({
          instanceID: customToken
        });
      })
      .catch(function(error) {
        console.log("Error creating custom token:", error);
    });
});
</code>```

The client frontend app then picks up the customToken and with it makes a request back to the backend to verify:

```<code>const fbPrivateKey = serviceAccount.private_key;
const key = new NodeRSA(fbPrivateKey).exportKey('pkcs8-public-pem');
router.get('/verifyIdToken', cors(), (req, res) => {
  jwt.verify(req.headers.authorization.split('Bearer ')[1], key, { algorithms: ['RS256'] }, function(err, decoded) {
    console.log('err', err);
    console.log('decoded', decoded);
  });
</code>```

This always errors with the message: JsonWebTokenError: invalid signature

Does this need signing? If anyone could explain this or has any pointers?

UPDATE:
When running req.headers.authorization.split('Bearer ')[1] through jwt.io is says that the signature is invalid, but then I enter my private key (key) and it validates.

Am I getting the method calls incorrect or passing the wrong arguments into jwt.verify() ?

答: It looks like you're calling verifyIdToken with a custom token. That's not going to work. verifyIdToken only accepts "ID tokens". To obtain an ID token from a custom token first call signInWithCustomToken(). Then call getToken() on the signed in user instance.

Body:
On the backend a custom token is generated via firebase's admin SDK thusly:

router.use('/get-token', (req, res) => {
    var uid = "big-secret";
    admin.auth().createCustomToken(uid)
      .then(function(customToken) {
        res.json({
          instanceID: customToken
        });
      })
      .catch(function(error) {
        console.log("Error creating custom token:", error);
    });
});

The client frontend app then picks up the customToken and with it makes a request back to the backend to verify:

const fbPrivateKey = serviceAccount.private_key;
const key = new NodeRSA(fbPrivateKey).exportKey('pkcs8-public-pem');
router.get('/verifyIdToken', cors(), (req, res) => {
  jwt.verify(req.headers.authorization.split('Bearer ')[1], key, { algorithms: ['RS256'] }, function(err, decoded) {
    console.log('err', err);
    console.log('decoded', decoded);
  });

This always errors with the message: JsonWebTokenError: invalid signature

Does this need signing? If anyone could explain this or has any pointers?

UPDATE:
When running req.headers.authorization.split('Bearer ')[1] through jwt.io is says that the signature is invalid, but then I enter my private key (key) and it validates.

Am I getting the method calls incorrect or passing the wrong arguments into jwt.verify() ?


来源: stackexchange

问:
Putting code in a text box (MS Access)
I am using a textbox for the header of my report, and based on what the user selects it will be "Baseline 8", "Baseline 9", etc. What I would like to do is have the text box coded so whatever number the user selects is entered into the text box. I managed to do it by using two text boxes, one just says "baseline" and the other text box says "=[Forms]![Navigation Form]![NavigationSubform]![Combo21]" and it will enter the correct value. But what I want to do is put it all in one box, and when I put "Baseline =[Forms]![Navigation Form]![NavigationSubform]![Combo21]" in the text box it doesn't work, it just leaves the code as the header when I generate the report. Is there something I'm not doing correctly?</p>

答:
First of all, when you state that a "textbox says", you really mean that "the Control Source property of the textbox equals."  For a textbox (and some other controls), the value that you see on the actual form IS the Control Source property.  I am not being picky for its own sake, rather it is important to recognize what value you are editing.

The Control Source property can essentially contain two types of values.  The first is without an equals sign and it indicates the name of a field from the form Record Source.  In that case, it binds the control to the field directly so that it automatically loads from the field and saves changes back to the field.

The second type of value always starts with =.  It is a VBA code expression and can include calls to functions and other VBA operators.  In your case, you want to concatenate (i.e. combine) two strings: one literal "Baseline" and one pulled from an access object [Forms]![Navigation Form]![NavigationSubform]![Combo21], so you need to use the string concatenation operator &.

```<code> ="Baseline " & [Forms]![Navigation Form]![NavigationSubform]![Combo21]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Putting code in a text box (MS Access)

Body:
First of all, when you state that a "textbox says", you really mean that "the Control Source property of the textbox equals."  For a textbox (and some other controls), the value that you see on the actual form IS the Control Source property.  I am not being picky for its own sake, rather it is important to recognize what value you are editing.

The Control Source property can essentially contain two types of values.  The first is without an equals sign and it indicates the name of a field from the form Record Source.  In that case, it binds the control to the field directly so that it automatically loads from the field and saves changes back to the field.

The second type of value always starts with =.  It is a VBA code expression and can include calls to functions and other VBA operators.  In your case, you want to concatenate (i.e. combine) two strings: one literal "Baseline" and one pulled from an access object [Forms]![Navigation Form]![NavigationSubform]![Combo21], so you need to use the string concatenation operator &.

 ="Baseline " & [Forms]![Navigation Form]![NavigationSubform]![Combo21]


问:
WPF DataGrid - retemplating cells causes bindings to not update
I have a DataGrid like so:

```<code><DataGrid ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Age}" CellStyle="{StaticResource EditableDataGridCellStyle}" />
    </DataGrid.Columns>
</DataGrid>
</code>```

I change the style of my DataGridCells with this code

```<code><Style x:Key="EditableDataGridCellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

However, when I edit the text of the TextBox, the DataGrid displays the new value, but the underlying Person object does not update his Age. When I get rid of the "EditableDataGridCellStyle" and edit the DataGridCell manually (by double-clicking), it works like I expect.

How can I make sure that an edit of the TextBox will have the same effect as editing a DataGrid cell (i.e., updating the bindings)?

答:
You should bind to the Age property and nothing else in your template for this to work as expected:

```<code><Style x:Key="EditableDataGridCellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <TextBox Text="{Binding Age}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

And yes, this unfortunately means that you need to define a different Style for each column. You probably better of using a DataGridTemplateColumn: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(v=vs.110).aspx.

Body:
I have a DataGrid like so:

<DataGrid ItemsSource="{Binding Persons}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Age}" CellStyle="{StaticResource EditableDataGridCellStyle}" />
    </DataGrid.Columns>
</DataGrid>

I change the style of my DataGridCells with this code

</Style>

However, when I edit the text of the TextBox, the DataGrid displays the new value, but the underlying Person object does not update his Age. When I get rid of the "EditableDataGridCellStyle" and edit the DataGridCell manually (by double-clicking), it works like I expect.

How can I make sure that an edit of the TextBox will have the same effect as editing a DataGrid cell (i.e., updating the bindings)?

Body:
You should bind to the Age property and nothing else in your template for this to work as expected:

<Style x:Key="EditableDataGridCellStyle" TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <TextBox Text="{Binding Age}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

And yes, this unfortunately means that you need to define a different Style for each column. You probably better of using a DataGridTemplateColumn: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(v=vs.110).aspx.


问:
protractor FOR loop using expectations
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

```<code>myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });
</code>```

答:
Your problem descrption is not clear. I'm assuming that location is list of elements. So i'm applying each() on set elements called 'location' . It will work perfectly.</p>

```<code>//replace location with myelement if it the correct one
location.each(function(ele,index){
        expect(ele.getText()).toEqual("something");
});
</code>```

Title: protractor FOR loop using expectations

Body:
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });

Body:
Your problem descrption is not clear. I'm assuming that location is list of elements. So i'm applying each() on set elements called 'location' . It will work perfectly.

//replace location with myelement if it the correct one
location.each(function(ele,index){
        expect(ele.getText()).toEqual("something");
});


问:
Distributed TensorFlow: Create a session in only one worker to print the results
I just need to print the values of some global variables assigned within training. After closing the 'MonitoredTrainingSession', I created a session in the chief worker only using:

```<code>    if FLAGS.task_index == 0:
        with tf.Session() as sess:
            print sess.run(some_variable)
</code>```

However I keep getting the error:

InvalidArgumentError (see above for traceback): Cannot assign a device to node 'save/RestoreV2_20': Could not satisfy explicit device specification '/job:ps/task:0/device:CPU:0' because no devices matching that specification are registered in this process; available devices: /job:localhost/replica:0/task:0/cpu:0

Any idea how to do that ?

答:
available devices: /job:localhost/replica:0/task:0/cpu:0

It suggest that you should use the server you created. Try passing server.target when creating the session.

```<code>with tf.Session(server.target) as sess:
    print sess.run(some_variable)
</code>```

Body:
I just need to print the values of some global variables assigned within training. After closing the 'MonitoredTrainingSession', I created a session in the chief worker only using:

    if FLAGS.task_index == 0:
        with tf.Session() as sess:
            print sess.run(some_variable)

However I keep getting the error:

InvalidArgumentError (see above for traceback): Cannot assign a device to node 'save/RestoreV2_20': Could not satisfy explicit device specification '/job:ps/task:0/device:CPU:0' because no devices matching that specification are registered in this process; available devices: /job:localhost/replica:0/task:0/cpu:0

Any idea how to do that ?

Body:
available devices: /job:localhost/replica:0/task:0/cpu:0

It suggest that you should use the server you created. Try passing server.target when creating the session.

with tf.Session(server.target) as sess:
    print sess.run(some_variable)


问:
Static Variables in WCF application hosted in IIS using NLOG
I'm confused by a recent change in the behavior of my WCF IIS application.  A week ago, I was able to make a request to my service to a simple "Health" function that incremented a static variable using Interlocked.Increment and returned it. Now, I always get '1' as a return value.

The code in that particular pathway hasn't changed:

```<code>[ServiceContract]
public interface IApi {
    [WebInvoke(
        Method = "GET",
        UriTemplate = "health",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    [OperationContract]
    int GetHealth();
}

static int HealthCount = 0;
public int GetHealth()
{
    return Interlocked.Increment(ref HealthCount);
}
</code>```

Possibly relevant web.config settings:

```<code><appSettings>
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"
</appSettings>
...
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
...
<modules runAllManagedModulesForAllRequests="true" />
</code>```

And in IIS, I've configured the AppPool to have a StartMode of AlwaysRunning.  But I did that after I discovered this issue and it makes no difference.

I have isolated the issue to NLog.  I have a static constructor:

```<code>    static Api()
    {
        Logger = LogManager.GetCurrentClassLogger();
        Logger.Log(LogLevel.Debug, "API Initialized.");
    }
</code>```

The degenerate, new behavior happens with the above static constructor, but not the below code:

```<code>    static Api()
    {
        Logger = LogManager.GetCurrentClassLogger();
    }
</code>```

In short, if I use the NLog Logger to log anything, it appears as if my AppDomain recycles on each request or that .NET is mysteriously determining that my class needs to be recompiled (https://stackoverflow.com/a/8919336/148051).  I have even created a Singleton and done all this stuff in the singleton and the behavior is the same.  As soon as I use the Logger, the static variables are clobbered.

Can anyone help me understand how to avoid this behavior?

答:
I discovered the answer.  I had NLOG writing the log file to the Assembly directory:

```<code>var logdir = SystemUtils.AssemblyDirectory(typeof(Api));
</code>```

Once I changed that to a different directory, problem solved.  So, apparently, how IIS works is to determine that the types in the app domain need to be recompiled if the application directory is written to.

There may be a way to configure IIS to ignore the log directory, but I was satisfied with moving it to a different location.

Body:
I'm confused by a recent change in the behavior of my WCF IIS application.  A week ago, I was able to make a request to my service to a simple "Health" function that incremented a static variable using Interlocked.Increment and returned it. Now, I always get '1' as a return value.

The code in that particular pathway hasn't changed:

[ServiceContract]
public interface IApi {
    [WebInvoke(
        Method = "GET",
        UriTemplate = "health",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    [OperationContract]
    int GetHealth();
}

static int HealthCount = 0;
public int GetHealth()
{
    return Interlocked.Increment(ref HealthCount);
}

Possibly relevant web.config settings:

<appSettings>
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"
</appSettings>
...
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
...
<modules runAllManagedModulesForAllRequests="true" />

And in IIS, I've configured the AppPool to have a StartMode of AlwaysRunning.  But I did that after I discovered this issue and it makes no difference.

I have isolated the issue to NLog.  I have a static constructor:

    static Api()
    {
        Logger = LogManager.GetCurrentClassLogger();
        Logger.Log(LogLevel.Debug, "API Initialized.");
    }

The degenerate, new behavior happens with the above static constructor, but not the below code:

    static Api()
    {
        Logger = LogManager.GetCurrentClassLogger();
    }

In short, if I use the NLog Logger to log anything, it appears as if my AppDomain recycles on each request or that .NET is mysteriously determining that my class needs to be recompiled (https://stackoverflow.com/a/8919336/148051).  I have even created a Singleton and done all this stuff in the singleton and the behavior is the same.  As soon as I use the Logger, the static variables are clobbered.

Can anyone help me understand how to avoid this behavior?

Body:
I discovered the answer.  I had NLOG writing the log file to the Assembly directory:

var logdir = SystemUtils.AssemblyDirectory(typeof(Api));

Once I changed that to a different directory, problem solved.  So, apparently, how IIS works is to determine that the types in the app domain need to be recompiled if the application directory is written to.

There may be a way to configure IIS to ignore the log directory, but I was satisfied with moving it to a different location.


问:
correct way to add custom (deep) copying logic to a python class
i am implementing a python class that provides some nested data structure. i want to add support for copying through copy.copy() and deep copying through copy.deepcopy(), which, as the docs for the copy module describe, involves writing __copy__() and __deepcopy__ special methods.

i know how to teach my class to make a copy of itself, but i want to avoid going through __init__() on the new instance, since __init__() does some things that my copying logic does not want (or need) to do.

what i ended up with is this method, which works as intended:

```<code>def __copy__(self):
    cls = type(self)
    obj = cls.__new__(cls)
    # custom copying logic that populates obj goes here
    return obj
</code>```

my question is: is calling cls.__new__(cls) the right approach for a __copy__() implementation that wants to skip __init__() for the copy? or is there a more "pythonic" approach that i overlooked?

答:
I don't know if this is more pythonic, but you could use a flag.

```<code>from collections import Mapping
from copy import copy, deepcopy

class CustomDict(dict, Mapping):
    _run_setup = True

    def __init__(self, *args, **kwargs):
        self._dict = dict(*args, **kwargs)
        if args and isinstance(args[0], CustomDict):
            self._run_setup = args[0]._run_setup
        if self._run_setup:
            print("Doing some setup stuff")
        else:
            try:
                print("Avoiding some setup stuff")
            finally:
                self._run_setup = True

    def __getitem__(self, key):
        return self._dict[key]

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)

    def __copy__(self):
        self._run_setup = False
        try:
            copied_custom_dict = CustomDict(self)
        finally:
            self._run_setup = True
        return copied_custom_dict
</code>```

In the __init__ above, the conditional setup stuff is only done if _run_setup = True. The only way to avoid this is by calling CustomDict with the first parameter being an instance of itself with _run_setup = False. This way, it's easy to flip the setup switch in different methods.

The try...finally blocks look clunky to me, but it's a way to make sure every method starts and ends with _run_setup = True.

Body:
i am implementing a python class that provides some nested data structure. i want to add support for copying through copy.copy() and deep copying through copy.deepcopy(), which, as the docs for the copy module describe, involves writing __copy__() and __deepcopy__ special methods.

i know how to teach my class to make a copy of itself, but i want to avoid going through __init__() on the new instance, since __init__() does some things that my copying logic does not want (or need) to do.

what i ended up with is this method, which works as intended:

def __copy__(self):
    cls = type(self)
    obj = cls.__new__(cls)
    # custom copying logic that populates obj goes here
    return obj

my question is: is calling cls.__new__(cls) the right approach for a __copy__() implementation that wants to skip __init__() for the copy? or is there a more "pythonic" approach that i overlooked?

Body:
I don't know if this is more pythonic, but you could use a flag.

from collections import Mapping
from copy import copy, deepcopy

class CustomDict(dict, Mapping):
    _run_setup = True

    def __init__(self, *args, **kwargs):
        self._dict = dict(*args, **kwargs)
        if args and isinstance(args[0], CustomDict):
            self._run_setup = args[0]._run_setup
        if self._run_setup:
            print("Doing some setup stuff")
        else:
            try:
                print("Avoiding some setup stuff")
            finally:
                self._run_setup = True

    def __getitem__(self, key):
        return self._dict[key]

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)

    def __copy__(self):
        self._run_setup = False
        try:
            copied_custom_dict = CustomDict(self)
        finally:
            self._run_setup = True
        return copied_custom_dict

In the __init__ above, the conditional setup stuff is only done if _run_setup = True. The only way to avoid this is by calling CustomDict with the first parameter being an instance of itself with _run_setup = False. This way, it's easy to flip the setup switch in different methods.

The try...finally blocks look clunky to me, but it's a way to make sure every method starts and ends with _run_setup = True.


问:
How to create a new docker image from a running container on Amazon?
Here is my problem:

I have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container.

I see the id of the instance  on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon.

Any ideas?

Regards and thanks.

答:
Apart from the answer provided by @Ben Whaley, I personally suggest you to make use of Docker APIs. To use Docker APIs you need to configure the docker daemon port and the procedure is explained here configuring docker daemon port

Lets run a container using an base Ubuntu Image and create a folder inside the container:

```<code>#docker run -it ubuntu:14.04 /bin/bash
root@58246867493d:/#
root@58246867493d:/# cd /root
root@58246867493d:~# ls
root@58246867493d:~# mkdir TEST_DIR
root@58246867493d:~# exit
</code>```

Status of the exited container:

```<code># docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
58246867493d        ubuntu:14.04        "/bin/bash"         2 minutes ago       Exited (127) 57 seconds ago                       hungry_turing
</code>```

JSON file which is an input for committing a container:

```<code>#cat container_create.json
{
  "AttachStdin": true,
  "AttachStdout": true,
  "AttachStderr": true,
  "ExposedPorts": {
    "property1": {},
    "property2": {}
  },
  "Tty": true,
  "OpenStdin": true,
  "StdinOnce": true,
  "Cmd": null,
  "Image": "ubuntu:14.04",
  "Volumes": {
    "additionalProperties": {}
  },
  "Labels": {
    "property1": "string",
    "property2": "string"
  }
}
</code>```

API to commit a container

```<code># curl -X POST http://127.0.0.1:6000/commit?container=58246867493d\&repo=ubuntu\&tag=15.0 -d @container_create.json --header "Content-Type: application/json" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   593  100    81  100   512    175   1106 --:--:-- --:--:-- --:--:--  1108
{
  "Id": "sha256:acac1f3733b2240b01e335642d2867585e5933b18de2264315f9b07814de113a"
}
</code>```

The Id that is generated is the new Image Id which is build from committing a container.

Get docker Images

```<code># docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
**ubuntu              15.0                acac1f3733b2        10 seconds ago      188MB**
ubuntu              14.04               132b7427a3b4        10 hours ago        188MB
</code>```

Run the newly build Image to see the changes commited in the previous container.

```<code># docker run -it ubuntu:15.0 /bin/bash
root@3a48af5eaec9:/# cd /root/
root@3a48af5eaec9:~# ls
TEST_DIR
root@3a48af5eaec9:~# exit
</code>```

To build an image from Docker file, how to build an image using docker API

For more information on docker APIs, refer here.

ContentLicense: CC BY-SA 4.0

Body:
Apart from the answer provided by @Ben Whaley, I personally suggest you to make use of Docker APIs. To use Docker APIs you need to configure the docker daemon port and the procedure is explained here configuring docker daemon port

Lets run a container using an base Ubuntu Image and create a folder inside the container:

#docker run -it ubuntu:14.04 /bin/bash
root@58246867493d:/#
root@58246867493d:/# cd /root
root@58246867493d:~# ls
root@58246867493d:~# mkdir TEST_DIR
root@58246867493d:~# exit

Status of the exited container:

# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
58246867493d        ubuntu:14.04        "/bin/bash"         2 minutes ago       Exited (127) 57 seconds ago                       hungry_turing

JSON file which is an input for committing a container:

#cat container_create.json
{
  "AttachStdin": true,
  "AttachStdout": true,
  "AttachStderr": true,
  "ExposedPorts": {
    "property1": {},
    "property2": {}
  },
  "Tty": true,
  "OpenStdin": true,
  "StdinOnce": true,
  "Cmd": null,
  "Image": "ubuntu:14.04",
  "Volumes": {
    "additionalProperties": {}
  },
  "Labels": {
    "property1": "string",
    "property2": "string"
  }
}

API to commit a container

# curl -X POST http://127.0.0.1:6000/commit?container=58246867493d\&repo=ubuntu\&tag=15.0 -d @container_create.json --header "Content-Type: application/json" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   593  100    81  100   512    175   1106 --:--:-- --:--:-- --:--:--  1108
{
  "Id": "sha256:acac1f3733b2240b01e335642d2867585e5933b18de2264315f9b07814de113a"
}

The Id that is generated is the new Image Id which is build from committing a container.

Get docker Images

# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
**ubuntu              15.0                acac1f3733b2        10 seconds ago      188MB**
ubuntu              14.04               132b7427a3b4        10 hours ago        188MB

Run the newly build Image to see the changes commited in the previous container.

# docker run -it ubuntu:15.0 /bin/bash
root@3a48af5eaec9:/# cd /root/
root@3a48af5eaec9:~# ls
TEST_DIR
root@3a48af5eaec9:~# exit

To build an image from Docker file, how to build an image using docker API

For more information on docker APIs, refer here.


问:
What is the minimum required to Run a .Net 3.5 Site WITHOUT compiling
Please note. Before anyone tells me about how I should compile the code for performance etc... this is just for a personal project and I want to be able to edit the code in a regular text editor and then it just works.

I usually code in C#, but this would be VB:

I have three files in a Virtual Directory

```<code>test.aspx
test.aspx.vb
web.config
</code>```

I have copied the .Net 3.5 web.config line for line from a File > New Project.

It's not recognizing the XDocument class. Says, it's not defined Since this is a .Net 3.5 class, I figure it has to do with .Net 3.5

So, here's the question: Is this even possible to run a single page without compiling? Asp.Net should compile on the fly. It works with 2.0. Is there something I'm missing?

答: Just add the assemblies to the web.config file (sorry cant recall the exact place to put it, but a normal VS generated one should have a few entries already).</p>

ContentLicense: CC BY-SA 2.5

Body:
Please note. Before anyone tells me about how I should compile the code for performance etc... this is just for a personal project and I want to be able to edit the code in a regular text editor and then it just works.

I usually code in C#, but this would be VB:

I have three files in a Virtual Directory

test.aspx
test.aspx.vb
web.config

I have copied the .Net 3.5 web.config line for line from a File > New Project.

It's not recognizing the XDocument class. Says, it's not defined Since this is a .Net 3.5 class, I figure it has to do with .Net 3.5

So, here's the question: Is this even possible to run a single page without compiling? Asp.Net should compile on the fly. It works with 2.0. Is there something I'm missing?


问:
troposphere to create alias A record when you have hosted zones with same name
```<code>funsetgroup = template.add_resource(RecordSet(
        'funsetgroup',
        HostedZoneName=Join('', [Ref(hostedzone), "."]),
        Comment='Hosted Zone Name',
        Type="A",
        Name=Join('fun.', [Ref(hostedzone), "."]),
        AliasTarget=AliasTarget(
            HostedZoneId=GetAtt(myelb, "CanonicalHostedZoneNameID"),
            DNSName=GetAtt(myelb, "DNSName"),
        )))
</code>```

In this troposphere code I am trying to create an Alias A record for my hosted zone say, example.com. But I have 2 hosted zones with the same name(hosted zone Id's will be different). Although I explicitly mention the hosted zone id cloud formation doesn't create the stack saying "duplicate hosted zone found". I also tried just mentioning the hosted zone id without the hostedzone name that fails as well.

答:
Did you also try using HostedZoneId instead of HostedZoneName in the RecordSet?  This should work - we created Alias records in different zones with the same name in Empire all the time, and our code there uses Cloudformation as well (with a shim similar to troposphere - so much so, we call it troposphere).  You can see that here:

https://github.com/remind101/empire/blob/ac27a91f3a5131b18700c350ca510d1befed7a51/scheduler/cloudformation/template.go#L647

Doing something similar in troposphere should work fine - just use HostedZoneId both in the RecordSet and the AliasTarget objects.

Body:
funsetgroup = template.add_resource(RecordSet(
        'funsetgroup',
        HostedZoneName=Join('', [Ref(hostedzone), "."]),
        Comment='Hosted Zone Name',
        Type="A",
        Name=Join('fun.', [Ref(hostedzone), "."]),
        AliasTarget=AliasTarget(
            HostedZoneId=GetAtt(myelb, "CanonicalHostedZoneNameID"),
            DNSName=GetAtt(myelb, "DNSName"),
        )))

In this troposphere code I am trying to create an Alias A record for my hosted zone say, example.com. But I have 2 hosted zones with the same name(hosted zone Id's will be different). Although I explicitly mention the hosted zone id cloud formation doesn't create the stack saying "duplicate hosted zone found". I also tried just mentioning the hosted zone id without the hostedzone name that fails as well.


问:
Get file from android package internal storage
So for test purposes I have an update function which checks the version of the up on my phone with the one that I have uploaded somewhere. Every works fine but when it goes to instal it just crashes and gives me this error.

java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.XXXX.demoapp/update/demo.apk

And here is where it crashes:

```<code>private static final String APK_SAVE_PATH  = "/data/data/com.example.XXXX.demoapp/update";

final File apk = new File(APK_SAVE_PATH,"demo.apk");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", apk);
                                    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                                    intent.setData(apkUri);
                                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    context.startActivity(intent);
                                } else {
                                    Uri apkUri = Uri.fromFile(apk);
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    context.startActivity(intent);
                                }

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="apk" path="/data/data/com.example.XXXX.demoapp/update/" />
</paths>
</code>```

答:
```<code><paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
    <files-path
        name="apk"
        path="/" />
</paths>
</code>```

<p>Apparently that does the trick </p>

Body:
So for test purposes I have an update function which checks the version of the up on my phone with the one that I have uploaded somewhere. Every works fine but when it goes to instal it just crashes and gives me this error.

java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.XXXX.demoapp/update/demo.apk

And here is where it crashes:

private static final String APK_SAVE_PATH  = "/data/data/com.example.XXXX.demoapp/update";

final File apk = new File(APK_SAVE_PATH,"demo.apk");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", apk);
                                    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                                    intent.setData(apkUri);
                                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    context.startActivity(intent);
                                } else {
                                    Uri apkUri = Uri.fromFile(apk);
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    context.startActivity(intent);
                                }

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="apk" path="/data/data/com.example.XXXX.demoapp/update/" />
</paths>

Body:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
    <files-path
        name="apk"
        path="/" />
</paths>

Apparently that does the trick


问:
regex to extract show name, which include the year
I'm working on a .net program that will use regex to capture the title of a show from a filename, but having trouble when the show name should include a year. Here is what I have so far.

```<code>(?i)(.*?(?:19\d{2}|20\d{2})(?=[ -]+([\d]|[S][\d]|Season)))
</code>```

The trouble is that this will match The Flash 2014 but not Top Chef. And if I make the (?:19\d{2}|20\d{2}) optional by adding a question mark at the end it will then match Top Chef but not The Flash 2014, it will be missing the year.

Example files:

```<code>Top Chef S14E14 Comida Final.mkv
The Flash 2014 03x01 720p HDTV X264-DIMENSION.mkv
</code>```

Is my issue related to the optional group being in front of the positive lookahead? How do I fix it so that the query matches both shows?

答:
I used the following to get it working.

```<code>^                         # BEGINNING OF STRING

(?<TITLE>                 # CAPTURE THE TITLE
  .+?                     # ANYTHING UP THROUGH (YEAR OR LOOKAHEAD FOR SEASON)
  (?:\s+(?:19|20)\d{2})?  # OPTIONALLY - A SPACE FOLLOWED BY A YEAR
)                         # END OF TITLE CAPTURE

(?=\s+(?:\d|S\d|Season))  # LOOKAHEAD FOR THE SEASON
</code>```

https://www.reddit.com/r/regex/comments/6fepo3/getting_show_title_from_filename/dihlh8a/

Body:
I'm working on a .net program that will use regex to capture the title of a show from a filename, but having trouble when the show name should include a year. Here is what I have so far.

(?i)(.*?(?:19\d{2}|20\d{2})(?=[ -]+([\d]|[S][\d]|Season)))

The trouble is that this will match The Flash 2014 but not Top Chef. And if I make the (?:19\d{2}|20\d{2}) optional by adding a question mark at the end it will then match Top Chef but not The Flash 2014, it will be missing the year.

Example files:

Top Chef S14E14 Comida Final.mkv
The Flash 2014 03x01 720p HDTV X264-DIMENSION.mkv

Is my issue related to the optional group being in front of the positive lookahead? How do I fix it so that the query matches both shows?

Body:
I used the following to get it working.

^                         # BEGINNING OF STRING

(?<TITLE>                 # CAPTURE THE TITLE
  .+?                     # ANYTHING UP THROUGH (YEAR OR LOOKAHEAD FOR SEASON)
  (?:\s+(?:19|20)\d{2})?  # OPTIONALLY - A SPACE FOLLOWED BY A YEAR
)                         # END OF TITLE CAPTURE

(?=\s+(?:\d|S\d|Season))  # LOOKAHEAD FOR THE SEASON

https://www.reddit.com/r/regex/comments/6fepo3/getting_show_title_from_filename/dihlh8a/


问:
Getting activerecord readonly error when adding a where clause
I have two queries for two different pages:

```<code>all_teams = Team.includes(:terms, :labs, people: [:schools], term_enrollments: [:lab])
current_teams = Team.includes(:terms, :labs, people: [:schools], term_enrollments: [:lab]).where(terms: {id: 3)
</code>```

I am trying to update the term_enrollments with each query.  For the first query, everything is good.  I do this with the first query:

```<code>a = all_teams.first.term_enrollments.first
a.update_attributes term: Term.find(2)
=> true
</code>```

When I try to do this with the second query, it doesn't work.  Here's the code I try to do for the second query:

```<code>a = current_teams.first.term_enrollments.first
a.update_attributes term: Term.find(2)
</code>```

But instead of working it says:

```<code>ActiveRecord::ReadOnlyRecord: TermEnrollment is marked as readonly
</code>```

Both of these queries are in controller actions and feed a page that loops through the activerecord relation and shows an edit form for each instance.

答:
current_teams is probably doing some join which in some cases causes the records to become readonly. You can get around this with

```<code>a = all_teams.first.term_enrollments.first.readonly(false)
a.update_attributes(term: Term.find(2))
</code>```

Body:
I have two queries for two different pages:

all_teams = Team.includes(:terms, :labs, people: [:schools], term_enrollments: [:lab])
current_teams = Team.includes(:terms, :labs, people: [:schools], term_enrollments: [:lab]).where(terms: {id: 3)

I am trying to update the term_enrollments with each query.  For the first query, everything is good.  I do this with the first query:

a = all_teams.first.term_enrollments.first
a.update_attributes term: Term.find(2)
=> true

When I try to do this with the second query, it doesn't work.  Here's the code I try to do for the second query:

a = current_teams.first.term_enrollments.first
a.update_attributes term: Term.find(2)

But instead of working it says:

ActiveRecord::ReadOnlyRecord: TermEnrollment is marked as readonly

Both of these queries are in controller actions and feed a page that loops through the activerecord relation and shows an edit form for each instance.

Body:
current_teams is probably doing some join which in some cases causes the records to become readonly. You can get around this with

a = all_teams.first.term_enrollments.first.readonly(false)
a.update_attributes(term: Term.find(2))


问:
Create collection of stubs with mockito
I want to create Collection of stubs so that first Item when I call getId() method return 0, second Item.getId() return 1 and so on. Value of getId() method must be equal index of element. I try this

```<code>@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;

@Before
public void setUp() throws Exception {
    initMocks(this);
}

@Test
public void mockCollection() throws Exception {
    when(items.get(0).getId()).thenReturn(0);
    when(items.get(1).getId()).thenReturn(1);
    ...
}
</code>```

But I get this Exception:

```<code>java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$42aa7d0b cannot be cast to com.gubin.designpatterns.behavioural.observer.Item
</code>```

How I can do this task?

答:
Here:

```<code>@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;
</code>```

Simply: wrong. You never mock a class that is so easy to create with real code.

You simple create an ordinary ArrayList (or any other thing that implements List) and fill that with mocked answer objects; configured to return the expected values.

Thing is: you use mocking as seldom as possible. It is a nice and convenient helper, but when you can go without it (and as said; that is super easy here); you simply don't do it.

Title: Create collection of stubs with mockito

Body:
I want to create Collection of stubs so that first Item when I call getId() method return 0, second Item.getId() return 1 and so on. Value of getId() method must be equal index of element. I try this

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;

@Before
public void setUp() throws Exception {
    initMocks(this);
}

@Test
public void mockCollection() throws Exception {
    when(items.get(0).getId()).thenReturn(0);
    when(items.get(1).getId()).thenReturn(1);
    ...
}

But I get this Exception:

java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$42aa7d0b cannot be cast to com.gubin.designpatterns.behavioural.observer.Item

How I can do this task?

Body:
Here:

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;

Simply: wrong. You never mock a class that is so easy to create with real code.

You simple create an ordinary ArrayList (or any other thing that implements List) and fill that with mocked answer objects; configured to return the expected values.

Thing is: you use mocking as seldom as possible. It is a nice and convenient helper, but when you can go without it (and as said; that is super easy here); you simply don't do it.


问:
Regex to match comma separated numbers or stop (Full match only)
I am trying to match comma separated numbers, but if any of the numbers is not valid stop regex and don't match it at all.

Here is an example that should be matched

```<code>3123123213212,3123123263212,3173123213212
</code>```

This string shouldn't be matched

```<code>3123123213212,3123123263212dad,3173123213212
</code>```

So at least one invalid number should lead to unmatched regex.

What I've tried is the following expression

```<code>(?:(\d+)(?=\,|\s|$))+
</code>```

Here is Regex101 link

https://regex101.com/r/JpuA5X/1

The problem that even if some number is invalid it matches other numbers, but this is not acceptable.

How can I modify my regex to get desired result ?

Thanks.

UPDATE

Sorry, I haven't mentioned, I need to group every single number.

答:
In this instance, I'm not sure it's possible to match and capture what you want without including some other (undesirable) captures, ones that would include the comma.

Instead you can test the string, and if it matches, split the string into an array using the comma as the delimiter. If the string doesn't match, return an empty array or some other value that you would like to symbolize "no match".

var regex = /^\d+(,\d+)*$/;
var valid_string = '3123123213212,3123123263212,3173123213212';
var invalid_string = '3123123213212,3123123263212dad,3173123213212';

console.log(regex.test(valid_string) ? valid_string.split(',') : []);
console.log(regex.test(invalid_string) ? invalid_string.split(',') : []);```

Body:
I am trying to match comma separated numbers, but if any of the numbers is not valid stop regex and don't match it at all.

Here is an example that should be matched

3123123213212,3123123263212,3173123213212

This string shouldn't be matched

3123123213212,3123123263212dad,3173123213212

So at least one invalid number should lead to unmatched regex.

What I've tried is the following expression

(?:(\d+)(?=\,|\s|$))+

Here is Regex101 link

https://regex101.com/r/JpuA5X/1

The problem that even if some number is invalid it matches other numbers, but this is not acceptable.

How can I modify my regex to get desired result ?

Thanks.

UPDATE

Sorry, I haven't mentioned, I need to group every single number.


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答:
You need to mount a remote share on your windows machine. This is what Samba/smb is for.

What you'll be doing is turning your Linux box into an SMB server, which lets it share files in a way that plays nice with Windows.

If you're not on the same network, you'll need to tunnel this through your SSH connection which may not be worth the effort.

OwnerDisplayName: Jared

LastEditorDisplayName: Michael Haren

OwnerDisplayName: Michael Haren


问:
How do I use an object for setting variable in JSP for loop?
I need to loop through the list, but foreach loop is not acceptable as I want to start from the second element.

```<code><c:forEach var="item" items="${items}">
<c:out value="${item.name}"/>
</c:forEach>
</code>```

I tried to use standard java code in "<% %>" but I cannot come up how to set it up right. My syntax is just wrong, I need something like this

```<code><% for (int i = 1; i < ${items.size()}; i++) { %>
    <c:out value="${item.name}"/>
<%} %>
</code>```

But, obviously, the code above is not working.

答:
You can use JSTL varStatus property. It might help you.

```<code><c:forEach var="item" items="${items}" varStatus="loop">
  <c:if test="${loop.index != 0}">
    <c:out value="${item.name}"/>
  </c:if>
</c:forEach>
</code>```

Body:
I need to loop through the list, but foreach loop is not acceptable as I want to start from the second element.

<c:forEach var="item" items="${items}">
<c:out value="${item.name}"/>
</c:forEach>

I tried to use standard java code in "<% %>" but I cannot come up how to set it up right. My syntax is just wrong, I need something like this

<% for (int i = 1; i < ${items.size()}; i++) { %>
    <c:out value="${item.name}"/>
<%} %>

But, obviously, the code above is not working.

Body:
You can use JSTL varStatus property. It might help you.

<c:forEach var="item" items="${items}" varStatus="loop">
  <c:if test="${loop.index != 0}">
    <c:out value="${item.name}"/>
  </c:if>
</c:forEach>


问:
How to execute a very heavy process exposed as REST services from wildfly?
I have a process that processes an input file, uses 100% of the processor (uses 16 cores), and 8 GB of RAM. I currently run it directly from the console. But I need to call this process from a REST service. The service must be asynchronous, and there will be another service to consult the output of the first service called. The input files must be queued, because it can only be processed one at a time.

I use RestEasy on Wildfly.

My query is:

What architecture do you suggest to call this process?

I have these possible solutions.

Call from my EJB to JAR with Runtime. And have a queue of files in a database.

Transform my JAR into a Demon, which is constantly monitoring a directory. And they will be storing the files there. And that the demon took one by one the files according to the date of arrival.

Copy the classes in my EAR project, and call them as a simple EJB, and let wildfly manage the resources. This would also imply having a file queue in a database.

Do you have any other suggestions?

答:
Instead of writing a queue use a JMS implementation or Kafka. Cloud solutions exist from Google and AWS. Have your REST endpoint publish to the queue and your "daemon" receive from it.

From there it's easy to pull these apart into microservice architecture


问:
Change status bar color with react-navigation
I use a DrawerNavigator from react-navigation in my app. Without any customization, the Android status bar is blue, and not black.

I tried to do

StatusBar.setBackgroundColor('#000000');
```

but it only works for a few seconds, and then it goes back to blue. It seems that something I am using set the status bar color to blue. However, I tried to remove all dependencies and only keep react-navigation, and it still happens and the docs of react-navigation do not say anything about that.

How can I set the status bar color to black with react-navigation ?

答:
```<code>import React, {Component} from 'react';
import {Text, TouchableOpacity, View, StatusBar} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from "../styles/Style";

class ProfileScreen extends Component {

    static navigationOptions = ({navigation}) => {
        return {
            headerLeft: (
                <TouchableOpacity onPress={() => {
                    navigation.navigate('DrawerOpen');
                }}>
                    <Icon name="menu" size={30} color="#fff" style={styles.burgerIcon}/>
                </TouchableOpacity>
            ),
            title: 'My Profile',
            headerRight: (
                <Icon name={'edit'} size={30} color={'#fff'} style={styles.headerRightIcon}/>
            ),
            headerTintColor: "#fff",
            headerStyle: {
                backgroundColor: '#8BC83D',
                height: 56,
                elevation: null
            }
        };
    };

    render() {
        return (
            <View style={styles.screenContainer}>

                <StatusBar
                    backgroundColor="#7CB236"
                    barStyle="light-content"
                />
                <Text style={styles.welcome}>
                    I amsecond reder
                </Text>
            </View>
        );
    }
}
const ProfileScreenList = StackNavigator(
    {
    ProfileScreenIndex: {screen: ProfileScreen},
}
);
export default ProfileScreenList
</code>```

Body:
I use a DrawerNavigator from react-navigation in my app. Without any customization, the Android status bar is blue, and not black.

I tried to do

StatusBar.setBackgroundColor('#000000');

but it only works for a few seconds, and then it goes back to blue. It seems that something I am using set the status bar color to blue. However, I tried to remove all dependencies and only keep react-navigation, and it still happens and the docs of react-navigation do not say anything about that.

How can I set the status bar color to black with react-navigation ?


问:
AVAudioRecorder never records
I am using an AVAudioRecorder to record human voice. My code is as follows:

```<code>// Property of Class
var recorder:AVAudioRecorder?

func recordButtonTapped() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setActive(true)
        if audioSession.recordPermission() != .granted {
            audioSession.requestRecordPermission({ (success) in
                self.startRecording()
            })
        }
        else {
            self.startRecording()
        }

    } catch {
        print("Unable To Set Category")
    }
}

func startRecording() {
    // libraryPathWith(media) just gets the path to the documents directory
    // Like so: Documents/MediaLibrary/Audio/<mediaID>.<mediaExtension>
    if let path = MMFileManager.libraryPathWith(media: self.media) {
        isRecording = true
        do {
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            recorder = try AVAudioRecorder(url: path, settings: settings)

            recorder?.delegate = self

            if recorder!.prepareToRecord() {
                recorder?.record()
            }
        }
        catch {
            isRecording = false
        }
    }
}

func stopRecording() {
    self.recordingLabel.text = "Recording Complete"
    self.recordingLabel.textColor = UIColor.white
    if let rec = recorder {
        rec.stop()
        recorder = nil
    }
    isRecording = false
}
</code>```

AVAudioRecorderDelegate

```<code>func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("RECORDED AUDIO SUCCESSFULLY \(flag)")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
    print("AUDIO RECORDER ERROR \(error?.localizedDescription)")
}
</code>```

After I call stop on the AVAudioRecorder the audioRecorderEncodeErrorDidOccur function never gets called, but the audioRecorderDidFinishRecording function does but the flag is always false. It prints out "RECORDED AUDIO SUCCESSFULLY false"

QUESTION

When I record using the code above I does save a file to my documents directory at the location specified. But this file is not something that I can play. It writes a text file, not an audio file as I specify the extension to be .aac.

Why does the AVAudioRecorder not record audio? And how do I get it to do so?

答: The issue was with the line in the stopRecording() function. Below the call to stop() the recorder I am immediately assigning the AVAudioRecorder instance to nil. This deallocates and ends the AVAudioRecorder before the post processing to create the authentic .aac file can be completed.

Title: AVAudioRecorder never records

Body:
I am using an AVAudioRecorder to record human voice. My code is as follows:

// Property of Class
var recorder:AVAudioRecorder?

func recordButtonTapped() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setActive(true)
        if audioSession.recordPermission() != .granted {
            audioSession.requestRecordPermission({ (success) in
                self.startRecording()
            })
        }
        else {
            self.startRecording()
        }

    } catch {
        print("Unable To Set Category")
    }
}

func startRecording() {
    // libraryPathWith(media) just gets the path to the documents directory
    // Like so: Documents/MediaLibrary/Audio/<mediaID>.<mediaExtension>
    if let path = MMFileManager.libraryPathWith(media: self.media) {
        isRecording = true
        do {
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            recorder = try AVAudioRecorder(url: path, settings: settings)

            recorder?.delegate = self

            if recorder!.prepareToRecord() {
                recorder?.record()
            }
        }
        catch {
            isRecording = false
        }
    }
}

func stopRecording() {
    self.recordingLabel.text = "Recording Complete"
    self.recordingLabel.textColor = UIColor.white
    if let rec = recorder {
        rec.stop()
        recorder = nil
    }
    isRecording = false
}

AVAudioRecorderDelegate

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("RECORDED AUDIO SUCCESSFULLY \(flag)")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
    print("AUDIO RECORDER ERROR \(error?.localizedDescription)")
}

After I call stop on the AVAudioRecorder the audioRecorderEncodeErrorDidOccur function never gets called, but the audioRecorderDidFinishRecording function does but the flag is always false. It prints out "RECORDED AUDIO SUCCESSFULLY false"

QUESTION

When I record using the code above I does save a file to my documents directory at the location specified. But this file is not something that I can play. It writes a text file, not an audio file as I specify the extension to be .aac.

Why does the AVAudioRecorder not record audio? And how do I get it to do so?


问:
Looking to convert repetitive values to 0 in SQL Server
I am working on a report where I need all the data based on highest hierarchy.
I have got the results but one column values are repetitive because its coming from the Parent Group level data source and I cannot get it on lower hierarchy level.

Here's my table:

答:
you can use Row_Number and provide values only for 1 as below:</p>

```<code>Select *,
       Case
           When Row_Number() over(partition by Parent_Group_Id order by Group_Id) = 1
               then Numbers
               else 0
       end YourOuputColumn
from yourtable
</code>```

Body:
you can use Row_Number and provide values only for 1 as below:

Select *,
       Case
           When Row_Number() over(partition by Parent_Group_Id order by Group_Id) = 1
               then Numbers
               else 0
       end YourOuputColumn
from yourtable


问:
SQLiteDatabase.execSQL(query) - Multiple SQL commands inside the onCreate() method not working
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

```<code>public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }
</code>```

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

答:
You could create a sql statement for each record

```<code>String query1 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹')" ;

String query2 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('USD','$')" ;

String query3 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('JPY','¥')" ;

db.execSQL(query1);
db.execSQL(query2);
db.execSQL(query3);
</code>```

Or insert multiple values in one statement, with the correct sintax it would be like this:

```<code>String query = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " +
             "('INR', '₹'), " +
             "('USD','$'), " +
             "('JPY','¥')";
db.execSQL(query);
</code>```

For more information visit SqlLite

Body:
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

Body:
You could create a sql statement for each record

String query1 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹')" ;

String query2 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('USD','$')" ;

String query3 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('JPY','¥')" ;

db.execSQL(query1);
db.execSQL(query2);
db.execSQL(query3);

Or insert multiple values in one statement, with the correct sintax it would be like this:

String query = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " +
             "('INR', '₹'), " +
             "('USD','$'), " +
             "('JPY','¥')";
db.execSQL(query);

For more information visit SqlLite


问:
Get share link of files in specific folder of OneDrive
Can anyone give me an example of VBA (Excel) code for get share links (edit) for each file in specific folder in OneDrive?
Or a useful link?

Thanks
Tudor

答:
If you want to email different files to different people, see the script below.

Make a list in Sheets("Sheet1") with :

In column A : Names of the people

In column B : E-mail addresses

In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)

The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.

```<code>Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -1).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                    If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub
</code>```

Body:
If you want to email different files to different people, see the script below.

Make a list in Sheets("Sheet1") with :

In column A : Names of the people

In column B : E-mail addresses

In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)

The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.

Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -1).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                    If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub


问:
excel sum column if value x is in column A or B and A does not equal B
I need to have a sum if function that would return all values where John is in column B and not in column A. So it should only return 50 for the below. </p>

```<code>Column A     Column B           Column C
John         John, Steve, Fred  100
Steve        John               50
Fred         Fred, Steve        150
</code>```

答:
You can use this SUMIFS:

```<code>=SUMIFS(C:C,A:A,"<>*" & "John" & "*",B:B,"=*" & "John" & "*")
</code>```

But that might lead to false positive like Ann will also see Anne.

To get around that you need to change to SUMPRODUCT:

```<code>=SUMPRODUCT($C$1:$C$3,(ISERROR(SEARCH("," & "John" & ",","," & $A$1:$A$3 & ",")))*(ISNUMBER(SEARCH("," & "John" & ",","," & $B$1:$B$3 & ","))))
</code>```

Body:
I need to have a sum if function that would return all values where John is in column B and not in column A. So it should only return 50 for the below.

Column A     Column B           Column C
John         John, Steve, Fred  100
Steve        John               50
Fred         Fred, Steve        150

Body:
You can use this SUMIFS:

=SUMIFS(C:C,A:A,"<>*" & "John" & "*",B:B,"=*" & "John" & "*")

But that might lead to false positive like Ann will also see Anne.

To get around that you need to change to SUMPRODUCT:

=SUMPRODUCT($C$1:$C$3,(ISERROR(SEARCH("," & "John" & ",","," & $A$1:$A$3 & ",")))*(ISNUMBER(SEARCH("," & "John" & ",","," & $B$1:$B$3 & ","))))


问:
Selenium launches new browser window then throws UnreachableBrowserException
I am trying to setup a new Selenium project, and can not make thinks work correctly. My environment:

```<code>OSX      : 10.12.4
Java     : 1.8.0_121
Selenium : 3.4.0
Gecko    : 0.16.1      ( located at /opt/garbage/geckodriver and on path )
Firefox  : 53.0.3
</code>```

Java Code

```<code>System.setProperty("webdriver.gecko.driver", "/opt/garbage/geckodriver");
System.setProperty("webdriver.firefox.marionette", "/opt/garbage/geckodriver");

WebDriver driver = new FirefoxDriver();  <--

driver.get("https://www.google.com");
</code>```

In this example, line 4 will open a new Firefox Browser window, but several seconds later throws the following stack:

```<code>org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'myhostname.corp', ip: '10.99.99.99', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.4', java.version: '1.8.0_121'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:658)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:191)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:104)
    at com.example.TestClass.testMethod(TestClass.java:19)
</code>```

And StdErr from the failed run:

```<code>2017-06-05 12:24:08.483 firefox-bin[35514:5688975] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x12cd37a00 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4097 "connection from pid 0" UserInfo={NSDebugDescription=connection from pid 0}, com.apple.inputmethod.EmojiFunctionRowItem
2017-06-05 12:24:08.891 firefox-bin[35514:5688975] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x12cd37a00 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4097 "connection from pid 0" UserInfo={NSDebugDescription=connection from pid 0}, com.apple.inputmethod.EmojiFunctionRowItem
2017-06-05 12:24:09.248 plugin-container[35516:5689303] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x983b, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2017-06-05 12:24:09.248 plugin-container[35516:5689303] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x9b03, name = 'com.apple.CFPasteboardClient'
See /usr/include/servers/bootstrap_defs.h for the error codes.
</code>```

What could I have misconfigured?

edit

I have also tried using the following capabilities - without change

```<code>DesiredCapabilities caps = new FirefoxOptions()//
        .setProfile(new FirefoxProfile())//
        .addTo(DesiredCapabilities.firefox());

WebDriver driver = new FirefoxDriver( caps );  <--
</code>```

答:
This code is working for me

```<code>System.setProperty("webdriver.gecko.driver", "/opt/garbage/geckodriver.exe");
`WebDriver driver = new FirefoxDriver();`  <--
 driver.get("https://www.google.com");
</code>```

My Config:

Selenium:3.4.0

Gecko:0.16.1

Firefox:53.0.3

Body:
I am trying to setup a new Selenium project, and can not make thinks work correctly. My environment:

OSX      : 10.12.4
Java     : 1.8.0_121
Selenium : 3.4.0
Gecko    : 0.16.1      ( located at /opt/garbage/geckodriver and on path )
Firefox  : 53.0.3

Java Code

System.setProperty("webdriver.gecko.driver", "/opt/garbage/geckodriver");
System.setProperty("webdriver.firefox.marionette", "/opt/garbage/geckodriver");

WebDriver driver = new FirefoxDriver();  <--

driver.get("https://www.google.com");

In this example, line 4 will open a new Firefox Browser window, but several seconds later throws the following stack:

org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'myhostname.corp', ip: '10.99.99.99', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.4', java.version: '1.8.0_121'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:658)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:191)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:104)
    at com.example.TestClass.testMethod(TestClass.java:19)

And StdErr from the failed run:

2017-06-05 12:24:08.483 firefox-bin[35514:5688975] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x12cd37a00 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4097 "connection from pid 0" UserInfo={NSDebugDescription=connection from pid 0}, com.apple.inputmethod.EmojiFunctionRowItem
2017-06-05 12:24:08.891 firefox-bin[35514:5688975] IMKInputSession presentFunctionRowItemTextInputViewWithEndpoint:completionHandler: : [self textInputContext]=0x12cd37a00 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4097 "connection from pid 0" UserInfo={NSDebugDescription=connection from pid 0}, com.apple.inputmethod.EmojiFunctionRowItem
2017-06-05 12:24:09.248 plugin-container[35516:5689303] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x983b, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
2017-06-05 12:24:09.248 plugin-container[35516:5689303] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x9b03, name = 'com.apple.CFPasteboardClient'
See /usr/include/servers/bootstrap_defs.h for the error codes.

What could I have misconfigured?

edit

I have also tried using the following capabilities - without change

DesiredCapabilities caps = new FirefoxOptions()//
        .setProfile(new FirefoxProfile())//
        .addTo(DesiredCapabilities.firefox());

WebDriver driver = new FirefoxDriver( caps );  <--

Body:
This code is working for me

System.setProperty("webdriver.gecko.driver", "/opt/garbage/geckodriver.exe");
`WebDriver driver = new FirefoxDriver();`  <--
 driver.get("https://www.google.com");

My Config:

Selenium:3.4.0

Gecko:0.16.1

Firefox:53.0.3


问:
How to force Chrome/Firefox/Opera to do crossdomain requests from localhost?
Hy,

So I've got this problem: I'm trying to develop an HTML file on my localhost, and all the browsers I have installed are preventing me to send cross-domain requests.

What I'm trying to do is to convert a script I wrote in Python (with Mechanize, pyquery and lxml) to Javascript, the reasons don't really matter (I thought in Javascript it would be easier to simulate something).

Cross-domain requests from local files used to work, and are still working on the latest Safari (stable), but I can't install Safari on this machine (it's a Linux box).

EDIT

I discovered the escalated privileges of Firefox, e.g.:

```<code>netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
// among others
</code>```

Problem is, I'm also trying to access the content loaded in an iFrame ... as I said, I'm trying to simulate a browser session, like I would with a library like Mechanize, but from Javascript. My script still works in Safari.

So how to force Chrome / Firefox / Opera to bypass all security restrictions from locally stored files?

I'm interested in a browser command-line option, I would even consider a patch to the browser (I'm the user, not trying to distribute this to anyone else).

Thanks,

答:
I'm unsure whether or not you have control of the content in the IFrames but since you are speaking of local files I guess you do. This article on  Ajaxian should cover your use case.
Since you are targeting grade A browsers (e.i. not IE) you could use html5 window.postMessage instead of IFrames.

Cheers, Jon.

I have no working knowledge of Python Mechanize lib.

Body:
Hy,

So I've got this problem: I'm trying to develop an HTML file on my localhost, and all the browsers I have installed are preventing me to send cross-domain requests.

What I'm trying to do is to convert a script I wrote in Python (with Mechanize, pyquery and lxml) to Javascript, the reasons don't really matter (I thought in Javascript it would be easier to simulate something).

Cross-domain requests from local files used to work, and are still working on the latest Safari (stable), but I can't install Safari on this machine (it's a Linux box).

EDIT

I discovered the escalated privileges of Firefox, e.g.:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
// among others

Problem is, I'm also trying to access the content loaded in an iFrame ... as I said, I'm trying to simulate a browser session, like I would with a library like Mechanize, but from Javascript. My script still works in Safari.

So how to force Chrome / Firefox / Opera to bypass all security restrictions from locally stored files?

I'm interested in a browser command-line option, I would even consider a patch to the browser (I'm the user, not trying to distribute this to anyone else).

Thanks,


问:
Is there a way to write a BLOB using Spring Integration's jdbc:oubound-channel-adapter?
I have incoming messages which have String payloads, but the database, (which I do not control), records this data as BLOBs.  Is there a way to get Spring Integration to massage a String into a CLOB or BLOB?

I have an outbound-channel-adapter doing a database insert, which (simplified) looks like:

```<code><int-jdbc:outbound-channel-adapter channel="inboundTraffic"
                                   datasource="localDataSource"
                                   query="insert into MESSAGES (DATA, SAVE_DATE)
                                          values (:payload, :saveDate)"
                                   sql-parameter-source-factory="spelSource" />

<bean id="spelSource" class="o.s.i.j.ExpressionEvaluatingSqlParameterSourceFactory">
    <property name="parameterExpressions">
         <map>
              <entry key="payload" value="payload" />
              <entry key="saveDate" value="new java.util.Date()" />
         </map>
    </property>
</bean>
</code>```

But I get the SQLException on the payload:

ORA-01461 can bind a LONG value only for insert into a LONG column.

Ch. 18 of the documentation has a blob example with the whole thing rewritten as a service activator instead of an oubound-channel-adapter, and streaming from a file... that seems like overkill, but is that the way BLOBs and CLOBS are  supposed to be done in the framework?

Thanks for the help!

答:
How about this:

```<code><entry key="payload" value="new org.springframework.jdbc.core.support.SqlLobValue(payload)" />
</code>```

?

See its JavaDoc:

```<code> * Object to represent an SQL BLOB/CLOB value parameter. BLOBs can either be an
 * InputStream or a byte array. CLOBs can be in the form of a Reader, InputStream
 * or String. Each CLOB/BLOB value will be stored together with its length.
 * The type is based on which constructor is used. Objects of this class are
 * immutable except for the LobCreator reference. Use them and discard them.
</code>```

UPDATE

"SqlLobValue only supports SQL types BLOB and CLOB", which originates from the SqlLobValue.setTypeValue(...) method.

Looks like there is no default sqlType for the SqlLobValue, so we should do something manually on the SqlParameterSource level since exactly that one provides a getSqlType() contract.

We can simply do that with the ExpressionEvaluatingSqlParameterSourceFactory extension:

```<code>public class MyExpressionEvaluatingSqlParameterSourceFactory extends ExpressionEvaluatingSqlParameterSourceFactory {
    @Override
    public SqlParameterSource createParameterSource(Object input) {
        AbstractSqlParameterSource parameterSource =
                (AbstractSqlParameterSource) super.createParameterSource(input);
        parameterSource.registerSqlType("payload", Types.BLOB);
        return parameterSource;
    }
}
</code>```

Feel free to raise a JIRA to add setSqlTypes() support to the ExpressionEvaluatingSqlParameterSourceFactory.

Body:
I have incoming messages which have String payloads, but the database, (which I do not control), records this data as BLOBs.  Is there a way to get Spring Integration to massage a String into a CLOB or BLOB?

I have an outbound-channel-adapter doing a database insert, which (simplified) looks like:

<int-jdbc:outbound-channel-adapter channel="inboundTraffic"
                                   datasource="localDataSource"
                                   query="insert into MESSAGES (DATA, SAVE_DATE)
                                          values (:payload, :saveDate)"
                                   sql-parameter-source-factory="spelSource" />

<bean id="spelSource" class="o.s.i.j.ExpressionEvaluatingSqlParameterSourceFactory">
    <property name="parameterExpressions">
         <map>
              <entry key="payload" value="payload" />
              <entry key="saveDate" value="new java.util.Date()" />
         </map>
    </property>
</bean>

But I get the SQLException on the payload:

ORA-01461 can bind a LONG value only for insert into a LONG column.

Ch. 18 of the documentation has a blob example with the whole thing rewritten as a service activator instead of an oubound-channel-adapter, and streaming from a file... that seems like overkill, but is that the way BLOBs and CLOBS are  supposed to be done in the framework?

Thanks for the help!

Body:
How about this:

<entry key="payload" value="new org.springframework.jdbc.core.support.SqlLobValue(payload)" />

?

See its JavaDoc:

 * Object to represent an SQL BLOB/CLOB value parameter. BLOBs can either be an
 * InputStream or a byte array. CLOBs can be in the form of a Reader, InputStream
 * or String. Each CLOB/BLOB value will be stored together with its length.
 * The type is based on which constructor is used. Objects of this class are
 * immutable except for the LobCreator reference. Use them and discard them.

UPDATE

"SqlLobValue only supports SQL types BLOB and CLOB", which originates from the SqlLobValue.setTypeValue(...) method.

Looks like there is no default sqlType for the SqlLobValue, so we should do something manually on the SqlParameterSource level since exactly that one provides a getSqlType() contract.

We can simply do that with the ExpressionEvaluatingSqlParameterSourceFactory extension:

public class MyExpressionEvaluatingSqlParameterSourceFactory extends ExpressionEvaluatingSqlParameterSourceFactory {
    @Override
    public SqlParameterSource createParameterSource(Object input) {
        AbstractSqlParameterSource parameterSource =
                (AbstractSqlParameterSource) super.createParameterSource(input);
        parameterSource.registerSqlType("payload", Types.BLOB);
        return parameterSource;
    }
}

Feel free to raise a JIRA to add setSqlTypes() support to the ExpressionEvaluatingSqlParameterSourceFactory.


问:
Magento address save after hook & database update
I have question about magento hook  "customer_address_save_after" & "address_save_after". I'd to make request from this hook to API, which gets User from Magento database. Unfortunnaly at this moment, in database are old data - not updated yet.

Is there any hook in Magento, which allow me make request AFTER database update? Or maybe is any method to save data in this hook to database? Something like $customer->save() ?

```<code>public function afterAddressSave($observer)
{
    $customerAddress = $observer->getCustomerAddress();
    $customer = $customerAddress->getCustomer();

    if ($customer->getDefaultBillingAddress() && $customer->getDefaultBillingAddress()->getCountryId()) {
        Mage::helper('iwsettings')->setStoreId($customer, $customer->getDefaultBillingAddress()->getCountryId());
    }
    $this->updateTypo3UserData($customer);
}
</code>```

答:
I believe you are confused a bit, the customer_address_save_after event is fired after data is committed to the database, however that data will not "stick" in the database if you throw an exception or a die() within your observer, as this causes the database to "roll back the save"

customer_address_save_after

$observer->getCustomerAddress() This is the address being submitted

Mage::getModel('customer/address')->load($id) Within the observer, by passing the id of the $observer->getCustomerAddress()->getEntityId() we can see the exact same data as above

If however, you use customer_address_save_before

$observer->getCustomerAddress() This is the address being submitted

$observer->getCustomerAddress()->getEntityId() will be blank if new, and will have the address id if edited

This does leave you with the issue of if the address is new, you don't know the entity ID yet (not until after save). However as the Observer is loaded as a singleton you can set a flag on your observer, and fetch the address id later on after save (it'll be there). As long as your observer does not throw an exception or die it'll save to the database!

So, for your query, you can use customer_address_save_after (there is also a customer_save_after if you want the customers values). just make sure nothing throws exception, i.e. wrap your code in a try{}catch{} and fail it silently if it pulls an exception.

Body:
I have question about magento hook  "customer_address_save_after" & "address_save_after". I'd to make request from this hook to API, which gets User from Magento database. Unfortunnaly at this moment, in database are old data - not updated yet.

Is there any hook in Magento, which allow me make request AFTER database update? Or maybe is any method to save data in this hook to database? Something like $customer->save() ?

public function afterAddressSave($observer)
{
    $customerAddress = $observer->getCustomerAddress();
    $customer = $customerAddress->getCustomer();

    if ($customer->getDefaultBillingAddress() && $customer->getDefaultBillingAddress()->getCountryId()) {
        Mage::helper('iwsettings')->setStoreId($customer, $customer->getDefaultBillingAddress()->getCountryId());
    }
    $this->updateTypo3UserData($customer);
}


问:
React Native - Native iOS module crashes when opening Settings app
I'm trying to create a simple React Native module which will allow me to open the iOS settings application from within a React Native application.

My implementation:

```<code>#import <UIKit/UIKit.h>
#import "RNOpenAppSettings.h"

@implementation RNOpenAppSettings

- (dispatch_queue_t)methodQueue
{
    return dispatch_queue_create("com.krazylabs.RNOpenAppSettings", DISPATCH_QUEUE_SERIAL);
}

RCT_EXPORT_MODULE(OpenAppSettings)

RCT_EXPORT_METHOD(open){
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

@end
</code>```

The above actually does open the iOS settings application but then crashes almost immediately. My first assumption was that perhaps the operation was taking too long and blocking the React Native queue; which is why I'm creating a separate queue. This did not help.

Has anyone run into this?

答:
I was able to resolve this by calling openURL asynchronously using GCD. Hopefully this helps someone else.</p>

```<code>#import <UIKit/UIKit.h>
#import "RNOpenAppSettings.h"

@implementation RNOpenAppSettings

RCT_EXPORT_MODULE(OpenAppSettings)

RCT_EXPORT_METHOD(open){
    dispatch_async(dispatch_get_main_queue(), ^{
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    });
}

@end
</code>```

Body:
I'm trying to create a simple React Native module which will allow me to open the iOS settings application from within a React Native application.

My implementation:

#import <UIKit/UIKit.h>
#import "RNOpenAppSettings.h"

@implementation RNOpenAppSettings

- (dispatch_queue_t)methodQueue
{
    return dispatch_queue_create("com.krazylabs.RNOpenAppSettings", DISPATCH_QUEUE_SERIAL);
}

RCT_EXPORT_MODULE(OpenAppSettings)

RCT_EXPORT_METHOD(open){
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

@end

The above actually does open the iOS settings application but then crashes almost immediately. My first assumption was that perhaps the operation was taking too long and blocking the React Native queue; which is why I'm creating a separate queue. This did not help.

Has anyone run into this?

Body:
I was able to resolve this by calling openURL asynchronously using GCD. Hopefully this helps someone else.

#import <UIKit/UIKit.h>
#import "RNOpenAppSettings.h"

@implementation RNOpenAppSettings

RCT_EXPORT_MODULE(OpenAppSettings)

RCT_EXPORT_METHOD(open){
    dispatch_async(dispatch_get_main_queue(), ^{
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    });
}

@end


问:
React / Redux fetching and filtering data
Lets say for example I have a giant list of items lets call it contacts this is 1000+ items in a list we have bunch of filters such as contact type, contact location, assigned to, filter ASC,filter DESC`. That a user can input whatever they want. The redux store consists of contacts in a normalized object

```<code>{
  "1": {
    "name": "Home Simpson",
    "type": "Lead",
    "location": "California",
    "created_at": "01/01/16"
  },
  "2": {
    "name": "Ned Flanders",
    "type": "Client",
    "location": "SpringField",
    "created_at": "05/01/16"
  },
  [...1000+]
}
</code>```

After fetching all of the contacts is it better to map and filter over all of the contacts on the client side based off of the user input?

Or should we be making another request to the server to get all of the contacts related to the specific filters?

Note that it is not just one param that can be queried for it is multiple params. Hence contact.type === : "Lead" || "Client", and contact.location === "Spring Field"

What are best practice for a query of this size and is making trips to the server for all the matching contacts worth the extra request or is it better to filter our redux store client side and not put the load on the server?

答:
IMO, the right place to filter data is not directly in the reducers but in the selectors.

From redux docs:

Computing Derived Data

Reselect is a simple library for creating memoized, composable selector functions. Reselect selectors can be used to efficiently compute derived data from the Redux store.

I'm currently using selectors to filter and sort data.

No data repetition in the state. You don't have to store a copy of the items filtered by one specific way.

The same data can be used in different components, each one using a different selector function to filter.

You can combine selector applying many data computations using selector that you already have in the application.

If you do right, your selectors will be pure functions, then you can easily test them.

Use the same selector in many components.

Body:
Lets say for example I have a giant list of items lets call it contacts this is 1000+ items in a list we have bunch of filters such as contact type, contact location, assigned to, filter ASC,filter DESC`. That a user can input whatever they want. The redux store consists of contacts in a normalized object

{
  "1": {
    "name": "Home Simpson",
    "type": "Lead",
    "location": "California",
    "created_at": "01/01/16"
  },
  "2": {
    "name": "Ned Flanders",
    "type": "Client",
    "location": "SpringField",
    "created_at": "05/01/16"
  },
  [...1000+]
}

After fetching all of the contacts is it better to map and filter over all of the contacts on the client side based off of the user input?

Or should we be making another request to the server to get all of the contacts related to the specific filters?

Note that it is not just one param that can be queried for it is multiple params. Hence contact.type === : "Lead" || "Client", and contact.location === "Spring Field"

What are best practice for a query of this size and is making trips to the server for all the matching contacts worth the extra request or is it better to filter our redux store client side and not put the load on the server?


问:
How to change color of toolbar title in Android?
I am developing an android app and I want to make the title of the toolbar white color.

I have removed the default toolbar and added a toolbar to my activities and am unable to figure out how to change the color of the title of the toolbar to white

MainActivity.java

```<code>package com.example.acer.videoapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        //toolbar.setTitleTextColor(white);
        listView = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("Subject", listView.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });
        listView.setAdapter(mAdapter);

    }
}
</code>```

答:
Set the color of the Toolbar text using toolbar.setTitleTextColor() method

```<code> toolbar = (Toolbar) findViewById(R.id.toolbar);
 toolbar.setTitle(getResources().getString(R.string.app_name));
 toolbar.setTitleTextColor(getColor(R.color.white));
</code>```

Body:
I am developing an android app and I want to make the title of the toolbar white color.

I have removed the default toolbar and added a toolbar to my activities and am unable to figure out how to change the color of the title of the toolbar to white

MainActivity.java

package com.example.acer.videoapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        //toolbar.setTitleTextColor(white);
        listView = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("Subject", listView.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });
        listView.setAdapter(mAdapter);

    }
}

Body:
Set the color of the Toolbar text using toolbar.setTitleTextColor() method

 toolbar = (Toolbar) findViewById(R.id.toolbar);
 toolbar.setTitle(getResources().getString(R.string.app_name));
 toolbar.setTitleTextColor(getColor(R.color.white));