问:
NPM Best Practices for Continuous Integration
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

```<code>$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s
</code>```

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?

答:
Have you considered using npm link or even symlinking your entire node_modules folder?
At least npm link could be used for your dev dependencies, which you normally want a controlled version of on the server anyway. This should speed things up a bit.</p>

Body:
I am building a HTML5 front-end using NPM-based tools (grunt).

One of the first steps of my continuous integration build process is to run an npm install.

npm install is SLOW. Even with a local NPM proxy caching artifacts (Sonatype's Nexus 3), it is still taking 4 minutes!

$> time npm install
real    4m17.427s
user    0m0.170s
sys     0m0.290s

If I follow my usual best practices for continuous integration, I would start from a pristine SCM repository and run the build. This means that each time the CI build will have to do a fresh npm install and take on the cost of 4 minutes.

This is a significant proportion of my build time. I am discontent that the build is taking so long.

The alternative seems to be to keep the node_modules around between builds. However, I've had problems with the build becoming unstable as a result.

Removing dependencies from package.json does not remove them from node_modules with a simple npm install. I can work-around this with an npm prune first.

What is considered to be best practice here?


来源: stackexchange

问:
"Unfortunately, Google Play Store has stopped" – after installing HTML-only Cordova app
I recently developed my first Cordova app for Android, which is very simple, it consists of a big website downloaded for offline browsing using HTTrack (.apk is about 30MB). That's all, and some parts of the webpage I removed manually, so it might have 404s.

Since I installed it, Google Play Store stops at random times. I just get the error messages, without actually using Google Play Store, or my own app, in the middle of something completely different. Not really disturbing, just strange. (This way I won't consider to publicize my app.) After a while, I even cannot access Google Play Store itself. It stops right after searching for a keyword.

Then I restart Android, my app somehow misteriously is uninstalled, and Google Play Store runs fine. Until I install my own app again...

答: Partial solution found in the meantime: using Aptoide instead of Google Play Store. This saves me of restarting device every time before installation. Apparently has the same selection of applications.</p>

ContentLicense: CC BY-SA 3.0


问:
aws cognito refresh token not validating username
In refresh_token scenario (REFRESH_TOKEN_AUTH AuthFlow), AWS Cognito API seems to be ignoring the value passed for USERNAME field. Validation seems to be limited to an email regex parsing. i.e API allowed to fetch access token for any USERNAME such as foo@bar.com with a refresh token of user@gmail.com.

Scenario:
Login to Cognito:

```<code>response = boto3_client.admin_initiate_auth(
            UserPoolId=POOL_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH',
            AuthParameters={
                'USERNAME': username,
                'PASSWORD': password,
            },
            ClientId=CLIENT_ID,
        )
</code>```

Refresh call

Using the login response refresh token, attempt a refresh for a different user, API did not return a failure.

```<code>response = boto3_client.admin_initiate_auth(
            UserPoolId=POOL_ID,
            AuthFlow='REFRESH_TOKEN_AUTH',
            AuthParameters={
                'USERNAME': username, #===== different user
                'REFRESH_TOKEN': refresh_token,
            },
            ClientId=CLIENT_ID,
        )
</code>```

Is this expected in ADMIN_NO_SRP_AUTH flow? or a bug in Cognito API?

答: In the refresh token flow, the username is not a required parameter as the refresh token can directly be associated with the given user that the token was issued in the first place. You can test this behavior by using the AWS CLI for example and passing just the refresh token.</p>

Body:
In refresh_token scenario (REFRESH_TOKEN_AUTH AuthFlow), AWS Cognito API seems to be ignoring the value passed for USERNAME field. Validation seems to be limited to an email regex parsing. i.e API allowed to fetch access token for any USERNAME such as foo@bar.com with a refresh token of user@gmail.com.

Scenario:
Login to Cognito:

response = boto3_client.admin_initiate_auth(
            UserPoolId=POOL_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH',
            AuthParameters={
                'USERNAME': username,
                'PASSWORD': password,
            },
            ClientId=CLIENT_ID,
        )

Refresh call

Using the login response refresh token, attempt a refresh for a different user, API did not return a failure.

response = boto3_client.admin_initiate_auth(
            UserPoolId=POOL_ID,
            AuthFlow='REFRESH_TOKEN_AUTH',
            AuthParameters={
                'USERNAME': username, #===== different user
                'REFRESH_TOKEN': refresh_token,
            },
            ClientId=CLIENT_ID,
        )

Is this expected in ADMIN_NO_SRP_AUTH flow? or a bug in Cognito API?


问:
Angular App not compiling when Component is Deleted
When I delete a component, (say nav-bar.component.ts and it's folder), The app fails to compile. I have removed the declaration from app.module.ts. The error that is being thrown says it has to do with "include.module.ts," which has nothing to do with nav-bar.component.ts.

Here is the CLI output:

```<code>C:\Users\Daniel\dev-projects\vile>ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2017-12-04T17:02:37.587Z
Hash: d00b13e972db5b32e6b8
Time: 2988ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 1.06 kB {vendor} [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 323 bytes {inline} [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 56.5 kB {inline} [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 338 kB [initial] [rendered]

ERROR in Error: Metadata version mismatch for module C:/Users/Daniel/dev-projects/vile/node_modules/@angular/material/toolbar/typings/index.d.ts, found version 4, expected 3, resolving symbol IncludeModule in C:/Users/Daniel/dev-projects/vile/src/app/include/include.module.ts, resolving symbol IncludeModule in C:/Users/Daniel/dev-projects/vile/src/app/include/include.module.ts
    at Error (native)
    at syntaxError (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:1729:34)
    at simplifyInContext (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24979:23)
    at StaticReflector.simplify (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24991:13)
    at StaticReflector.annotations (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24418:41)
    at _getNgModuleMetadata (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
    at C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
    at Array.reduce (native)
    at _extractLazyRoutesFromStaticModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
    at Object.listLazyRoutesOfModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (C:\Users\Daniel\dev-projects\vile\node_modules\@ngtools\webpack\src\plugin.js:207:44)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\Users\Daniel\dev-projects\vile\node_modules\@ngtools\webpack\src\plugin.js:443:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)

webpack: Failed to compile.
</code>```

答: I figured out the problem. I had imported a module (MatToolbarModule from '@angular/material/toolbar') in include.module.ts (my module to import other modules) that was exported to nav-bar.module.ts. For some reason, even though there should have been no problem with include.module.ts exporting MatToolbarModule, it failed to compile. MY simple fix: remove the import statement for MatToolbarModule and put it back again.</p>

Body:
When I delete a component, (say nav-bar.component.ts and it's folder), The app fails to compile. I have removed the declaration from app.module.ts. The error that is being thrown says it has to do with "include.module.ts," which has nothing to do with nav-bar.component.ts.

Here is the CLI output:

C:\Users\Daniel\dev-projects\vile>ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2017-12-04T17:02:37.587Z
Hash: d00b13e972db5b32e6b8
Time: 2988ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 1.06 kB {vendor} [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 323 bytes {inline} [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 56.5 kB {inline} [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 338 kB [initial] [rendered]

ERROR in Error: Metadata version mismatch for module C:/Users/Daniel/dev-projects/vile/node_modules/@angular/material/toolbar/typings/index.d.ts, found version 4, expected 3, resolving symbol IncludeModule in C:/Users/Daniel/dev-projects/vile/src/app/include/include.module.ts, resolving symbol IncludeModule in C:/Users/Daniel/dev-projects/vile/src/app/include/include.module.ts
    at Error (native)
    at syntaxError (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:1729:34)
    at simplifyInContext (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24979:23)
    at StaticReflector.simplify (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24991:13)
    at StaticReflector.annotations (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler\bundles\compiler.umd.js:24418:41)
    at _getNgModuleMetadata (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
    at C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
    at Array.reduce (native)
    at _extractLazyRoutesFromStaticModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
    at Object.listLazyRoutesOfModule (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\Users\Daniel\dev-projects\vile\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (C:\Users\Daniel\dev-projects\vile\node_modules\@ngtools\webpack\src\plugin.js:207:44)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\Users\Daniel\dev-projects\vile\node_modules\@ngtools\webpack\src\plugin.js:443:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)

webpack: Failed to compile.


问:
Directly setting values for an ArrayList in Java
Setting a list of values for a Java ArrayList works:

```<code>Integer[] a = {1,2,3,4,5,6,7,8,9};
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList(a));
</code>```

However, the following doesn't work and has the error "Illegal start of type" as well as other. Why not? Since the first line in the first code block is simply assignment, shouldn't it not have an effect?

```<code>ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList({1,2,3,4,5,6,7,8,9}));
</code>```

答:
A strange and little used idiom,

```<code>List<Integer> ints = new ArrayList<Integer>() {{add(1); add(2); add(3);}}
</code>```

This is creating an anonymous class that extends ArrayList (outer brackets), and then implements the instance initializer (inner brackets) and calls List.add() there.

The advantage of this over Arrays.asList() is that it works for any collection type:

```<code>Map<String,String> m = new HashMap<>() {{
  put("foo", "bar");
  put("baz", "buz");
  ...
}}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Setting a list of values for a Java ArrayList works:

Integer[] a = {1,2,3,4,5,6,7,8,9};
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList(a));

However, the following doesn't work and has the error "Illegal start of type" as well as other. Why not? Since the first line in the first code block is simply assignment, shouldn't it not have an effect?

ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList({1,2,3,4,5,6,7,8,9}));

Body:
A strange and little used idiom,

List<Integer> ints = new ArrayList<Integer>() {{add(1); add(2); add(3);}}

This is creating an anonymous class that extends ArrayList (outer brackets), and then implements the instance initializer (inner brackets) and calls List.add() there.

The advantage of this over Arrays.asList() is that it works for any collection type:

Map<String,String> m = new HashMap<>() {{
  put("foo", "bar");
  put("baz", "buz");
  ...
}}

ContentLicense: CC BY-SA 4.0


问:
How to get Pandoc from m Pandoc?
I started to write few programs using the pandoc api ,taking examples  from , https://johnmacfarlane.net/BayHac2014/#/the-pandoc-types , But I am unable to isolate Pandoc from m Pandoc.

```<code>module ImageAttr where
import Text.Pandoc.Builder
import Text.Pandoc.Generic
import Text.Pandoc.Definition
import Text.Pandoc.JSON
import qualified Data.Char as DataChar
import qualified Data.List as DataList
import Data.Either
import Text.Parsec as Parsec
import Text.Pandoc
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b

fromLeft :: b -> Either b a -> b
fromLeft  _ (Left b)  = b
fromLeft  b _        = b

main :: IO ()
main = do
        result <- runIO $ do
            doc <- readMarkdown def (T.pack "[testing](url)")
            writeRST def doc
        x<-((handleError result))
        print x
</code>```

output is String but I need pandoc ast previously it was Either PandocError Pandoc type , instead I am getting "m Pandoc". How to get Pandoc out of "m Pandoc".

any Thought?
By the way , I am new and still learning haskell.

I am getting error message  as :

```<code>ImageSizeModifer.hs:28:12:
    Couldn't match expected type ‘PandocIO a0’ with actual type ‘IO ()’
    In a stmt of a 'do' block: print ""
    In the second argument of ‘($)’, namely
      ‘do { doc <- readMarkdown def (T.pack "[testing](url)");
            print "" }’
Failed, modules loaded: none.
Prelude T>
</code>```

My problem is I need Pandoc , but I have not much idea how to to get it ? There are new PandocIO and PandocPure , I believe these are new.

答:
The new version of pandoc has readMarkdown :: PandocMonad m => ReaderOptions -> Text -> m Pandoc. This follows the usual mtl-style of specifying the constraints on the monad, instead of the actual monad.

That means that to use readMarkdown, you need to pick a particular m satisfying PandocMonad. You can find what instances PandocMonad has by scrolling to the "Instances" section of its doc. In this case, you find:

PandocMonad PandocPure maybe interesting

PandocMonad PandocIO maybe interesting

(MonadTrans t, PandocMonad m, Functor (t m), MonadError PandocError (t m), Monad (t m), Applicative (t m)) => PandocMonad (t m) - not interesting, requires another PandocMonad m

PandocMonad m => PandocMonad (ParsecT s st m) - not interesting, requires another PandocMonad m

Now, scrolling past where PandocPure and PandocIO are defined, you can find ways of running extracting information out of those:

runIO :: PandocIO a -> IO (Either PandocError a)

runPure :: PandocPure a -> Either PandocError a

Combining either of these functions with readMarkdown, you can get a concrete Either type.

```<code>runIO (readMarkdown def (T.pack "[testing](url)")) :: IO (Either PandocError Pandoc)
runPure (readMarkdown def (T.pack "[testing](url)")) :: Either PandocError Pandoc
</code>```

Note that I know nothing about Pandoc or its API - all I did was walk through the above process.

Title: How to get Pandoc from m Pandoc?

Body:
I started to write few programs using the pandoc api ,taking examples  from , https://johnmacfarlane.net/BayHac2014/#/the-pandoc-types , But I am unable to isolate Pandoc from m Pandoc.

module ImageAttr where
import Text.Pandoc.Builder
import Text.Pandoc.Generic
import Text.Pandoc.Definition
import Text.Pandoc.JSON
import qualified Data.Char as DataChar
import qualified Data.List as DataList
import Data.Either
import Text.Parsec as Parsec
import Text.Pandoc
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b

fromLeft :: b -> Either b a -> b
fromLeft  _ (Left b)  = b
fromLeft  b _        = b

main :: IO ()
main = do
        result <- runIO $ do
            doc <- readMarkdown def (T.pack "[testing](url)")
            writeRST def doc
        x<-((handleError result))
        print x

output is String but I need pandoc ast previously it was Either PandocError Pandoc type , instead I am getting "m Pandoc". How to get Pandoc out of "m Pandoc".

any Thought?
By the way , I am new and still learning haskell.

I am getting error message  as :

ImageSizeModifer.hs:28:12:
    Couldn't match expected type ‘PandocIO a0’ with actual type ‘IO ()’
    In a stmt of a 'do' block: print ""
    In the second argument of ‘($)’, namely
      ‘do { doc <- readMarkdown def (T.pack "[testing](url)");
            print "" }’
Failed, modules loaded: none.
Prelude T>

My problem is I need Pandoc , but I have not much idea how to to get it ? There are new PandocIO and PandocPure , I believe these are new.

Body:
The new version of pandoc has readMarkdown :: PandocMonad m => ReaderOptions -> Text -> m Pandoc. This follows the usual mtl-style of specifying the constraints on the monad, instead of the actual monad.

That means that to use readMarkdown, you need to pick a particular m satisfying PandocMonad. You can find what instances PandocMonad has by scrolling to the "Instances" section of its doc. In this case, you find:

PandocMonad PandocPure maybe interesting

PandocMonad PandocIO maybe interesting

(MonadTrans t, PandocMonad m, Functor (t m), MonadError PandocError (t m), Monad (t m), Applicative (t m)) => PandocMonad (t m) - not interesting, requires another PandocMonad m

PandocMonad m => PandocMonad (ParsecT s st m) - not interesting, requires another PandocMonad m

Now, scrolling past where PandocPure and PandocIO are defined, you can find ways of running extracting information out of those:

runIO :: PandocIO a -> IO (Either PandocError a)

runPure :: PandocPure a -> Either PandocError a

Combining either of these functions with readMarkdown, you can get a concrete Either type.

runIO (readMarkdown def (T.pack "[testing](url)")) :: IO (Either PandocError Pandoc)
runPure (readMarkdown def (T.pack "[testing](url)")) :: Either PandocError Pandoc

Note that I know nothing about Pandoc or its API - all I did was walk through the above process.


问:
Overriding prototype.toString doesn't work
I have the following code.

```<code>function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);
</code>```

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?

答:
According to the specifications (console.log --> Logger --> Printer) the implementation of console.log is ultimately up to the implementation.

So, it is likely that in the environment you are working in the implementation of console.log(obj) is not simply Printer("log", obj.toString()).

Body:
I have the following code.

function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?


问:
Calling GCP Translate API within Dataproc pyspark map
I am trying to call the language detection method of the translate client api from pyspark for each row in a file.

I created a map method as the following but the job seems to just freeze with no error. If I remove the call to the translate API it executes fine. Is it possible to call Google client API methods within pySpark map ?

mapping method to do translation

def doTranslate(data):

```<code>translate_client = translate.Client()

# Get the message information
messageId = data[0]
messageContent = data[6]

detectedLang = translate_client.detect_language(messageContent)

r = []
r.append(detectedLang)
return r
</code>```

答:
Figured it out!! your question led me in the right direction. thanks!

Turns out I was getting an exception from the call because I was going past the default quota for sizes of messages. I added a try/except block and determined this was the problem. Then cutting the message size down (I am just testing so dont want to mess with the quota) fixed the issue.

Body:
I am trying to call the language detection method of the translate client api from pyspark for each row in a file.

I created a map method as the following but the job seems to just freeze with no error. If I remove the call to the translate API it executes fine. Is it possible to call Google client API methods within pySpark map ?

mapping method to do translation

def doTranslate(data):

translate_client = translate.Client()

# Get the message information
messageId = data[0]
messageContent = data[6]

detectedLang = translate_client.detect_language(messageContent)

r = []
r.append(detectedLang)
return r


问:
Remove space and Uppercase first letter

I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

```<code>    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}
</code>```

How can i erase the space between the last word and "." in each sentence?

```<code>Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .
</code>```

答:
Here's the way I would do it. Performs at lot less inefficient string concatenation, and handles full stops, question marks, and exclamation marks.</p>

```<code>public static void main(String[] args) {
    System.out.println("Bitte geben Sie einen String ein: ");
    String text = "Hallo mir gehts gut!! Wie gehts dir. mir gehts spitze.";

    System.out.println(reverseSentences(text));
}

/**
 * Reverse the order of the words in the sentence.
 * @param sentence the sentence to reverse.
 * @param terminal the symbol to add at the end.
 * @return the reversed sentence, with added terminal.
 */
static String reverse(String sentence, String terminal) {
    sentence = sentence.trim();
    if (sentence.isEmpty()) {
        return terminal;
    }

    // find words by splitting the sentence at spaces
    // then put the words back together in reverse order
    String[] words = sentence.split("\\s+");
    StringBuilder sb = new StringBuilder(sentence.length());

    for (int i = words.length - 1; i >= 0; i--) {
        String word = words[i];
        // capitalize the last word before placing it at the start
        if (i == words.length - 1 && !word.isEmpty()) {
            sb.append(word.substring(0, 1).toUpperCase());
            sb.append(word.substring(1));
        } else {
            sb.append(word);
        }
        if (i > 0) sb.append(' ');
    }

    // append terminal
    sb.append(terminal);
    return sb.toString();
}

/**
 * Reverse each sentence in the string.
 * @param s the string to act on.
 * @return the string, with sentences reversed.
 */
public static String reverseSentences(String s) {
    // Match each sentence, with an optional terminal
    // terminal may be one or more
    // full stops, question or exclamation marks
    Pattern p = Pattern.compile("([^.?!]+)([.?!]*)");
    Matcher m = p.matcher(s);

    // find and reverse the sentences, then recombine them
    StringBuilder sb = new StringBuilder(s.length());
    while (m.find()) {
        String sentence = m.group(1);
        String terminal = m.group(2);
        sb.append(reverse(sentence, terminal));
        sb.append(' ');
    }

    return sb.toString().trim();
}
</code>```

Title: Remove space and Uppercase first letter

Body:
I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}

How can i erase the space between the last word and "." in each sentence?

Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .

Body:
Here's the way I would do it. Performs at lot less inefficient string concatenation, and handles full stops, question marks, and exclamation marks.

public static void main(String[] args) {
    System.out.println("Bitte geben Sie einen String ein: ");
    String text = "Hallo mir gehts gut!! Wie gehts dir. mir gehts spitze.";

    System.out.println(reverseSentences(text));
}

/**
 * Reverse the order of the words in the sentence.
 * @param sentence the sentence to reverse.
 * @param terminal the symbol to add at the end.
 * @return the reversed sentence, with added terminal.
 */
static String reverse(String sentence, String terminal) {
    sentence = sentence.trim();
    if (sentence.isEmpty()) {
        return terminal;
    }

    // find words by splitting the sentence at spaces
    // then put the words back together in reverse order
    String[] words = sentence.split("\\s+");
    StringBuilder sb = new StringBuilder(sentence.length());

    for (int i = words.length - 1; i >= 0; i--) {
        String word = words[i];
        // capitalize the last word before placing it at the start
        if (i == words.length - 1 && !word.isEmpty()) {
            sb.append(word.substring(0, 1).toUpperCase());
            sb.append(word.substring(1));
        } else {
            sb.append(word);
        }
        if (i > 0) sb.append(' ');
    }

    // append terminal
    sb.append(terminal);
    return sb.toString();
}

/**
 * Reverse each sentence in the string.
 * @param s the string to act on.
 * @return the string, with sentences reversed.
 */
public static String reverseSentences(String s) {
    // Match each sentence, with an optional terminal
    // terminal may be one or more
    // full stops, question or exclamation marks
    Pattern p = Pattern.compile("([^.?!]+)([.?!]*)");
    Matcher m = p.matcher(s);

    // find and reverse the sentences, then recombine them
    StringBuilder sb = new StringBuilder(s.length());
    while (m.find()) {
        String sentence = m.group(1);
        String terminal = m.group(2);
        sb.append(reverse(sentence, terminal));
        sb.append(' ');
    }

    return sb.toString().trim();
}


问:
How to convert JSON string to array
What I want to do is the following:

taking JSON as input from text area in php

use this input and convert it to JSON and pass it to php curl to send request.

this m getting at php from get of api this json  string i want to pass to json but it is not converting to array

```<code>echo $str='{
        action : "create",
        record: {
            type: "n$product",
            fields: {
                n$name: "Bread",
                n$price: 2.11
            },
            namespaces: { "my.demo": "n" }
        }
    }';
    $json = json_decode($str, true);
</code>```

the above code is not returning me array.

答:
this my solution:
json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"

so i use json_decode twice like that :

```<code>$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation);

var_dump($js_column_validation);
</code>```

and the result is :

```<code> array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }
</code>```

Title: How to convert JSON string to array

Body:
What I want to do is the following:

taking JSON as input from text area in php

use this input and convert it to JSON and pass it to php curl to send request.

this m getting at php from get of api this json  string i want to pass to json but it is not converting to array

echo $str='{
        action : "create",
        record: {
            type: "n$product",
            fields: {
                n$name: "Bread",
                n$price: 2.11
            },
            namespaces: { "my.demo": "n" }
        }
    }';
    $json = json_decode($str, true);

the above code is not returning me array.

Body:
this my solution:
json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"

so i use json_decode twice like that :

$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation);

var_dump($js_column_validation);

and the result is :

 array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }


问:
How to Split or break a Python list into Unequal chunks, with specified chunk sizes
I have two Python lists of numbers.

```<code>list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes
</code>```

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2.
As a result, I would like to have this:

```<code>a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1
d_list = [154,122,563] ##next 3 numbers from list1
</code>```

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1,
the second chunk should have the next 5 elements, and so on.

How can I do this?

Body:
I have two Python lists of numbers.

list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2.
As a result, I would like to have this:

a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1
d_list = [154,122,563] ##next 3 numbers from list1

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1,
the second chunk should have the next 5 elements, and so on.

How can I do this?

Body:
There are lots of ways to do this. One way is to create a list of indices for slicing, using itertools.accumulate()

from itertools import accumulate
list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes
ind = [0] + list(accumulate(list2))

[list1[ind[i]:ind[i+1]] for i in range(len(ind)-1)]

This gives the following result:

[[123, 452],
 [342, 533, 222, 402, 124],
 [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],
 [154, 122, 563]]


问:
Get only values from array (without key)
I've have the function:

```<code>function getCotas() {
  var values = [];
  values['first'] = 10;
  $('.loop.scota').each(function(key, value) {
    var id = key + 1;
    values[$('.sdate.id' + id).text()] = parseInt($(this).text());
  });

  return values;
}
</code>```

The output is the array with the keys:

[first: 160, 01/12/2017: 157, 04/12/2017: 153]

What I need is just the values of the array, without the keys:

[160,157,153]

I already tried to do a loop with the values, like this answer, but always return an empty [] or an error with the functions.

Someone knows how to resolve this problem?

答:
Array push should be what you're looking for.</p>

```<code>values.push(parseInt($(this).text());
</code>```

Body:
I've have the function:

function getCotas() {
  var values = [];
  values['first'] = 10;
  $('.loop.scota').each(function(key, value) {
    var id = key + 1;
    values[$('.sdate.id' + id).text()] = parseInt($(this).text());
  });

  return values;
}

The output is the array with the keys:

[first: 160, 01/12/2017: 157, 04/12/2017: 153]

What I need is just the values of the array, without the keys:

[160,157,153]

I already tried to do a loop with the values, like this answer, but always return an empty [] or an error with the functions.

Someone knows how to resolve this problem?

Body:
Array push should be what you're looking for.

values.push(parseInt($(this).text());


问:
Extern Variables seemingly not working "symbols not found for architecture x86_64"
I've been searching through Stackoverflow and the web for the answer and it seems like I'm doing this correctly, however I can't get it to work.

I made a test program for using extern, (it's on xCode using the projects feature if that makes a difference). I'm trying to declare a variable, that I can access anywhere in my program, whenever I change the value of that variable, I want to be able to access the changed value.

What I've done so far is I have a header file

```<code> externFile.h
</code>```

and a

```<code>externFile.c
</code>```

and of course my
main.c

In externFile.h I defined:

```<code> extern int ply;
</code>```

In main.c I have:

```<code>int main()
{
   int ply;
   ply = 5;
   printPly();
}
</code>```

In externFile.c I have:

```<code> void printPly(){
 printf("%d is ply.\n", ply);
 }
</code>```

However I'm getting this error:

```<code> _ply referenced from _printPly
 ld symbols not found for architecture x86_64
</code>```

Does anyone have any sort of ideas about this?

答:
You haven't actually defined ply globally:

```<code>int main(void)
{
    int ply;
    ply = 5;
    printPly();
}
</code>```

Here, ply is a local variable, not a global, since it is defined inside of a function.  The extern line in your header file does not define the global, but declares it.  It says "this variable exists somewhere", but it doesn't create it.  Because there is no global defined, you get an undefined reference error.

Global variables must be defined at file scope, i.e. outside of a function:

```<code>int ply = 5;

int main(void)
{
    printPly();
}
</code>```

Body:
I've been searching through Stackoverflow and the web for the answer and it seems like I'm doing this correctly, however I can't get it to work.

I made a test program for using extern, (it's on xCode using the projects feature if that makes a difference). I'm trying to declare a variable, that I can access anywhere in my program, whenever I change the value of that variable, I want to be able to access the changed value.

What I've done so far is I have a header file

 externFile.h

and a

externFile.c

and of course my
main.c

In externFile.h I defined:

 extern int ply;

In main.c I have:

int main()
{
   int ply;
   ply = 5;
   printPly();
}

In externFile.c I have:

 void printPly(){
 printf("%d is ply.\n", ply);
 }

However I'm getting this error:

 _ply referenced from _printPly
 ld symbols not found for architecture x86_64

Does anyone have any sort of ideas about this?

Body:
You haven't actually defined ply globally:

int main(void)
{
    int ply;
    ply = 5;
    printPly();
}

Here, ply is a local variable, not a global, since it is defined inside of a function.  The extern line in your header file does not define the global, but declares it.  It says "this variable exists somewhere", but it doesn't create it.  Because there is no global defined, you get an undefined reference error.

Global variables must be defined at file scope, i.e. outside of a function:

int ply = 5;

int main(void)
{
    printPly();
}


问:
Specific request for Youtube API from shell
Using bash, I try to retrieve information from my YouTube channel.

```<code>curl -G https://www.googleapis.com/youtube/v3/search -d part="snippet" -d q="THISISMYCHANNELID" -d key="THISISMYKEY"
</code>```

This works quite well, but it doesn't give me the 2 information I need:

-The number of subscribers of the channel

-The number of uploaded videos of the channel

I went trough the official documentation ( https://developers.google.com/apis-explorer/#p/youtube/v3/ ) but I didn't find any relevant query, though I am sure there is a solution for that.

答:
You just need to call Channel List API and use snippet=statistics. From channel model it will give :

```<code>"statistics": {
    "viewCount": unsigned long,
    "commentCount": unsigned long,
    "subscriberCount": unsigned long,
    "hiddenSubscriberCount": boolean,
    "videoCount": unsigned long
}
</code>```

Using curl & jq, you can use :

```<code>curl -G -s https://www.googleapis.com/youtube/v3/channels \
     -d part="statistics" \
     -d id="UC_x5XG1OV2P6uZZ5FSM9Ttw" \
     -d key="your_key" | \
     jq -r '.items[].statistics | (.subscriberCount, .videoCount)'
</code>```

Body:
Using bash, I try to retrieve information from my YouTube channel.

curl -G https://www.googleapis.com/youtube/v3/search -d part="snippet" -d q="THISISMYCHANNELID" -d key="THISISMYKEY"

This works quite well, but it doesn't give me the 2 information I need:

-The number of subscribers of the channel

-The number of uploaded videos of the channel

I went trough the official documentation ( https://developers.google.com/apis-explorer/#p/youtube/v3/ ) but I didn't find any relevant query, though I am sure there is a solution for that.

Body:
You just need to call Channel List API and use snippet=statistics. From channel model it will give :

"statistics": {
    "viewCount": unsigned long,
    "commentCount": unsigned long,
    "subscriberCount": unsigned long,
    "hiddenSubscriberCount": boolean,
    "videoCount": unsigned long
}

Using curl & jq, you can use :

curl -G -s https://www.googleapis.com/youtube/v3/channels \
     -d part="statistics" \
     -d id="UC_x5XG1OV2P6uZZ5FSM9Ttw" \
     -d key="your_key" | \
     jq -r '.items[].statistics | (.subscriberCount, .videoCount)'


问:
Rails many-to-many same class bi-directional relationship.. how?
So heres the deal.. i'm writing a rails application to manage contact data..

I have a contact model and that contact needs to have many family members (still the contact class).. that relationship needs associated relationship data.. ie

```<code>ContactA | ContactB | Relationship
1          2          Contact A is Contact B's Father
</code>```

How can i relate 2 objects of the same class and attach some data and be able to traverse te relationship bidirectionally like so:

```<code>@guy1 = Contact.find(1) #Guy A
@guy1.family_relationships
>>> [[guyb, "f"], [guyc, "s"]]
@guy2 = @guy1.family_members.first
@guy1.family_members
>>> [[guya]]
</code>```

Thats probably not 100% correct but its late and ive been battling with a server all day so please forgive me!!

I've heard you have to do all kinds of hacky SQL to do it..

Thanks!

Daniel

答:
I had a similar situation in one of my projects earlier. I went with the following design:

```<code>class Patient < AR::Base
  has_many :relatives, :dependent => :destroy do
    def husband
      select { |r| r.relation.eql?('Husband').first
    end

    def father
      select { |r| r.relation.eql?('Father').first
    end

    ...

    def sons
      select { |r| r.relation.eql?('Son')
    end
    ...
  end
end

class Relative < AR::Base
  belongs_to :patient

  validates :relation,
    :inclusion => {
      :in => %w( Husband Daughter Son Father Mother Brother Sister )
    }
end
</code>```

This works for me. Hope this helps you or at least point you in the right direction!

Body:
So heres the deal.. i'm writing a rails application to manage contact data..

I have a contact model and that contact needs to have many family members (still the contact class).. that relationship needs associated relationship data.. ie

ContactA | ContactB | Relationship
1          2          Contact A is Contact B's Father

How can i relate 2 objects of the same class and attach some data and be able to traverse te relationship bidirectionally like so:

@guy1 = Contact.find(1) #Guy A
@guy1.family_relationships
>>> [[guyb, "f"], [guyc, "s"]]
@guy2 = @guy1.family_members.first
@guy1.family_members
>>> [[guya]]

Thats probably not 100% correct but its late and ive been battling with a server all day so please forgive me!!

I've heard you have to do all kinds of hacky SQL to do it..

Thanks!

Daniel

Body:
I had a similar situation in one of my projects earlier. I went with the following design:

class Patient < AR::Base
  has_many :relatives, :dependent => :destroy do
    def husband
      select { |r| r.relation.eql?('Husband').first
    end

    def father
      select { |r| r.relation.eql?('Father').first
    end

    ...

    def sons
      select { |r| r.relation.eql?('Son')
    end
    ...
  end
end

class Relative < AR::Base
  belongs_to :patient

  validates :relation,
    :inclusion => {
      :in => %w( Husband Daughter Son Father Mother Brother Sister )
    }
end

This works for me. Hope this helps you or at least point you in the right direction!


问:
How to prevent Hibernate from assuming data types for parameter binding based on names
I just noticed that Hibernate automatically assumes data types for query parameters based on names (maybe column or annotated class). I'm trying to store a unix timestamp as long in a BIGINT column in a MySQL database. When the name is timestamp in the database and in my (JPA) annotated class, Hibernate automatically assumes, that it is a temporal value and thus I get an exception, when I try to bind a long value for this column in a query, because Hibernate expects a java.util.Date. When I rename this column in the database and in the class to 'foobar' everything works as expected. How can I stop Hibernate doing such stupid assumptions?

Edit:

DB Table:

```<code>CREATE TABLE candle
(
   `open` decimal(25,15) NOT NULL,
   `high` decimal(25,15) NOT NULL,
   `low` decimal(25,15) NOT NULL,
   `close` decimal(25,15) NOT NULL,
   `volume` decimal(15,2) NOT NULL,
   `symbol` varchar(255) NOT NULL,
   `exchange` varchar(255) NOT NULL,
   `timestamp` bigint NOT NULL,
   `width` bigint NOT NULL,
   PRIMARY KEY(`symbol`, `exchange`, `timestamp`, `width`),
   KEY idx_symbol (`symbol`),
   KEY idx_exchange (`exchange`),
   KEY idx_timestamp (`timestamp`),
   KEY idx_width (`width`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

JPA class:

```<code>@Entity(name="candle")
public class JpaCandle {

    @EmbeddedId
    private Key id;

    @Column
    private BigDecimal open;

    @Column
    private BigDecimal high;

    @Column
    private BigDecimal low;

    @Column
    private BigDecimal close;

    @Column
    private BigDecimal volume;

    public Key getId() {
        return id;
    }

    @Embeddable
    public static class Key implements Serializable {
        @Column
        private String symbol;

        @Column
        private String exchange;

        @Column
        private long timestamp;

        @Column
        private long width;
    }
}
</code>```

Query:

```<code>TypedQuery<JpaCandle> q = em.createQuery("FROM candle WHERE symbol = :symbol AND width = :width AND timestamp >= :from AND timestamp <= :until ORDER BY timestamp ASC", JpaCandle.class);
q.setParameter("from", from.toEpochMilli());
q.setParameter("until", until.toEpochMilli());
q.setParameter("symbol", symbol);
q.setParameter("width", width.getSeconds());
List<JpaCandle> jpaCandles = q.getResultList();
</code>```

答: TIMESTAMP is a column type in the MySQL. Better to not use such name for a column. Perhaps, MySQL returns the type of such value as Date.

Body:
I just noticed that Hibernate automatically assumes data types for query parameters based on names (maybe column or annotated class). I'm trying to store a unix timestamp as long in a BIGINT column in a MySQL database. When the name is timestamp in the database and in my (JPA) annotated class, Hibernate automatically assumes, that it is a temporal value and thus I get an exception, when I try to bind a long value for this column in a query, because Hibernate expects a java.util.Date. When I rename this column in the database and in the class to 'foobar' everything works as expected. How can I stop Hibernate doing such stupid assumptions?

Edit:

DB Table:

CREATE TABLE candle
(
   `open` decimal(25,15) NOT NULL,
   `high` decimal(25,15) NOT NULL,
   `low` decimal(25,15) NOT NULL,
   `close` decimal(25,15) NOT NULL,
   `volume` decimal(15,2) NOT NULL,
   `symbol` varchar(255) NOT NULL,
   `exchange` varchar(255) NOT NULL,
   `timestamp` bigint NOT NULL,
   `width` bigint NOT NULL,
   PRIMARY KEY(`symbol`, `exchange`, `timestamp`, `width`),
   KEY idx_symbol (`symbol`),
   KEY idx_exchange (`exchange`),
   KEY idx_timestamp (`timestamp`),
   KEY idx_width (`width`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

JPA class:

@Entity(name="candle")
public class JpaCandle {

    @EmbeddedId
    private Key id;

    @Column
    private BigDecimal open;

    @Column
    private BigDecimal high;

    @Column
    private BigDecimal low;

    @Column
    private BigDecimal close;

    @Column
    private BigDecimal volume;

    public Key getId() {
        return id;
    }

    @Embeddable
    public static class Key implements Serializable {
        @Column
        private String symbol;

        @Column
        private String exchange;

        @Column
        private long timestamp;

        @Column
        private long width;
    }
}

Query:

TypedQuery<JpaCandle> q = em.createQuery("FROM candle WHERE symbol = :symbol AND width = :width AND timestamp >= :from AND timestamp <= :until ORDER BY timestamp ASC", JpaCandle.class);
q.setParameter("from", from.toEpochMilli());
q.setParameter("until", until.toEpochMilli());
q.setParameter("symbol", symbol);
q.setParameter("width", width.getSeconds());
List<JpaCandle> jpaCandles = q.getResultList();


问:
How do I pull up the Expo QR code after React Native app has been started?
I've already started the app and did not see the QR code on the initial terminal after CRNA set up.
How can I pull it up now to scan the code?</p>

答: you can shake the device and get a link to copy paste for someone else. Otherwise would recommend just restarting the packager to get the code. </p>


问:
How to render an svg image in the front of background image on react native?
I want to render an svg image on the 'front layer' of an background image.

When the view loads, only the background image appears, and i don't get any erros. Is the image even loading (at the background of the background)?

Here is what i've done so far:

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  View,
  Image,
} from 'react-native';

import SVGImage from 'react-native-svg-image';

export default class ShowScreen extends Component {

  render() {
    return (
      <View style={styles.container}>
        <Image
        source={require('../img/image.jpg')}
        style={styles.backgroundImage}
        blurRadius={1}>

          <View style={styles.content}>
            <SVGImage
            style={{ width: 80, height: 80 }}
            source={{uri:'https://fluent-panda.appspot.com.storage.googleapis.com/dumbbell.svg'}}/>
          </View>
        </Image>
      </View>
    );
  }

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
    justifyContent: 'center',
  },
  content: {
    alignItems: 'center',
  }
});
</code>```

Why the image is not appearing? I am using react-native.

答: Had a similar problem with adding text over map components and it was solved by adding z-index: -1 to the back element (in this case, the map)

Body:
I want to render an svg image on the 'front layer' of an background image.

When the view loads, only the background image appears, and i don't get any erros. Is the image even loading (at the background of the background)?

Here is what i've done so far:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  View,
  Image,
} from 'react-native';

import SVGImage from 'react-native-svg-image';

export default class ShowScreen extends Component {

  render() {
    return (
      <View style={styles.container}>
        <Image
        source={require('../img/image.jpg')}
        style={styles.backgroundImage}
        blurRadius={1}>

          <View style={styles.content}>
            <SVGImage
            style={{ width: 80, height: 80 }}
            source={{uri:'https://fluent-panda.appspot.com.storage.googleapis.com/dumbbell.svg'}}/>
          </View>
        </Image>
      </View>
    );
  }

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
    justifyContent: 'center',
  },
  content: {
    alignItems: 'center',
  }
});

Why the image is not appearing? I am using react-native.


问:
LinkageError: loading contraint violation
I have seen the other linkage errors but none of them says what can be done with the jars. When I deploy my application in Jboss it works fine, but when I deploy my application to websphere I am having this linkage errors. A similar issue can be found here: LinkageError when calling webservice method but not sure what to do to fix it

Mainly it loaded from com/ibm/oti/vm/BootstrapClassLoader and com/ibm/ws/classloader/CompoundClassLoader with the shared class javax/xml/soap/SOAPFault

```<code>Caused by: java.lang.LinkageError: loading constraint violation: loader "com/ibm/oti/vm/BootstrapClassLoader@dda62209" previously initiated loading for a different type with name "javax/xml/soap/SOAPFault" defined by loader "com/ibm/ws/classloader/CompoundClassLoader@fdebcda2"
        at com.ibm.oti.vm.VM.findClassOrNull(Native Method)
        at com.ibm.oti.vm.BootstrapClassLoader.loadClass(BootstrapClassLoader.java:63)
        at javax.xml.ws.soap.SOAPFaultException.<init>(SOAPFaultException.java:78)
        at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:160)
        at com.sun.proxy.$Proxy118.collectionsInquiryV2(Unknown Source)
</code>```

What I have is jsp calling a webservice.
From the message the only jars I saw is from axis.jar with contains the class javax/xml/soap/SOAPFault

does it mean I need to remove the SOAPFault.class from axis.jar? (it does not work tried and other webservice would fail if this was removed)

答:
Do you have a SOAP API jar in your application?  The "loading constraint violation" LinkageError generally implies duplicate visibility to a class through two different class loaders.  What I'm guessing is happening here based on the stack is that your application has the SOAP API but not the JAX-WS API.  When that JAX-WS class references the SOAP class, that means that the classes in your app can "see" the SOAP API from two different loaders - directly, in the local class loader, and indirectly through the JAX-WS API.

Simplest answer is just to get rid of any SOAP API jar(s) in your app - you can just rely on the copy in the server, unless you have a really specific version need.  Alternately, you could add a JAX-WS API jar to the application package, so the application loads its own copy of the API rather than pulling it from the server.

Body:
I have seen the other linkage errors but none of them says what can be done with the jars. When I deploy my application in Jboss it works fine, but when I deploy my application to websphere I am having this linkage errors. A similar issue can be found here: LinkageError when calling webservice method but not sure what to do to fix it

Mainly it loaded from com/ibm/oti/vm/BootstrapClassLoader and com/ibm/ws/classloader/CompoundClassLoader with the shared class javax/xml/soap/SOAPFault

Caused by: java.lang.LinkageError: loading constraint violation: loader "com/ibm/oti/vm/BootstrapClassLoader@dda62209" previously initiated loading for a different type with name "javax/xml/soap/SOAPFault" defined by loader "com/ibm/ws/classloader/CompoundClassLoader@fdebcda2"
        at com.ibm.oti.vm.VM.findClassOrNull(Native Method)
        at com.ibm.oti.vm.BootstrapClassLoader.loadClass(BootstrapClassLoader.java:63)
        at javax.xml.ws.soap.SOAPFaultException.<init>(SOAPFaultException.java:78)
        at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:160)
        at com.sun.proxy.$Proxy118.collectionsInquiryV2(Unknown Source)

What I have is jsp calling a webservice.
From the message the only jars I saw is from axis.jar with contains the class javax/xml/soap/SOAPFault

does it mean I need to remove the SOAPFault.class from axis.jar? (it does not work tried and other webservice would fail if this was removed)


问:
XML values with same name to list
I have the following XML from which I need to map the "DUE" and "RATE" to a list of objects with XmlSerializer. There can be zero to many, and they're always coming as a pair with the same "idx".

```<code><INVOICE ID="4">
    <STATUS>S</STATUS>
    <TOTAL>6230.00</TOTAL>
    <DUE idx="1">14.12.17</DUE>
    <RATE idx="1">6230.00</RATE>
</INVOICE >
<INVOICE ID="5">
    <STATUS>S</STATUS>
    <TOTAL>3270.00</TOTAL>
    <DUE idx="1">30.11.17</DUE>
    <RATE idx="1">1090.00</RATE>
    <DUE idx="2">07.12.17</DUE>
    <RATE idx="2">1090.00</RATE>
    <DUE idx="3">14.12.17</DUE>
    <RATE idx="3">1090.00</RATE>
</INVOICE>
</code>```

I have the following setup which is working fine without a list of "Rate" and "Due":

```<code>[Serializable]
public class UserInvoicesDto
{
    [XmlElement("INVOICE")]
    public List<UserInvoiceDto> Invoices { get; set; }
}

[Serializable, XmlRoot("INVOICE")]
public class UserInvoiceDto
{
    [XmlAttribute("id")]
    public int InvoiceId { get; set; }
    [XmlElement("TOTAL")]
    public string Total { get; set; }
}
</code>```

And then I have the following class.

```<code>[Serializable]
public class InvoicesDueDates
{
    [XmlAttribute("idx")]
    public string Id { get; set; }
    [XmlElement("DUE")]
    public string DueDate { get; set; }
    [XmlElement("RATE")]
    public string Rate { get; set; }
}
</code>```

Is it somehow possible?

答:
If you only need to deserialize, you can use do so using XmlSerializer to the following types:

```<code>[XmlRoot(ElementName = "DUE")]
public class DueDTO
{
    [XmlAttribute(AttributeName = "idx")]
    public string Idx { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "RATE")]
public class RateDTO
{
    [XmlAttribute(AttributeName = "idx")]
    public string Idx { get; set; }
    [XmlText]
    public decimal Text { get; set; }
}

[XmlRoot(ElementName = "INVOICE")]
public partial class InvoicesDTO
{
    [XmlAttribute(AttributeName = "ID")]
    public string Id { get; set; }
    [XmlElement(ElementName = "STATUS")]
    public string Status { get; set; }
    [XmlElement(ElementName = "TOTAL")]
    public decimal Total { get; set; }

    [XmlElement(ElementName = "DUE")]
    public List<DueDTO> Due { get; set; }
    [XmlElement(ElementName = "RATE")]
    public List<RateDTO> Rate { get; set; }
}
</code>```

Then, to combine the Rate and Due list into a single InvoicesDueDates collection, you can use LINQ, e.g. as follows:

```<code>public partial class InvoicesDTO
{
    public InvoicesDueDates[] InvoicesDueDates
    {
        get
        {
            // To make suure we handle cases where only a Rate or Due item of a specific index is present,
            // perform left outer joins with all indices on both Rate and Due.
            // https://learn.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins
            var query = from i in Due.Select(d => d.Idx).Concat(Rate.Select(r => r.Idx)).Distinct()
                        join due in Due on i equals due.Idx into dueGroup
                        // Throw an exception if we have more than one due item for a given index
                        let due = dueGroup.SingleOrDefault()
                        join rate in Rate on i equals rate.Idx into rateGroup
                        // Throw an exception if we have more than one rate item for a given index
                        let rate = rateGroup.SingleOrDefault()
                        select new InvoicesDueDates { Id = i, DueDate = due == null ? null : due.Text, Rate = rate == null ? (decimal?)null : rate.Text };
            return query.ToArray();
        }
    }
}

public class InvoicesDueDates
{
    public string Id { get; set; }
    public string DueDate { get; set; }
    public decimal? Rate { get; set; }
}
</code>```

Notes:

This solution takes advantage of the fact that, when XmlSerializer is deserializing a List<T> property and encounters list elements interleaved with other elements, it will append each list element encountered to the growing list.

If you re-serialize an InvoicesDTO the result will look like:

```<code>  <INVOICE ID="5">
    <STATUS>S</STATUS>
    <TOTAL>3270.00</TOTAL>
    <DUE idx="1">30.11.17</DUE>
    <DUE idx="2">07.12.17</DUE>
    <DUE idx="3">14.12.17</DUE>
    <RATE idx="1">1090.00</RATE>
    <RATE idx="2">1090.00</RATE>
    <RATE idx="3">1090.00</RATE>
  </INVOICE>
</code>```

Notice that all the information has been retained and re-serialized but the <RATE> and <DUE> sequences have been separated out.

If you need to re-serialize with interleaved <RATE> and <DUE> elements, you will have to adopt a different strategy, such as the ones from serializing a list of KeyValuePair to XML or Xml Sequence deserialization with RestSharp.

I auto-generated the DTO classes using https://xmltocsharp.azurewebsites.net/ then modified them to fit my naming contentions.

Sample working .Net fiddle.

Title: XML values with same name to list

Body:
I have the following XML from which I need to map the "DUE" and "RATE" to a list of objects with XmlSerializer. There can be zero to many, and they're always coming as a pair with the same "idx".

<INVOICE ID="4">
    <STATUS>S</STATUS>
    <TOTAL>6230.00</TOTAL>
    <DUE idx="1">14.12.17</DUE>
    <RATE idx="1">6230.00</RATE>
</INVOICE >
<INVOICE ID="5">
    <STATUS>S</STATUS>
    <TOTAL>3270.00</TOTAL>
    <DUE idx="1">30.11.17</DUE>
    <RATE idx="1">1090.00</RATE>
    <DUE idx="2">07.12.17</DUE>
    <RATE idx="2">1090.00</RATE>
    <DUE idx="3">14.12.17</DUE>
    <RATE idx="3">1090.00</RATE>
</INVOICE>

I have the following setup which is working fine without a list of "Rate" and "Due":

[Serializable]
public class UserInvoicesDto
{
    [XmlElement("INVOICE")]
    public List<UserInvoiceDto> Invoices { get; set; }
}

[Serializable, XmlRoot("INVOICE")]
public class UserInvoiceDto
{
    [XmlAttribute("id")]
    public int InvoiceId { get; set; }
    [XmlElement("TOTAL")]
    public string Total { get; set; }
}

And then I have the following class.

[Serializable]
public class InvoicesDueDates
{
    [XmlAttribute("idx")]
    public string Id { get; set; }
    [XmlElement("DUE")]
    public string DueDate { get; set; }
    [XmlElement("RATE")]
    public string Rate { get; set; }
}

Is it somehow possible?

Body:
If you only need to deserialize, you can use do so using XmlSerializer to the following types:

[XmlRoot(ElementName = "DUE")]
public class DueDTO
{
    [XmlAttribute(AttributeName = "idx")]
    public string Idx { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "RATE")]
public class RateDTO
{
    [XmlAttribute(AttributeName = "idx")]
    public string Idx { get; set; }
    [XmlText]
    public decimal Text { get; set; }
}

[XmlRoot(ElementName = "INVOICE")]
public partial class InvoicesDTO
{
    [XmlAttribute(AttributeName = "ID")]
    public string Id { get; set; }
    [XmlElement(ElementName = "STATUS")]
    public string Status { get; set; }
    [XmlElement(ElementName = "TOTAL")]
    public decimal Total { get; set; }

    [XmlElement(ElementName = "DUE")]
    public List<DueDTO> Due { get; set; }
    [XmlElement(ElementName = "RATE")]
    public List<RateDTO> Rate { get; set; }
}

Then, to combine the Rate and Due list into a single InvoicesDueDates collection, you can use LINQ, e.g. as follows:

public partial class InvoicesDTO
{
    public InvoicesDueDates[] InvoicesDueDates
    {
        get
        {
            // To make suure we handle cases where only a Rate or Due item of a specific index is present,
            // perform left outer joins with all indices on both Rate and Due.
            // https://learn.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins
            var query = from i in Due.Select(d => d.Idx).Concat(Rate.Select(r => r.Idx)).Distinct()
                        join due in Due on i equals due.Idx into dueGroup
                        // Throw an exception if we have more than one due item for a given index
                        let due = dueGroup.SingleOrDefault()
                        join rate in Rate on i equals rate.Idx into rateGroup
                        // Throw an exception if we have more than one rate item for a given index
                        let rate = rateGroup.SingleOrDefault()
                        select new InvoicesDueDates { Id = i, DueDate = due == null ? null : due.Text, Rate = rate == null ? (decimal?)null : rate.Text };
            return query.ToArray();
        }
    }
}

public class InvoicesDueDates
{
    public string Id { get; set; }
    public string DueDate { get; set; }
    public decimal? Rate { get; set; }
}

Notes:

This solution takes advantage of the fact that, when XmlSerializer is deserializing a List<T> property and encounters list elements interleaved with other elements, it will append each list element encountered to the growing list.

If you re-serialize an InvoicesDTO the result will look like:

  <INVOICE ID="5">
    <STATUS>S</STATUS>
    <TOTAL>3270.00</TOTAL>
    <DUE idx="1">30.11.17</DUE>
    <DUE idx="2">07.12.17</DUE>
    <DUE idx="3">14.12.17</DUE>
    <RATE idx="1">1090.00</RATE>
    <RATE idx="2">1090.00</RATE>
    <RATE idx="3">1090.00</RATE>
  </INVOICE>

Notice that all the information has been retained and re-serialized but the <RATE> and <DUE> sequences have been separated out.

If you need to re-serialize with interleaved <RATE> and <DUE> elements, you will have to adopt a different strategy, such as the ones from serializing a list of KeyValuePair to XML or Xml Sequence deserialization with RestSharp.

I auto-generated the DTO classes using https://xmltocsharp.azurewebsites.net/ then modified them to fit my naming contentions.

Sample working .Net fiddle.


问:
SQL query to return top line manager by area

We are trying to populate our User table with the top manager of the Site (consider its like a department or cost centre) to help define an Owner of the Site.

EG:

in the example above, we would want to return employee "1002" to update "Owner" within all records where site = '123'

the difficulty we have is there are 90,000 employee records with a giant number of management structures within the Site.  It could be 1 level of management, it could be 5...

I am a novice when it comes to SQL, and I am baffled.  I'm not even sure it is possible.

Any suggestions?

答:
It looks like the definition of a Site owner would be someone who:

a) Is a line manager within the site, and

b) Doesn't have a different site manager within the same site

Translating this to SQL:

```<code>update employee a set Owner = (
    select EmployeeId from employee b where b.Site = a.Site
        and exists (select 1 from employee c where c.Site = b.Site and c.LineManager = b.EmployeeId)
        and not exists (select 1 from employee d where d.Site = b.Site and d.EmployeeId = b.EmployeeId and d.LineManager <> b.EmployeeId)
)
</code>```

Please see if this definition makes sense and run it by the business. I'm assuming there are no dupes by EmployeeID.

Body:
It looks like the definition of a Site owner would be someone who:

a) Is a line manager within the site, and

b) Doesn't have a different site manager within the same site

Translating this to SQL:

update employee a set Owner = (
    select EmployeeId from employee b where b.Site = a.Site
        and exists (select 1 from employee c where c.Site = b.Site and c.LineManager = b.EmployeeId)
        and not exists (select 1 from employee d where d.Site = b.Site and d.EmployeeId = b.EmployeeId and d.LineManager <> b.EmployeeId)
)

Please see if this definition makes sense and run it by the business. I'm assuming there are no dupes by EmployeeID.


问:
How to disable selection highlighting in a QTableWidget?
I have a QTableWidget with a disabled setSelectionMode (QTableWidget::NoSelection) and the QTableWidgetItems I fill in don't have the Qt::ItemIsEditable flag.

Nevertheless, a cell that has been clicked gets some kind of cursor (the black line at the bottom in my case):

How can I disable this "cursor"?

答:
The below solution worked for me:

```<code>tableWidget->setFocusPolicy(Qt::NoFocus);
</code>```

But the problem is that, you can not work with keyboard for going up and down on the QTableWidget.

So I think that solution is not good.

Body:
The below solution worked for me:

tableWidget->setFocusPolicy(Qt::NoFocus);

But the problem is that, you can not work with keyboard for going up and down on the QTableWidget.

So I think that solution is not good.


答:
See the below example code:

```<code>var values = [];
    values["key1"] = "value";
    values["key2"] = "value";
var result = [];
for (var key in values) {
    result = result.concat(values[key]);
}

alert(result);
</code>```

https://jsfiddle.net/afje1Lhb/

Title: Get only values from array (without key)

Body:
See the below example code:

var values = [];
    values["key1"] = "value";
    values["key2"] = "value";
var result = [];
for (var key in values) {
    result = result.concat(values[key]);
}

alert(result);

https://jsfiddle.net/afje1Lhb/


问:
How to send a value from one component to another?
I make a componenet in which I have one input field and button.On click of button I am diplaying the second component.I want to send data from one component to another component ?

how I will send data from one component to another ..I need to send input value (what ever user type in input field ) I need to show on next component or next page .On button click .how to send data ?
here is my plunker
http://plnkr.co/edit/IINX8Zq8J2LUTIyf4DYD?p=preview

```<code>import {Component,View} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    templateUrl: 'home/home.html'
})

export class AppComponent {
   toDoModel;
  constructor(private _router:Router) {

  }

  onclck(inputValue){
    alert(inputValue)
    this._router.navigate(['Second']);
  }

}
</code>```

答:
its always better to have a backend and a service calling backend to get data .
first you need to post the input data to service and get that data from some database through nodejs or database.
That would be the nicest way to get that based on some primary key of the data
atleast how enterprise apps work in reality</p>

Body:
I make a componenet in which I have one input field and button.On click of button I am diplaying the second component.I want to send data from one component to another component ?

how I will send data from one component to another ..I need to send input value (what ever user type in input field ) I need to show on next component or next page .On button click .how to send data ?
here is my plunker
http://plnkr.co/edit/IINX8Zq8J2LUTIyf4DYD?p=preview

import {Component,View} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    templateUrl: 'home/home.html'
})

export class AppComponent {
   toDoModel;
  constructor(private _router:Router) {

  }

  onclck(inputValue){
    alert(inputValue)
    this._router.navigate(['Second']);
  }

}


问:
Drupal:After installing boost module, images are not uploaded in files/imagecache
Title explains it pretty much. After installing Boost module, i have troubles with uploading images. I can upload them, but only thumbnails are saved. Big image in sites/default/files/imagecache is not created. I tried to play with permissions, but didnt work. I have no idea where the problem is. What did boost module change that images cant be uploaded?
What shall I do?

This is critical. I tried to uninstall the module, but the problem still persists.

答: Boost is not the issue here. If the module is uninstalled and you still have a problem then it's not Boost. To be 100% sure make sure to get rid of the htaccess rules. I have not idea why people like to blame boost but it does happen.</p>


问:
Reverse DNS-style string
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

```<code>example.org
</code>```

What would be a good way to reverse it, so that the string would read:

```<code>org.example
</code>```

A longer example:

```<code>www.example.org
</code>```

should reverse to:

```<code>org.example.www
</code>```

答:
You could use an iterative approach to build a reversed address:

Initialize the reversed result to empty string

While the string contains .

Extract the last segment chopping off everything from the start until a dot using parameter expansion ${var##*.}

Chop off the last segment with another parameter expansion ${var%.*}

Append to the reversed result the previously saved last segment

Here's one way to implement using pure Bash features:

```<code>rdns() {
    local s=$1
    local reversed last

    while [[ "$s" == *.* ]]; do
        last=${s##*.}
        s=${s%.*}
        reversed=$reversed$last.
    done

    reversed=$reversed$s

    echo "$reversed"
}

rdns example
rdns example.org
rdns www.example.org
</code>```

Outputs:

```<code>example
org.example
org.example.www
</code>```

Title: Reverse DNS-style string

Body:
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

example.org

What would be a good way to reverse it, so that the string would read:

org.example

A longer example:

www.example.org

should reverse to:

org.example.www

Body:
You could use an iterative approach to build a reversed address:

Initialize the reversed result to empty string

While the string contains .

Extract the last segment chopping off everything from the start until a dot using parameter expansion ${var##*.}

Chop off the last segment with another parameter expansion ${var%.*}

Append to the reversed result the previously saved last segment

Here's one way to implement using pure Bash features:

rdns() {
    local s=$1
    local reversed last

    while [[ "$s" == *.* ]]; do
        last=${s##*.}
        s=${s%.*}
        reversed=$reversed$last.
    done

    reversed=$reversed$s

    echo "$reversed"
}

rdns example
rdns example.org
rdns www.example.org

Outputs:

example
org.example
org.example.www


问:
Adding JTextField corrupts key bindings
I have a problem with the creation of my panel and setting properly key bindings. When I add JTextField to my JFrame, my key binding(s) do stop working. So, for example here is the SSCCE showing my problem - if you comment lines containing JTextField pressing p will work as desired. Why does this happen and how do I fix this?

```<code>import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Example{
    Example(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);

        JPanel panel = new JPanel(true);
        panel.setBackground(Color.BLACK);
        panel.setLayout(new FlowLayout());
        panel.setPreferredSize(new Dimension(500, 500));
        panel.setBorder(BorderFactory.createEmptyBorder());
        panel.setFocusable(true);
        frame.add(panel, BorderLayout.SOUTH);
        KeyboardInput keyboard = new KeyboardInput(panel);

        // adding JTextField corrupts key bindings
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(500, 100));
        textField.setFont(textField.getFont().deriveFont(15));
        textField.setText("text");
        textField.setEditable(false);
        textField.setFocusable(true);
        textField.setBorder(BorderFactory.createEmptyBorder());
        textField.setBackground(Color.BLACK);
        frame.add(textField, BorderLayout.NORTH);

        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String[] args){
        new Example();
    }
}

class KeyboardInput{
    KeyboardInput(JPanel panel){
        InputMap inMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        ActionMap actMap = panel.getActionMap();
        inMap.put(KeyStroke.getKeyStroke("P"), "pauseGame");
        actMap.put("pauseGame", new pauseAction());
    }

    class pauseAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("PAUSE");
        }
    }
}
</code>```

答:
Problem solved…

textField.setFocusable(true); should be changed to textField.setFocusable(false);

Title: Adding JTextField corrupts key bindings

Body:
I have a problem with the creation of my panel and setting properly key bindings. When I add JTextField to my JFrame, my key binding(s) do stop working. So, for example here is the SSCCE showing my problem - if you comment lines containing JTextField pressing p will work as desired. Why does this happen and how do I fix this?

import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

public class Example{
    Example(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);

        JPanel panel = new JPanel(true);
        panel.setBackground(Color.BLACK);
        panel.setLayout(new FlowLayout());
        panel.setPreferredSize(new Dimension(500, 500));
        panel.setBorder(BorderFactory.createEmptyBorder());
        panel.setFocusable(true);
        frame.add(panel, BorderLayout.SOUTH);
        KeyboardInput keyboard = new KeyboardInput(panel);

        // adding JTextField corrupts key bindings
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(500, 100));
        textField.setFont(textField.getFont().deriveFont(15));
        textField.setText("text");
        textField.setEditable(false);
        textField.setFocusable(true);
        textField.setBorder(BorderFactory.createEmptyBorder());
        textField.setBackground(Color.BLACK);
        frame.add(textField, BorderLayout.NORTH);

        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String[] args){
        new Example();
    }
}

class KeyboardInput{
    KeyboardInput(JPanel panel){
        InputMap inMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        ActionMap actMap = panel.getActionMap();
        inMap.put(KeyStroke.getKeyStroke("P"), "pauseGame");
        actMap.put("pauseGame", new pauseAction());
    }

    class pauseAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("PAUSE");
        }
    }
}


问:
A "catch-all" for SFINAE functions?
I am trying to make a typed compare function that do some customized comparison for different types.

```<code> #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}
</code>```

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

答:
Why?

In short, you use SFINAE incorrectly so both function templates are valid when you call typedCompare for doubles.

And how could I resolve this issue?

In this particular case, fix SFINAE to make it work correctly:

```<code>template <typename T>
typename std::enable_if<!std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}
</code>```

Please note, that this solution is not that good in terms of customization for many types. Another way is to use tag dispatching:

```<code>struct floating_point_tag {};
// other tags

template <typename T>
bool typedCompare(const T& lhs, const T& rhs, floating_point_tag) {
    return (lhs - rhs) < 1e-10;
}

// implementations for other tags

template <typename T>
bool typedCompare(const T& lhs, const T& rhs) {
    if (std::is_floating_point<T>::value) {
        return typedCompare(lhs, rhs, floating_point_tag{});
    }

    // other checks here

    return lhs == rhs;
}
</code>```

Finally, with C++17 you might make use of if constexpr:

```<code>template <typename T>
bool typedCompare(const T& lhs, const T& rhs) {
    if constexpr (std::is_floating_point<T>::value) {
        return (lhs - rhs) < 1e-10;
    } else { // add other if-else here
        return lhs == rhs;
    }
}
</code>```

Title: A "catch-all" for SFINAE functions?

Body:
I am trying to make a typed compare function that do some customized comparison for different types.

 #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

Body:
Why?

In short, you use SFINAE incorrectly so both function templates are valid when you call typedCompare for doubles.

And how could I resolve this issue?

In this particular case, fix SFINAE to make it work correctly:

template <typename T>
typename std::enable_if<!std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

Please note, that this solution is not that good in terms of customization for many types. Another way is to use tag dispatching:

struct floating_point_tag {};
// other tags

template <typename T>
bool typedCompare(const T& lhs, const T& rhs, floating_point_tag) {
    return (lhs - rhs) < 1e-10;
}

// implementations for other tags

template <typename T>
bool typedCompare(const T& lhs, const T& rhs) {
    if (std::is_floating_point<T>::value) {
        return typedCompare(lhs, rhs, floating_point_tag{});
    }

    // other checks here

    return lhs == rhs;
}

Finally, with C++17 you might make use of if constexpr:

template <typename T>
bool typedCompare(const T& lhs, const T& rhs) {
    if constexpr (std::is_floating_point<T>::value) {
        return (lhs - rhs) < 1e-10;
    } else { // add other if-else here
        return lhs == rhs;
    }
}


问:
Can we user razorpay plugin with reactnative and expo
In plugin they mentioned that the razorpay is not going to work with expo. i want to acces razorpay plugin in my react native app. is there any way..? i am using expo. please help me</p>

答:
if the react native library you want requires a linking step, then you can detach and use ExpoKit directly.

https://docs.expo.io/versions/latest/guides/detach.html


问:
How to discover the file that contains a CSS definition
I am dealing with a complex page with a lot of CSS files (that were not created by me). I am fighting with a CSS style that is not on the more obvious places (css files) that I can find and I don't have a clue where it is being define.

Is there any tool available that can tell me the file where a particular property of a class or id is being defined (having in mind that this property can be inherit from other definition)?

答: Chrome Devtools enables you to quickly do this.


问:
iPhone: starting an NSThread from a C++ object
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

```<code>NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];
</code>```

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!

答:
For a C++-style rephrasing of my previous answer:

```<code>//The C++ base
class ThreadBase
{
    virtual void Run() = 0;
};

