问:
DialogFlow Webhook : Error: EROFS: read-only file system, open '.node-xmlhttprequest-sync-2'
I'm creating DialogFlow app and deployed fulfillment with Cloud Functions for Firebase which uses XMLHttpRequest.
But following error occurred.

Error: EROFS: read-only file system, open '.node-xmlhttprequest-sync-2'
      at Error (native)
      at Object.fs.openSync (fs.js:642:18)
      at Object.fs.writeFileSync (fs.js:1348:33)
      at send (/user_code/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:477:10)

My code is something like this.

```<code>'use strict';

const admin = require('firebase-admin');
const functions = require('firebase-functions');

const DialogflowApp = require('actions-on-google').DialogflowApp;
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
const googleAssistantRequest = 'google';

const Actions = {
  UNRECOGNIZED_DEEP_LINK: 'deeplink.unknown',
  TEST_HTTPREQUEST: 'test.httprequest'
};

const testHttpRequest = app => {
    var req = new XMLHttpRequest();
    req.open('GET', 'http://www.google.com', false);
    req.send();
    if (req.status === 200) {
      console.log(req.responseText);
    }
}

const actionMap = new Map();
actionMap.set(Actions.TEST_HTTPREQUEST, testHttpRequest);

exports.mytestapp = functions.https.onRequest((request, response) => {
  const app = new DialogflowApp({ request, response });
  console.log(`Request headers: ${JSON.stringify(request.headers)}`);
  console.log(`Request body: ${JSON.stringify(request.body)}`);
  app.handleRequest(actionMap);
});
</code>```

Does anyone have idea on how to solve this error?

答:
Your function testHttpRequest needs to use app to respond to the user's request from Dialogflow.  Use the ask or tell methods to respond to the request.   For example after the if statement in testHttpRequest you could add:

```<code>app.tell('This response came from Cloud Functions for Firebase!');
</code>```

which tells the Action on Google client library to send the string as a response to your request when you call your Assistant app from the Action on Google simulator or Google Assistant device (see Action on Google testing docs).

You may also be running into a issue with action names.  The action you refer to in your fulfillment here (deeplink.unknown and test.httprequest) must also be list as an action in an intent in your Dialogflow agent otherwise your code will never be triggered.  The Google Assistant also requires a welcome intent.  By default the welcome intent in Dialogflow has an action of input.welcome which is not included in your code so you code may not be trigger until you match the actions listed in your code and in your Dialogflow agent.

Furthermore external HTTP calls (outside the Google's network) are not permitted on Cloud Functions without setting up billing first.

Body:
I'm creating DialogFlow app and deployed fulfillment with Cloud Functions for Firebase which uses XMLHttpRequest.
But following error occurred.

Error: EROFS: read-only file system, open '.node-xmlhttprequest-sync-2'
      at Error (native)
      at Object.fs.openSync (fs.js:642:18)
      at Object.fs.writeFileSync (fs.js:1348:33)
      at send (/user_code/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:477:10)

My code is something like this.

'use strict';

const admin = require('firebase-admin');
const functions = require('firebase-functions');

const DialogflowApp = require('actions-on-google').DialogflowApp;
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
const googleAssistantRequest = 'google';

const Actions = {
  UNRECOGNIZED_DEEP_LINK: 'deeplink.unknown',
  TEST_HTTPREQUEST: 'test.httprequest'
};

const testHttpRequest = app => {
    var req = new XMLHttpRequest();
    req.open('GET', 'http://www.google.com', false);
    req.send();
    if (req.status === 200) {
      console.log(req.responseText);
    }
}

const actionMap = new Map();
actionMap.set(Actions.TEST_HTTPREQUEST, testHttpRequest);

exports.mytestapp = functions.https.onRequest((request, response) => {
  const app = new DialogflowApp({ request, response });
  console.log(`Request headers: ${JSON.stringify(request.headers)}`);
  console.log(`Request body: ${JSON.stringify(request.body)}`);
  app.handleRequest(actionMap);
});

Does anyone have idea on how to solve this error?

Body:
Your function testHttpRequest needs to use app to respond to the user's request from Dialogflow.  Use the ask or tell methods to respond to the request.   For example after the if statement in testHttpRequest you could add:

app.tell('This response came from Cloud Functions for Firebase!');

which tells the Action on Google client library to send the string as a response to your request when you call your Assistant app from the Action on Google simulator or Google Assistant device (see Action on Google testing docs).

You may also be running into a issue with action names.  The action you refer to in your fulfillment here (deeplink.unknown and test.httprequest) must also be list as an action in an intent in your Dialogflow agent otherwise your code will never be triggered.  The Google Assistant also requires a welcome intent.  By default the welcome intent in Dialogflow has an action of input.welcome which is not included in your code so you code may not be trigger until you match the actions listed in your code and in your Dialogflow agent.

Furthermore external HTTP calls (outside the Google's network) are not permitted on Cloud Functions without setting up billing first.


来源: stackexchange

问:
Clarion based application in WinServer 2016, frozen. Suggestions needed on tools we could use to gather more information
I have a clarion application running in Win Server 2016 talking to a sybase DB, over the past few weeks we find the application gets frozen for different users at a given time. However the user can leave the session as such and start a new one and that works good. The users are known to use multiple instances of the same application in one remote server or on multiple servers. Having said that, I wanted to get more information on the freezeup and looked through the application event logs in the system where I see explorer.exe crashes but these correlate to the time of occurrence of the issue at certain times but not always, checked the DB transaction logs from Sybase and I do not find any crashes, errors or stuck connections. Having said that, since I have exhausted all possible options I am reaching out to you guys to know if there are any other places that i can look for to gather more information.

I would love to know of any application / tools that we could use to gather logs of a frozen clarion application on windows. Also good to know if anyone has faced such a situation and where and how have you guys looked into the issue.

Thanks in advance for your help in this.

答:
Clarion's runtime library and database drivers expect a persistent connection. Disconnects that are normal with remote ODBC can cause a problem (including app hangs) unless you test for them at the ABC file mgr level and reconnect, or use similar steps to test and recover.

If you're looking for specifics about what's going on between the driver and the SQL backend, I suggest using Clarion's database driver trace facilities. From the help topic: "Logging Driver I/O for debugging":

To view the trace details in debugview, name the target trace file "DEBUG:"

Logging opens the named logfile for exclusive access. If the file exists, the new log data is appended to the file.

On Demand Logging

For on-demand logging you can use property syntax within your program to conditionally turn various levels of logging on and off. The logging is effective for the target table and any view for which the target table is the primary table.

```<code>file{PROP:Profile}=Pathname   !Turns Clarion I/O logging on
file{PROP:Profile}="DEBUG:"   !Turns Clarion I/O logging on and
                              !sends output via OutputDebugString()
                              !(viewable via debugview, etc)

file{PROP:Profile}=''         !Turns Clarion I/O logging off

PathName = file{PROP:Profile} !Queries the name of the log file

file{PROP:Log}=string         !Writes the string to the log file
file{PROP:Log}="DEBUG:"       !Writes the string to the log file

file{PROP:Details}=1          !Turns Record Buffer logging on

fFile{PROP:Details}=0         !Turns Record Buffer logging off
</code>```

where Pathname is the full pathname or the filename of the log file to create. If you do not specify a path, the driver writes the log file to the current directory.

You can also accomplish on demand logging with a SEND() command and the LOGFILE driver string. See LOGFILE for more information.

Example I use frequently, which was based on the help above:

```<code>SYSTEM{PROP:DriverTracing} = '1'
 CRMNotes{PROP:TraceFile} = 'DEBUG:'
 CRMNotes{PROP:Details}=1
 CRMNotes{PROP:Profile}= 'DEBUG:'
 CRMNotes{PROP:LogSQL} = 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Clarion's runtime library and database drivers expect a persistent connection. Disconnects that are normal with remote ODBC can cause a problem (including app hangs) unless you test for them at the ABC file mgr level and reconnect, or use similar steps to test and recover.

If you're looking for specifics about what's going on between the driver and the SQL backend, I suggest using Clarion's database driver trace facilities. From the help topic: "Logging Driver I/O for debugging":

To view the trace details in debugview, name the target trace file "DEBUG:"

Logging opens the named logfile for exclusive access. If the file exists, the new log data is appended to the file.

On Demand Logging

For on-demand logging you can use property syntax within your program to conditionally turn various levels of logging on and off. The logging is effective for the target table and any view for which the target table is the primary table.

file{PROP:Profile}=Pathname   !Turns Clarion I/O logging on
file{PROP:Profile}="DEBUG:"   !Turns Clarion I/O logging on and
                              !sends output via OutputDebugString()
                              !(viewable via debugview, etc)

file{PROP:Profile}=''         !Turns Clarion I/O logging off

PathName = file{PROP:Profile} !Queries the name of the log file

file{PROP:Log}=string         !Writes the string to the log file
file{PROP:Log}="DEBUG:"       !Writes the string to the log file

file{PROP:Details}=1          !Turns Record Buffer logging on

fFile{PROP:Details}=0         !Turns Record Buffer logging off

where Pathname is the full pathname or the filename of the log file to create. If you do not specify a path, the driver writes the log file to the current directory.

You can also accomplish on demand logging with a SEND() command and the LOGFILE driver string. See LOGFILE for more information.

Example I use frequently, which was based on the help above:

SYSTEM{PROP:DriverTracing} = '1'
 CRMNotes{PROP:TraceFile} = 'DEBUG:'
 CRMNotes{PROP:Details}=1
 CRMNotes{PROP:Profile}= 'DEBUG:'
 CRMNotes{PROP:LogSQL} = 1


问:
Not redirect to login when not authorized
I have an ASP.NET Core web application and I am decorating a few controller action methods with Authorize attribute.

So, when I am not logged in, it doesn't do any redirect and only shows me a blank page for that controller action. I have gone through a couple of tutorials and they talk about Cookie authentication.
Below is my Configure method in Startup.cs.

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "MainCookie",
        LoginPath = "/Login",
        AccessDeniedPath = "/Home/Forbidden/",
        AutomaticAuthenticate = true,
        AutomaticChallenge = false
    });
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "ExternalCookie",
        AutomaticAuthenticate = false,
        AutomaticChallenge = false
    });
    app.UseGoogleAuthentication(new GoogleOptions()
    {
        ClientId = "*****",
        ClientSecret = "*****",
        SignInScheme = "ExternalCookie"
    });
    app.UseFacebookAuthentication(new FacebookOptions()
    {
        SignInScheme = "ExternalCookie",
        AppId = "AppId",
        AppSecret = "AppSecret"
    });
    app.UseLinkedInAuthentication(new LinkedInOptions()
    {
        SignInScheme = "ExternalCookie",
        ClientId = "*****",
        ClientSecret = "*****",
        ProfileScheme = LinkedInDefaults.ProfileLoadFormat.AppDefined
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseStaticFiles();

    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
</code>```

My action here,

```<code>[Authorize]
[HttpGet("/questions/ask", Name = "askquestions")]
public IActionResult Ask()
</code>```

答: Looks like you're expected to see login page, if the user is not authenticated Since you configured AutomaticChallenge property to false, you won't redirect to the login page. This behaviour is by design. More details here

Body:
I have an ASP.NET Core web application and I am decorating a few controller action methods with Authorize attribute.

So, when I am not logged in, it doesn't do any redirect and only shows me a blank page for that controller action. I have gone through a couple of tutorials and they talk about Cookie authentication.
Below is my Configure method in Startup.cs.

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "MainCookie",
        LoginPath = "/Login",
        AccessDeniedPath = "/Home/Forbidden/",
        AutomaticAuthenticate = true,
        AutomaticChallenge = false
    });
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "ExternalCookie",
        AutomaticAuthenticate = false,
        AutomaticChallenge = false
    });
    app.UseGoogleAuthentication(new GoogleOptions()
    {
        ClientId = "*****",
        ClientSecret = "*****",
        SignInScheme = "ExternalCookie"
    });
    app.UseFacebookAuthentication(new FacebookOptions()
    {
        SignInScheme = "ExternalCookie",
        AppId = "AppId",
        AppSecret = "AppSecret"
    });
    app.UseLinkedInAuthentication(new LinkedInOptions()
    {
        SignInScheme = "ExternalCookie",
        ClientId = "*****",
        ClientSecret = "*****",
        ProfileScheme = LinkedInDefaults.ProfileLoadFormat.AppDefined
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseStaticFiles();

    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

My action here,

[Authorize]
[HttpGet("/questions/ask", Name = "askquestions")]
public IActionResult Ask()


问:
How to get an AWS EC2 instance ID from within that EC2 instance?
How can I find out the instance id of an ec2 instance from within the ec2 instance?

答:
Alternative approach for PHP:

```<code>$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document'),true);
$id = $instance['instanceId'];
print_r($instance);
</code>```

That will provide a lot of data about the instance, all nicely packed in an array, no external dependencies.
As it's a request that never failed or delayed for me it should be safe to do it that way, otherwise I'd go for curl()

OwnerDisplayName: andy

ContentLicense: CC BY-SA 4.0

Body:
Alternative approach for PHP:

$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document'),true);
$id = $instance['instanceId'];
print_r($instance);

That will provide a lot of data about the instance, all nicely packed in an array, no external dependencies.
As it's a request that never failed or delayed for me it should be safe to do it that way, otherwise I'd go for curl()


问:
javascript file input onchange not working [ios safari only]
The code below works everywhere except on safari mobile.
Apparently the onchange is never triggered.

```<code> // create a hidden file input element
 var input  = document.createElement("input");
 input.type = "file";

 // when the input content changes, do something
 input.onchange =
 function(event)
 {
  // upload files
 }

 // Trigger file browser
 input.click();
</code>```

I have found similar examples however they all refer to scenarios where there is even a form of some other visible representation of the file input and they all involve form-clearing workarounds. That wouldn't work here.

This code is being called upon clicking a picture, in order to upload a new one as a replacement.

Any hints? Anything I'm doing wrong?

答:
I'll be damned: on iOS safari two extra conditions are necessary compared to other browsers:

1) The input must be actually appended to the DOM.

2) setting .onchange won't work: addEventListener must be used instead.

