问:
How to check if PayPal app is installed on iPhone from code?
This is how I check if WeChat app is installed:

```<code>static func isWechatAvailable() -> Bool {
    if let url = NSURL(string:"weixin://scanqrcode")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}
</code>```

How do I do it for PayPal? PayPal doesn't seem to have the scheme url. And installing and using PayPal SDK is a huge amount of work. Any suggestions?

Thanks!

答:
you should open that URL just as it is, with its https:// URL scheme. So that the URL will open in Safari.

paypal:// URL scheme is intended only for certain limited PayPal usage

Body:
This is how I check if WeChat app is installed:

static func isWechatAvailable() -> Bool {
    if let url = NSURL(string:"weixin://scanqrcode")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}

How do I do it for PayPal? PayPal doesn't seem to have the scheme url. And installing and using PayPal SDK is a huge amount of work. Any suggestions?

Thanks!


来源: stackexchange

问:
How to “crop” SCNAnimationPlayer to a specific start and end time, iOS 11
I have a .dae model with a long animation. The animation includes segments of walking, running, hitting, death, etc. I know the frame numbers of the start and end of each segment. I also know the frame per second rate. So getting the time of the start and end of each segment is pretty easy.

I can get the full animation as a SCNAnimationPlayer object. What I’ve been experimenting with is making a copy of the full animation and then setting the timeOffset and duration of the animation.

```<code>let walkPlayer = fullPlayer.copy() as! SCNAnimationPlayer
walkPlayer.stop()
walkPlayer.animation.timeOffset = walk.offset
walkPlayer.animation.duration = walk.duration
</code>```

I then add the walkPlayer back to the Bip01 node (where I got the full animation from).

I can play the walk easily enough by calling animationPlayer(forKey:"walk")?.play()

I can change the duration and other aspects of the animation easily enough. But the animation always starts at frame 0. Whatever value I put into .timeOffset, it just gets ignored.

How can I play from a start frame to an end frame of an SCNAnimation found in SCNAnimationPlayer?

答:
For anyone who wants to stop animation on one specular frame. By the way, It is pretty weird that SCNAnimationPlayer.animation doesn't support timeOffset setting.

```<code>+(SCNAnimationPlayer*)animationPlayer:(SCNAnimationPlayer *)animPlayer onTimeOffset:(CGFloat)timeOffset{
     SCNAnimation *anim = animPlayer.animation;
     CAAnimation *caAnim = [CAAnimation animationWithSCNAnimation:anim];
     caAnim.timeOffset = timeOffset * caAnim.duration;
     caAnim.speed = 0;
     caAnim.usesSceneTimeBase = NO;
     anim = [SCNAnimation animationWithCAAnimation:caAnim];
     animPlayer = [SCNAnimationPlayer animationPlayerWithAnimation:anim];
     return animPlayer;
}
</code>```

If you want to stop skeleton animation on the half of progress, set the timeOffset to 0.5.

```<code>SCNAnimationPlayer *animPlayer = [SCNAnimationPlayer animationPlayer:[node animationPlayerForKey:key] onTimeOffset:0.5];
[node addAnimationPlayer:animPlayer forKey:key];
[animPlayer play];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a .dae model with a long animation. The animation includes segments of walking, running, hitting, death, etc. I know the frame numbers of the start and end of each segment. I also know the frame per second rate. So getting the time of the start and end of each segment is pretty easy.

I can get the full animation as a SCNAnimationPlayer object. What I’ve been experimenting with is making a copy of the full animation and then setting the timeOffset and duration of the animation.

let walkPlayer = fullPlayer.copy() as! SCNAnimationPlayer
walkPlayer.stop()
walkPlayer.animation.timeOffset = walk.offset
walkPlayer.animation.duration = walk.duration

I then add the walkPlayer back to the Bip01 node (where I got the full animation from).

I can play the walk easily enough by calling animationPlayer(forKey:"walk")?.play()

I can change the duration and other aspects of the animation easily enough. But the animation always starts at frame 0. Whatever value I put into .timeOffset, it just gets ignored.

How can I play from a start frame to an end frame of an SCNAnimation found in SCNAnimationPlayer?

Body:
For anyone who wants to stop animation on one specular frame. By the way, It is pretty weird that SCNAnimationPlayer.animation doesn't support timeOffset setting.

+(SCNAnimationPlayer*)animationPlayer:(SCNAnimationPlayer *)animPlayer onTimeOffset:(CGFloat)timeOffset{
     SCNAnimation *anim = animPlayer.animation;
     CAAnimation *caAnim = [CAAnimation animationWithSCNAnimation:anim];
     caAnim.timeOffset = timeOffset * caAnim.duration;
     caAnim.speed = 0;
     caAnim.usesSceneTimeBase = NO;
     anim = [SCNAnimation animationWithCAAnimation:caAnim];
     animPlayer = [SCNAnimationPlayer animationPlayerWithAnimation:anim];
     return animPlayer;
}

If you want to stop skeleton animation on the half of progress, set the timeOffset to 0.5.

SCNAnimationPlayer *animPlayer = [SCNAnimationPlayer animationPlayer:[node animationPlayerForKey:key] onTimeOffset:0.5];
[node addAnimationPlayer:animPlayer forKey:key];
[animPlayer play];


问:
Filter matched items in an array of string with another (key,value) objects in angularjs
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

```<code>var obj = {"viki-1100":6,"mark-2100":2}
</code>```

To return only the non matched keys from stringArr,So desired output:

```<code>var result = ["vijay-1110","ram-2110"]
</code>```

I haven tried the below code which doesnot return the desired output?

```<code>var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}
</code>```

this wont filter the stringArr, It always return all the results in stringArr?

答:
Try

```<code>stringArr.filter( s => typeof obj[s] != "undefined" )
</code>```

Edit

I realized that OP is looking for the opposite of my answer, so simply replaced != with ==

```<code>stringArr.filter( s => typeof obj[s] == "undefined" )
</code>```

Body:
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

var obj = {"viki-1100":6,"mark-2100":2}

To return only the non matched keys from stringArr,So desired output:

var result = ["vijay-1110","ram-2110"]

I haven tried the below code which doesnot return the desired output?

var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}

this wont filter the stringArr, It always return all the results in stringArr?

Body:
Try

stringArr.filter( s => typeof obj[s] != "undefined" )

Edit

I realized that OP is looking for the opposite of my answer, so simply replaced != with ==

stringArr.filter( s => typeof obj[s] == "undefined" )


问:
Create a NET Core Project Reference to another project of a specific RID
Essientially I need to say:

```<code><ProjectRefererence Target="../tool/tool.csproj">
    <RID>any</RID>
</ProjectReference>
</code>```

where I need to specifically reference the "any" rid that is produced by dotnet build without the -r. Trying to reference a specific rid is guaranteed to not work. The default behavior is to build the dependent dll for the specific rid the current project is being built with. This will not work. The output assembly must be portable across architectures as it is loaded by reflection on potentially a different architecture it originated from.

答:
You can change the project reference to include a global property that will override the defined value in the project (global properties from a command line or project reference will override properties statically defined in a project file):

```<code><ItemGroup>
  <ProjectReference Include="..\ridspecificproj\ridspecificproj.csproj" Properties="RuntimeIdentifier=" />
</ItemGroup>
</code>```

This will set RuntimeIdentifier to empty and the project will be built RID-independent.

Body:
Essientially I need to say:

<ProjectRefererence Target="../tool/tool.csproj">
    <RID>any</RID>
</ProjectReference>

where I need to specifically reference the "any" rid that is produced by dotnet build without the -r. Trying to reference a specific rid is guaranteed to not work. The default behavior is to build the dependent dll for the specific rid the current project is being built with. This will not work. The output assembly must be portable across architectures as it is loaded by reflection on potentially a different architecture it originated from.

Body:
You can change the project reference to include a global property that will override the defined value in the project (global properties from a command line or project reference will override properties statically defined in a project file):

<ItemGroup>
  <ProjectReference Include="..\ridspecificproj\ridspecificproj.csproj" Properties="RuntimeIdentifier=" />
</ItemGroup>

This will set RuntimeIdentifier to empty and the project will be built RID-independent.


问:
Extension to increase the maximum registers to compile a shader program?
I am trying to store a kernel in GLSL code as an immediate array of vec4 as follow:

```<code>vec4 kernel1[512] = vec4[512](
   vec4(0,0,0,0), ...);