//The ObjC wrapper

@interface ThreadStarter:NSObject
{
    ThreadBase *TheThread;
}

-(void)Run;
-(id)init:(ThreadBase)tb;
@end

@implementation ThreadStarter
-(id)init:(ThreadBase)tb
{
    TheThread = tb;
    return [super init];
}

-(void)Run
{
    TheThread->Run();
}
@end

//
class MyThread: public ThreadBase
{
    //...
};

//And finally usage

MyThread *Thread = new MyThread();
ThreadStarter *tc = [[ThreadStarter alloc]init:Thread];
NSThread* myThread = [[NSThread alloc] initWithTarget:tc selector:@selector(Run) object:nil];
[myThread start];
</code>```

Much cleaner this way, IMHO. If you're insist that the thread start routine is an arbitrary function in an atrbitrary class not of your creation, here's your answer:

```<code>class MyThread: public ThreadBase, public MyOtherObject
{
    void Run()
    {
        DoWork(); //Function defined in MyOtherObject
    }
}
</code>```

You see, if you want to parametrize by member function, you have to parametrize by both function and class. And class cannot be a run-time variable in C++.

Body:
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!

Body:
For a C++-style rephrasing of my previous answer:

//The C++ base
class ThreadBase
{
    virtual void Run() = 0;
};

//The ObjC wrapper

@interface ThreadStarter:NSObject
{
    ThreadBase *TheThread;
}

-(void)Run;
-(id)init:(ThreadBase)tb;
@end

@implementation ThreadStarter
-(id)init:(ThreadBase)tb
{
    TheThread = tb;
    return [super init];
}

-(void)Run
{
    TheThread->Run();
}
@end

//
class MyThread: public ThreadBase
{
    //...
};

//And finally usage

MyThread *Thread = new MyThread();
ThreadStarter *tc = [[ThreadStarter alloc]init:Thread];
NSThread* myThread = [[NSThread alloc] initWithTarget:tc selector:@selector(Run) object:nil];
[myThread start];

Much cleaner this way, IMHO. If you're insist that the thread start routine is an arbitrary function in an atrbitrary class not of your creation, here's your answer:

class MyThread: public ThreadBase, public MyOtherObject
{
    void Run()
    {
        DoWork(); //Function defined in MyOtherObject
    }
}

You see, if you want to parametrize by member function, you have to parametrize by both function and class. And class cannot be a run-time variable in C++.


问:
How to get the name of the api gateway invoking aws lambda using java
I'm trying to retrieve apigateway name in my Lambda code. I'v referred the following document on AWS http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html.

I understand that we can retrieve the API ID using the context variable. However I'm interested in retrieving the actual name of the API which was created. Is there any way of getting it?

Thanks in advance.

答:
To my knowledge, you can't get the API Gateway name directly, but you can get the API Gateway Id.

Both an event and context are passed in. In the event, there is a key called "requestContext". Inside the request context is the "apiId" key.

You could then use the API key id to look up the name if needed.


问:
VB6 Access update query not updating table
I am trying to add a number sequentially to a field for a job number in a do loop. My code is not breaking but it is not adding the records to the table. The code is written in a function that is being called when the access form button is pressed to update the records. Below is my code:

```<code>Dim NumofBatches As Integer
    NumofBatches = [Batches]
    Dim startnum As Integer
    startnum = 1
    Dim jobnum As String
    jobnum = [JobNumber]

    Do While startnum <= NumofBatches
        Dim mynumString As String
        mynumString = startnum
        DoCmd.RunSQL "INSERT INTO Production (CardCode,JobItemNo,JobIndex,DrawingRef,DRDescription,[CreationDate],Quantity,FinishDate,LastLocation,DateLastMoved) VALUES ('" & jobnum & mynumString & "', ItemNumber, JobNumber, DrawingRef, DRDescription, [CreationDate], Quantity, FinishDate, LastLocation, DateLastMoved)"
        startnum = startnum + 1
    Loop