Body:
The code below works everywhere except on safari mobile.
Apparently the onchange is never triggered.

 // create a hidden file input element
 var input  = document.createElement("input");
 input.type = "file";

 // when the input content changes, do something
 input.onchange =
 function(event)
 {
  // upload files
 }

 // Trigger file browser
 input.click();

I have found similar examples however they all refer to scenarios where there is even a form of some other visible representation of the file input and they all involve form-clearing workarounds. That wouldn't work here.

This code is being called upon clicking a picture, in order to upload a new one as a replacement.

Any hints? Anything I'm doing wrong?


问:
Cross Domain Tracking with new gtag.js framework
We have a few questions related to the new gtag google analytics tracking code in relation to the cross-domain bi-directional auto linker. In there documentation, they mention you can use one line of code across all sites with unknown origin using the following code,

Documentation for Cross Site

To simplify bi-directional cross-domain tracking further, you can list
  all possible domains you want to track in the domains property of the
  linker parameter of property's config for each domain, allowing you to
  use the same snippet of code on every domain:

On example-1.com, update the property's config:

```<code>gtag('config', 'GA_TRACKING_ID_1', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com']
  }
});
On example-2.com, update the property's config:

gtag('config', 'GA_TRACKING_ID_2', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com']
  }
});
</code>```

There are some inconsistencies in this code, for one, it shows the example-1 and example-2 as using different GA_TRACKING_ID's while all the other examples on the page show the same GA TRACKING ID being used across snippets. We need to use the same piece of code, not multiple pieces. We currently are looking to use this method with ONE gtag code across all sites, not multiple gtag snippets as shown. If you reference the other examples in the link above, you will see they also use one gtag.

We have a situation where we require access to a 3rd site for cross-domain tracking, but the company will not be able to immediately give us access. We do not want to make multiple requests to website #2, so in the meantime can we add all three websites into our cross-domain linking? Will it cause a conflict to add a third website that is not actively tracking basically, but eventually will be added into the mix

Google's old documentation mentions the ability to add more than three domains, does the new gtag framework still have this ability and will it work bidirectionally.

I would assume the proper method of adding bi-directional tracking would be to add it as followed to all sites

gtag('config', 'GA_TRACKING_ID_1', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com', 'example-3.com']
  }
});

答:
Just had a similar dilemma reading through the docs and implementing the solution.
A better step by step overview, that includes a link to the docs you have referenced in your question, is this Cross domain tracking with gtag.js

Code that worked in my case, and that I will mention in my answer bellow, was implemented for a situation where I needed to implement Bi-directional cross-domain tracking across multiple domains. Some of the domains that also needed to be tracked where actually sub-domains (subdomain.example.com), for them you just need to include the root domain (example.com) in the linker parameter domains property array.
Example:

```<code>gtag('config', 'GA_TRACKING_ID', {
    'linker': {
        'domains': ['example.com', 'second-example.com', 'third-example.com']
    }
});
</code>```

And the complete code, including the script src tag if someone needs it:

```<code><!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID', {
    'linker': {
        'domains': ['example.com', 'second-example.com', 'third-example.com']
    }
});
</script>
</code>```

To answer your questions:

You need/have to use one Tracking ID (also known as Property ID). That example snippet confused me as well. But you need to use the same Tracking ID as it gathers data to a single property, and that's what you want with cross-domain tracking. More about Properties here.

I don't see a problem with adding the third website domain to the domains array. The gtag tracking code gets activated only when there is a user on the website where the code is implemented. So in your case, Google Analytics just won't be able to track the traffic on the third domain until you add the appropriate code to it. The tracking on the first two websites where the code IS implemented won't be affected by this.

Yes it will work. Working example displayed above this list.

Yes, that is correct. But you've also included that extra numbering after the Tracking ID in your example that got us both confused initially :)

Of course this isn't all you need to do in order to setup a correct cross-domain tracking. As mentioned in the document referenced at the top of my answer you will also need to:

Create a copy of the reporting views and add a custom filter if you want to get full domain names in your reports. It's easier to differentiate the visits between domains this way (example: you may have an about-us.html page on every domain).

It's important that you add the tracked domains to the Referral Exclusion List. If you don't do this, cross-domain tracking will not work. It will register a single visitor going from the second-example.com to example.com as a new session.

Extra tip from the docs, that proved really helpful:
For quick testing of the above setup, you can use a Chrome extension developed by Google called "Google Tag Assistant".
It saved me a lot of time in debugging the issues.
Especially useful when working on live sites with a lot of traffic. About Tag Assistant Recordings

Body:
We have a few questions related to the new gtag google analytics tracking code in relation to the cross-domain bi-directional auto linker. In there documentation, they mention you can use one line of code across all sites with unknown origin using the following code,

Documentation for Cross Site

To simplify bi-directional cross-domain tracking further, you can list
  all possible domains you want to track in the domains property of the
  linker parameter of property's config for each domain, allowing you to
  use the same snippet of code on every domain:

On example-1.com, update the property's config:

gtag('config', 'GA_TRACKING_ID_1', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com']
  }
});
On example-2.com, update the property's config:

gtag('config', 'GA_TRACKING_ID_2', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com']
  }
});

There are some inconsistencies in this code, for one, it shows the example-1 and example-2 as using different GA_TRACKING_ID's while all the other examples on the page show the same GA TRACKING ID being used across snippets. We need to use the same piece of code, not multiple pieces. We currently are looking to use this method with ONE gtag code across all sites, not multiple gtag snippets as shown. If you reference the other examples in the link above, you will see they also use one gtag.

We have a situation where we require access to a 3rd site for cross-domain tracking, but the company will not be able to immediately give us access. We do not want to make multiple requests to website #2, so in the meantime can we add all three websites into our cross-domain linking? Will it cause a conflict to add a third website that is not actively tracking basically, but eventually will be added into the mix

Google's old documentation mentions the ability to add more than three domains, does the new gtag framework still have this ability and will it work bidirectionally.

I would assume the proper method of adding bi-directional tracking would be to add it as followed to all sites

gtag('config', 'GA_TRACKING_ID_1', {
  'linker': {
    'domains': ['example-1.com', 'example-2.com', 'example-3.com']
  }
});

Body:
Just had a similar dilemma reading through the docs and implementing the solution.
A better step by step overview, that includes a link to the docs you have referenced in your question, is this Cross domain tracking with gtag.js

Code that worked in my case, and that I will mention in my answer bellow, was implemented for a situation where I needed to implement Bi-directional cross-domain tracking across multiple domains. Some of the domains that also needed to be tracked where actually sub-domains (subdomain.example.com), for them you just need to include the root domain (example.com) in the linker parameter domains property array.
Example:

gtag('config', 'GA_TRACKING_ID', {
    'linker': {
        'domains': ['example.com', 'second-example.com', 'third-example.com']
    }
});

And the complete code, including the script src tag if someone needs it:

<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID', {
    'linker': {
        'domains': ['example.com', 'second-example.com', 'third-example.com']
    }
});
</script>

To answer your questions:

You need/have to use one Tracking ID (also known as Property ID). That example snippet confused me as well. But you need to use the same Tracking ID as it gathers data to a single property, and that's what you want with cross-domain tracking. More about Properties here.

I don't see a problem with adding the third website domain to the domains array. The gtag tracking code gets activated only when there is a user on the website where the code is implemented. So in your case, Google Analytics just won't be able to track the traffic on the third domain until you add the appropriate code to it. The tracking on the first two websites where the code IS implemented won't be affected by this.

Yes it will work. Working example displayed above this list.

Yes, that is correct. But you've also included that extra numbering after the Tracking ID in your example that got us both confused initially :)

Of course this isn't all you need to do in order to setup a correct cross-domain tracking. As mentioned in the document referenced at the top of my answer you will also need to:

Create a copy of the reporting views and add a custom filter if you want to get full domain names in your reports. It's easier to differentiate the visits between domains this way (example: you may have an about-us.html page on every domain).

It's important that you add the tracked domains to the Referral Exclusion List. If you don't do this, cross-domain tracking will not work. It will register a single visitor going from the second-example.com to example.com as a new session.

Extra tip from the docs, that proved really helpful:
For quick testing of the above setup, you can use a Chrome extension developed by Google called "Google Tag Assistant".
It saved me a lot of time in debugging the issues.
Especially useful when working on live sites with a lot of traffic. About Tag Assistant Recordings


问:
grep on unix / linux: how to replace or capture text?
So I'm pretty good with regular expressions, but I'm having some trouble with them on unix. Here are two things I'd love to know how to do:

1) Replace all text except letters, numbers, and underscore

In PHP I'd do this: (works great)```
preg_replace('#[^a-zA-Z0-9_]#','',$text).
```

In bash I tried this (with limited success); seems like it dosen't allow you to use the full set of regex:  ```
text="my #1 example!"
${text/[^a-zA-Z0-9_]/'')
```

I tried it with sed but it still seems to have problems with the full regex set:

```echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//
```

I'm sure there is a way to do it with grep, too, but it was breaking it into multiple lines when i tried:

```echo abc\!\@\#\$\%\^\&\*\(222 | grep -Eos '[a-zA-Z0-9\_]+'```

And finally I also tried using expr but it seemed like that had really limited support for extended regex...

2) Capture (multiple) parts of text

In PHP I could just do something like this:

```
preg_match('#(word1).*(word2)#',$text,$matches);
```

I'm not sure how that would be possible in *nix...

答:
Part 1

You are almost there with the sed just add the g modifier so that the replacement happen globally, without the g, replacement will happen just once.

```<code>$ echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//g
my1example
$
</code>```

You did the same mistake with your bash pattern replacement too: not making replacements globally:

```<code>$ text="my #1 example!"

# non-global replacement. Only the space is delete.
$ echo ${text/[^a-zA-Z0-9_]/''}
my#1 example!

# global replacement by adding an additional /
$ echo ${text//[^a-zA-Z0-9_]/''}
my1example
</code>```

Part 2

Capturing works the same in sed as it did in PHP's regex: enclosing the pattern in parenthesis triggers capturing:

```<code># swap foo and bar's number using capturing and back reference.
$ echo 'foo1 bar2' | sed -r 's/foo([0-9]+) bar([0-9]+)/foo\2 bar\1/'
foo2 bar1
$
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I'm pretty good with regular expressions, but I'm having some trouble with them on unix. Here are two things I'd love to know how to do:

1) Replace all text except letters, numbers, and underscore

In PHP I'd do this: (works great)

preg_replace('#[^a-zA-Z0-9_]#','',$text).

In bash I tried this (with limited success); seems like it dosen't allow you to use the full set of regex:

text="my #1 example!"
${text/[^a-zA-Z0-9_]/'')

I tried it with sed but it still seems to have problems with the full regex set:

echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//

I'm sure there is a way to do it with grep, too, but it was breaking it into multiple lines when i tried:

echo abc\!\@\#\$\%\^\&\*\(222 | grep -Eos '[a-zA-Z0-9\_]+'

And finally I also tried using expr but it seemed like that had really limited support for extended regex...

2) Capture (multiple) parts of text

In PHP I could just do something like this:

preg_match('#(word1).*(word2)#',$text,$matches);

I'm not sure how that would be possible in *nix...

Body:
Part 1

You are almost there with the sed just add the g modifier so that the replacement happen globally, without the g, replacement will happen just once.

$ echo "my #1 example!" | sed s/[^a-zA-Z0-9\_]//g
my1example
$

You did the same mistake with your bash pattern replacement too: not making replacements globally:

$ text="my #1 example!"

# non-global replacement. Only the space is delete.
$ echo ${text/[^a-zA-Z0-9_]/''}
my#1 example!

# global replacement by adding an additional /
$ echo ${text//[^a-zA-Z0-9_]/''}
my1example

Part 2

Capturing works the same in sed as it did in PHP's regex: enclosing the pattern in parenthesis triggers capturing:

# swap foo and bar's number using capturing and back reference.
$ echo 'foo1 bar2' | sed -r 's/foo([0-9]+) bar([0-9]+)/foo\2 bar\1/'
foo2 bar1
$


问:
How to combine Arbitrary and IO monads?
I am trying to write a program which writes to a file a list of data generated by an Arbitrary instance, and I am having trouble combining the Arbitrary and IO monads.

A simplified version of what I am trying to do is shown below.

```<code>main = do
  let n = 10
  list <- vector n
  writeFile "output.txt" (unlines $ show <$> list)
</code>```

This leads to a type error since writeFile's IO monad does not match vector's Gen monad.

```<code>TestCases.hs:31:3: error:
    • Couldn't match type ‘IO’ with ‘Test.QuickCheck.Gen.Gen’
      Expected type: Test.QuickCheck.Gen.Gen ()
        Actual type: IO ()
    • In a stmt of a 'do' block:
        writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n;
             writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n;
                   writeFile "output.txt" (unlines $ show <$> list) }
</code>```

I have tried using liftIO to resolve this type mismatch, but it appears that this does not work due to Gen lacking a MonadIO instance.

```<code>main = do
  let n = 10
  list <- vector n :: Gen [Integer]
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)
</code>```

gives the error

```<code>TestCases.hs:32:3: error:
    • No instance for (MonadIO Gen) arising from a use of ‘liftIO’
    • In a stmt of a 'do' block:
        liftIO $ writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n :: Gen [Integer];
             liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n :: Gen [Integer];
                   liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