vec4 kernel2[512] = vec4[512](
   vec4(0,0,0,0), ...);
vec4 identity matrix[4] = vec4[4](...);
</code>```

All of them are used in the GLSL code. The problem is now, the vulkan cannot use the shader and debug extension reports the following error message:

Constant register limit exceeded at XXXXX; more than 1024 registers needed to compiled program

I have the same setup in my dx11 code and everything works fine. I was wondering if there is an extension which allows me to use more 1024 registers. I would be appreciated if you know another solution to have the same setup in vulkan.

答:
The SPIR-V generated for this shader is a pretty straightforward translation of your code. The driver's compiler will need to store at least 1024 vec4 literal values somewhere to create the dynamic arrays. Think of this as data stored in the code segment. Apparently this exceeds some internal limit Nvidia has (which probably isn't valid, but you don't want to do this anyway, see below).

I don't have a DX11 fxc handy, but if I remember right it would take code like this and move the kernel1 and kernel2 declarations into, essentially, a hidden constant buffer reserved for the hlsl compiler. This was done by the front-end compiler, not the driver's compiler (though the driver could map that reserved constant buffer to code-segment data, or to a normal constant buffer slot, or something else, whatever it wanted).

Vulkan and SPIR-V don't have a uniform (constant) buffer binding reserved for the compiler, but you want effectively the same thing the HLSL compiler is doing. Just replace those declarations with uniform buffer declarations, and put the data in those buffers via the API.

Body:
I am trying to store a kernel in GLSL code as an immediate array of vec4 as follow:

vec4 kernel1[512] = vec4[512](
   vec4(0,0,0,0), ...);
vec4 kernel2[512] = vec4[512](
   vec4(0,0,0,0), ...);
vec4 identity matrix[4] = vec4[4](...);

All of them are used in the GLSL code. The problem is now, the vulkan cannot use the shader and debug extension reports the following error message:

Constant register limit exceeded at XXXXX; more than 1024 registers needed to compiled program

I have the same setup in my dx11 code and everything works fine. I was wondering if there is an extension which allows me to use more 1024 registers. I would be appreciated if you know another solution to have the same setup in vulkan.


问:
Java Multi Threading - real world use cases
I want to work on multi-threading, but my current project do not have such opportunities. Can someone please guide me where should I start. I need real time scenarios so that I can directly jump onto coding. I am reading side by side as well.

Can you please refer some websites for practicing.

答:
When single thread is taking long time to complete a computational activity, you should break it into small tasks and use multi-threading to reduce computation time.

You can see lot of use cases for multi threading in your project.

Where some tasks can run independently  with-out depending on other tasks ( Just span a new Thread or submit Runnable/Callable tasks to ExecutorService/ThreadPoolExecutor)

When you need to wait for completion of multiple parallel tasks to proceed with next task ( invokeAll())

e.g. Task 1 starts three independent tasks Task 2, Task 3 and Task 4 but Task 5 has to start after completion of Task 2, Task 3 and Task 4.

```<code> Task 1
----->
         Task 2
         ----->
         Task 3
         ----->
         Task 4
         ----->
                  Task 5
-------------------------->

</code>```

System is capable of using multiple CPU cores

When you have use cases like Fork-Join tasks ( use: ForkJoinPool)

When you want to show progress of long computation task ( Progress bar can be shown in one thread and long computation task can be executed by other Thread)

Related posts:

How to properly use Java Executor?

Whether to use invokeAll or submit - java Executor service

Java's Fork/Join vs ExecutorService - when to use which?

wait until all threads finish their work in java

ContentLicense: CC BY-SA 4.0

Body:
When single thread is taking long time to complete a computational activity, you should break it into small tasks and use multi-threading to reduce computation time.

You can see lot of use cases for multi threading in your project.

Where some tasks can run independently  with-out depending on other tasks ( Just span a new Thread or submit Runnable/Callable tasks to ExecutorService/ThreadPoolExecutor)

When you need to wait for completion of multiple parallel tasks to proceed with next task ( invokeAll())

e.g. Task 1 starts three independent tasks Task 2, Task 3 and Task 4 but Task 5 has to start after completion of Task 2, Task 3 and Task 4.

 Task 1
----->
         Task 2
         ----->
         Task 3
         ----->
         Task 4
         ----->
                  Task 5
-------------------------->

System is capable of using multiple CPU cores

When you have use cases like Fork-Join tasks ( use: ForkJoinPool)

When you want to show progress of long computation task ( Progress bar can be shown in one thread and long computation task can be executed by other Thread)

Related posts:

How to properly use Java Executor?

Whether to use invokeAll or submit - java Executor service

Java's Fork/Join vs ExecutorService - when to use which?

wait until all threads finish their work in java


问:
Can't Import Flink into Project
So I used this to install a sample Flink project.
https://github.com/tillrohrmann/flink-project.g8

I am trying to use this template that lets me just start writing a Flink ingestion application and not have to worry about dependencies but it's backfiring. It turns out I can't find Flink when I try to sync with sbt (not going to lie but this part is even fuzzy for me). Was wondering if anyone knew how to make my project find Flink. Very excited to use the technology.

Error while importing sbt project:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=384M; support was removed in 8.0
[info] Loading project definition from /Users/Sam/IdeaProjects/cryptoingestion/project
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
>
[info] Defining */*:sbtStructureOptions, */*:sbtStructureOutputFile, root/*:shellPrompt
[info] The new values will be used by no settings or tasks.
[info] Reapplying settings...
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
[info] Applying State transformations org.jetbrains.sbt.CreateTasks from /Users/Sam/Library/Application Support/IdeaIC2017.3/Scala/launcher/sbt-structure-0.13.jar
[info] Reapplying settings...
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
[info] Updating {file:/Users/Sam/IdeaProjects/cryptoingestion/}root...
[info] Resolving org.scala-lang#scala-library;2.12.2 ...
[info] Resolving org.apache.flink#flink-scala_2.12;1.3.2 ...
[info] Resolving org.apache.flink#flink-scala_2.12;1.3.2 ...
[warn]  module not found: org.apache.flink#flink-scala_2.12;1.3.2
[warn] ==== local: tried
[warn]   /Users/Sam/.ivy2/local/org.apache.flink/flink-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/Sam/.sbt/preloaded/org.apache.flink/flink-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/Sam/.sbt/preloaded/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== Apache Development Snapshot Repository: tried
[warn]   https://repository.apache.org/content/repositories/snapshots/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== Maven2 Local: tried
[warn]   file:/Users/Sam/.m2/repository/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[info] Resolving org.apache.flink#flink-streaming-scala_2.12;1.3.2 ...
[info] Resolving org.apache.flink#flink-streaming-scala_2.12;1.3.2 ...
[warn]  module not found: org.apache.flink#flink-streaming-scala_2.12;1.3.2
[warn] ==== local: tried
[warn]   /Users/Sam/.ivy2/local/org.apache.flink/flink-streaming-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/Sam/.sbt/preloaded/org.apache.flink/flink-streaming-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/Sam/.sbt/preloaded/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== Apache Development Snapshot Repository: tried
[warn]   https://repository.apache.org/content/repositories/snapshots/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== Maven2 Local: tried
[warn]   file:/Users/Sam/.m2/repository/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[info] Resolving org.scala-lang#scala-compiler;2.12.2 ...
[info] Resolving org.scala-lang#scala-reflect;2.12.2 ...
[info] Resolving org.scala-lang.modules#scala-xml_2.12;1.0.6 ...
[info] Resolving jline#jline;2.14.3 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.flink#flink-scala_2.12;1.3.2: not found
[warn]  :: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.apache.flink:flink-scala_2.12:1.3.2 (/Users/Sam/IdeaProjects/cryptoingestion/build.sbt#L22)
[warn]        +- com.cryptocorp:cryptoingestion_2.12:0.1
[warn]      org.apache.flink:flink-streaming-scala_2.12:1.3.2 (/Users/Sam/IdeaProjects/cryptoingestion/build.sbt#L22)
[warn]        +- com.cryptocorp:cryptoingestion_2.12:0.1
[trace] Stack trace suppressed: run 'last mainRunner/*:ssExtractDependencies' for the full output.
[trace] Stack trace suppressed: run 'last root/*:ssExtractDependencies' for the full output.
[trace] Stack trace suppressed: run 'last root/*:update' for the full output.
[error] (mainRunner/*:ssExtractDependencies) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] (root/*:ssExtractDependencies) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] (root/*:update) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] Total time: 2 s, completed Dec 5, 2017 12:51:24 AM
```