</code>```

I realize I will have duplicated rows of fields except for the cardcode field which is what I am trying to achieve. The cardcode fields should be sequential in each row for the jobnumber. An example, 100011, 100012, where 10001 is the job number and it is adding 1, 2, etc. sequentially.

答:
You have a couple of problems. The first is in the field list in the INSERT part of your SQL statement. Unless you have a column in your Production table named "CardCode + mynumString" (and if you did it would have to have square brackets around it because it has a space and a symbol in it) it's not going to work. Inside the parentheses after INSERT INTO <TableName> you have to list column names from the table you are inserting into. Fix your target column names first.

Next you have a SELECT statement as the source of values you're inserting. Unless the values you need are found in a table, you should probably use a VALUES list:

```<code>INSERT INTO <TableName> (Col1, Col2, ...) VALUES (Val1, Val2, ...)
</code>```

The final issue is that you have to concatenate your variables into the SQL string. I'm going to assume that [Text90] is a control with your CardCode value in it and you're wanting to concatenate it with mynumString. That would look something like this:

```<code>DoCmd.RunSQL "INSERT INTO Production (Col1, Col2, ...) VALUES ('" & [Text90] & mynumString & "', Val2, ...)"
</code>```

Note that you have to resolve your value outside of the quoted SQL string and concatenate that value into the string and set all of that off with single-tick quotes inside the SQL string.

I find it handy to build dynamic SQL strings like this using a variable and then execute it as:

```<code>DoCmd.RunSQL mySQLVariable
</code>```

Having the SQL string in a variable makes it a little easier to spot errors in the concatenation if you inspect the variable during debugging or if you just dump the value to the immediate window with Debug.Print.

Body:
I am trying to add a number sequentially to a field for a job number in a do loop. My code is not breaking but it is not adding the records to the table. The code is written in a function that is being called when the access form button is pressed to update the records. Below is my code:

Dim NumofBatches As Integer
    NumofBatches = [Batches]
    Dim startnum As Integer
    startnum = 1
    Dim jobnum As String
    jobnum = [JobNumber]

    Do While startnum <= NumofBatches
        Dim mynumString As String
        mynumString = startnum
        DoCmd.RunSQL "INSERT INTO Production (CardCode,JobItemNo,JobIndex,DrawingRef,DRDescription,[CreationDate],Quantity,FinishDate,LastLocation,DateLastMoved) VALUES ('" & jobnum & mynumString & "', ItemNumber, JobNumber, DrawingRef, DRDescription, [CreationDate], Quantity, FinishDate, LastLocation, DateLastMoved)"
        startnum = startnum + 1
    Loop

I realize I will have duplicated rows of fields except for the cardcode field which is what I am trying to achieve. The cardcode fields should be sequential in each row for the jobnumber. An example, 100011, 100012, where 10001 is the job number and it is adding 1, 2, etc. sequentially.

Body:
You have a couple of problems. The first is in the field list in the INSERT part of your SQL statement. Unless you have a column in your Production table named "CardCode + mynumString" (and if you did it would have to have square brackets around it because it has a space and a symbol in it) it's not going to work. Inside the parentheses after INSERT INTO <TableName> you have to list column names from the table you are inserting into. Fix your target column names first.

Next you have a SELECT statement as the source of values you're inserting. Unless the values you need are found in a table, you should probably use a VALUES list:

INSERT INTO <TableName> (Col1, Col2, ...) VALUES (Val1, Val2, ...)

The final issue is that you have to concatenate your variables into the SQL string. I'm going to assume that [Text90] is a control with your CardCode value in it and you're wanting to concatenate it with mynumString. That would look something like this:

DoCmd.RunSQL "INSERT INTO Production (Col1, Col2, ...) VALUES ('" & [Text90] & mynumString & "', Val2, ...)"

Note that you have to resolve your value outside of the quoted SQL string and concatenate that value into the string and set all of that off with single-tick quotes inside the SQL string.

I find it handy to build dynamic SQL strings like this using a variable and then execute it as:

DoCmd.RunSQL mySQLVariable

Having the SQL string in a variable makes it a little easier to spot errors in the concatenation if you inspect the variable during debugging or if you just dump the value to the immediate window with Debug.Print.


问:
Git / SourceTree - remote invalid username or password
I've just reinstalled SourceTree on my new computer and I'm having trouble when trying to push my commits.

If I use the built-in Push button from SourceTree, it brings up a dialog where I enter my username and password but then I get an error: remote invalid username or password.

The strangest thing is that if I bring the Git console by clicking on the Console button in SourceTree, type git push then enter the exact same credentials, it works...

I'm assuming SourceTree might be overriding some Git config somehow but I can't find a solution.

I tried deleting all credentials saved by SourceTree, I disallowed SourceTree to modify my Git config in the Tools > General menu but it didn't change anything...

Thanks for your help!

答: SourceTree -> Preference --> accounts you can delete and add your account again and then try SourceTree -> Preference set Protocol = HTTPS</p>