</code>```

How can I print an Arbitrary-generated list to a file?

答:
The vector function gives you the list generator, and not a particular list:

```<code>vector :: Arbitrary a => Int -> Gen [a]
</code>```

Since (>>=) :: Monad m => m a -> (a -> m b) -> m b, it won't get you out of Gen. But generate from Test.QuickCheck.Gen does the particular-value-generation suitable for this situation: generate :: Gen a -> IO a. So generate (vector n) >>= writeFile "output.txt" . unlines . map show should do what you want (save for the the type ambiguity: it's not clear in your example for what Gen [a] your vector will yield, so perhaps add something like (vector n :: Gen [Int]) unless your actual application provides enough context for type inference.

Title: How to combine Arbitrary and IO monads?

Body:
I am trying to write a program which writes to a file a list of data generated by an Arbitrary instance, and I am having trouble combining the Arbitrary and IO monads.

A simplified version of what I am trying to do is shown below.

main = do
  let n = 10
  list <- vector n
  writeFile "output.txt" (unlines $ show <$> list)

This leads to a type error since writeFile's IO monad does not match vector's Gen monad.

TestCases.hs:31:3: error:
    • Couldn't match type ‘IO’ with ‘Test.QuickCheck.Gen.Gen’
      Expected type: Test.QuickCheck.Gen.Gen ()
        Actual type: IO ()
    • In a stmt of a 'do' block:
        writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n;
             writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n;
                   writeFile "output.txt" (unlines $ show <$> list) }

I have tried using liftIO to resolve this type mismatch, but it appears that this does not work due to Gen lacking a MonadIO instance.

main = do
  let n = 10
  list <- vector n :: Gen [Integer]
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)

gives the error

TestCases.hs:32:3: error:
    • No instance for (MonadIO Gen) arising from a use of ‘liftIO’
    • In a stmt of a 'do' block:
        liftIO $ writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n :: Gen [Integer];
             liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n :: Gen [Integer];
                   liftIO $ writeFile "output.txt" (unlines $ show <$> list) }

How can I print an Arbitrary-generated list to a file?

Body:
The vector function gives you the list generator, and not a particular list:

vector :: Arbitrary a => Int -> Gen [a]

Since (>>=) :: Monad m => m a -> (a -> m b) -> m b, it won't get you out of Gen. But generate from Test.QuickCheck.Gen does the particular-value-generation suitable for this situation: generate :: Gen a -> IO a. So generate (vector n) >>= writeFile "output.txt" . unlines . map show should do what you want (save for the the type ambiguity: it's not clear in your example for what Gen [a] your vector will yield, so perhaps add something like (vector n :: Gen [Int]) unless your actual application provides enough context for type inference.


问:
Format Code As a Code Block in R Markdown
Is there anyway to format code in the "code" format offered by many websites like Stackoverflow in R Markdown.

I want to be able to do something like the following:

Any model that takes the form income ~ education + parental_income
  ...

I want to emulate that greyed out text in R markdown for ease of readability when I eventually knit the document.

答:
One can use backticks or indenting by 4 spaces to generate the equivalent of the HTML   tag block. Here is an Rmd document illustrating this behavior.

```<code>---
title: "Sample Document"
author: "bigNumber"
date: "12/5/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

here is some example code written in R Markdown. If we want to enter a code block we use the backtick, such as `inc ~ ed + occ`.

If we want a code block with multiple lines, indenting by 4 spaces also works

    # first line of code
    for(i in 1:100) {
       # do something here
    }

More text after the code block ends.
</code>```

...and the output. Unfortunately I have to include an image to show that it renders correctly.

Body:
One can use backticks or indenting by 4 spaces to generate the equivalent of the HTML <code> </code> tag block. Here is an Rmd document illustrating this behavior.

---
title: "Sample Document"
author: "bigNumber"
date: "12/5/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

here is some example code written in R Markdown. If we want to enter a code block we use the backtick, such as `inc ~ ed + occ`.

If we want a code block with multiple lines, indenting by 4 spaces also works

    # first line of code
    for(i in 1:100) {
       # do something here
    }

More text after the code block ends.

...and the output. Unfortunately I have to include an image to show that it renders correctly.


问:
how to use node js to combine data from two jsons
I want to merge data from two tables and then send the result as the response.

I'm new to nodejs and lambda and I'm unable to figure out how I can merge json data from both scan calls and send it as the response.

If I uncomment the callback then response for only one table is sent.

My code is below, can someone please help in completing it

```<code>'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}

}
</code>```

答:
Welcome to JavaScript asynchronous callbacks (aka callback hell).

Fortunately, the AWS SDK supports promises so you can use Promise.all() to wait for multiple promises to be resolved. When that happens, merge the JSON results and return the merged result via the Lambda function's callback() method.

Body:
I want to merge data from two tables and then send the result as the response.

I'm new to nodejs and lambda and I'm unable to figure out how I can merge json data from both scan calls and send it as the response.

If I uncomment the callback then response for only one table is sent.

My code is below, can someone please help in completing it

'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}

}


问:
How to detect DOM modification event
I have been trying to get listen to DOM change event for a several hours, however still cannot get it working.

I need to detect events that are showed in Chrome Debug Tools as changes displayed as pink color.

Here is what I've tried

```<code>  function listenForDomModified(node, listener) {
            node.addEventListener("DOMSubtreeModified", listener, false);
            var iframes = node.getElementsByTagName("iframe");
            for (var i = 0, len = iframes.length, doc; i < len; ++i) {
                // Catch and ignore errors caused by iframes from other domains
                try {
                    doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
                    doc.addEventListener("DOMSubtreeModified", listener, false);
                } catch (ex) {}
            }
        }
        var findElements = function () {
            elements.iframeBlock = $(SELECTOR.IFRAME_BLOCK);
        };
        var onIframeChange = function (e) {

            console.log("CHANGE !!!");
            alert("DOM CHANGES");
        };
        var setListeners = function () {
            listenForDomModified(elements.iframeBlock[0],onIframeChange);
            elements.iframeBlock.bind('DOMSubtreeModified', function(e) {
                  if (e.target.innerHTML.length > 0) {
                    alert("ON CHANGE");
                  }
                  alert("ON CHANGE");
            });
            //elements.iframeBlock.change(onIframeChange);
        };
</code>```

Please note, I tried these methods separately.

But still cannot get my function called. However Chrome displays these changes.

I would be grateful for any help.

Thanks

答:
Try this jQuery approach:

```<code>$("iframe").contents().find('body').on("change", function() {
   alert("DOM CHANGES");
});
</code>```

not tested...

Title: How to detect DOM modification event

Body:
I have been trying to get listen to DOM change event for a several hours, however still cannot get it working.

I need to detect events that are showed in Chrome Debug Tools as changes displayed as pink color.

Here is what I've tried

  function listenForDomModified(node, listener) {
            node.addEventListener("DOMSubtreeModified", listener, false);
            var iframes = node.getElementsByTagName("iframe");
            for (var i = 0, len = iframes.length, doc; i < len; ++i) {
                // Catch and ignore errors caused by iframes from other domains
                try {
                    doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
                    doc.addEventListener("DOMSubtreeModified", listener, false);
                } catch (ex) {}
            }
        }
        var findElements = function () {
            elements.iframeBlock = $(SELECTOR.IFRAME_BLOCK);
        };
        var onIframeChange = function (e) {

            console.log("CHANGE !!!");
            alert("DOM CHANGES");
        };
        var setListeners = function () {
            listenForDomModified(elements.iframeBlock[0],onIframeChange);
            elements.iframeBlock.bind('DOMSubtreeModified', function(e) {
                  if (e.target.innerHTML.length > 0) {
                    alert("ON CHANGE");
                  }
                  alert("ON CHANGE");
            });
            //elements.iframeBlock.change(onIframeChange);
        };

Please note, I tried these methods separately.

But still cannot get my function called. However Chrome displays these changes.

I would be grateful for any help.

Thanks

Body:
Try this jQuery approach:

$("iframe").contents().find('body').on("change", function() {
   alert("DOM CHANGES");
});

not tested...


问:
How can I pause an entire script, then continuing the script
What I have is many scripts that has several thousand calls to the setTimeout() function that basically draws animated lines on a canvas. It works beautifully on a computer (of course), and also on mobile devices if the user doesn't touch anything. That being the case I added an touchstart event listener, that will start the entire animation over (they are all about 30 to 40 seconds long) when anything is touched. Works well once again. Issue being is that almost everyone has there mobile devices screen dim then shut off before the animation is complete, and of course when you see the screen dim you touch the screen to prevent it from shutting off, hence the animation starts over !!

I have fooled around with clearTimeout() function, the best I can do is clear all the calls to it at once, then start it over again. This is what I have noticed, I sometimes throw an alert(whatever) in the code to debug it and I have noticed that when the box pops up on a mobile device it actually pauses the entire javascript INCLUDING all thousands of the setTimeout calls, then when you press ok on the alert box, the script continues on its merry way exactly from where it stopped. That's what I want.

Question is, is there  global script pause function that will SIMULATE an alert box that will pause the entire script on a touch (allowing a user to say scroll the page or fill in a text box or whatever) then continue on from where it left off ?

Just adding a complaint here: Why would scrolling a page on a mobile device or zooming or simply clicking a text box which brings up the keyboard affect in anyway the timing in the setTimeout() function, it is all loaded into memory from the get go, time is absolute, it keeps going and going, makes no sense.

Thank you for reading.

答:
Confusing man, lots to read. And still confused, I think you need something that constantly checks if it needs to throw alert, or if you throw alert. Pause something until alert is gone.

You would use a loop function, that only runs when alert = false, or sleep = false.

```<code>var sleep = false;