edit: I got the project to build but I can not click around in my IDE. By that I mean when I try to move into a Flink class it can not find declarations.

答: Flink Scala currently only supports Scala 2.10 and 2.11, so you have to downgrade your Scala to one of those releases or use its Java interface.</p>

Title: Can't Import Flink into Project

Body:
So I used this to install a sample Flink project.
https://github.com/tillrohrmann/flink-project.g8

I am trying to use this template that lets me just start writing a Flink ingestion application and not have to worry about dependencies but it's backfiring. It turns out I can't find Flink when I try to sync with sbt (not going to lie but this part is even fuzzy for me). Was wondering if anyone knew how to make my project find Flink. Very excited to use the technology.

Error while importing sbt project:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=384M; support was removed in 8.0
[info] Loading project definition from /Users/Sam/IdeaProjects/cryptoingestion/project
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
>
[info] Defining */*:sbtStructureOptions, */*:sbtStructureOutputFile, root/*:shellPrompt
[info] The new values will be used by no settings or tasks.
[info] Reapplying settings...
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
[info] Applying State transformations org.jetbrains.sbt.CreateTasks from /Users/Sam/Library/Application Support/IdeaIC2017.3/Scala/launcher/sbt-structure-0.13.jar
[info] Reapplying settings...
[info] Set current project to cryptoingestion (in build file:/Users/Sam/IdeaProjects/cryptoingestion/)
[info] Updating {file:/Users/Sam/IdeaProjects/cryptoingestion/}root...
[info] Resolving org.scala-lang#scala-library;2.12.2 ...
[info] Resolving org.apache.flink#flink-scala_2.12;1.3.2 ...
[info] Resolving org.apache.flink#flink-scala_2.12;1.3.2 ...
[warn]  module not found: org.apache.flink#flink-scala_2.12;1.3.2
[warn] ==== local: tried
[warn]   /Users/Sam/.ivy2/local/org.apache.flink/flink-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/Sam/.sbt/preloaded/org.apache.flink/flink-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/Sam/.sbt/preloaded/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== Apache Development Snapshot Repository: tried
[warn]   https://repository.apache.org/content/repositories/snapshots/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[warn] ==== Maven2 Local: tried
[warn]   file:/Users/Sam/.m2/repository/org/apache/flink/flink-scala_2.12/1.3.2/flink-scala_2.12-1.3.2.pom
[info] Resolving org.apache.flink#flink-streaming-scala_2.12;1.3.2 ...
[info] Resolving org.apache.flink#flink-streaming-scala_2.12;1.3.2 ...
[warn]  module not found: org.apache.flink#flink-streaming-scala_2.12;1.3.2
[warn] ==== local: tried
[warn]   /Users/Sam/.ivy2/local/org.apache.flink/flink-streaming-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/Sam/.sbt/preloaded/org.apache.flink/flink-streaming-scala_2.12/1.3.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////Users/Sam/.sbt/preloaded/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== Apache Development Snapshot Repository: tried
[warn]   https://repository.apache.org/content/repositories/snapshots/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[warn] ==== Maven2 Local: tried
[warn]   file:/Users/Sam/.m2/repository/org/apache/flink/flink-streaming-scala_2.12/1.3.2/flink-streaming-scala_2.12-1.3.2.pom
[info] Resolving org.scala-lang#scala-compiler;2.12.2 ...
[info] Resolving org.scala-lang#scala-reflect;2.12.2 ...
[info] Resolving org.scala-lang.modules#scala-xml_2.12;1.0.6 ...
[info] Resolving jline#jline;2.14.3 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.flink#flink-scala_2.12;1.3.2: not found
[warn]  :: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.apache.flink:flink-scala_2.12:1.3.2 (/Users/Sam/IdeaProjects/cryptoingestion/build.sbt#L22)
[warn]        +- com.cryptocorp:cryptoingestion_2.12:0.1
[warn]      org.apache.flink:flink-streaming-scala_2.12:1.3.2 (/Users/Sam/IdeaProjects/cryptoingestion/build.sbt#L22)
[warn]        +- com.cryptocorp:cryptoingestion_2.12:0.1
[trace] Stack trace suppressed: run 'last mainRunner/*:ssExtractDependencies' for the full output.
[trace] Stack trace suppressed: run 'last root/*:ssExtractDependencies' for the full output.
[trace] Stack trace suppressed: run 'last root/*:update' for the full output.
[error] (mainRunner/*:ssExtractDependencies) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] (root/*:ssExtractDependencies) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] (root/*:update) sbt.ResolveException: unresolved dependency: org.apache.flink#flink-scala_2.12;1.3.2: not found
[error] unresolved dependency: org.apache.flink#flink-streaming-scala_2.12;1.3.2: not found
[error] Total time: 2 s, completed Dec 5, 2017 12:51:24 AM

edit: I got the project to build but I can not click around in my IDE. By that I mean when I try to move into a Flink class it can not find declarations.


问:
JMeter - generate Dashboard report on specific times or steps (Load testing)
I want to get a clear results when server is "fully loaded" with users operations and also a clear results when server start to get X login requests.

In JMeter I'm able to generate Dashboard report with given jtl or for all test.

In my load testing I have a test which doesn't stops (until shutdown manually)

In the first steps and minutes it ramp up all the users

In next steps it makes other actions on servers in a loop (while)

I want to generate 2 separated dashboard reports, one for ramping up/login users

and second for execution different actions on server (with full users)

Should I add 2 or more listeners in a controller for different steps and check its jtl after test is finish?

Can it be more flexible? I really wants to generate dashboard on demands or by time, for example, will include requests after 3 minutes the test start and until 15 minutes.

答:
You can create 2 reports by running web report generation with date interval.
Add to user.properties:</p>

```<code> jmeter.reportgenerator.date_format=yyyyMMddHHmmss

# Used to generate a report based on a date range
 # If jmeter.save.saveservice.timestamp_format does not contain year
# then use 1970 as year

# Date range start date as per format declared in jmeter.reportgenerator.date_format

jmeter.reportgenerator.start_date=
# Date range end date as per format declared in  jmeter.reportgenerator.date_format

jmeter.reportgenerator.end_date=
</code>```

Body:
You can create 2 reports by running web report generation with date interval.
Add to user.properties:

 jmeter.reportgenerator.date_format=yyyyMMddHHmmss

# Used to generate a report based on a date range
 # If jmeter.save.saveservice.timestamp_format does not contain year
# then use 1970 as year

# Date range start date as per format declared in jmeter.reportgenerator.date_format

jmeter.reportgenerator.start_date=
# Date range end date as per format declared in  jmeter.reportgenerator.date_format

jmeter.reportgenerator.end_date=


问:
HashMap and int as key
I am trying to build a HashMap which will have integer as keys and objects as values.

My syntax is:

```<code>HashMap<int, myObject> myMap = new HashMap<int, myObject>();
</code>```

However, the error returned is - Syntax error on token "int", Dimensions expected after this token - I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

What could I do?

答:
I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

Title: HashMap and int as key

Body:
I am trying to build a HashMap which will have integer as keys and objects as values.

My syntax is:

HashMap<int, myObject> myMap = new HashMap<int, myObject>();

However, the error returned is - Syntax error on token "int", Dimensions expected after this token - I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

What could I do?


问:
AndroidViewModel - Making duplicate calls doesn't return data in observe function
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

```<code>@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}
</code>```

In Activity, the ViewModel is defined as followed -

```<code>final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);
</code>```

The observeViewModel function is used to add observable on ViewModel.

```<code>public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }
</code>```

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

```<code>//observeViewModel(networkInformationViewModel);
</code>```

Please note:-
I don't need RxJava implementation for implementing this.

答:
I have already updated the linked question's answer. Re-posting here since I have placed a bounty on the question and hopefully someone will verify that this is the proper way to handle the issue.

Following is the updated working solution -

```<code>@Singleton
public class SplashScreenViewModel extends AndroidViewModel {
  private final APIClient apiClient;
  // This is the observable which listens for the changes
  // Using 'Void' since the get method doesn't need any parameters. If you need to pass any String, or class
  // you can add that here
  private MutableLiveData<Void> networkInfoObservable;
  // This LiveData contains the information required to populate the UI
  private LiveData<Resource<NetworkInformation>> networkInformationLiveData;

  @Inject
  SplashScreenViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;

    // Initializing the observable with empty data
    networkInfoObservable = new MutableLiveData<Void>();
    // Using the Transformation switchMap to listen when the data changes happen, whenever data
    // changes happen, we update the LiveData object which we are observing in the MainActivity.
    networkInformationLiveData = Transformations.switchMap(networkInfoObservable, input -> apiClient.getNetworkInformation());
  }

  /**
   * Function to get LiveData Observable for NetworkInformation class
   * @return LiveData<Resource<NetworkInformation>>
   */
  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInformationLiveData;
  }

  /**
   * Whenever we want to reload the networkInformationLiveData, we update the mutable LiveData's value
   * which in turn calls the `Transformations.switchMap()` function and updates the data and we get
   * call back
   */
  public void setNetworkInformation() {
    networkInfoObservable.setValue(null);
  }
}
</code>```

The Activity's code will be updated as -

```<code>final SplashScreenViewModel splashScreenViewModel =
  ViewModelProviders.of(this, viewModelFactory).get(SplashScreenViewModel.class);