function main() {
     if (!sleep) {

        // We run the script
        // Throw alert
        // Sleep now = true, because we threw alert
       sleep = true;

    } else if (sleep == true) {
        // Pause
        // Re-run when sleep is not false;
        main();
    } else {
 //whatevs
}
</code>```

or

```<code>while (!sleep) {
  // do stuff
  alert()
  sleep = true;
}
</code>```

Body:
Confusing man, lots to read. And still confused, I think you need something that constantly checks if it needs to throw alert, or if you throw alert. Pause something until alert is gone.

You would use a loop function, that only runs when alert = false, or sleep = false.

var sleep = false;

function main() {
     if (!sleep) {

        // We run the script
        // Throw alert
        // Sleep now = true, because we threw alert
       sleep = true;

    } else if (sleep == true) {
        // Pause
        // Re-run when sleep is not false;
        main();
    } else {
 //whatevs
}

or

while (!sleep) {
  // do stuff
  alert()
  sleep = true;
}


问:
PostgreSQL, distinct, order by and parentheses
I have the following request:

```<code>select distinct m1.firstname, m1.surname
  from cd.members as m1
  join cd.members as m2 on m2.recommendedby = m1.memid
  order by m1.surname, m1.firstname;
</code>```

and it works fine. But this one:

```<code>select distinct m1.firstname, m1.surname
  from cd.members as m1
  join cd.members as m2 on m2.recommendedby = m1.memid
  order by (m1.surname, m1.firstname);
</code>```

gives me the error:

```<code>ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
</code>```

I can't understand when I have to use parentheses and when not.

答:
Postgres has the concept of tuples or composite types.  These are scalar values that appear together -- much like a record or struct in many programming languages.

You can use tuples for expressions, such as:

```<code>where (m1.surname, m1.firstname) in ( ('a', 'b'), ('x', 'y') )
</code>```

The problem with your order by expression is that the tuple is not in the select.  You could solve this by using parentheses there too:

```<code>select distinct (m1.firstname, m1.surname)
from cd.members m1 join
     cd.members m2
     on m2.recommendedby = m1.memid
order by (m1.surname, m1.firstname);
</code>```

But I would stick with the parentheses-less version, which is standard SQL and works in all databases.

Body:
I have the following request:

select distinct m1.firstname, m1.surname
  from cd.members as m1
  join cd.members as m2 on m2.recommendedby = m1.memid
  order by m1.surname, m1.firstname;

and it works fine. But this one:

select distinct m1.firstname, m1.surname
  from cd.members as m1
  join cd.members as m2 on m2.recommendedby = m1.memid
  order by (m1.surname, m1.firstname);

gives me the error:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

I can't understand when I have to use parentheses and when not.

Body:
Postgres has the concept of tuples or composite types.  These are scalar values that appear together -- much like a record or struct in many programming languages.

You can use tuples for expressions, such as:

where (m1.surname, m1.firstname) in ( ('a', 'b'), ('x', 'y') )

The problem with your order by expression is that the tuple is not in the select.  You could solve this by using parentheses there too:

select distinct (m1.firstname, m1.surname)
from cd.members m1 join
     cd.members m2
     on m2.recommendedby = m1.memid
order by (m1.surname, m1.firstname);

But I would stick with the parentheses-less version, which is standard SQL and works in all databases.


问:
scrapy: if node contains child node

I have the following web page:
https://www.bbc.co.uk/search?q=Juice&sa_f=search-product&filter=news&suggid=

for each article, I have the following html section i want to scrape the text of  from:

```<code><dd>
<span class="signpost-site" data-site="news">News
</span>
<span class="signpost-section">Europe
</span>
</dd>
</code>```

In this case, I want "Europe"

sometimes the

```<code><span class="signpost-section">
</code>```

is missing and instead there is

```<code><dd>
<span class="signpost-site" data-site="news">News
</span>
</dd>
</code>```

In this case I want ""

The intention is to create a csv and ensure each article has the right tag at the right index number.

currently my code is

```<code>response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract()
</code>```

which gets existing tags only. I am unsure on how to check whether or not the

```<code><span class="signpost-section">
</code>```

exists within

```<code>response.xpath('//footer//dd/span[@class="signpost-site"])
</code>```

ideally i want something along the lines of

```<code>if  <span class="signpost-section"> (exists in) response.xpath('//footer//dd/span[@class="signpost-site"])
then
response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract()
else ""
</code>```

答:
I would just use .extract_first() with a specified default value (used when no match):

```<code>response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract_first(default='')
</code>```

Title: scrapy: if node contains child node

Body:
I have the following web page:
https://www.bbc.co.uk/search?q=Juice&sa_f=search-product&filter=news&suggid=

for each article, I have the following html section i want to scrape the text of  from:

News

Europe

In this case, I want "Europe"

sometimes the

is missing and instead there is

News

In this case I want ""

The intention is to create a csv and ensure each article has the right tag at the right index number.

currently my code is

response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract()

which gets existing tags only. I am unsure on how to check whether or not the

exists within

response.xpath('//footer//dd/span[@class="signpost-site"])

ideally i want something along the lines of

if   (exists in) response.xpath('//footer//dd/span[@class="signpost-site"])
then
response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract()
else ""

Body:
I would just use .extract_first() with a specified default value (used when no match):

response.xpath('//footer//dd/span[@class="signpost-section"]/text()').extract_first(default='')


问:
How to handle null while setting date in log4j2 jdbcappender?
When I set null value in the date column I get "1900-01-01 00:00:00.000" value in my table and I am expecting NULL in that column.
As this is handled properly in jdbc if I put like this

```<code>preparedStatement.setBindParam(Types.TIMESTAMP, 12, startdate);
</code>```

log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">

    <CustomLevels>
        <CustomLevel name="TESTLOG" intLevel="552" />
    </CustomLevels>

    <Appenders>

        <JDBC name="myAppender" tableName="MYTABLE">
            <DataSource jndiName="java:MyDataSource" />
            <Column name="ID" pattern="%X{ID}" isUnicode="false"/>
            <Column name="startdate" pattern="%X{startdate}" isUnicode="false"/>
            <Column name="enddate" pattern="%X{enddate}" isUnicode="false"/>
        </JDBC>

    </Appenders>

    <Loggers>
        <Root level="trace"  includeLocation="false">
            <AppenderRef ref="myAppender" level="TESTLOG" />
        </Root>
    </Loggers>

</Configuration>
</code>```

Datatype of columns startdate and enddate is datetime

```<code>ThreadContext.put("startdate", startdate != null ? startdate.toString() : null);
ThreadContext.put("enddate", a_reportEndDate != null ? enddate.toString() : null);
final Logger LOGGER = LogManager.getLogger();
LOGGER.log(Level.forName("TESTLOG", 552), "");
</code>```

The same is for String with null value.

答:
Inserting null

I don't think it's possible to get null into any column of any type using JDBCAppender with patterns like this.

This thread popped up a couple of years ago, followed by this Jira issue.  None of it seems to have gotten any attention.

The short version is that a StringBuilder is used between pattern and prepared statement, and thus the INSERT always gets a non-null string, even if (in your example) null is the value in the ThreadContext.  So it's possible to insert an empty string, or the string "null", but it doesn't appear to be possible to insert the value null.

January 1, 1900

When I run your example against a MySQL database, the insert fails up front, because MySQL doesn't know how to construct a DATETIME from an empty string.

I'm guessing you're using SQL Server, which will happily turn an empty string into 1900-01-01 00:00:00.000, because of course that's what you meant.

Regardless of the database you use, JDBCAppender is going to fill the INSERT statement with non-null strings.  What happens from there will vary from DB to DB.

Why?

At first it may seem strange that the framework is changing your value (null) to another value (empty string).  However, at its core, logging is about strings of text.

Yes, there's an appender that will write these strings to a database.  And yes, your database can in turn coax those strings into types like DATETIME or INTEGER.  But to any given appender, it's all really just about manipulating and outputting strings.

Possible work-around

If you really want to get null into the database using JDBCAppender, you may be able to write a trigger.

Final Observation

Not sure if this helps any, but I may as well present all my findings:

Using ColumnMapping instead of Column in your log4j config allows you to specify a class name.  The presence (or absence) and value of this class name does change the value that is inserted into the database.  For example, using SQL Server Express 2014:

```<code><ColumnMapping name="startdate" pattern="%X{startdate}" type="java.sql.Timestamp"/>
</code>```

Will cause the current date and time to be logged when startdate is null, instead of 1900-01-01.  Using java.sql.Date instead will log the current date without time.

Body:
When I set null value in the date column I get "1900-01-01 00:00:00.000" value in my table and I am expecting NULL in that column.
As this is handled properly in jdbc if I put like this

preparedStatement.setBindParam(Types.TIMESTAMP, 12, startdate);

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">

    <CustomLevels>
        <CustomLevel name="TESTLOG" intLevel="552" />
    </CustomLevels>

    <Appenders>

        <JDBC name="myAppender" tableName="MYTABLE">
            <DataSource jndiName="java:MyDataSource" />
            <Column name="ID" pattern="%X{ID}" isUnicode="false"/>
            <Column name="startdate" pattern="%X{startdate}" isUnicode="false"/>
            <Column name="enddate" pattern="%X{enddate}" isUnicode="false"/>
        </JDBC>

    </Appenders>

    <Loggers>
        <Root level="trace"  includeLocation="false">
            <AppenderRef ref="myAppender" level="TESTLOG" />
        </Root>
    </Loggers>

</Configuration>

Datatype of columns startdate and enddate is datetime

ThreadContext.put("startdate", startdate != null ? startdate.toString() : null);
ThreadContext.put("enddate", a_reportEndDate != null ? enddate.toString() : null);
final Logger LOGGER = LogManager.getLogger();
LOGGER.log(Level.forName("TESTLOG", 552), "");

The same is for String with null value.

Body:
Inserting null

I don't think it's possible to get null into any column of any type using JDBCAppender with patterns like this.

This thread popped up a couple of years ago, followed by this Jira issue.  None of it seems to have gotten any attention.

The short version is that a StringBuilder is used between pattern and prepared statement, and thus the INSERT always gets a non-null string, even if (in your example) null is the value in the ThreadContext.  So it's possible to insert an empty string, or the string "null", but it doesn't appear to be possible to insert the value null.

January 1, 1900

When I run your example against a MySQL database, the insert fails up front, because MySQL doesn't know how to construct a DATETIME from an empty string.

I'm guessing you're using SQL Server, which will happily turn an empty string into 1900-01-01 00:00:00.000, because of course that's what you meant.

Regardless of the database you use, JDBCAppender is going to fill the INSERT statement with non-null strings.  What happens from there will vary from DB to DB.

Why?

At first it may seem strange that the framework is changing your value (null) to another value (empty string).  However, at its core, logging is about strings of text.

Yes, there's an appender that will write these strings to a database.  And yes, your database can in turn coax those strings into types like DATETIME or INTEGER.  But to any given appender, it's all really just about manipulating and outputting strings.

Possible work-around

If you really want to get null into the database using JDBCAppender, you may be able to write a trigger.

Final Observation

Not sure if this helps any, but I may as well present all my findings:

Using ColumnMapping instead of Column in your log4j config allows you to specify a class name.  The presence (or absence) and value of this class name does change the value that is inserted into the database.  For example, using SQL Server Express 2014:

<ColumnMapping name="startdate" pattern="%X{startdate}" type="java.sql.Timestamp"/>

Will cause the current date and time to be logged when startdate is null, instead of 1900-01-01.  Using java.sql.Date instead will log the current date without time.


问:
ALIAS record pointing to AWS endpoint, bad idea?
We have an AWS RDS Multi AZ deployment and one of our teams is using a subdomain (rds1.company.com) to access it. The subdomain uses an ALIAS record to point to the AWS endpoint and when I replaced the instance with a restored snapshot last week, it took at least an hour to refresh and point to the new instance.

Since the idea of a Multi AZ deployment is so that the endpoint can point to the fallback server whenever needed, isn't a custom domain a bad idea? I was told by our network admin that the ALIAS record refreshes once an hour.

答:
Route53 ALIAS records have a fixed TTL of 60 seconds. This is stated in the Route53 FAQ. Public Internet DNS servers often times ignore the TTL.

Route53 ALIAS records do not support RDS, so you are most likely using a CNAME with a TTL of 3600 seconds. The TTL (expiration) can be set as short as 1 second but Amazon recommends a minimum TTL of 10 seconds.

Multi-AZ RDS endpoint will failover automatically in less than 60 seconds with Aurora and as fast as 30 seconds with MariaDB Connector/J. Other instance types can take from one to two minutes. This is covered in the RDS FAQ.

Make sure that the Route53 CNAME record is using the RDS DNS Name (endpoint) and not the IP address. You can set the CNAME TTL to be a small as you need.

Amazon Route 53 FAQ

Amazon RDS FAQs


问:
need to generate text box automatically when I click on the mouse point in image box (while after browsing image in the form.) for the .net form
I need generate text box while I click on the mouse point in image box. in this code only generate text box click on the form. it not generate text box for click on the image box.  </p>

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        TextBox tb = new TextBox();
        tb.Location = new Point(e.X, e.Y);
        tb.Width = 100;
        this.Controls.Add(tb);
    }
}
</code>```

答:
public Form1()
  {
     InitializeComponent();
     this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
  }

This code of yours adds the mousedown event on the form .
If you want to have the mouse down event in the image box ,
Do this

1) Go to form designer
2) In the properties of image box, go to events and in mousedown choose the Form1_MouseDown event.

Hope this helps

Body:
I need generate text box while I click on the mouse point in image box. in this code only generate text box click on the form. it not generate text box for click on the image box.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        TextBox tb = new TextBox();
        tb.Location = new Point(e.X, e.Y);
        tb.Width = 100;
        this.Controls.Add(tb);
    }
}


问:
Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL
I have a site that treats / and %2F in the path portion (not the query string) of a URL differently. Is this a bad thing to do according to either the RFC or the real world?

I ask because I keep running into little surprises with the web framework I'm using (Ruby on Rails) as well as the layers below that (Passenger, Apache, e.g., I had to enable ALLOW_ENCODED_SLASHES for Apache). I am now leaning toward getting rid of the encoded slashes completely, but I wonder if I should be filing bug reports where I see weird behavior involving the encoded slashes.

As to why I have the encoded slashes in the first place, basically I have routes such as this:

```<code>:controller/:foo/:bar
</code>```

where :foo is something like a path that can contain slashes. I thought the most straightforward thing to do would be to just URL escape foo so the slashes are ignored by the routing mechanism. Now I am having doubts, and it's pretty clear that the frameworks don't really support this, but according to the RFC is it wrong to do it this way?

Here is some information I have gathered:

RFC 1738 (URLs):

Usually a URL has the same interpretation when an octet is represented by a character and when it encoded. However, this is not true for reserved characters: encoding a character reserved for a particular scheme may change the semantics of a URL.

RFC 2396 (URIs):

These characters are called "reserved", since their usage within the URI component is limited to their reserved purpose. If the data for a URI component would conflict with the reserved purpose, then the conflicting data must be escaped before forming the URI.

(does escaping here mean something other than encoding the reserved character?)

RFC 2616 (HTTP/1.1):

Characters other than those in the "reserved" and "unsafe" sets (see RFC 2396 [42]) are equivalent to their "% HEX HEX" encoding.

There is also this bug report for Rails, where they seem to expect the encoded slash to behave differently:

Right, I'd expect different results because they're pointing at different resources.

It's looking for the literal file foo/bar in the root directory. The non escaped version is looking for the file bar within directory foo.

It's clear from the RFCs that raw vs. encoded is the equivalent for unreserved characters, but what is the story for reserved characters?

答:
What to do if :foo in its natural form contains slashes?  You wouldn't want it to  Isn't that the distinction the recommendation is attempting to preserve?  It specifically notes,

The similarity to unix and other disk operating system filename conventions should be taken as purely coincidental, and should not be taken to indicate that URIs should be interpreted as file names.

If one was building an online interface to a backup program, and wished to express the path as a part of the URL path, it would make sense to encode the slashes in the file path, as that is not really part of the hierarchy of the resource - and more importantly, the route.  /backups/2016-07-28content//home/dan/ loses the root of the filesystem in the double slash.  Escaping the slashes is the appropriate way to distinguish, as I read it.

Body:
I have a site that treats / and %2F in the path portion (not the query string) of a URL differently. Is this a bad thing to do according to either the RFC or the real world?

I ask because I keep running into little surprises with the web framework I'm using (Ruby on Rails) as well as the layers below that (Passenger, Apache, e.g., I had to enable ALLOW_ENCODED_SLASHES for Apache). I am now leaning toward getting rid of the encoded slashes completely, but I wonder if I should be filing bug reports where I see weird behavior involving the encoded slashes.

As to why I have the encoded slashes in the first place, basically I have routes such as this:

:controller/:foo/:bar

where :foo is something like a path that can contain slashes. I thought the most straightforward thing to do would be to just URL escape foo so the slashes are ignored by the routing mechanism. Now I am having doubts, and it's pretty clear that the frameworks don't really support this, but according to the RFC is it wrong to do it this way?

Here is some information I have gathered:

RFC 1738 (URLs):

Usually a URL has the same interpretation when an octet is represented by a character and when it encoded. However, this is not true for reserved characters: encoding a character reserved for a particular scheme may change the semantics of a URL.

RFC 2396 (URIs):

These characters are called "reserved", since their usage within the URI component is limited to their reserved purpose. If the data for a URI component would conflict with the reserved purpose, then the conflicting data must be escaped before forming the URI.

(does escaping here mean something other than encoding the reserved character?)

RFC 2616 (HTTP/1.1):

Characters other than those in the "reserved" and "unsafe" sets (see RFC 2396 [42]) are equivalent to their "% HEX HEX" encoding.

There is also this bug report for Rails, where they seem to expect the encoded slash to behave differently:

Right, I'd expect different results because they're pointing at different resources.

It's looking for the literal file foo/bar in the root directory. The non escaped version is looking for the file bar within directory foo.

It's clear from the RFCs that raw vs. encoded is the equivalent for unreserved characters, but what is the story for reserved characters?


问:
PHP Parse error while trying to write to a MySQL table
I'm new to php and to MySQL. I have checked other examples here but I am not able to understand where I went wrong. I am trying to write user data into a table called enrolled on the MySQL database. However I keep getting this error

```<code>Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
</code>```

and this is my code that is creating the error

```<code> $enroll = "INSERT INTO enrollment VALUES($srow['family'] $srow['uid'] $course)";
</code>```

答:
As stated already, you can access the values inside the array this way:

```<code>"values({$arr['key']})"
</code>```

Also, are you properly escaping all input before inserting it? How are you executing that query?

Using SQL APIs would be the proper way to do this (and way safer). Take a look at this page on PHP manual: http://php.net/manual/en/mysqlinfo.api.choosing.php, it should help you out understanding the proper way to manage interactions with your databases.

Body:
I'm new to php and to MySQL. I have checked other examples here but I am not able to understand where I went wrong. I am trying to write user data into a table called enrolled on the MySQL database. However I keep getting this error

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

and this is my code that is creating the error

 $enroll = "INSERT INTO enrollment VALUES($srow['family'] $srow['uid'] $course)";

Body:
As stated already, you can access the values inside the array this way:

"values({$arr['key']})"

Also, are you properly escaping all input before inserting it? How are you executing that query?

Using SQL APIs would be the proper way to do this (and way safer). Take a look at this page on PHP manual: http://php.net/manual/en/mysqlinfo.api.choosing.php, it should help you out understanding the proper way to manage interactions with your databases.


问:
Angular 4: marking an entire component as dirty
I have a component with many input elements. I am aware that I can use ng-model and ids to access properties such as dirty and pristine (as per the Angular documentation).

However I'm wondering if there's an easier way to set the dirty property at the component level.

答: You would typically wrap your HTML elements in a Form, and that form would be set to dirty. I mean, if you want your component to be marked dirty, you could just create a property called 'dirty' but I'm not sure that would buy you anything.</p>


问:
Is it possible to make sure addClass() is rendered before showing confirm() box?
In the following code, the confirm box shows before addClass has been rendered (i.e. Safari 6.0.5).  Is it possible to make sure addClass() is rendered before showing confirm() box?</p>

```<code><style type="text/css">
.preview    { background-color: #eee;width:100;height:100;color:red; }
.preview_s  { border:3px solid blue;}
</style>

<script type="text/javascript">
function test(i)
{
    $("#testdiv"+i).addClass('preview_s');
    if (confirm('border not blue and checkmark not visible on some browsers until after choice is made'))
    {
        // Do confirmed thing here
    } else {
        // Abort
    }
}
</script>

<form id="testform">
<div class="preview" id="testdiv1">test1</div>
<input type="checkbox" onclick="test(1);">
<div class="preview" id="testdiv2">test2</div>
<input type="checkbox" onclick="test(2);">
</form>
</code>```

答:
I realized it in the following way, but I did not use it. Because it is ambiguous whether the class attribute is attached before the confirm box opens, and I disliked waiting for 80 ms.</p>

```<code>const wrapper = button.closest('.js-item-row')
let needsSubmit = false
button.addEventListener('click', function(e){
  if(!needsSubmit) {
    e.preventDefault()
    const message = button.getAttribute('data-confirm-message')
    wrapper.classList.add('dynamicScaffold-destorying')
    setTimeout(function(){
      if(!confirm(message)){
        wrapper.classList.remove("dynamicScaffold-destorying");
      } else {
        needsSubmit = true
        button.click()
      }
    }, 80)
  }
})
</code>```

Body:
In the following code, the confirm box shows before addClass has been rendered (i.e. Safari 6.0.5).  Is it possible to make sure addClass() is rendered before showing confirm() box?

<form id="testform">

test1

<input type="checkbox" onclick="test(1);">

test2

<input type="checkbox" onclick="test(2);">
</form>

Body:
I realized it in the following way, but I did not use it. Because it is ambiguous whether the class attribute is attached before the confirm box opens, and I disliked waiting for 80 ms.

const wrapper = button.closest('.js-item-row')
let needsSubmit = false
button.addEventListener('click', function(e){
  if(!needsSubmit) {
    e.preventDefault()
    const message = button.getAttribute('data-confirm-message')
    wrapper.classList.add('dynamicScaffold-destorying')
    setTimeout(function(){
      if(!confirm(message)){
        wrapper.classList.remove("dynamicScaffold-destorying");
      } else {
        needsSubmit = true
        button.click()
      }
    }, 80)
  }
})


问:
How to schedule a dag to run a particular time of day of a month of a year. i.e., once
I'm trying to execute a dag which needs to be run only once. So I placed the dag execution interval as '@once'. However, I'm getting the error as mentioned in this link -
https://issues.apache.org/jira/browse/AIRFLOW-1400

Now i'm trying to pass the exact date of execution as below:

```<code>default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 2017',concurrency=1)
</code>```

This is throwing error as:

```<code>File "/usr/lib/python2.7/site-packages/croniter/croniter.py", line 543, in expand
expr_format))
CroniterBadCronError: [12 09 13 11 2017] is not acceptable, out of range
</code>```

Can someone help to resolve this.

Thanks,
Arjun

答:
Set a yearly interval for the minute, hour, day, month, and weekday number you want. I.E. 12 09 13 11 *. Set your DAG's start_date and end_date before and after that date respectively, and it should run only once at that time.

```<code>default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,1,1),
'end_date': datetime(2017,12,31),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 *',concurrency=1)
</code>```

It's possible that since datetime can take your time you might set the start_date with the hour and minute and then use the @once schedule. But I haven't tried that myself.

```<code>default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13,9,11),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='@once',concurrency=1)
</code>```

Body:
I'm trying to execute a dag which needs to be run only once. So I placed the dag execution interval as '@once'. However, I'm getting the error as mentioned in this link -
https://issues.apache.org/jira/browse/AIRFLOW-1400

Now i'm trying to pass the exact date of execution as below:

default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 2017',concurrency=1)

This is throwing error as:

File "/usr/lib/python2.7/site-packages/croniter/croniter.py", line 543, in expand
expr_format))
CroniterBadCronError: [12 09 13 11 2017] is not acceptable, out of range

Can someone help to resolve this.

Thanks,
Arjun

Body:
Set a yearly interval for the minute, hour, day, month, and weekday number you want. I.E. 12 09 13 11 *. Set your DAG's start_date and end_date before and after that date respectively, and it should run only once at that time.

default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,1,1),
'end_date': datetime(2017,12,31),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 *',concurrency=1)

It's possible that since datetime can take your time you might set the start_date with the hour and minute and then use the @once schedule. But I haven't tried that myself.

default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13,9,11),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='@once',concurrency=1)


问:
How to find the sum of the minor diagonal in a matrix (JAVA)
I am trying to find the sum of the minor diagonal in a matrix, but my code only shows the first number in the matrix. Is there any way to fix it?</p>

```<code>//sum of minor diagonal in matrix
public static int minorDiagonal(int[][] array){
    int k = 0, j = 0;
    int sumMinD = 0;
     k = array.length - 1;
    for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
            sumMinD += array[j][k];

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

答:
Why did you set k as 0 in this line?

```<code>for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--)
</code>```

It will run for loop once because k will be -1 after first time. So

k >=0

will be false.

I think you have to remove k=0 part.

Body:
I am trying to find the sum of the minor diagonal in a matrix, but my code only shows the first number in the matrix. Is there any way to fix it?

//sum of minor diagonal in matrix
public static int minorDiagonal(int[][] array){
    int k = 0, j = 0;
    int sumMinD = 0;
     k = array.length - 1;
    for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
            sumMinD += array[j][k];

    }
return sumMinD;
}

Body:
Why did you set k as 0 in this line?

for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--)

It will run for loop once because k will be -1 after first time. So

k >=0

will be false.

I think you have to remove k=0 part.


问:
How to clean x of non alphabets or digits
How can I remove every character from string except digits or alphabets?
example:

dirty x:

x = as-.213sadf34-.-&¤%#

cleaned x:

x = as213sadf34

答:
Since I don't know which language your are using, I will propose the following high level way of processing:

Fetch all the strings you want to clean from your file

Use the following regex [^\da-zA-Z] on all your strings and replace the match by the empty string ''


问:
Android Studio : Missing SDK
I am on windows 7, i have installed all the java environnement.
JAVA_HOME is working.
When i try to install android studio, he display me a window that said :

Missing SDK

So it's impossible to create or open a project. I have nothing on AppData folder.
I saw all the posts about this question on stackoverflow, nothing helped me.

I try everything, do you have an advice or an idea.

Thx.

答: FINALLY, I had the same exact problem downloading the latest software 3.0.1 for windows. This process works, before hitting open a new project, go to "configuration" at the bottom of the screen find settings for SDK manager and route the separately downloaded SDK files location to the file. Then any other additional SDK selections you need you can simply click on the box and select it and it will download. No other answers I found helped me except this one. Very simple solution but not so simple if your a first-time user learning this program.</p>