observeViewModel(splashScreenViewModel);
// This function will ensure that Transformation.switchMap() function is called
splashScreenViewModel.setNetworkInformation();
</code>```

Watch her droidCon NYC video for more information on LiveData. The official Google repository for LiveData is https://github.com/googlesamples/android-architecture-components/ look for GithubBrowserSample project.

The apiClient.getNetworkInformation() call doesn't need it any parameters to get additional information. Hence, the 'Void' added in MutableLiveData.

```<code>public LiveData<Resource<NetworkInformation>> getNetworkInformation() {
    final MutableLiveData<Resource<NetworkInformation>> data = new MutableLiveData<>();

    apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
      @Override
      public void onResponse(
        @NonNull Call<NetworkInformation> call, @NonNull Response<NetworkInformation> response
      ) {
        if (response.body() != null && response.isSuccessful()) {
          data.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
        } else {
          data.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
        }
      }

      @Override
      public void onFailure(@NonNull Call<NetworkInformation> call, @NonNull Throwable throwable) {
        data.setValue(
          new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
      }
    });
    return data;
  }
</code>```

Body:
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}

In Activity, the ViewModel is defined as followed -

final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);

The observeViewModel function is used to add observable on ViewModel.

public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

//observeViewModel(networkInformationViewModel);

Please note:-
I don't need RxJava implementation for implementing this.

Body:
I have already updated the linked question's answer. Re-posting here since I have placed a bounty on the question and hopefully someone will verify that this is the proper way to handle the issue.

Following is the updated working solution -

@Singleton
public class SplashScreenViewModel extends AndroidViewModel {
  private final APIClient apiClient;
  // This is the observable which listens for the changes
  // Using 'Void' since the get method doesn't need any parameters. If you need to pass any String, or class
  // you can add that here
  private MutableLiveData<Void> networkInfoObservable;
  // This LiveData contains the information required to populate the UI
  private LiveData<Resource<NetworkInformation>> networkInformationLiveData;

  @Inject
  SplashScreenViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;

    // Initializing the observable with empty data
    networkInfoObservable = new MutableLiveData<Void>();
    // Using the Transformation switchMap to listen when the data changes happen, whenever data
    // changes happen, we update the LiveData object which we are observing in the MainActivity.
    networkInformationLiveData = Transformations.switchMap(networkInfoObservable, input -> apiClient.getNetworkInformation());
  }

  /**
   * Function to get LiveData Observable for NetworkInformation class
   * @return LiveData<Resource<NetworkInformation>>
   */
  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInformationLiveData;
  }

  /**
   * Whenever we want to reload the networkInformationLiveData, we update the mutable LiveData's value
   * which in turn calls the `Transformations.switchMap()` function and updates the data and we get
   * call back
   */
  public void setNetworkInformation() {
    networkInfoObservable.setValue(null);
  }
}

The Activity's code will be updated as -

final SplashScreenViewModel splashScreenViewModel =
  ViewModelProviders.of(this, viewModelFactory).get(SplashScreenViewModel.class);
observeViewModel(splashScreenViewModel);
// This function will ensure that Transformation.switchMap() function is called
splashScreenViewModel.setNetworkInformation();

Watch her droidCon NYC video for more information on LiveData. The official Google repository for LiveData is https://github.com/googlesamples/android-architecture-components/ look for GithubBrowserSample project.

The apiClient.getNetworkInformation() call doesn't need it any parameters to get additional information. Hence, the 'Void' added in MutableLiveData.

public LiveData<Resource<NetworkInformation>> getNetworkInformation() {
    final MutableLiveData<Resource<NetworkInformation>> data = new MutableLiveData<>();

    apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
      @Override
      public void onResponse(
        @NonNull Call<NetworkInformation> call, @NonNull Response<NetworkInformation> response
      ) {
        if (response.body() != null && response.isSuccessful()) {
          data.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
        } else {
          data.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
        }
      }

      @Override
      public void onFailure(@NonNull Call<NetworkInformation> call, @NonNull Throwable throwable) {
        data.setValue(
          new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
      }
    });
    return data;
  }


问:
Upgrading project to Qt5 throws error

I upgraded my Qt project from Qt4 to Qt5. Now whenever I try to include a widget say QLabel or QLineEdit, the compiler throws an error. The project is quite huge so I tried running a sample Hello World GUI program in Qt5 and it worked, thus the installation can't be at fault. I will paste the error below. And if more code is needed please let me know.

The .pro file:

答: The libqxt extension for qt4 doesn't work properly with qt5, so that was the error. Thanks for all the help guys. cheers</p>

Title: Upgrading project to Qt5 throws error


问:
How to know if the network state is WiFi hotspot on iOS
Now I can just recognize WiFi/2G/3G/4G, but when the state is WiFi hotspot, AFNetworkReachabilityManager or Reachability also recognize the state as WiFi. Please help me to achieve this requirement, thanks a lot.

答:
I had found the right way:</p>

```<code>- (void)startMonitorWifiChange {
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                    NULL,
                                    &onNotifyCallback,
                                    CFSTR("com.apple.system.config.network_change"),
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}
static void onNotifyCallback(CFNotificationCenterRef center,
                             void *observer,
                             CFStringRef name,
                             const void *object,
                             CFDictionaryRef userInfo) {
    if (CFStringCompare(name, CFSTR("com.apple.system.config.network_change"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
        //TODO when wifi changed
        [[BaiduLocationManager sharedManager].baiduLocationManager requestNetworkState];
    }
    else {
        NBLog(@"intercepted %@", name);
    }
}
- (void)stopMonitorWifiChange {
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                       NULL,
                                       CFSTR("com.apple.system.config.network_change"),
                                       NULL);
}
</code>```

Body:
I had found the right way:

- (void)startMonitorWifiChange {
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                    NULL,
                                    &onNotifyCallback,
                                    CFSTR("com.apple.system.config.network_change"),
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}
static void onNotifyCallback(CFNotificationCenterRef center,
                             void *observer,
                             CFStringRef name,
                             const void *object,
                             CFDictionaryRef userInfo) {
    if (CFStringCompare(name, CFSTR("com.apple.system.config.network_change"), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
        //TODO when wifi changed
        [[BaiduLocationManager sharedManager].baiduLocationManager requestNetworkState];
    }
    else {
        NBLog(@"intercepted %@", name);
    }
}
- (void)stopMonitorWifiChange {
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                       NULL,
                                       CFSTR("com.apple.system.config.network_change"),
                                       NULL);
}


问:
Async Call in $http request
How to wait till the response comes from the $http request, in "angularjs"?
In ajax, a successful method is to set async = false like this,

```<code>jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});
</code>```

But Its not working in $http request in angularjs.Is there any method for this?

答:
```<code>$http.get("url")
    .then(response => {
        // async success callback
    })
    .catch(err => {
      // async error callback
    });