Title: Android Studio : Missing SDK


问:
Using params in a sqlite INSERT statement in Smart Mobile Studio?
I have created the following database

```<code>SqlResult := fDataBase.Exec("CREATE TABLE workstations (workstation string, location string, userId string);");
</code>```

How do you use params in a sqlite INSERT statement.

For example, I assume it would be something as such

```<code>FDatabase.Exec("INSERT INTO workstations values(?,?,?);", [AWorkstation, ALocation, AUserId]);
</code>```

However, Exec only takes a string........so do I have to actually build out the whole string to include the params?

```<code>FDatabase.Exec("INSERT INTO workstations values( + AWorkstation + ',' + ALocation + ',' +  AUserId +');" );
</code>```

reason I ask, is that the

TSQLiteDatabase  has a CreateStatement function that returns a

TSQLiteStatement  class

which has a SQL & Params property

and the following methods

prepare
execute
release

do I instead of calling the databases exec, i instead do a createstatement, assign sql and params, and then execute ?

e.g.

```<code>stm:= fDatabase.CreateStatement;
stm.SQL:= ?
stm.Params:=  ?
stm.execute;
</code>```

i have even tried

```<code>FDatabase.Exec('INSERT INTO workstations (workstation, location, userid) values(' + AWorkstation + ',' + ALocation + ',' +  AUserId +');');
</code>```

If I hardcode the values, this works

```<code>FDatabase.Exec("INSERT INTO workstations (workstation, location, userid) values('WS0202', 'Maintenance', 'jdoe');");
</code>```

but, i need to be able to use params

also tried it with a format function and still doesn't work

```<code>FDatabase.Exec(Format("INSERT INTO workstations (workstation, location, userid) values(%s ,%s, %s );", [AWorkstation, ALocation, AUserId]));
</code>```

答:
```<code>FDatabase.Exec(Format("INSERT INTO workstations (workstation, location, userid) values('%s' ,'%s', '%s');", [AWorkstation, ALocation, AUserId]));
</code>```

Body:
I have created the following database

SqlResult := fDataBase.Exec("CREATE TABLE workstations (workstation string, location string, userId string);");