</code>```

Title: Async Call in $http request

Body:
How to wait till the response comes from the $http request, in "angularjs"?
In ajax, a successful method is to set async = false like this,

jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});

But Its not working in $http request in angularjs.Is there any method for this?


问:
How can I achieve google-style table views with UITableView?
I have a UITableView and I'd like to use it for a "card" like interface where users can scroll for content thumbnails. Basically like 10 pts on all sides of the cell. This will require some overriding of UITableView. Keep in mind I'm using prototype cells in the storyboard so I'd like to storyboard a much as possible.

I need to get a transparent background and a fill for the cells

I need to get a border on the top, bottom, and sides

How can I accomplish this?

答:
This is a very broad question. There are multiple ways this can be achieved. I'll just highlight what I did in my last app.

Subclass UITableViewCell along with a xib. Using a xib, or designing in storyboard is entirely upto you. I use a dedicated nib so as to keep the cells reusable in case they're needed in other tableViews.

Set background of cell, and conentView to clearColor.

Added a UIView (called it internalContentView in it's outlet) inside the contentView with layout constraints on all 4 sides.

Set the background color of internalContentView as per my design.

Further, I added code in setHighlighted: and setSelected: to override selection and highlighting behaviour. Since internalContentView is a UIView, it can easily be customised for corner radii, borders, etc (advised to do so in awakeFromNib)


问:
Key size for AES vs DES in KeyGenerator
I am using javax.crypto.KeyGenerator to generate Keys.

Below is my code for AES :

```<code>Key key = null;
        SecureRandom rand = new SecureRandom();
        KeyGenerator generator;
        try {
            generator = KeyGenerator.getInstance("AES");
            generator.init(rand);
            generator.init(128);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("AES key is : ");
        System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
</code>```

Code for DES :

```<code>Key key = null;
        SecureRandom rand = new SecureRandom();
        KeyGenerator generator;
        try {
            generator = KeyGenerator.getInstance("DES");
            generator.init(rand);
            generator.init(56);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("DES key is : ");
        System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
</code>```

As you can see when I use DES, i have to pass 56 to init() method, as opposed to 128 in AES.

Can someone please explain why i can't use 128 bit and which encryption is preferable from this two types?

答:
AES is an advanced version of DES with bigger key size. So if you need more secure encryption, using AES should be your option.

Data Encryption Standard (DES) : DES is an implementation of a Feistel Cipher. It uses 16 round Feistel structure. The block size is
  64-bit. Though, key length is 64-bit, DES has an effective key length
  of 56 bits, since 8 of the 64 bits of the key are not used by the
  encryption algorithm (function as check bits only).

Advanced Encryption Standard(AES) :The more popular and widely adopted symmetric encryption algorithm likely to be encountered
  nowadays is the Advanced Encryption Standard (AES). It is found at
  least six time faster than triple DES. A replacement for DES was needed as its key size was too small. With increasing computing power, it was considered vulnerable against exhaustive key search attack. Triple DES was designed to overcome this drawback but it was found slow

Title: Key size for AES vs DES in KeyGenerator

Body:
I am using javax.crypto.KeyGenerator to generate Keys.

Below is my code for AES :

Key key = null;
        SecureRandom rand = new SecureRandom();
        KeyGenerator generator;
        try {
            generator = KeyGenerator.getInstance("AES");
            generator.init(rand);
            generator.init(128);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("AES key is : ");
        System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));

Code for DES :

Key key = null;
        SecureRandom rand = new SecureRandom();
        KeyGenerator generator;
        try {
            generator = KeyGenerator.getInstance("DES");
            generator.init(rand);
            generator.init(56);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("DES key is : ");
        System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));

As you can see when I use DES, i have to pass 56 to init() method, as opposed to 128 in AES.

Can someone please explain why i can't use 128 bit and which encryption is preferable from this two types?


问:
How to get Woocommerce Variation ID?
I've already had this code on functions.php

This code is to add a new field on each product variation to have datetime input field, so variations would automatically expired when the current date is past the input date.

```<code>// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

//Create New fields for Variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
    // Text Field
    woocommerce_wp_text_input(
        array(
            'id'          => '_text_field_date_expire[' . $variation->ID . ']',
            'class'       => '_text_field_date_expire',
            'type'        => 'datetime-local',
            'label'       => __( 'Date of Expiration', 'woocommerce' ),
            'placeholder' => '',
            'desc_tip'    => 'true',
            'description' => __( 'Expiration of Each Product Variation', 'woocommerce' ),
            'value'       => get_post_meta( $variation->ID, '_text_field_date_expire', true )
        )
    );
}

//Save New Fields for Variation
function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $post_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $post_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}
</code>```

This is to add a new field on each variation of Wocommerce.

What I am trying to do is to get each "_text_field_date_expire" meta so I could delete expired variation for each of the products..

How do I get each woocommerce variation ID on functions.php so I could add a rule that it will expire when it is already past the current date right now?

```<code>var_dump(get_post_meta( $variation_id , '_text_field_date_expire', true ));
</code>```

This code is the one that I will use to get the datetime field, but not sure how I could get each $variation_id field?

答:
Try this one:

```<code>$args = array(
    'post_type'     => 'product_variation',
    'post_status'   => array( 'private', 'publish' ),
    'numberposts'   => -1,
    'orderby'       => 'menu_order',
    'order'         => 'asc',
    'post_parent'   => get_the_ID() // get parent post-ID
);
$variations = get_posts( $args );

foreach ( $variations as $variation ) {

    // get variation ID
    $variation_ID = $variation->ID;

    // get variations meta
    $product_variation = new WC_Product_Variation( $variation_ID );

    // get variation featured image
    $variation_image = $product_variation->get_image();

    // get variation price
    $variation_price = $product_variation->get_price_html();

    get_post_meta( $variation_ID , '_text_field_date_expire', true );

}
</code>```

Hope this will helps you. For more information:

How To Get Product Variations & Meta – WooCommerce

How to get the Variation ID in a Woocommerce product

Title: How to get Woocommerce Variation ID?

Body:
I've already had this code on functions.php

This code is to add a new field on each product variation to have datetime input field, so variations would automatically expired when the current date is past the input date.

// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

//Create New fields for Variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
    // Text Field
    woocommerce_wp_text_input(
        array(
            'id'          => '_text_field_date_expire[' . $variation->ID . ']',
            'class'       => '_text_field_date_expire',
            'type'        => 'datetime-local',
            'label'       => __( 'Date of Expiration', 'woocommerce' ),
            'placeholder' => '',
            'desc_tip'    => 'true',
            'description' => __( 'Expiration of Each Product Variation', 'woocommerce' ),
            'value'       => get_post_meta( $variation->ID, '_text_field_date_expire', true )
        )
    );
}

//Save New Fields for Variation
function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $post_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $post_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}

This is to add a new field on each variation of Wocommerce.

What I am trying to do is to get each "_text_field_date_expire" meta so I could delete expired variation for each of the products..

How do I get each woocommerce variation ID on functions.php so I could add a rule that it will expire when it is already past the current date right now?

var_dump(get_post_meta( $variation_id , '_text_field_date_expire', true ));

This code is the one that I will use to get the datetime field, but not sure how I could get each $variation_id field?

Body:
Try this one:

$args = array(
    'post_type'     => 'product_variation',
    'post_status'   => array( 'private', 'publish' ),
    'numberposts'   => -1,
    'orderby'       => 'menu_order',
    'order'         => 'asc',
    'post_parent'   => get_the_ID() // get parent post-ID
);
$variations = get_posts( $args );

foreach ( $variations as $variation ) {

    // get variation ID
    $variation_ID = $variation->ID;

    // get variations meta
    $product_variation = new WC_Product_Variation( $variation_ID );

    // get variation featured image
    $variation_image = $product_variation->get_image();

    // get variation price
    $variation_price = $product_variation->get_price_html();

    get_post_meta( $variation_ID , '_text_field_date_expire', true );

}

Hope this will helps you. For more information:

How To Get Product Variations & Meta – WooCommerce

How to get the Variation ID in a Woocommerce product


问:
How to correctly use pointers in my c program
So I turned in this code for my assignment to my teacher thinking I had completed his request that we use pointer techniques for writing our hangman assignment. He gave it back and said I used array techniques and not pointer techniques. I have struggled with learning pointers and arrays, so I am a bit confused how to fix where he said I went wrong.

These are the parts of my program he marked were array techniques and not pointer techniques:

```<code>*(q + i) = '*';

if (ch[0] == *(p + i))

*(q + i) = ch[0];
</code>```

My full program code is below (can anyone help me understand how a proper pointer technique can be implemented, I clearly don't get it - THANKS in advance):

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

void Instructions();
void PlayGame();
void PrintToLog(char *word);

int main()
{

Instructions();
PlayGame();

return 0;
getchar();
}

void Instructions()
{
printf("This is a game of hangman. Attempt to guess secret word\n");
printf("by entering a letter from a to z. The game is over once you\n");
printf("have entered 8 incorrect guesses.\n\n");
}

void PlayGame()
{
char word[] = { "hello" };
char guessed[20];
int i, incorrect_count, found;
char ch[2];
char *p, *q;

p = &word;
q = &guessed;
strcpy(guessed, word);

PrintToLog(word);

for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}
incorrect_count = 0;

while (incorrect_count < 8 && strcmp(guessed, word) != 0)
{
    for (i = 0; i < strlen(guessed); i++)
        printf("%c ", guessed[i]);
        printf("\n");
        printf("Enter your guess:");
        gets(ch);
        found = 0;
    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }
    if (found == 0)
        incorrect_count++;
}

if (incorrect_count < 8)
{
    printf("\nThe word is %s. You win!", word);
    getchar();
}
else
{
    printf("\nThe correct word is %s. You lose!", word);
    getchar();
}

return 0;
}

void PrintToLog(char *word)
{
FILE *pOutput;

pOutput = fopen("MyLogFile.txt", "w+");
if (!pOutput) return;
fprintf(pOutput, "Start of game\n");
fprintf(pOutput, "This is the word player is trying to guess: %s\n", word);

fclose(pOutput);
}
</code>```

答:
Original:

```<code>    *(q + i) = '*';
    if (ch[0] == *(p + i))
    *(q + i) = ch[0];
</code>```

Becomes:

```<code>    q[i] = '*';
    if (ch[0] == p[i]))
    q[i] = ch[0];
</code>```

A pointer is the base address, you can index it just like an array and the compiler will work out the offset according to the type declaration of the pointer.

q = base address of your data, [i] indexes from the base address.

I think I've interpreted your question wrong if you wanted to convert all the array references to pointers then:

Original:

```<code>    *(q + i) = '*';
    if (ch[0] == *(p + i))
    *(q + i) = ch[0];
</code>```

Becomes:

```<code>    *(q + i) = '*';
    if (*ch == *(p + i)))
    *(q + i) = *ch;
</code>```

I can't quite see the point that is trying to be made, in C there is no difference in pointers and arrays they are the same and you can access them either way.

Lets recode your loop:

```<code>    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }
</code>```

Becomes:

```<code>    for( p=word; *p!='\0'; p++ ) {
        if ( *ch == *p ) {
            *p = *ch;
            found = 1;
            break;
        }
    }
</code>```

Body:
So I turned in this code for my assignment to my teacher thinking I had completed his request that we use pointer techniques for writing our hangman assignment. He gave it back and said I used array techniques and not pointer techniques. I have struggled with learning pointers and arrays, so I am a bit confused how to fix where he said I went wrong.

These are the parts of my program he marked were array techniques and not pointer techniques:

*(q + i) = '*';

if (ch[0] == *(p + i))

*(q + i) = ch[0];

My full program code is below (can anyone help me understand how a proper pointer technique can be implemented, I clearly don't get it - THANKS in advance):

#include<stdio.h>
#include<string.h>

void Instructions();
void PlayGame();
void PrintToLog(char *word);

int main()
{

Instructions();
PlayGame();

return 0;
getchar();
}

void Instructions()
{
printf("This is a game of hangman. Attempt to guess secret word\n");
printf("by entering a letter from a to z. The game is over once you\n");
printf("have entered 8 incorrect guesses.\n\n");
}

void PlayGame()
{
char word[] = { "hello" };
char guessed[20];
int i, incorrect_count, found;
char ch[2];
char *p, *q;

p = &word;
q = &guessed;
strcpy(guessed, word);

PrintToLog(word);

for (i = 0; i < strlen(guessed); i++)
{
    *(q + i) = '*';
}
incorrect_count = 0;

while (incorrect_count < 8 && strcmp(guessed, word) != 0)
{
    for (i = 0; i < strlen(guessed); i++)
        printf("%c ", guessed[i]);
        printf("\n");
        printf("Enter your guess:");
        gets(ch);
        found = 0;
    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }
    if (found == 0)
        incorrect_count++;
}

if (incorrect_count < 8)
{
    printf("\nThe word is %s. You win!", word);
    getchar();
}
else
{
    printf("\nThe correct word is %s. You lose!", word);
    getchar();
}

return 0;
}

void PrintToLog(char *word)
{
FILE *pOutput;

pOutput = fopen("MyLogFile.txt", "w+");
if (!pOutput) return;
fprintf(pOutput, "Start of game\n");
fprintf(pOutput, "This is the word player is trying to guess: %s\n", word);

fclose(pOutput);
}

Body:
Original:

    *(q + i) = '*';
    if (ch[0] == *(p + i))
    *(q + i) = ch[0];

Becomes:

    q[i] = '*';
    if (ch[0] == p[i]))
    q[i] = ch[0];

A pointer is the base address, you can index it just like an array and the compiler will work out the offset according to the type declaration of the pointer.

q = base address of your data, [i] indexes from the base address.

I think I've interpreted your question wrong if you wanted to convert all the array references to pointers then:

Original:

    *(q + i) = '*';
    if (ch[0] == *(p + i))
    *(q + i) = ch[0];

Becomes:

    *(q + i) = '*';
    if (*ch == *(p + i)))
    *(q + i) = *ch;

I can't quite see the point that is trying to be made, in C there is no difference in pointers and arrays they are the same and you can access them either way.

Lets recode your loop:

    for (i = 0; i < strlen(word); i++){
        if (ch[0] == *(p + i))
        {
            *(q + i) = ch[0];
            found = 1;
        }
    }

Becomes:

    for( p=word; *p!='\0'; p++ ) {
        if ( *ch == *p ) {
            *p = *ch;
            found = 1;
            break;
        }
    }


问:
Running python in php for image processing

hi everyone
I want to run a python script through php in which i've to do image processing and update a database and then use that database in same php program.
Is it feasible ?
If yes then how ?
I am a beginner so apology if the question isn't up to the mark.
Please help me making my first project :)

答:
you can use exec command to run python script from php

```<code>exec(python script_name parameter)
</code>```

To know more about exec go to this link

http://php.net/manual/en/function.exec.php

Body:
you can use exec command to run python script from php