How do you use params in a sqlite INSERT statement.

For example, I assume it would be something as such

FDatabase.Exec("INSERT INTO workstations values(?,?,?);", [AWorkstation, ALocation, AUserId]);

However, Exec only takes a string........so do I have to actually build out the whole string to include the params?

FDatabase.Exec("INSERT INTO workstations values( + AWorkstation + ',' + ALocation + ',' +  AUserId +');" );

reason I ask, is that the

TSQLiteDatabase  has a CreateStatement function that returns a

TSQLiteStatement  class

which has a SQL & Params property

and the following methods

prepare
execute
release

do I instead of calling the databases exec, i instead do a createstatement, assign sql and params, and then execute ?

e.g.

stm:= fDatabase.CreateStatement;
stm.SQL:= ?
stm.Params:=  ?
stm.execute;

i have even tried

FDatabase.Exec('INSERT INTO workstations (workstation, location, userid) values(' + AWorkstation + ',' + ALocation + ',' +  AUserId +');');

If I hardcode the values, this works

FDatabase.Exec("INSERT INTO workstations (workstation, location, userid) values('WS0202', 'Maintenance', 'jdoe');");

but, i need to be able to use params

also tried it with a format function and still doesn't work

FDatabase.Exec(Format("INSERT INTO workstations (workstation, location, userid) values(%s ,%s, %s );", [AWorkstation, ALocation, AUserId]));


问:
How to convert trained model to Core ML with Tensorflow
Apple introduces Core ML this year on iOS11. There's a Core ML Tool to convert trained model to Core ML format (.mlmodel).

Is it possible to convert Core ML model with Tensorflow? How?

答:
Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano.

Currently, coremltools 0.7 can convert the model of
Keras (1.2.2, 2.0.4+) with Tensorflow (1.0.x, 1.1.x)

```<code># Make a Keras model
>>> model = Sequential()
>>> model.add(Dense(num_channels, input_dim = input_dim))

# Convert it with default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.keras.convert(model)

# Saving the Core ML model to a file.
>>> coreml_model.save('my_model.mlmodel')
</code>```

You can take a look at my project here

Body:
Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano.

Currently, coremltools 0.7 can convert the model of
Keras (1.2.2, 2.0.4+) with Tensorflow (1.0.x, 1.1.x)

# Make a Keras model
>>> model = Sequential()
>>> model.add(Dense(num_channels, input_dim = input_dim))

# Convert it with default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.keras.convert(model)

# Saving the Core ML model to a file.
>>> coreml_model.save('my_model.mlmodel')

You can take a look at my project here


问:
list of frequencies in time to signal in python
I'm trying to make (audio) signal from single tone, frequency, which changes over time.

I have tone as 1d numpy array:
freq = [100, 102, 103, 100, 115, 113, ..., 430]

Every value correspondent no N (e.g. 100) samples. I know how to make sure it matches every pattern (N=1). (it can grow and fall at the during of the time)

Now I need this frequency 'curve' convert to sinusoid signal.

I know about scipy.signal.sweep_poly (and similar) functions, but i can't describe frequency as polynom.

Please, can you help me, how can I generate signal from frequency list?

Thank you so much!

答:
Not sure I understand 100% what you want but how about:

```<code>freqs = np.random.uniform(100, 400, (20,))
times = np.cumsum(np.random.uniform(0.01, 0.02, (20,)))
# or np.arange(20) / sample_freq if evenly sampled
grid, dt = np.linspace(0, times[-1], 10000, retstep=True)
signal = np.sin(2*np.pi*dt*np.cumsum(np.interp(grid, times, freqs)))
</code>```

This uses linear interpolation between the sampled time points. Other methods are available in scipy.interpolate

Body:
Not sure I understand 100% what you want but how about:

freqs = np.random.uniform(100, 400, (20,))
times = np.cumsum(np.random.uniform(0.01, 0.02, (20,)))
# or np.arange(20) / sample_freq if evenly sampled
grid, dt = np.linspace(0, times[-1], 10000, retstep=True)
signal = np.sin(2*np.pi*dt*np.cumsum(np.interp(grid, times, freqs)))

This uses linear interpolation between the sampled time points. Other methods are available in scipy.interpolate


问:
Spring Integration WebFlux.outboundGateway is never invoked
I've a simple flow:

```<code>return IntegrationFlows.from(ARTIFACTORY_INPUT_CHANNEL)
    .handle(WebFlux.outboundGateway(url)
            .expectedResponseType(new ParameterizedTypeReference<Mono<ArtifactorySearchResponse>>() {
            })
            .httpMethod(GET)
            .encodeUri(true))
    .transform(new ArtifactorySearchResponseTransformer())
    .channel(ARTIFACTORY_OUTPUT_CHANNEL)
    .get();
</code>```

And a simple test:

```<code>outputChannel.subscribe(mockMessageHandler);
inputChannel.send(new GenericMessage<>("test"));

verify(mockMessageHandler).handleMessage(argThat(m -> {
    Object payload = m.getPayload();

    return payload instanceof String
            && payload.toString().equals("businesses.20171203.json.gz");
}));
</code>```

that keep failing because the mockMessageHandler is never invoked. I've looked, and looked, and looked, but there are exactly zero examples of testing WebFlux.outboundGateway. Spring integration does have many examples, but those are almost useless because they

Are in XML (yeah, 2005 is calling)

Don't cover WebFlux.

答:
As always, looking in the Spring source code if often times more productive than waiting for help. Turns out, I was missing a few things:

The expectedResponseType is not supposed to be a reactive publisher, just my DTO/domain object, or some collection of those.

The HTTP call was failing but the error didn't show up because I wasn't paying attention to the error channel, and hadn't configured one for my app. I assumed that at least during testing, Spring would log the exceptions, but that wasn't the case. I am considering creating a ticket so that a simple console logging error handler is enabled for tests.

I also needed to provide a timeout to allow for the HTTP call to complete. This is done using Mockito VerificationAfterDelay

Body:
I've a simple flow:

return IntegrationFlows.from(ARTIFACTORY_INPUT_CHANNEL)
    .handle(WebFlux.outboundGateway(url)
            .expectedResponseType(new ParameterizedTypeReference<Mono<ArtifactorySearchResponse>>() {
            })
            .httpMethod(GET)
            .encodeUri(true))
    .transform(new ArtifactorySearchResponseTransformer())
    .channel(ARTIFACTORY_OUTPUT_CHANNEL)
    .get();

And a simple test:

outputChannel.subscribe(mockMessageHandler);
inputChannel.send(new GenericMessage<>("test"));

verify(mockMessageHandler).handleMessage(argThat(m -> {
    Object payload = m.getPayload();

    return payload instanceof String
            && payload.toString().equals("businesses.20171203.json.gz");
}));

that keep failing because the mockMessageHandler is never invoked. I've looked, and looked, and looked, but there are exactly zero examples of testing WebFlux.outboundGateway. Spring integration does have many examples, but those are almost useless because they

Are in XML (yeah, 2005 is calling)

Don't cover WebFlux.


问:
help with if statement - min of 3 characters
Since there is no minlength="" for input, how can I make an if statement that does the following:

If the user has not input more than 3 characters it will not be saved in a database.

Here is the input:

```<code> QTY<input title="QUANTITY PER ITEM" size="1"  name="inputQTY" value="**(minimun of 3 characters)**"/>
</code>```

any ideas??

答:
Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.

Here is how it works: A form has an onsubmit event handler, when the user clicks Submit, or presses Enter, onsubmit will be triggered. onsubmit is where you put the form validation code.

```<code><script>
function onsubmit() {
  if (document.forms.mainForm.inputQTY.value.length < 3) {
    alert("ERROR: Must be more than 3 characters");
    return false; // stops the form submission
  }
  return true;
}
</script>
</code>```

And here is how you add the onsubmit handler

   ...

The onsubmit function can return a value: true to let the form to be submitted, or false to stop the submission.

What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm references to the form named mainForm, while .inputQTY finds the inputQTY field.
You can use document.getElementsByTagName to manually find these elements, but it is [time and space]-consuming to write that type of code.

Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.

Server-side code will be something like this:

```<code>if (strlen($_GET['inputQTY']) < 3) {
  echo "ERROR: Must be more than 3 characters";
} else {
  // submit data
}
</code>```

NOTE: code written from head, not tested

Body:
Since there is no minlength="" for input, how can I make an if statement that does the following:

If the user has not input more than 3 characters it will not be saved in a database.

Here is the input:

 QTY<input title="QUANTITY PER ITEM" size="1"  name="inputQTY" value="**(minimun of 3 characters)**"/>

any ideas??

Body:
Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.

Here is how it works: A form has an onsubmit event handler, when the user clicks Submit, or presses Enter, onsubmit will be triggered. onsubmit is where you put the form validation code.

<script>
function onsubmit() {
  if (document.forms.mainForm.inputQTY.value.length < 3) {
    alert("ERROR: Must be more than 3 characters");
    return false; // stops the form submission
  }
  return true;
}
</script>

And here is how you add the onsubmit handler

   ...

The onsubmit function can return a value: true to let the form to be submitted, or false to stop the submission.

What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm references to the form named mainForm, while .inputQTY finds the inputQTY field.
You can use document.getElementsByTagName to manually find these elements, but it is [time and space]-consuming to write that type of code.

Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.

Server-side code will be something like this:

if (strlen($_GET['inputQTY']) < 3) {
  echo "ERROR: Must be more than 3 characters";
} else {
  // submit data
}

NOTE: code written from head, not tested