exec(python script_name parameter)

To know more about exec go to this link

http://php.net/manual/en/function.exec.php


问:
How to retrieve the previous data into the textbox after deciding that you will not update the data?

I'm trying to make a cancel button that would clear the new inputted data from the user and return it to its old data using angular and localstorage.

I don't have a code yet because I don't know where to start.

I expect that after I will click the cancel button, it will then put back the original data whom I've clicked from the table.

答: If you for example use a different component like a dialog, you can do it the other way round. Use a one-way binding '<' or @Input since angular2 and on submit either call a service to update or use @Output. If you want to implement a undo function with the cancel button, try to implement some kind of changelog/script.</p>


问:
Other Computer Show Input String was not in correct format

I have problem installing VB.NET application to other Computer.

When Button Add is pressed and Choose item, the program say Input String was not in correct format.
my Datatable Declare is Here :

```<code>Private Sub prvFillDT()
        dtSales = New DataTable
        dtSales.Columns.Add("no", System.Type.GetType("System.String"))
        dtSales.Columns.Add("goodscode", System.Type.GetType("System.String"))
        dtSales.Columns.Add("goodsname", System.Type.GetType("System.String"))
        dtSales.Columns.Add("information", System.Type.GetType("System.String"))
        dtSales.Columns.Add("qty", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("price", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("discount", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("total", System.Type.GetType("System.Double"))
End Sub
</code>```

And Here is The Button Add Code

```<code>Dim arrFields() As String = {"GoodsCode", "GoodsName", "Stock", "UnitPrice"}
Dim kn As SqlConnection = OpenKNS(Settings.ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("usp_is_Goods_SLC_01", kn)
If fLookup.GetLookUpSP("List Goods", cmd, arrFields, "", "") Then
    Try
        If fLookup.pubLookUpDone Then
            If arrFields(2) = "0" Then
                MsgBox(arrFields(1) & " stock is not enough !")
                   Exit Sub
            End If
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodscode", arrFields(0))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodsname", arrFields(1))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "qty", 1)
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "price", arrFields(3))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "total", 1 * arrFields(3))
        End If
    Catch ex As Exception
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodscode", "")
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodsname", "")
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "qty", 0)
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "price", 0)
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "total", 0)
    End Try
    bndReport2.UpdateSummary()
End If
</code>```

Here the Storedprocedure :

```<code>SELECT GoodsCode,GoodsName,Stock,
CONVERT(varchar,UnitPrice,1) UnitPrice
FROM Ms_Goods WHERE [Status]=1
</code>```

The problem is only show on other computer but mine is no problem is the problem on the Code or The Computer ?

答:
I already find my own answer after testing some sample.

The Answer for this question is because Region & Language my Computer using English (United States) and other Computer using different format like (Indonesian, India, Singapore and etc.)

Body:
I have problem installing VB.NET application to other Computer.

When Button Add is pressed and Choose item, the program say Input String was not in correct format.
my Datatable Declare is Here :

Private Sub prvFillDT()
        dtSales = New DataTable
        dtSales.Columns.Add("no", System.Type.GetType("System.String"))
        dtSales.Columns.Add("goodscode", System.Type.GetType("System.String"))
        dtSales.Columns.Add("goodsname", System.Type.GetType("System.String"))
        dtSales.Columns.Add("information", System.Type.GetType("System.String"))
        dtSales.Columns.Add("qty", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("price", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("discount", System.Type.GetType("System.Double"))
        dtSales.Columns.Add("total", System.Type.GetType("System.Double"))
End Sub

And Here is The Button Add Code

Dim arrFields() As String = {"GoodsCode", "GoodsName", "Stock", "UnitPrice"}
Dim kn As SqlConnection = OpenKNS(Settings.ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("usp_is_Goods_SLC_01", kn)
If fLookup.GetLookUpSP("List Goods", cmd, arrFields, "", "") Then
    Try
        If fLookup.pubLookUpDone Then
            If arrFields(2) = "0" Then
                MsgBox(arrFields(1) & " stock is not enough !")
                   Exit Sub
            End If
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodscode", arrFields(0))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodsname", arrFields(1))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "qty", 1)
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "price", arrFields(3))
            bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "total", 1 * arrFields(3))
        End If
    Catch ex As Exception
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodscode", "")
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "goodsname", "")
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "qty", 0)
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "price", 0)
    bndReport2.SetRowCellValue(bndReport2.FocusedRowHandle, "total", 0)
    End Try
    bndReport2.UpdateSummary()
End If

Here the Storedprocedure :

SELECT GoodsCode,GoodsName,Stock,
CONVERT(varchar,UnitPrice,1) UnitPrice
FROM Ms_Goods WHERE [Status]=1

The problem is only show on other computer but mine is no problem is the problem on the Code or The Computer ?


问:
What is the difference between (for example) p.post {color: #336;} and .post p {color: #336;}?
I've always used this structure in the style sheet:

```<code>.post {padding: 10px;}
.post h1 {color: #336;}
.post p {font-size: 1em;}
</code>```

with this html:

```<code><div class="post">
<h1>title</h1>
<p>content</p>
</div>
</code>```

However, I frequently see this structure in style sheets:

```<code>h1.post {color:#336;}
p.post {font-size: 1em;}
</code>```

with this html:

```<code><h1 class="post">title</h1>
<p class="post">content</p>
</code>```

I'm working on a theme that I will be giving to others, therefore, it's not enough that it works--I want it to reflect "best practices" (and keep me from appearing to be a total newbie).

My attempts to find an answer haven't been successful--perhaps because the search terms (element, selector, css, etc) are too broad.

Thank you in advance for any assistance.

(Also, an overdue thanks for past assistance.  This is my first question, but not my first visit to the site.)

答:
As answered already but with some HTML examples. [] subbed for tags.

p.post
- [p class="post"]Hello[/p]

.post p
- [div class="post"][p]Hello again[/p][/div]

ContentLicense: CC BY-SA 2.5

Body:
I've always used this structure in the style sheet:

.post {padding: 10px;}
.post h1 {color: #336;}
.post p {font-size: 1em;}

with this html:

title

content

However, I frequently see this structure in style sheets:

h1.post {color:#336;}
p.post {font-size: 1em;}

with this html:

title

content

I'm working on a theme that I will be giving to others, therefore, it's not enough that it works--I want it to reflect "best practices" (and keep me from appearing to be a total newbie).

My attempts to find an answer haven't been successful--perhaps because the search terms (element, selector, css, etc) are too broad.

Thank you in advance for any assistance.

(Also, an overdue thanks for past assistance.  This is my first question, but not my first visit to the site.)


问:
Python script stops working with BEX error
I have a Python script running on Windows, which is basically RESTful interface client with multiple connections to SQL database. It has to be restarted with some period of time (for example, 15 minutes). For this purpose I wrapped the code inside the loop with function os.execl(). I run script from PowerShell using following format:

```<code>PS C:\test> python.exe .\script.pyc
</code>```

Script itself (without disclosing implementation details):

```<code>import base64
import datetime
import glob
import logging
import os
import socket
import sys
import threading
import time
import pyodbc
import binascii
import configparser
import codecs
import requests
from collections import namedtuple
from binascii import unhexlify, b2a_base64

FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
log = logging.getLogger()

# some class declarations here

if __name__ == '__main__':

    # Initializing counter for time
    timeLast = time.time()

    while 1:
        timeCurrent = time.time()
        if ((timeCurrent - timeLast) > resetTime):
            timeLast = timeCurrent
            os.execl(sys.executable, sys.executable, * sys.argv)

        try:
            # Fetching data from DB
            # Processing data

        except Exception as e:
            log.error(repr(e))
            time.sleep(1)

# Wait for user input before exiting
sys.stdin.read()
</code>```

However, after few days of running script stops working with following buffer overflow exception (BEX):

Faulting application python.exe, version 3.6.3150.1013, time stamp
  0x59d3c90d, faulting module ucrtbase.dll, version 10.0.10586.1171,
  time stamp 0x59ae5046, exception code 0xc0000417, fault offset
  0x000834c4, process id 0xecc, application start time
  0x01d351c6613b826e.

Also I noticed that PowerShell console window is not refreshing window content unless I put its window in focus and press arrow down. Maybe some different issue.

Environment:

Windows Server Standard SP2 (32-bit)

PowerShell 2.0

Python 3.6.3

答: Seems issue is related to that fact that script is running inside PowerShell. It is not observed, while script is being run inside Python Shell.</p>

Body:
I have a Python script running on Windows, which is basically RESTful interface client with multiple connections to SQL database. It has to be restarted with some period of time (for example, 15 minutes). For this purpose I wrapped the code inside the loop with function os.execl(). I run script from PowerShell using following format:

PS C:\test> python.exe .\script.pyc

Script itself (without disclosing implementation details):

import base64
import datetime
import glob
import logging
import os
import socket
import sys
import threading
import time
import pyodbc
import binascii
import configparser
import codecs
import requests
from collections import namedtuple
from binascii import unhexlify, b2a_base64

FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
log = logging.getLogger()

# some class declarations here

if __name__ == '__main__':

    # Initializing counter for time
    timeLast = time.time()

    while 1:
        timeCurrent = time.time()
        if ((timeCurrent - timeLast) > resetTime):
            timeLast = timeCurrent
            os.execl(sys.executable, sys.executable, * sys.argv)

        try:
            # Fetching data from DB
            # Processing data

        except Exception as e:
            log.error(repr(e))
            time.sleep(1)

# Wait for user input before exiting
sys.stdin.read()

However, after few days of running script stops working with following buffer overflow exception (BEX):

Faulting application python.exe, version 3.6.3150.1013, time stamp
  0x59d3c90d, faulting module ucrtbase.dll, version 10.0.10586.1171,
  time stamp 0x59ae5046, exception code 0xc0000417, fault offset
  0x000834c4, process id 0xecc, application start time
  0x01d351c6613b826e.

Also I noticed that PowerShell console window is not refreshing window content unless I put its window in focus and press arrow down. Maybe some different issue.

Environment:

Windows Server Standard SP2 (32-bit)

PowerShell 2.0

Python 3.6.3


问:
Database design - "Separate Tables Vs One table" for Select Queries
I have a MySQL table like following

Books Table

```<code>book-id      category    author     author_place       book_name   book_price --------other 50 columns directly related to  book-id
1           adventure    tom          USA               skydiving     300
2           spiritual    rom         Germany           what you are   500
3           adventure    som         India              woo woo       700
4           education    kom         Italy               boring       900
5           adventure    lom         Pak                 yo yo         90
.
.
4000        spiritual    tom          USA                you are          10
</code>```

As you can see there are around 4000 rows and around 55 columns, I am using this table mostly for select query, Maybe add or update new book after2-3 weeks

I have doubt about the category and author columns

now if I need to select the table by category and author, I can simply do

```<code>SELECT * from books Where author = 'tom'

Select * FROM books WHERE category='education'
</code>```

It works fine, But according to standard database design I think I should separate the category and authors  columns into separate tables (especially authors) and use their primary key as foreign key in the books table
Something like this

Books Table

```<code>book-id      categ_id    author_id          book_name   book_price --------other 50 columns directly related to  book-id
1                   1          1             skydiving     300
2                   2          2             what you are   500
3                   1          3             woo woo       700
4                   3          4             boring       900
5                   1          5              yo yo         90
.
.
4000                3          1              you are          10
</code>```

Category Table

```<code>categ_id      category_name
1              advernture
2              spiritual
3              education
.              .
.              .
30             something
</code>```

Authors Table

```<code>author_id  author      country
 1         tom          USA
 2         rom         Germany
 3         som         India
 4         kom         Italy
 5         lom         Pak
</code>```

But then I have to use join the tables each time I make a select query by authors or category, Which I think will be inefficient, Something like this

```<code>SELECT * FROM Books LEFT JOIN authors on authors.author_id = books.author_id WHERE books.author_id =1
SELECT * FROM Books LEFT JOIN categories on categories.categ_id = books.categ_id_id WHERE books.categ_id =1
</code>```

So should I separate the first table into separate tables or first table design is better in this case?

答:
This question has it's answer from Mr. Edgar F. Codd himself - the inventor of the relation model upon which all RDBMS are build.

Shortly after releasing the relational model papers he and his team followed with papers on the so called normal forms. There are few of them but the first 3 (at least) should be generally considered mandatory:

First normal form (1NF)

Second normal form (2NF)

Third normal form (3NF)

When you read them you'll see that your initial design is in violation of 2NF and you have come with a solution that more or less respects it. Go ahead with a the NF-compliant design without any doubts.

To elaborate a bit on your concerns with Join's performance. This is not an issue as long as the following criteria is met:

your database schema is well designed (2NF compliant at least)

you use Foreign keys to link the tables (MySQL's docs)

you join the tables by their FK

you have the hardware resources necessary to run your data
efficiently

e.g. on MySQL with InnoDB, on 2NF compliant schema using Foreign keys the join performance by the FK will be among the last things you'd ever be concerned.

Historically there was a DB engine in MySQL - the MyISAM - that did not support foreign key constraints. Perhaps it's the main source of feedback about poor join performance (along poor schema designs of course).

Body:
I have a MySQL table like following

Books Table

book-id      category    author     author_place       book_name   book_price --------other 50 columns directly related to  book-id
1           adventure    tom          USA               skydiving     300
2           spiritual    rom         Germany           what you are   500
3           adventure    som         India              woo woo       700
4           education    kom         Italy               boring       900
5           adventure    lom         Pak                 yo yo         90
.
.
4000        spiritual    tom          USA                you are          10

As you can see there are around 4000 rows and around 55 columns, I am using this table mostly for select query, Maybe add or update new book after2-3 weeks

I have doubt about the category and author columns

now if I need to select the table by category and author, I can simply do

SELECT * from books Where author = 'tom'

Select * FROM books WHERE category='education'

It works fine, But according to standard database design I think I should separate the category and authors  columns into separate tables (especially authors) and use their primary key as foreign key in the books table
Something like this

Books Table

book-id      categ_id    author_id          book_name   book_price --------other 50 columns directly related to  book-id
1                   1          1             skydiving     300
2                   2          2             what you are   500
3                   1          3             woo woo       700
4                   3          4             boring       900
5                   1          5              yo yo         90
.
.
4000                3          1              you are          10

Category Table

categ_id      category_name
1              advernture
2              spiritual
3              education
.              .
.              .
30             something

Authors Table

author_id  author      country
 1         tom          USA
 2         rom         Germany
 3         som         India
 4         kom         Italy
 5         lom         Pak

But then I have to use join the tables each time I make a select query by authors or category, Which I think will be inefficient, Something like this

SELECT * FROM Books LEFT JOIN authors on authors.author_id = books.author_id WHERE books.author_id =1
SELECT * FROM Books LEFT JOIN categories on categories.categ_id = books.categ_id_id WHERE books.categ_id =1

So should I separate the first table into separate tables or first table design is better in this case?


问:
Does Microsoft BOT Framework allows to develop interactive UIs?
I have a requirement to implement some interactive UIs using Microsoft Bot Framework for Cortana Channel but I have not found any way to implement this. I want to apply styles on buttons and importantly use graphs & charts (like web dashboard) on Cortana.</p>

答:
I want to apply styles on buttons and importantly use graphs & charts (like web dashboard) on Cortana.

A bot is an web application service which works on server side, BotFramework provides channels which are the connection between bot and native apps such as Skype and here Cortana. The UI part is rendered in each native app, I can't find a way to customize the style for Cortana app. However, AdaptiveCards provides several simple properties for styling, for more information, you can refer to the official sample: cards-AdaptiveCards.

For the question of interactive graphs & charts, AFAIK, it is not currently supported. What we can do for now, is to render the chart to an image and display this image in HeroCard or AdaptiveCard, but this workaround will make the chart lose its interactivity. You can refer to my last answer in the thread How to create Charts using c# Bot Framework?