问:
ProC complains about undefined symbols on Linux (CentOS 7.3)
TLDR: Running ProC from Oracle instant client 12.2 on CentOS 7.3 doesn't seem to be able to properly process even a trivial input file.

Minimal input file demonstrating the problem:

```<code>EXEC SQL BEGIN DECLARE SECTION;
     EXEC SQL INCLUDE oci.h;
EXEC SQL END DECLARE SECTION;
</code>```

The real files obviously include my own project's header, but ultimately they pull in oci.h, which is one of the instant client SDK headers and this seems to be where the build issues are coming from.

Invocation of ProC:

The following script demonstrates the problem (again, a cut-down version of the real situation):

```<code>#!/bin/sh

export ORACLE_HOME=/some/path/instantclient_12_2
export ORACLE_SID=SomeSID
export PATH=/various/paths:${ORACLE_HOME}:${ORACLE_HOME}/sdk:${ORACLE_HOME}/bin:/some/more/paths/like:usr/bin:
export LD_LIBRARY_PATH=${ORACLE_HOME}:${ORACLE_HOME}/lib32:${ORACLE_HOME}/lib

${ORACLE_HOME}/sdk/proc \
  LTYPE=LONG \
  PARSE=PARTIAL \
  MODE=ORACLE \
  CODE=ANSI_C \
  iname=foo.pc
</code>```

Oracle configuration:

The contents of my pcscfg.cfg file look like this:

```<code>sys_include=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
sys_include=/usr/include
include=/some/path/instantclient_12_2/sdk/include
</code>```

I've also tried various reordering, switching include and sys_include, but all seem to give the same behaviour. Adding define=__x86_64__ as seen in various online references makes no difference. I've chosen to expand out the $ORACLE_PATH in the above to make the example clearer.

Sample error output:

Using the input file defined above results in output with errors like the following (truncated to help focus the discussion):

```<code>Pro*C/C++: Release 12.2.0.1.0 - Production on Mon Sep 4 16:19:45 2017

Copyright (c) 1982, 2017, Oracle and/or its affiliates.  All rights reserved.

System default option values taken from: /some/path/instantclient_12_2/precomp/admin/pcscfg.cfg

Syntax error at line 46, column 1, file /usr/include/bits/byteswap-16.h:
Error at line 46, column 1 in file /usr/include/bits/byteswap-16.h
{
1
PCC-S-02201, Encountered the symbol "{" when expecting one of the following:

   ; , = ( [
</code>```

The contents around the line it is complaining about look like this:

```<code>static __inline unsigned short int
__bswap_16 (unsigned short int __bsx)
{                                       // <---- this is line 46
  return __bswap_constant_16 (__bsx);
}
</code>```

If I insert #include <stdlib.h> before the EXEC SQL BEGIN DECLARE SECTION line, the error message changes to this:

```<code>Syntax error at line 265, column 50, file /some/path/instantclient_12_2/sdk/include/ociextp.h:
Error at line 265, column 50 in file /some/path/instantclient_12_2/sdk/include/ociextp.h
void  *ociepacm(OCIExtProcContext *with_context, size_t amount);
.................................................1
PCC-S-02201, Encountered the symbol "size_t" when expecting one of the following
:

   ... auto, char, const, double, enum, float, int, long,
   ulong_varchar, OCIBFileLocator OCIBlobLocator,
   OCIClobLocator, OCIDateTime, OCIExtProcContext, OCIInterval,
   OCIRowid, OCIDate, OCINumber, OCIRaw, OCIString, register,
   short, signed, sql_context, sql_cursor, static, struct,
   union, unsigned, utext, uvarchar, varchar, void, volatile,
   a typedef name, exec oracle, exec oracle begin, exec,
   exec sql, exec sql begin, exec sql type, exec sql var,
The symbol "enum," was substituted for "size_t" to continue.
</code>```

This one is more interesting because I've traced through the logic more carefully and even forcing size_t to be defined by various means, I still get the above error. But if I change the ProC invocation to use PARSE=FULL, it is successful. Unfortunately, that causes other problems with the real code and those problems have a similar nature to this one (i.e. chokes on compiler headers for things that should really have been defined by the compiler headers).

Further comments:

Looking at various solutions online, these issues are normally the result of having incorrectly set include search paths, but I've verified from the output listing that the correct headers are indeed being found. It is as though there are some compiler defines missing that GCC would normally provide but ProC isn't providing. There have been various other related examples which support this theory, giving errors on things like __INT_LEAST8_TYPE__ being unknown (which as far as I can tell GCC defines internally rather than explicitly in any of its headers).

Specific question:

ProC doesn't seem to be processing the system compiler headers correctly. Any idea why or even further things to try to help diagnose the underlying cause?

答:
I have been able to get my application to compile correctly, I found that even though some compile problems were resolved by adding the output of the command "gcc -dM -E - < /dev/null" into a header file and including it in every Pro*C source file, new compile problems were introduced because of that and trying to resolve those new problems again introduced others so that approach was going nowhere.

In the end I started again from scratch and only included those #defines that were realy needed by the proc compiler. Also, I had to re-arrange the paths in the proc configuration file ${ORACLE_HOME}/precomp/admin/pcscfg.cfg

This is what it looks like now:

```<code>sys_include=$ORACLE_HOME/precomp/public
sys_include=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
sys_include=/usr/local/include
sys_include=/usr/include
sys_include=/usr/include/linux
ltype=short
define=__x86_64__
</code>```

the reason for this is that there are several files located in the gcc include directory that are also present in some of the other directories, but those assume that all of those gcc internal defines are set as well. The system include files located in the gcc include directory sometimes differ significantly from the ones in the usual include directories that are listed below it and it would seem that proc has a lot less difficulties in parsing the ones located in the gcc 4.8.5 directory.

Next to this, the include file I created and #include into every source file proc choked on now looks this:

```<code>#ifndef __GCC4_INTERNAL_DEFINES_H__
#define __GCC4_INTERNAL_DEFINES_H__

/* Proceed only when using the Oracle Pro*C compiler on RHEL7 */
#ifdef DB_PRE_COMP
#ifdef OS_IS_RHEL7

/* These are some of the defines that gcc4 sets by itself. The Pro*C precompiler
   does not know them and they are needed in order to correctly parse several
   system header files. Full list of gcc4 internal defines may be obtained with
   the following command: gcc -dM -E - < /dev/null */
#define __INT_LEAST8_TYPE__ signed char
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_TYPE__ long int
#define __UINT_LEAST8_TYPE__ unsigned char
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_TYPE__ long int
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_TYPE__ long unsigned int
#define __INTMAX_TYPE__ long int
#define __UINTMAX_TYPE__ long unsigned int

#include </usr/include/stdint.h>

#endif /* OS_IS_RHEL7 */
#endif /* DB_PRE_COMP */

#endif /* __GCC4_INTERNAL_DEFINES_H__ */
</code>```

Much to my relief, I got everything to compile again with these updates. For completeness sake, proc is executed with the parse=full option, this is what I used to do under RHEL6 as well and what my application apparently needs; as part of my efforts to get it to compile I tried with partial option as well but that did not make a difference, it still choked.

Body:
TLDR: Running ProC from Oracle instant client 12.2 on CentOS 7.3 doesn't seem to be able to properly process even a trivial input file.

Minimal input file demonstrating the problem:

EXEC SQL BEGIN DECLARE SECTION;
     EXEC SQL INCLUDE oci.h;
EXEC SQL END DECLARE SECTION;

The real files obviously include my own project's header, but ultimately they pull in oci.h, which is one of the instant client SDK headers and this seems to be where the build issues are coming from.

Invocation of ProC:

The following script demonstrates the problem (again, a cut-down version of the real situation):

#!/bin/sh

export ORACLE_HOME=/some/path/instantclient_12_2
export ORACLE_SID=SomeSID
export PATH=/various/paths:${ORACLE_HOME}:${ORACLE_HOME}/sdk:${ORACLE_HOME}/bin:/some/more/paths/like:usr/bin:
export LD_LIBRARY_PATH=${ORACLE_HOME}:${ORACLE_HOME}/lib32:${ORACLE_HOME}/lib

${ORACLE_HOME}/sdk/proc \
  LTYPE=LONG \
  PARSE=PARTIAL \
  MODE=ORACLE \
  CODE=ANSI_C \
  iname=foo.pc

Oracle configuration:

The contents of my pcscfg.cfg file look like this:

sys_include=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
sys_include=/usr/include
include=/some/path/instantclient_12_2/sdk/include

I've also tried various reordering, switching include and sys_include, but all seem to give the same behaviour. Adding define=__x86_64__ as seen in various online references makes no difference. I've chosen to expand out the $ORACLE_PATH in the above to make the example clearer.

Sample error output:

Using the input file defined above results in output with errors like the following (truncated to help focus the discussion):

Pro*C/C++: Release 12.2.0.1.0 - Production on Mon Sep 4 16:19:45 2017

Copyright (c) 1982, 2017, Oracle and/or its affiliates.  All rights reserved.

System default option values taken from: /some/path/instantclient_12_2/precomp/admin/pcscfg.cfg

Syntax error at line 46, column 1, file /usr/include/bits/byteswap-16.h:
Error at line 46, column 1 in file /usr/include/bits/byteswap-16.h
{
1
PCC-S-02201, Encountered the symbol "{" when expecting one of the following:

   ; , = ( [

The contents around the line it is complaining about look like this:

static __inline unsigned short int
__bswap_16 (unsigned short int __bsx)
{                                       // <---- this is line 46
  return __bswap_constant_16 (__bsx);
}

If I insert #include <stdlib.h> before the EXEC SQL BEGIN DECLARE SECTION line, the error message changes to this:

Syntax error at line 265, column 50, file /some/path/instantclient_12_2/sdk/include/ociextp.h:
Error at line 265, column 50 in file /some/path/instantclient_12_2/sdk/include/ociextp.h
void  *ociepacm(OCIExtProcContext *with_context, size_t amount);
.................................................1
PCC-S-02201, Encountered the symbol "size_t" when expecting one of the following
:

   ... auto, char, const, double, enum, float, int, long,
   ulong_varchar, OCIBFileLocator OCIBlobLocator,
   OCIClobLocator, OCIDateTime, OCIExtProcContext, OCIInterval,
   OCIRowid, OCIDate, OCINumber, OCIRaw, OCIString, register,
   short, signed, sql_context, sql_cursor, static, struct,
   union, unsigned, utext, uvarchar, varchar, void, volatile,
   a typedef name, exec oracle, exec oracle begin, exec,
   exec sql, exec sql begin, exec sql type, exec sql var,
The symbol "enum," was substituted for "size_t" to continue.

This one is more interesting because I've traced through the logic more carefully and even forcing size_t to be defined by various means, I still get the above error. But if I change the ProC invocation to use PARSE=FULL, it is successful. Unfortunately, that causes other problems with the real code and those problems have a similar nature to this one (i.e. chokes on compiler headers for things that should really have been defined by the compiler headers).

Further comments:

Looking at various solutions online, these issues are normally the result of having incorrectly set include search paths, but I've verified from the output listing that the correct headers are indeed being found. It is as though there are some compiler defines missing that GCC would normally provide but ProC isn't providing. There have been various other related examples which support this theory, giving errors on things like __INT_LEAST8_TYPE__ being unknown (which as far as I can tell GCC defines internally rather than explicitly in any of its headers).

Specific question:

ProC doesn't seem to be processing the system compiler headers correctly. Any idea why or even further things to try to help diagnose the underlying cause?

Body:
I have been able to get my application to compile correctly, I found that even though some compile problems were resolved by adding the output of the command "gcc -dM -E - < /dev/null" into a header file and including it in every Pro*C source file, new compile problems were introduced because of that and trying to resolve those new problems again introduced others so that approach was going nowhere.

In the end I started again from scratch and only included those #defines that were realy needed by the proc compiler. Also, I had to re-arrange the paths in the proc configuration file ${ORACLE_HOME}/precomp/admin/pcscfg.cfg

This is what it looks like now:

sys_include=$ORACLE_HOME/precomp/public
sys_include=/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
sys_include=/usr/local/include
sys_include=/usr/include
sys_include=/usr/include/linux
ltype=short
define=__x86_64__

the reason for this is that there are several files located in the gcc include directory that are also present in some of the other directories, but those assume that all of those gcc internal defines are set as well. The system include files located in the gcc include directory sometimes differ significantly from the ones in the usual include directories that are listed below it and it would seem that proc has a lot less difficulties in parsing the ones located in the gcc 4.8.5 directory.

Next to this, the include file I created and #include into every source file proc choked on now looks this:

#ifndef __GCC4_INTERNAL_DEFINES_H__
#define __GCC4_INTERNAL_DEFINES_H__

/* Proceed only when using the Oracle Pro*C compiler on RHEL7 */
#ifdef DB_PRE_COMP
#ifdef OS_IS_RHEL7

/* These are some of the defines that gcc4 sets by itself. The Pro*C precompiler
   does not know them and they are needed in order to correctly parse several
   system header files. Full list of gcc4 internal defines may be obtained with
   the following command: gcc -dM -E - < /dev/null */
#define __INT_LEAST8_TYPE__ signed char
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_TYPE__ long int
#define __UINT_LEAST8_TYPE__ unsigned char
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_TYPE__ long int
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_TYPE__ long unsigned int
#define __INTMAX_TYPE__ long int
#define __UINTMAX_TYPE__ long unsigned int

#include </usr/include/stdint.h>

#endif /* OS_IS_RHEL7 */
#endif /* DB_PRE_COMP */

#endif /* __GCC4_INTERNAL_DEFINES_H__ */

Much to my relief, I got everything to compile again with these updates. For completeness sake, proc is executed with the parse=full option, this is what I used to do under RHEL6 as well and what my application apparently needs; as part of my efforts to get it to compile I tried with partial option as well but that did not make a difference, it still choked.


来源: stackexchange

问:
NPE injecting Singleton bean into a Singleton bean
I'm having a weird problem where I get a NullPointerException when injecting a singleton bean (class B) into another singleton bean (class A) where both beans are using EJB 3.1 annotations. The NPE occurs because the map is null when accessing from class A even though class B was injected.
eg:

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

@Singleton
@Startup
public class A {
    @Inject
    B b;

    @PostConstruct
    public void initialise() {
        b.map.put("test", 1);
        System.out.println("A initialised");
    }
}
```

<pre class="lang-java prettyprint-override"><code>import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import java.util.HashMap;

@Singleton
public class B {
    HashMap<String, Integer> map;

    @PostConstruct
    public void initialise() {
        map = new HashMap<>();
        System.out.println("B initialised");
    }
}
</code>```

However, if I use the CDI singleton annotation for class B, the code executes as expected:

```<code>import javax.annotation.PostConstruct;
import javax.inject.Singleton;
import java.util.HashMap;

@Singleton
public class B {
    HashMap<String, Integer> map;

    @PostConstruct
    public void initialise() {
        map = new HashMap<>();
        System.out.println("B initialised");
    }
}
</code>```

Is there a reason why the EJB annotation is not working in this situation?

答:
An important fact that many fail to realise is that an EJB client only sees a "view" of the public methods of an EJB where ever it is injected.

You are attempting to access one of it's instance variables directly:

```<code>    b.map.put("test", 1);
</code>```

If you add a delegate method to EJB B:

```<code>public Integer put(String key, Integer value) {
    return map.put(key, value);
}
</code>```

and invoke it:

```<code>@PostConstruct
public void initialise() {
    b.put("test", 1);
    System.out.println("A initialised");
}
</code>```

then you will get

20:18:16,823 INFO  [stdout] (ServerService Thread Pool -- 70) B initialised

  20:18:16,824 INFO  [stdout] (ServerService Thread Pool -- 70) A initialised

as expected.

See §3 of the EJB specification for more information. Here you will find the statement:

The container provides security, concurrency, transactions, swapping to secondary storage, and other services for the session object transparently to the client.

If you were to successfully access the instance variable directly then you would bypass all of this.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a weird problem where I get a NullPointerException when injecting a singleton bean (class B) into another singleton bean (class A) where both beans are using EJB 3.1 annotations. The NPE occurs because the map is null when accessing from class A even though class B was injected.
eg:

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

@Singleton
@Startup
public class A {
    @Inject
    B b;

    @PostConstruct
    public void initialise() {
        b.map.put("test", 1);
        System.out.println("A initialised");
    }
}

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import java.util.HashMap;

@Singleton
public class B {
    HashMap<String, Integer> map;

    @PostConstruct
    public void initialise() {
        map = new HashMap<>();
        System.out.println("B initialised");
    }
}

However, if I use the CDI singleton annotation for class B, the code executes as expected:

import javax.annotation.PostConstruct;
import javax.inject.Singleton;
import java.util.HashMap;

@Singleton
public class B {
    HashMap<String, Integer> map;

    @PostConstruct
    public void initialise() {
        map = new HashMap<>();
        System.out.println("B initialised");
    }
}

Is there a reason why the EJB annotation is not working in this situation?

Body:
An important fact that many fail to realise is that an EJB client only sees a "view" of the public methods of an EJB where ever it is injected.

You are attempting to access one of it's instance variables directly:

    b.map.put("test", 1);

If you add a delegate method to EJB B:

public Integer put(String key, Integer value) {
    return map.put(key, value);
}

and invoke it:

@PostConstruct
public void initialise() {
    b.put("test", 1);
    System.out.println("A initialised");
}

then you will get

20:18:16,823 INFO  [stdout] (ServerService Thread Pool -- 70) B initialised

  20:18:16,824 INFO  [stdout] (ServerService Thread Pool -- 70) A initialised

as expected.

See §3 of the EJB specification for more information. Here you will find the statement:

The container provides security, concurrency, transactions, swapping to secondary storage, and other services for the session object transparently to the client.

If you were to successfully access the instance variable directly then you would bypass all of this.


问:
What can WebMatrix do that Visual Studio 2010 Ultimate SP1 beta as an IDE can't?
I am seeing a lot of blog posts lately about WebMatrix. I don't read them because I tell myself "I have Visual Studio 2010 Ultimate with SP1 beta". The king of IDE's.

Just in case I am not missing on something important, as an IDE, is there anything that WebMatrix can do that VS 2010 can't do or does better?

答:
If you have been using VS 2010 or even VWD 2010 and haven't been confused by them so far, you are not missing out on anything. WebMatrix is not intended for you. It has been designed to attract beginner developers, or those who know a little PHP or perhaps classic ASP and would like to try out ASP.NET.

It is primarily designed to make developing Razor Web Pages sites easy, with no clutter. No code complete, no Intellisense (well... except for the wrong kind of HTML Intellisense), no debugging, no compilation required (or possible), no wizards. Bare bones. Knuckle deep in HTML tags and inline code...

Actually, if you are anything like me, you are missing out on a lot of fun ;o)

ContentLicense: CC BY-SA 2.5


问:
Using pip in CMD and getting a syntax error
I haven't done much with modules before and I am trying to install PIL (python 2.7)- using pip - and this shows up.

Is this my error, and how can I fix this?

答:
Two things.

First of all, m3-pil hasn't been updated in three years and contains security vulnerabilities. https://pypi.python.org/pypi/m3-PIL/1.1.7

Instead, please use Pillow, the maintained fork of PIL.
https://pillow.readthedocs.io/

Secondly, as Soon comments, it looks like you're using pip for Python 3. To install with Python 2 on Windows:

```<code>python2 -m pip install pillow
</code>```

Body:
Two things.

First of all, m3-pil hasn't been updated in three years and contains security vulnerabilities. https://pypi.python.org/pypi/m3-PIL/1.1.7

Instead, please use Pillow, the maintained fork of PIL.
https://pillow.readthedocs.io/

Secondly, as Soon comments, it looks like you're using pip for Python 3. To install with Python 2 on Windows:

python2 -m pip install pillow


问:
How to upload a file using Ajax in Scalajs
I'm learning Scalajs by building an image sharing webapp.
In a form, I have a classic file input tag and would like to upload it using Ajax and jQuery to a remote server through a HTTP Post request.

This is the html:

```<code><input id="postTitle" class="form-control" placeholder="Title" type="text" aria-describedby="basic-addon1">

<input id="file" class="form-control" placeholder="Browse" type="file" aria-describedby="basic-addon1">

<input id="tags" class="form-control" placeholder="Tags in format ['tag 1', 'tag 2',...]" type="text">

<button id="postButton" class="btn btn-success">Submit</button>
</code>```

And here is the underlying Scala code:

```<code>lazy val submitElement = jQuery("#postButton")
jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
            dom.ext.Ajax.post(
          url = [server_url],
          data = ???, // <-- How do I get the file?
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})
</code>```

Any help would be greatly appreciated

答:
Refer Scalajs Showcase Ajax example for performing post methods in scalajs.

Extending the above example, you can write postAsFormData method and pass the uploaded file as a formData.

```<code>def postAsFormData(url: String,
     data: FormData,
     timeout: Int = 0,
     headers: Map[String, String] = Map.empty,
     withCredentials: Boolean = false) = {
        ajax.post( url, InputData.formdata2ajax(data), timeout,headers, withCredentials, "")
    }
</code>```

Pass the file input as

```<code>val formData= new FormData()
formData.append("file",$("#fileInput").prop("files").item(0))
</code>```

And then call the ajax postAsFormData method.

Body:
I'm learning Scalajs by building an image sharing webapp.
In a form, I have a classic file input tag and would like to upload it using Ajax and jQuery to a remote server through a HTTP Post request.

This is the html:

<input id="postTitle" class="form-control" placeholder="Title" type="text" aria-describedby="basic-addon1">

<input id="file" class="form-control" placeholder="Browse" type="file" aria-describedby="basic-addon1">

<input id="tags" class="form-control" placeholder="Tags in format ['tag 1', 'tag 2',...]" type="text">

<button id="postButton" class="btn btn-success">Submit</button>

And here is the underlying Scala code:

lazy val submitElement = jQuery("#postButton")
jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
            dom.ext.Ajax.post(
          url = [server_url],
          data = ???, // <-- How do I get the file?
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})

Any help would be greatly appreciated

Body:
Refer Scalajs Showcase Ajax example for performing post methods in scalajs.

Extending the above example, you can write postAsFormData method and pass the uploaded file as a formData.

def postAsFormData(url: String,
     data: FormData,
     timeout: Int = 0,
     headers: Map[String, String] = Map.empty,
     withCredentials: Boolean = false) = {
        ajax.post( url, InputData.formdata2ajax(data), timeout,headers, withCredentials, "")
    }

Pass the file input as

val formData= new FormData()
formData.append("file",$("#fileInput").prop("files").item(0))

And then call the ajax postAsFormData method.


问:
Selecting meta tags with Selenium
I want to extract data from a meta tag but the tag is as follows

```<code><meta property="og:description" content="blah"/>
</code>```

Since there is no id/class/etc. I can't use

```<code>driver.FindElement(By.[id/class/etc.]);
</code>```

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

答:
You can use xPath to grab the specified meta tag</p>

```<code>driver.FindElement(By.XPath("//meta[@property='og:description']"));
</code>```

Title: Selecting meta tags with Selenium

Body:
I want to extract data from a meta tag but the tag is as follows

<meta property="og:description" content="blah"/>

Since there is no id/class/etc. I can't use

driver.FindElement(By.[id/class/etc.]);

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

Body:
You can use xPath to grab the specified meta tag

driver.FindElement(By.XPath("//meta[@property='og:description']"));


问:
Resize image to one resolution
I have a bunch of images, with different resolution.
Also there is a mix of landscape and portrait pictures. I need to resize the images to one resolution (1024x768). If i have a portrait picture, the max height needs to be 768, and my landscape pictures has to have a max width of 1024.

The space that is over, has to be made black.
Right now i use mogrify -resize 1024x768 -verbose *.jpg

I know i can use 1024x!768 , but like i said i'm using different kind of pictures.
My exif information also doesn't contains information about if a picture is landscape or not.

答: I use ImageMagick for such tasks. When installed, you have the "convert" command, which is very common, and does your task easyly. </p>

Title: Resize image to one resolution


问:
Using PyMongo with Public SSL Key
I'm trying out the hosted MongodDB+ beta from Compose.io, which supports SSL connections. It provides a public SSL key, and to connect from the command line you use the following arguments:

```<code>$ mongo -ssl -sslCAFile example.pem example.dblayer.com:10373/admin -u user -p pass
</code>```

I need to access my DB from a Python script using PyMongo, but I'm not sure how to translate the above syntax to MongoClient connection arguments; I'm only familiar with connecting without SSL, i.e.

```<code>client = MongoClient('mongodb://<user>:<pass>@example.dblayer.com:10373/admin')
</code>```

答:
This should work for you.</p>

```<code>import os
import ssl
from pymongo import MongoClient

mongoDB_uri = 'mongodb://%s:%s@%s/%s' % ("user_name", "password",
"host_name", "db_name")

client = MongoClient(mongoDB_uri,
        ssl=True,
        ssl_cert_reqs=ssl.CERT_REQUIRED,
        ssl_ca_certs="/path/to/cert.pem")

db_conn = client["db_name"]
print(db_conn.collection_name.find_one())
</code>```

Title: Using PyMongo with Public SSL Key

Body:
I'm trying out the hosted MongodDB+ beta from Compose.io, which supports SSL connections. It provides a public SSL key, and to connect from the command line you use the following arguments:

$ mongo -ssl -sslCAFile example.pem example.dblayer.com:10373/admin -u user -p pass

I need to access my DB from a Python script using PyMongo, but I'm not sure how to translate the above syntax to MongoClient connection arguments; I'm only familiar with connecting without SSL, i.e.

client = MongoClient('mongodb://<user>:<pass>@example.dblayer.com:10373/admin')

Body:
This should work for you.

import os
import ssl
from pymongo import MongoClient

mongoDB_uri = 'mongodb://%s:%s@%s/%s' % ("user_name", "password",
"host_name", "db_name")

client = MongoClient(mongoDB_uri,
        ssl=True,
        ssl_cert_reqs=ssl.CERT_REQUIRED,
        ssl_ca_certs="/path/to/cert.pem")

db_conn = client["db_name"]
print(db_conn.collection_name.find_one())


问:
How to run (not only install) an android application using .apk file?
Is there any command on cmd.exe that would allow me to start the main activity of a particular android application using the .apk file of that application. Please note that I know this command which only installs an android application:

```<code>adb install myapp.apk
</code>```

This command will only install myapp onto the emulator and I have to manually run this application from the emulator (by performing single click on its icon).

What I want to do is use a command which not only installs the application but also starts its main activity (please note that I have only its .apk file so I don't know what the package name or any activity name is).

答:
This is a solution in shell script:

```<code>apk="$apk_path"
</code>```

1. Install apk

```<code>adb install "$apk"
sleep 1
</code>```

2. Get package name

```<code>pkg_info=`aapt dump badging "$apk" | head -1 | awk -F " " '{print $2}'`
eval $pkg_info > /dev/null
</code>```

3. Start app

```<code>pkg_name=$name
adb shell monkey -p "${pkg_name}" -c android.intent.category.LAUNCHER 1
</code>```

Body:
Is there any command on cmd.exe that would allow me to start the main activity of a particular android application using the .apk file of that application. Please note that I know this command which only installs an android application:

adb install myapp.apk

This command will only install myapp onto the emulator and I have to manually run this application from the emulator (by performing single click on its icon).

What I want to do is use a command which not only installs the application but also starts its main activity (please note that I have only its .apk file so I don't know what the package name or any activity name is).

Body:
This is a solution in shell script:

apk="$apk_path"

1. Install apk

adb install "$apk"
sleep 1

2. Get package name

pkg_info=`aapt dump badging "$apk" | head -1 | awk -F " " '{print $2}'`
eval $pkg_info > /dev/null

3. Start app

pkg_name=$name
adb shell monkey -p "${pkg_name}" -c android.intent.category.LAUNCHER 1


问:
Unable to center content of a div
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
    <div class="divTableRow">
      <div class="divTableCell"> 6</div>
    </div>
  </div>
</div></code>```

Here I want 6 to be in center. How can I achieve this?

basically like below table

```<code><table border="1px solid black">
  <tr>
    <td>$2</td>
    <td>1</td>
  </tr>
  <tr>
    <td colspan="2" align="center">6</td>
  </tr>
</table>
</code>```

答:
If this cell is going to be at the bottom then you can go for table-caption like this

```<code><div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
  </div>
  <div class="divTableCaption">
    6
  </div>
</div>
</code>```

css

```<code>.divTable {
  display: table;
  width: 100%;
}
.divTableRow {
  display: table-row;
}
.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}
.divTableBody {
  display: table-row-group;
}
.divTableCaption { /* <== Only added this */
  display: table-caption;
  text-align: center;
  border: 1px solid #999999;
  caption-side: bottom;
}
</code>```

Title: Unable to center content of a div

Body:
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}

$2

1

 6

Here I want 6 to be in center. How can I achieve this?

basically like below table

    $2
    1

    6

Body:
If this cell is going to be at the bottom then you can go for table-caption like this

<div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
  </div>
  <div class="divTableCaption">
    6
  </div>
</div>

css

.divTable {
  display: table;
  width: 100%;
}
.divTableRow {
  display: table-row;
}
.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}
.divTableBody {
  display: table-row-group;
}
.divTableCaption { /* <== Only added this */
  display: table-caption;
  text-align: center;
  border: 1px solid #999999;
  caption-side: bottom;
}


问:
How to check Item exists in Firebase Database? - react-native-firebase
Currently, I am using https://github.com/invertase/react-native-firebase for my project. I have a custom database for users and I want to check if the user exists or not by email.

Here is a screenshot of the database:

答:
Here's a generic firebase method but you may need to reconfigure the method to suit your data structure. Please refer to the official docs if you wish to know more.

```<code>firebase.database()
    .ref(`/users`)
    .orderByChild("email")
    .equalTo(email)
    .once("value")
    .then(snapshot => {
        if (snapshot.val()) {
            // data exist, do something else
        }
    })
</code>```

You can also query the registration status with hasChild method. Refer to your root path and query with .once and check the result returned.

```<code>export function checkUserExist(email) {
  return(dispatch) => {
    firebase.database().ref(`/ExistingUser/`)
      .once('value', snapshot => {
        if(snapshot.hasChild(email)) {
          dispatch({
            type: FIREBASE_USER_EXISTED
          });
        } else {
          dispatch({
            type: FIREBASE_USER_NOT_EXISTED,
          });
        }
      });
  }
}
</code>```

Another preferred method would be using the fetchProvidersForEmail method provided by Firebase. It takes an email and returns a promise that resolves with the list of providers linked to that email if it is already registered, refer here.

Is there a good reason to store users credential in your database? In my daily practice, I would use the createUserWithEmailAndPassword provided by Firebase for security purposes, refer here. Just make sure rules are defined properly to prevent unauthorized access.

Body:
Here's a generic firebase method but you may need to reconfigure the method to suit your data structure. Please refer to the official docs if you wish to know more.

firebase.database()
    .ref(`/users`)
    .orderByChild("email")
    .equalTo(email)
    .once("value")
    .then(snapshot => {
        if (snapshot.val()) {
            // data exist, do something else
        }
    })

You can also query the registration status with hasChild method. Refer to your root path and query with .once and check the result returned.

export function checkUserExist(email) {
  return(dispatch) => {
    firebase.database().ref(`/ExistingUser/`)
      .once('value', snapshot => {
        if(snapshot.hasChild(email)) {
          dispatch({
            type: FIREBASE_USER_EXISTED
          });
        } else {
          dispatch({
            type: FIREBASE_USER_NOT_EXISTED,
          });
        }
      });
  }
}

Another preferred method would be using the fetchProvidersForEmail method provided by Firebase. It takes an email and returns a promise that resolves with the list of providers linked to that email if it is already registered, refer here.

Is there a good reason to store users credential in your database? In my daily practice, I would use the createUserWithEmailAndPassword provided by Firebase for security purposes, refer here. Just make sure rules are defined properly to prevent unauthorized access.


问:
Scapy import fails without Wifi connection
I have just installed Scapy (v 2.3.3) on Mac OS Sierra.
It works fine as long as I am connected to WiFi but gives an import error when I run my code without the connection.

Below is the error statement:

```<code>File "/usr/local/lib/python2.7/site-packages/scapy/all.py", line 25, in <module>
    from scapy.route import *
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 163, in <module>
    conf.route=Route()
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 22, in __init__
    self.resync()
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 31, in resync
    self.routes = read_routes()
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/unix.py", line 102, in read_routes
    ifaddr = scapy.arch.get_if_addr(netif)
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/__init__.py", line 48, in get_if_addr
    return socket.inet_ntoa(get_if_raw_addr(iff))
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/pcapdnet.py", line 519, in get_if_raw_addr
    return i.get(ifname)["addr"].data
KeyError: 'addr'
</code>```

答: You should upgrade to the current development version from the repository. If you still have this issue, you should report it as a bug.</p>

Body:
I have just installed Scapy (v 2.3.3) on Mac OS Sierra.
It works fine as long as I am connected to WiFi but gives an import error when I run my code without the connection.

Below is the error statement:

File "/usr/local/lib/python2.7/site-packages/scapy/all.py", line 25, in <module>
    from scapy.route import *
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 163, in <module>
    conf.route=Route()
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 22, in __init__
    self.resync()
  File "/usr/local/lib/python2.7/site-packages/scapy/route.py", line 31, in resync
    self.routes = read_routes()
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/unix.py", line 102, in read_routes
    ifaddr = scapy.arch.get_if_addr(netif)
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/__init__.py", line 48, in get_if_addr
    return socket.inet_ntoa(get_if_raw_addr(iff))
  File "/usr/local/lib/python2.7/site-packages/scapy/arch/pcapdnet.py", line 519, in get_if_raw_addr
    return i.get(ifname)["addr"].data
KeyError: 'addr'


问:
Understand AngularJS Minification
I am about to deploy an angularjs app, I would like to minify my code, but it is still confusing for me

I would like for exemple to transform

```<code>**Controller**
myApp.controller('myCtrl', function($scope, $location, $etc) {
  $scope.message = "Hello World";
});
**View**
<p>{{message}}</p>
</code>```

To

```<code>**Controller**
myApp.controller('myCtrl',function($a,$b){$a.m="Hello World";});
**View**
<p>{{m}}</p>
</code>```

I can use grunt to minify the code, is grunt can also reduce the variables names? Like changing message to m for exemple? And how the mapping will be done with the view?

答:
You need to inject your dependencies as strings, so that angular would know which variable does what. Just add a manual injection for each service:

```<code>myCtrl.$inject = ["$scope","$location","$etc"]; // <--- injection

myApp.controller('myCtrl', function($scope, $location, $etc) {
  $scope.message = "Hello World";
});
</code>```

There are other syntaxes you can use, but this one is pretty clear and modular.

Title: Understand AngularJS Minification

Body:
I am about to deploy an angularjs app, I would like to minify my code, but it is still confusing for me

I would like for exemple to transform

**Controller**
myApp.controller('myCtrl', function($scope, $location, $etc) {
  $scope.message = "Hello World";
});
**View**

{{message}}

To

**Controller**
myApp.controller('myCtrl',function($a,$b){$a.m="Hello World";});
**View**

{{m}}

I can use grunt to minify the code, is grunt can also reduce the variables names? Like changing message to m for exemple? And how the mapping will be done with the view?

Body:
You need to inject your dependencies as strings, so that angular would know which variable does what. Just add a manual injection for each service:

myCtrl.$inject = ["$scope","$location","$etc"]; // <--- injection

myApp.controller('myCtrl', function($scope, $location, $etc) {
  $scope.message = "Hello World";
});

There are other syntaxes you can use, but this one is pretty clear and modular.


问:
How to return autocomplete result to spring mvc controller using ajax and jquery
I'm trying to return to the controller the selection from the autocomplete. Currently the autocomplete is working fine. I'm getting from my db the results to the form I need. The thing is I want also to pass this result to the controller to do some extra work with it.

So my controller looks like this:

```<code>@ResponseBody
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET)
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports(@ModelAttribute("flight")FlightInfo flightInfo) {
        Map<String, List<AirportInfo>> map = new HashMap<>();
        List<AirportInfo> airportList = airportService.findAll();
        map.put("airportList", airportList);
        return map;
}

@PostMapping("/autoCompleteAirportInfo")
public String post(@ModelAttribute("flight") FlightInfo flightInfo) {
    return "index";
}
</code>```

the index.html thymeleaf containing the .js:

```<code><script>
    $(function() {
        $( "#searchAirports" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "/autoCompleteAirportInfo",
                    dataType: "json",
                    data: {
                        maxRows: 6,
                        startsWith: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.airportList, function( item ) {
                            return {
                                label: item.city + ", " + item.country + ", " + item.code + ", " + item.name,
                                value: item.city + ", " + item.country + ", " + item.code + ", " + item.name
                            }
                        }));
                    }
                });
            },
            minLength: 1,
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });
    });
</code>```

and the form:

```<code><form form ACTION="#" th:action="@{/autoCompleteAirportInfo}" th:object="${flight}" method="post">
                <div>
                    <div>
                        <input type="text" id="searchAirports"  placeholder="Search:"/>
                    </div>
                </div>
</form>
</code>```

答:
I just tried by setting up some sample as below.

```<code>@ResponseBody
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET)
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports() {
        List<AirportInfo> list = new ArrayList<AirportInfo>();
        AirportInfo airportInfo = new AirportInfo("A","B","C","D");
        list.add(airportInfo);
        airportInfo = new AirportInfo("E","F","G","H");
        list.add(airportInfo);
        map.put("airportList", list);
        return map;
}

@RequestMapping("/submittedAirport")
public String post(@RequestParam("searchAirports") String value) {
  System.out.println("Selected Value="+value)
  return "index";
}
</code>```

Sample JSP:

```<code>...
<form action="">
    <div class="ui-widget">
        <input name="searchAirports" id="searchAirports"/>
    </div>
    <input type="submit"/>
</form>
</code>```

On Submitting the form, I was able get the selected value in the post method

```<code>Selected Value=A, B, C, D
</code>```

Body:
I'm trying to return to the controller the selection from the autocomplete. Currently the autocomplete is working fine. I'm getting from my db the results to the form I need. The thing is I want also to pass this result to the controller to do some extra work with it.

So my controller looks like this:

@ResponseBody
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET)
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports(@ModelAttribute("flight")FlightInfo flightInfo) {
        Map<String, List<AirportInfo>> map = new HashMap<>();
        List<AirportInfo> airportList = airportService.findAll();
        map.put("airportList", airportList);
        return map;
}

@PostMapping("/autoCompleteAirportInfo")
public String post(@ModelAttribute("flight") FlightInfo flightInfo) {
    return "index";
}

the index.html thymeleaf containing the .js:

Body:
I just tried by setting up some sample as below.

@ResponseBody
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET)
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports() {
        List<AirportInfo> list = new ArrayList<AirportInfo>();
        AirportInfo airportInfo = new AirportInfo("A","B","C","D");
        list.add(airportInfo);
        airportInfo = new AirportInfo("E","F","G","H");
        list.add(airportInfo);
        map.put("airportList", list);
        return map;
}

@RequestMapping("/submittedAirport")
public String post(@RequestParam("searchAirports") String value) {
  System.out.println("Selected Value="+value)
  return "index";
}

Sample JSP:

...
<form action="">
    <div class="ui-widget">
        <input name="searchAirports" id="searchAirports"/>
    </div>
    <input type="submit"/>
</form>

On Submitting the form, I was able get the selected value in the post method

Selected Value=A, B, C, D


问:
Pydev Eclipse executes previously executed program before executing current program
I have a single project which contain multiple pydev module programs. None of the modules are inter-linked or imported into other modules. All are independent modules.
I am seeing an issue with two programs namely: "CmdOnRemoteServer" and "ipaddress"

When i execute program "CmdOnRemoteServer" program, the console prints the output of previous/old program "ipaddress" and then jumps into the current program "CmdOnRemoteServer" and prints the output.
I could find this behaviour by putting the program debug and having breakpoints in both programs.

In the Preferences>>Run/Debug>>Launching, the options selected are "Launch the selected resource or active editor" and "If not launchable>>Launch the previously launched application"

I added 'if ____name____ == "____main____":' code to "CmdOnRemoteServer", but this also didnt help.
I am attaching the debug screenshot which shows both programs listed in the mainthread.

Can someone please help me with this issue?

As requested, adding the code to the question:

```<code>if __name__ == "__main__":
    remoteServer=winrm.Session("IDCQEAM190.amdom009.lab", auth = ("Administrator", "Control123"))
remoteCMD = remoteServer.run_cmd("ipconfig", ["/all"])

myfile = open(r"C:\Users\pshastri\Desktop\remoteServer.txt", "w")
myfile.write(remoteCMD.std_out)
myfile.close()

myfile = open(r"C:\Users\pshastri\Desktop\remoteServer.txt", "r")
ipPatt = "IPv4 Address[\.\s]{1,}:\s[\d+\.]{1,}"
hostPatt = "Host Name [\.\s]{1,}: [A-Za-z0-9]+"
domPatt = "Primary Dns Suffix [\.\s]{1,}: [A-Za-z0-9]+\.[A-Za-z0-9]+"
myfile.seek(0)
ipReg = re.findall(ipPatt, myfile.read())
myfile.seek(0)
hostReg = re.findall(hostPatt, myfile.read())
myfile.seek(0)
domReg = re.findall(domPatt, myfile.read())
print "".join(ipReg), "\n", "".join(hostReg), "\n", "".join(domReg)
</code>```

答: As you can see on your debug stacktrace, the problem seems to be that you're program (CmdOnRemoteServer) ends up in a chain where the Python standard library imports an ipaddress module (so, to fix the error, rename your ipaddress module to something else as that name is already used in the standard library).

Body:
I have a single project which contain multiple pydev module programs. None of the modules are inter-linked or imported into other modules. All are independent modules.
I am seeing an issue with two programs namely: "CmdOnRemoteServer" and "ipaddress"

When i execute program "CmdOnRemoteServer" program, the console prints the output of previous/old program "ipaddress" and then jumps into the current program "CmdOnRemoteServer" and prints the output.
I could find this behaviour by putting the program debug and having breakpoints in both programs.

In the Preferences>>Run/Debug>>Launching, the options selected are "Launch the selected resource or active editor" and "If not launchable>>Launch the previously launched application"

I added 'if ____name____ == "____main____":' code to "CmdOnRemoteServer", but this also didnt help.
I am attaching the debug screenshot which shows both programs listed in the mainthread.

Can someone please help me with this issue?

As requested, adding the code to the question:

if __name__ == "__main__":
    remoteServer=winrm.Session("IDCQEAM190.amdom009.lab", auth = ("Administrator", "Control123"))
remoteCMD = remoteServer.run_cmd("ipconfig", ["/all"])

myfile = open(r"C:\Users\pshastri\Desktop\remoteServer.txt", "w")
myfile.write(remoteCMD.std_out)
myfile.close()

myfile = open(r"C:\Users\pshastri\Desktop\remoteServer.txt", "r")
ipPatt = "IPv4 Address[\.\s]{1,}:\s[\d+\.]{1,}"
hostPatt = "Host Name [\.\s]{1,}: [A-Za-z0-9]+"
domPatt = "Primary Dns Suffix [\.\s]{1,}: [A-Za-z0-9]+\.[A-Za-z0-9]+"
myfile.seek(0)
ipReg = re.findall(ipPatt, myfile.read())
myfile.seek(0)
hostReg = re.findall(hostPatt, myfile.read())
myfile.seek(0)
domReg = re.findall(domPatt, myfile.read())
print "".join(ipReg), "\n", "".join(hostReg), "\n", "".join(domReg)


问:
requests.post with Authentication giving error 415 for jira rest api in python
```<code>url = "https://example.com/jira/rest/api/2/issue/issue_key/comment"
data = json.dumps({"body": 'some string'})
headers = {'content-type':'application/json'}
r = requests.post(url, data, auth=('username', 'password'))
</code>```

-->  r.status_code output is 415.

But in case of

```<code>r = requests.get(url, data, auth=('username', 'password'))
</code>```

-->  r.status_code output is 200. Please help me to identify issue.

答:
you forgot to add the headers variable to your post requests. thats why it fails. just add this to your post request and you should get a 201 status code as response:</p>

```<code>r = requests.post(url, data, auth=('username', 'password'), headers=headers)
</code>```

Body:
url = "https://example.com/jira/rest/api/2/issue/issue_key/comment"
data = json.dumps({"body": 'some string'})
headers = {'content-type':'application/json'}
r = requests.post(url, data, auth=('username', 'password'))

-->  r.status_code output is 415.

But in case of

r = requests.get(url, data, auth=('username', 'password'))

-->  r.status_code output is 200. Please help me to identify issue.

Body:
you forgot to add the headers variable to your post requests. thats why it fails. just add this to your post request and you should get a 201 status code as response:

r = requests.post(url, data, auth=('username', 'password'), headers=headers)


问:
css3 box shadows in one direction only?
I have an element that has inset box shadows, but I want the shadow on only the top.

Is there no way to set only the top shadow? Do I have to resort to creating additional elements to overlay the side shadows?

答:
A better way would be using a background gradient, here are both side to side.

http://jsfiddle.net/wh3L8/

Title: css3 box shadows in one direction only?


问:
How to use the Tooltip() function to be global
I have 2 file.php, file1.php it is a file for the core page, file2.php to display the added form.
file2.php included to file1.php in a statement.
when i need to use function from Boostraps.js, to beautify tooltip, i call function from Boostraps.js in file1.php as follows:

$('.Btn').Tooltip({
placement: 'bottom'
});```
</div>
</div>
</p>

<p>why tooltip() function only runs on <em>file1.php</em> only, does not work for <em>file2.php</em> included in <em>file1.php</em>
how to keep this tooltip function running in 2 different files that are included.
if calling globally I've used action just like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on('click',function(){
// Bla bla bla ...
})</code>```

答:
So what you want to do right now use that both 2 file php at the same time/page?

If you want do something like set it globally without need to set it again.

Maybe you can try check this code.

```<code>$(document).on("mouseover",".btn",function(){
    var ele     = $(this);
    if(!ele.data("setthis")){ // check it. so we only bind only once
        $(this).tooltip({
            placement: 'bottom'
        });
        $(this).tooltip("show");
        ele.data("setthis",true); // set this to true, don't set it anymore
    }else{ // just a log. can delete it.
        console.log("Don't Set Another Tooltip");
    }
});
</code>```

Just run it once in core page @ anything.
And jsfiddle here : https://jsfiddle.net/synz/o8sue511/3/

Body:
I have 2 file.php, file1.php it is a file for the core page, file2.php to display the added form.
file2.php included to file1.php in a statement.
when i need to use function from Boostraps.js, to beautify tooltip, i call function from Boostraps.js in file1.php as follows:

$('.Btn').Tooltip({
placement: 'bottom'
});

why tooltip() function only runs on file1.php only, does not work for file2.php included in file1.php
how to keep this tooltip function running in 2 different files that are included.
if calling globally I've used action just like this:

$(document).on('click',function(){
// Bla bla bla ...
})

Body:
So what you want to do right now use that both 2 file php at the same time/page?

If you want do something like set it globally without need to set it again.

Maybe you can try check this code.

$(document).on("mouseover",".btn",function(){
    var ele     = $(this);
    if(!ele.data("setthis")){ // check it. so we only bind only once
        $(this).tooltip({
            placement: 'bottom'
        });
        $(this).tooltip("show");
        ele.data("setthis",true); // set this to true, don't set it anymore
    }else{ // just a log. can delete it.
        console.log("Don't Set Another Tooltip");
    }
});

Just run it once in core page @ anything.
And jsfiddle here : https://jsfiddle.net/synz/o8sue511/3/


问:
Is there a CSS selector for elements containing certain text?
I am looking for a CSS selector for the following table:

```<code>Peter    | male    | 34
Susanne  | female  | 12
</code>```

Is there any selector to match all TDs containing "male"?

答:
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:

td.male { color: blue; }
td.female { color: pink; }
```

<p>can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:</p>

```
```

<p>Just make sure that the content is only one word! Or you could even map to different CSS class names with:</p>

```
```

<p>For completeness, here's the data attribute approach:</p>

```
```

Body:
I am looking for a CSS selector for the following table:

Peter    | male    | 34
Susanne  | female  | 12

Is there any selector to match all TDs containing "male"?

Body:
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:

td.male { color: blue; }
td.female { color: pink; }

can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:

<td class="{{person.gender}}">

Just make sure that the content is only one word! Or you could even map to different CSS class names with:

<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">

For completeness, here's the data attribute approach:

<td data-gender="{{person.gender}}">


问:
Dynamic widths for css class with ::after pseudoelement
I'm doing some mvc testing and I've hit a roadblock when I'm going through my model to display some elements. Each element will have to have an "EXP" amount that is displayed dynamically in the ::after element in the css.

Is there a way to dynamically change the width of the ::after element? I am passing through the width for each element through the model but I don't display it yet

That's the bar that needs to change dynamically, here's an example piece of code of how I've done it so far:

.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
    }

        .pkmn-summary:after {
            content: '';
            position: relative;
            left: -181px;
            bottom: -31px;
            height: 5px;
            background: green;
            width: 73%;
            display: inline-block;
            border-radius: 0 0 0 5px;
        }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pkmn-pc">
    <div class="pkmn-summary">
        <img class="pkmn-sprite" src="https://cdn.bulbagarden.net/upload/e/ea/113MS.png" />
        <code class="pkmn-name">15Characterssss</code>
    </div>
    <div class="pkmn-info">
        <img class="crown" src="https://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" />
        <div class="pkmn-outer">
            <img class="heart" src="https://image.ibb.co/kB8vi6/heart.png">
            <div class="pkmn-inner"></div>
            <img class="star" src="https://image.ibb.co/e7w4bR/Shiny_VIStar.png">
        </div>
        <code class="pkmn-lvl">lvl 100</code>
    </div>
</div></code>```

Any help would be greatly appreciated! Thanks!

答:
Unfortunately you cannot script the ::after elements as they are not part of the dom.
You could either

Use a set of predefined classes and apply them to parent

add a bar element and script it like

var p = 0;
var bar = document.querySelector(".pkmn-bar");
window.setInterval(function() {
  bar.style.width=p+"%";
  p++;
  if(p>100) p=0;
},50);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
        position: relative;
    }

    .pkmn-bar {
        content: '';
        background: #745fb5;
        white-space: nowrap;
        text-align: left;
        position: absolute;
        left: 0;
        bottom: -5px;
        height: 5px;
        background: green;
        display: block;
        border-radius: 0 0 0 5px;
    }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }</code>```

        15Characterssss

        lvl 100

```

Body:
I'm doing some mvc testing and I've hit a roadblock when I'm going through my model to display some elements. Each element will have to have an "EXP" amount that is displayed dynamically in the ::after element in the css.

Is there a way to dynamically change the width of the ::after element? I am passing through the width for each element through the model but I don't display it yet

That's the bar that needs to change dynamically, here's an example piece of code of how I've done it so far:

.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
    }

        .pkmn-summary:after {
            content: '';
            position: relative;
            left: -181px;
            bottom: -31px;
            height: 5px;
            background: green;
            width: 73%;
            display: inline-block;
            border-radius: 0 0 0 5px;
        }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }

        15Characterssss

        lvl 100

Any help would be greatly appreciated! Thanks!

Body:
Unfortunately you cannot script the ::after elements as they are not part of the dom.
You could either

Use a set of predefined classes and apply them to parent

add a bar element and script it like

var p = 0;
var bar = document.querySelector(".pkmn-bar");
window.setInterval(function() {
  bar.style.width=p+"%";
  p++;
  if(p>100) p=0;
},50);

.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
        position: relative;
    }

    .pkmn-bar {
        content: '';
        background: #745fb5;
        white-space: nowrap;
        text-align: left;
        position: absolute;
        left: 0;
        bottom: -5px;
        height: 5px;
        background: green;
        display: block;
        border-radius: 0 0 0 5px;
    }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }

<div class="pkmn-pc">
    <div class="pkmn-summary">
        <img class="pkmn-sprite" src="https://cdn.bulbagarden.net/upload/e/ea/113MS.png" />
        <code class="pkmn-name">15Characterssss</code>
        <div class="pkmn-bar"></div>
    </div>
    <div class="pkmn-info">
        <img class="crown" src="https://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" />
        <div class="pkmn-outer">
            <img class="heart" src="https://image.ibb.co/kB8vi6/heart.png">
            <div class="pkmn-inner"></div>
            <img class="star" src="https://image.ibb.co/e7w4bR/Shiny_VIStar.png">
        </div>
        <code class="pkmn-lvl">lvl 100</code>
    </div>

</div>


问:
Rancher with cattle vs Rancher with Kubernetes vs Standalone Kubernetes
I'm trying to dig into Rancher, and was wondering if having Rancher plugged in with Kubernetes has any additional benefits over Cattle which is Rancher's in home orchestration framework. So far, I haven't been able to figure out why someone would opt for Rancher with Kubernetes. Does it only help ease out the initial setup of Kubernetes? How do these options differ from a stand alone setup of Kubernetes ?</p>

答:
In our experience,
Cattle is just a toy. It's just suit for development or some small environment. If you used Cattle in PROD, you will know what I say.

But Rancher is far more concise and simple than k8s.

So I'm looking forward to the Rancher 2.0,

Rancher 2.0 is a complete container management platform built on Kubernetes


问:
AWS DataPipeline EMR cluster with spark
I have created an AWS DataPipeline using EMR template, but its not installing Spark on EMR cluster. Do I need to set any special action for that ?
I see some bootstrapaction is need for spark installation but that is also not working.</p>

答:
That install-spark bootstrap action is only for 3.x AMI versions. If you are using a releaseLabel (emr-4.x or beyond), the applications to install are specified in a different way.

When you are creating a pipeline, you click "Edit in Architect" at the bottom or edit your pipeline on pipelines home page then you can then click on the EmrCluster node and select Applications from the "Add an optional field..." dropdown. That is where you may add Spark.

Title: AWS DataPipeline EMR cluster with spark


问:
How to programatically insert link at current position in CKEditor 5
In my app, I have a specific dialog to create internal links. After user finishes filling the dialog I want to programatically insert generated link to current caret position in the editor. So far I've been using SummerNote and there it is easy:

```<code>editor.summernote('createLink', {
     text: linkTitle,
     url: url
});
</code>```

In CKEditor 5 I found this method which seems like it could do what I need:

```<code>doc.enqueueChanges(() => {
    editor.data.insertContent(content, doc.selection);
});
</code>```

My problem is that I don't know how to create this "content" parameter. I tried to create a link in HTML and pass it there, but that doesn't work.

I also tried to create an instance of LinkElement, but that class doesn't seem to exist in the JS runtime (I'm running CKEditor from build, not from sources).

It's not clear to me if this is even possible without writing a plugin for CKEditor (which seems to me like an overkill).

答:
After 1.0.0-beta (March 2018):

To insert some data into an editor, simply use a "change block":

```<code>editor.model.change( writer => {
    const insertPosition = editor.model.document.selection.getFirstPosition();
    writer.insertText( linkText, { linkHref: linkUrl }, insertPosition );
} );
</code>```

where linkText and linkUrl are variables that you should provide from your custom UI.

The above will work well for collapsed selection. The linked text will be inserted at caret position.

The big difference introduced in 1.0.0-beta is that we are providing the writer object in change() calls, so you don't need to (and should not) use framework classes constructors directly.

You can also use editor.model.insertContent in a similar way that you proposed:

```<code>editor.model.change( writer => {
    const linkedText = writer.createText( linkText, { linkHref: linkUrl } );
    editor.model.insertContent( linkedText, editor.model.document.selection );
} );
</code>```

This will work properly also if the selection is not collapsed, as insertContent does a little bit more (for example, if selection was not collapsed and was between two paragraphs, selection contents will be removed and paragraphs merged).

Before 1.0.0-beta

DataController#insertContent() accepts model's DocumentFragment or Node (so Element or Text – I've just noticed that this info is missing in the API docs).

Unfortunately, right now you need to have access to Element's or Text's constructors in order to create them. This means that you need to build CKEditor 5 from source instead of using existing builds. This isn't hard, but it's indeed an overkill. Therefore, we're working now on exposing a sufficient part of the API in the existing classes so that you could write simple integration code like this without building CKEditor 5 into your app.

Anyway, if you'll configure webpack (or simply fork an existing build) you can write a simple function for inserting a linked text:

```<code>import Text from '@ckeditor/ckeditor5-engine/src/model/text';

function insertLink( linkText, linkHref ) {
    const text = new Text( linkText, { linkHref } );

    editor.document.enqueueChanges( () => {
        editor.data.insertContent( text, editor.document.selection );
    } );
}
</code>```

Body:
In my app, I have a specific dialog to create internal links. After user finishes filling the dialog I want to programatically insert generated link to current caret position in the editor. So far I've been using SummerNote and there it is easy:

editor.summernote('createLink', {
     text: linkTitle,
     url: url
});

In CKEditor 5 I found this method which seems like it could do what I need:

doc.enqueueChanges(() => {
    editor.data.insertContent(content, doc.selection);
});

My problem is that I don't know how to create this "content" parameter. I tried to create a link in HTML and pass it there, but that doesn't work.

I also tried to create an instance of LinkElement, but that class doesn't seem to exist in the JS runtime (I'm running CKEditor from build, not from sources).

It's not clear to me if this is even possible without writing a plugin for CKEditor (which seems to me like an overkill).

Body:
After 1.0.0-beta (March 2018):

To insert some data into an editor, simply use a "change block":

editor.model.change( writer => {
    const insertPosition = editor.model.document.selection.getFirstPosition();
    writer.insertText( linkText, { linkHref: linkUrl }, insertPosition );
} );

where linkText and linkUrl are variables that you should provide from your custom UI.

The above will work well for collapsed selection. The linked text will be inserted at caret position.

The big difference introduced in 1.0.0-beta is that we are providing the writer object in change() calls, so you don't need to (and should not) use framework classes constructors directly.

You can also use editor.model.insertContent in a similar way that you proposed:

editor.model.change( writer => {
    const linkedText = writer.createText( linkText, { linkHref: linkUrl } );
    editor.model.insertContent( linkedText, editor.model.document.selection );
} );

This will work properly also if the selection is not collapsed, as insertContent does a little bit more (for example, if selection was not collapsed and was between two paragraphs, selection contents will be removed and paragraphs merged).

Before 1.0.0-beta

DataController#insertContent() accepts model's DocumentFragment or Node (so Element or Text – I've just noticed that this info is missing in the API docs).

Unfortunately, right now you need to have access to Element's or Text's constructors in order to create them. This means that you need to build CKEditor 5 from source instead of using existing builds. This isn't hard, but it's indeed an overkill. Therefore, we're working now on exposing a sufficient part of the API in the existing classes so that you could write simple integration code like this without building CKEditor 5 into your app.

Anyway, if you'll configure webpack (or simply fork an existing build) you can write a simple function for inserting a linked text:

import Text from '@ckeditor/ckeditor5-engine/src/model/text';

function insertLink( linkText, linkHref ) {
    const text = new Text( linkText, { linkHref } );

    editor.document.enqueueChanges( () => {
        editor.data.insertContent( text, editor.document.selection );
    } );
}


问:
How to print out information from data used in arrays?
My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?

Code:

```<code>package SMKTeamStandings;

import java.util.Scanner;

public class SMKTeamStandings {

public static Scanner in = new Scanner(System.in);

public static int number(int max, int min) {
    int teamchoice = 0;
    for (boolean valid = false; valid == false;) {
        teamchoice = in.nextInt();
        if (teamchoice >= min && teamchoice <= max) {
            valid = true;
        } else {
            System.out.println("Please enter a different value.");
        }
    }
    return teamchoice;
}

public static boolean finished(boolean[] completedArray) {
    int i = 0;
    boolean done;
    for (done = true; done == true;) {
        if (completedArray[i++] == false) {
            done = false;
        }
    }
    return done;
}

public static void main(String[] args) {

    int teamChoice = 0, gamesNum;

    String[] sportteams = {"Basketball", "Football",
       "Hockey", "Rugby",
       "Soccer", "Volleyball"};

    boolean[] completed = new boolean[sportteams.length];
    int[][] Outcome = new int[64][sportteams.length];

    for (boolean done = false; done == false;) {
        for (int i = 0; i < sportteams.length; i++) {
            System.out.print(i + 1 + " - " + sportteams[i]);
            if (completed[i] == true) {
                System.out.println(" - Finished");
            } else {
                System.out.println();
            }
        }

        System.out.print("\nChoose a team from the list above:");

        teamChoice = number(6, 1);
        teamChoice--;

        System.out.print("\nHow many games total did the " + sportteams[teamChoice]
                + " team play this season?: ");

        gamesNum = in.nextInt();

        System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
                "1 - Win",
                "2 - Tie",
                "3 - Loss");

        for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
            System.out.print("\nEnter the outcome for game "
                    + (wintieloss + 1) + ": ");
            Outcome[wintieloss][teamChoice] = number(3, 1);
        }
        System.out.println("\n");
        completed[teamChoice] = true;
        done = finished(completed);
</code>```

答:
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.</p>

```<code>for(int team = 0; team < sportteams.length; team++) { // for each team
    System.out.println((team + 1) + " - " + sportteams[team]); // output the team
    int game = 0; // index of the current game
    while(Outcome[game][team] != 0) { // while there is data
        System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
        game++; // increment the index
    }
    System.out.println("Total games: " + game); // print the last index == total number of games
    System.out.println();
}
</code>```

Body:
My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?

Code:

package SMKTeamStandings;

import java.util.Scanner;

public class SMKTeamStandings {

public static Scanner in = new Scanner(System.in);

public static int number(int max, int min) {
    int teamchoice = 0;
    for (boolean valid = false; valid == false;) {
        teamchoice = in.nextInt();
        if (teamchoice >= min && teamchoice <= max) {
            valid = true;
        } else {
            System.out.println("Please enter a different value.");
        }
    }
    return teamchoice;
}

public static boolean finished(boolean[] completedArray) {
    int i = 0;
    boolean done;
    for (done = true; done == true;) {
        if (completedArray[i++] == false) {
            done = false;
        }
    }
    return done;
}

public static void main(String[] args) {

    int teamChoice = 0, gamesNum;

    String[] sportteams = {"Basketball", "Football",
       "Hockey", "Rugby",
       "Soccer", "Volleyball"};

    boolean[] completed = new boolean[sportteams.length];
    int[][] Outcome = new int[64][sportteams.length];

    for (boolean done = false; done == false;) {
        for (int i = 0; i < sportteams.length; i++) {
            System.out.print(i + 1 + " - " + sportteams[i]);
            if (completed[i] == true) {
                System.out.println(" - Finished");
            } else {
                System.out.println();
            }
        }

        System.out.print("\nChoose a team from the list above:");

        teamChoice = number(6, 1);
        teamChoice--;

        System.out.print("\nHow many games total did the " + sportteams[teamChoice]
                + " team play this season?: ");

        gamesNum = in.nextInt();

        System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
                "1 - Win",
                "2 - Tie",
                "3 - Loss");

        for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
            System.out.print("\nEnter the outcome for game "
                    + (wintieloss + 1) + ": ");
            Outcome[wintieloss][teamChoice] = number(3, 1);
        }
        System.out.println("\n");
        completed[teamChoice] = true;
        done = finished(completed);

Body:
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.

for(int team = 0; team < sportteams.length; team++) { // for each team
    System.out.println((team + 1) + " - " + sportteams[team]); // output the team
    int game = 0; // index of the current game
    while(Outcome[game][team] != 0) { // while there is data
        System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
        game++; // increment the index
    }
    System.out.println("Total games: " + game); // print the last index == total number of games
    System.out.println();
}


问:
addValueEventListener runs even when I just return to the app from a sleep mode
I am developing an android app using Firebase Realtime Database.

My addValueEventListener for a specific reference runs whenever there is a data change in the database. It also runs whenever the app starts. These make sense to me, but this even runs when I return to my app from a different activity. For example, it runs when I go to the HOME screen of my phone and go back to this app, the addValueEventListener runs.

This is a problem for me because I am implementing a vibration whenever there is a data change in my app. I put a global int variable to prevent vibration on the first time i get to the app.

It works like:

```<code>matchReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(notificationCounter > 0) notifyGoals(getView());

                clearCurrentList();
                notificationCounter++;

                // Fires every single time the channelReference updates in the
                }

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

I initialize int notificationCounter = 0 outside of this function so that it gets reset to 0 whenever I re-run this app. But, whenever I go to a different activity on my phone (HOME Screen or LOCK screen) and return to this screen, it runs the addValueEventListener before the int notificationCounter = 0 initialization. How can I solve this problem?

答: This is happening because onDataChange() method is called asynchronous which means that this method does not wait to get the data from your database and is called even before. To solve this, you have 2 choices. One would be to move the declaration of your notificationCounter int inside the onDataChange() method or second, to dive into the asynchronous word and use my answer from this post.

Body:
I am developing an android app using Firebase Realtime Database.

My addValueEventListener for a specific reference runs whenever there is a data change in the database. It also runs whenever the app starts. These make sense to me, but this even runs when I return to my app from a different activity. For example, it runs when I go to the HOME screen of my phone and go back to this app, the addValueEventListener runs.

This is a problem for me because I am implementing a vibration whenever there is a data change in my app. I put a global int variable to prevent vibration on the first time i get to the app.

It works like:

matchReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(notificationCounter > 0) notifyGoals(getView());

                clearCurrentList();
                notificationCounter++;

                // Fires every single time the channelReference updates in the
                }

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

I initialize int notificationCounter = 0 outside of this function so that it gets reset to 0 whenever I re-run this app. But, whenever I go to a different activity on my phone (HOME Screen or LOCK screen) and return to this screen, it runs the addValueEventListener before the int notificationCounter = 0 initialization. How can I solve this problem?


问:
How to create a mini-game?
I'am wondering how to create a mini-game like "diner dash" or like "big fish games". I want my game to be 2D but it looks like 3D. See this image:

(source: topxgames.com)

If you know some good game-engine to create like those games, please let me know.

答: You could always use the ever popular Unreal engine or Directx, or even the XNA framework for .NET. Just to name a few. For web based you can try unity 3d or if you want to keep it simple maybe flash will work for you. There's too many choices and it all depends on your preference.</p>

ContentLicense: CC BY-SA 4.0

Title: How to create a mini-game?


问:
Set different folders in different alias in the same server
In my windows server 2012 I have setting two alias :

http://kpi.xxx.yyy

http://kpc.xxx.yyy

Now I need associate the alias on different folders on inetpub/wwwroot in IIS

http://kpi.xxx.yyy >>> folder KPI;

http://kpc.xxx.yyy >>> folder KPC.

I have find in Google without success.

How to do resolve this?

Can you help me?

Thank you in advance for any help, really appreciated.

答:
Please, try this Default.asp in your directory inetpub/wwwroot :

```<code><%
Dim strProtocol
Dim strDomain
Dim strFullUrl

If lcase(Request.ServerVariables("HTTPS")) = "on" Then
    strProtocol = "https"
Else
    strProtocol = "http"
End If

strDomain= Request.ServerVariables("SERVER_NAME")

strFullUrl = strProtocol & "://" & strDomain & "/"

If strFullUrl = "http://kpi.xxx.yyy/" then
   Response.Redirect("http://kpi.xxx.yyy/folder KPI/")
ElseIf strFullUrl = "http://kpc.xxx.yyy/" then
   Response.Redirect("http://kpc.xxx.yyy/folder KPC/")
End If

%>
</code>```

Body:
Please, try this Default.asp in your directory inetpub/wwwroot :

<%
Dim strProtocol
Dim strDomain
Dim strFullUrl

If lcase(Request.ServerVariables("HTTPS")) = "on" Then
    strProtocol = "https"
Else
    strProtocol = "http"
End If

strDomain= Request.ServerVariables("SERVER_NAME")

strFullUrl = strProtocol & "://" & strDomain & "/"

If strFullUrl = "http://kpi.xxx.yyy/" then
   Response.Redirect("http://kpi.xxx.yyy/folder KPI/")
ElseIf strFullUrl = "http://kpc.xxx.yyy/" then
   Response.Redirect("http://kpc.xxx.yyy/folder KPC/")
End If

%>


问:
Dispatching clear state action in redux
I'm using redux in my react project. My question is how to clear state when some works that use state finished.

For example, I have search state in my redux store.

```<code>search:{
  status: 'INIT',
  result: [],
}
</code>```

Since my search is an async request, it has status field.

when the user searches a word, it will dispatch 'FETCH_SEARCH' to make status to 'LOADING'.

when fetch done, it will dispatch 'SUCCESS_SEARCH' or 'FAILURE_SEARCH' to make status 'SUCCESS' or 'FAILURE'.

And in my component that shows the result of a search, it renders depend on search state's status. If a status is 'SUCCESS', it will render the result of the search.

So far, there is no problem.

but what if the user has searched before and try to search again after some works? Since the user has successfully searched before, search state has 'SUCCESS' state. So my component will render 'unwanted' result.

So currently, i dispatch 'CLEAR_SEARCH' action to initialize search state.

My question is how to clear redux state after some submission has done.
Am i doing correctly? Or is it anti-pattern?

答:
I've done this before and what I do is follow a workflow.

After a search submission you shouldn't clear state. You should reset it when the user searches again.

Let's say the user searches "Term A". You "SEARCH_SUCCESS" is set and it's rendering the results. When he searches again put that state to "SEARCHING" or "LOADING" as you have it.

Now in your render method if you have something like

```<code>// etc..

if (isLoading) {
  return <LoadingComponent />
}

// etc..
</code>```

You will render a loading before rendering any results. Then your search action should set either the SUCCESS or FAILURE and if you have your components mapped out correctly it should be really straightforward.

EDIT

After a brief discussion in the comment section you wanted INIT only at the start (the first ever time it's rendered) but then resetting the state still.

So you can go for this workflow:

First time:
-> INIT -> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE

Second time (still in same screen):
-> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE

And then you would have the desired workflow.

Hope I helped

Title: Dispatching clear state action in redux

Body:
I'm using redux in my react project. My question is how to clear state when some works that use state finished.

For example, I have search state in my redux store.

search:{
  status: 'INIT',
  result: [],
}

Since my search is an async request, it has status field.

when the user searches a word, it will dispatch 'FETCH_SEARCH' to make status to 'LOADING'.

when fetch done, it will dispatch 'SUCCESS_SEARCH' or 'FAILURE_SEARCH' to make status 'SUCCESS' or 'FAILURE'.

And in my component that shows the result of a search, it renders depend on search state's status. If a status is 'SUCCESS', it will render the result of the search.

So far, there is no problem.

but what if the user has searched before and try to search again after some works? Since the user has successfully searched before, search state has 'SUCCESS' state. So my component will render 'unwanted' result.

So currently, i dispatch 'CLEAR_SEARCH' action to initialize search state.

My question is how to clear redux state after some submission has done.
Am i doing correctly? Or is it anti-pattern?

Body:
I've done this before and what I do is follow a workflow.

After a search submission you shouldn't clear state. You should reset it when the user searches again.

Let's say the user searches "Term A". You "SEARCH_SUCCESS" is set and it's rendering the results. When he searches again put that state to "SEARCHING" or "LOADING" as you have it.

Now in your render method if you have something like

// etc..

if (isLoading) {
  return <LoadingComponent />
}

// etc..

You will render a loading before rendering any results. Then your search action should set either the SUCCESS or FAILURE and if you have your components mapped out correctly it should be really straightforward.

EDIT

After a brief discussion in the comment section you wanted INIT only at the start (the first ever time it's rendered) but then resetting the state still.

So you can go for this workflow:

First time:
-> INIT -> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE

Second time (still in same screen):
-> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE

And then you would have the desired workflow.

Hope I helped


问:
operator is invalid for atomic vectors Error with imported data from SQL to shiny
I try to get my raw data from SQL Server using (RODBCext) and then deploy my results to my shinyApp
this is my code:

```<code>    #loading Packages
        library(RODBC)
        library(shiny)
        library(rsconnect)
        library(dplyr)
        library(RODBCext)
 #global code
        #connect to DB
        Test <- odbcDriverConnect("driver={SQL Server};server=***********;database=*******;uid=*****;pwd=******")
        #build query
        Orders<- sqlExecute(Test,"
                            SELECT
                            WHWorkOrderHeaderId
                            ,OtherLangDescription
                            FROM   Warehouse.WHWorkOrderDetails
                            INNER JOIN Warehouse.WHWorkOrderHeader AS WHH
                            ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = WHH.ID
                            INNER JOIN Warehouse.StockItems
                            ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id
                            WHERE Type = 'IO'
                            ORDER BY OtherLangDescription ASC")
            #close the connection
            odbcClose(Test)
            #return results
            Orders$OtherLangDescription <- as.factor(Orders$OtherLangDescription)
            orderList <- unique(Orders$OtherLangDescription)
            ListId <- lapply(orderList, function(x) subset(Orders, OtherLangDescription == x)$WHWorkOrderHeaderId)
            Initial_Tab <- lapply(ListId, function(x) subset(Orders, WHWorkOrderHeaderId %in% x)$OtherLangDescription)
            Correlation_Tab <- mapply(function(Product, ID) table(Product)/length(ID),Initial_Tab, ListId)
            colnames(Correlation_Tab) <- orderList
            cor_per<- round(Correlation_Tab*100,2)
            DF<-data.frame(row=rownames(cor_per)[row(cor_per)],
            col=colnames(cor_per)[col(cor_per)], corr=c(cor_per))
            DF

 #ui.R code
        ui <- fluidPage(
          titlePanel("Item Correlation"),
          sidebarPanel(
            selectInput("Item","Select Item",choices= DF$FirstItem),
            # ,selectInput("Item","SelectItem",choices= DF$SecondItem),

          ),
          mainPanel(
            tableOutput("Itemcorr")
          )
        )

        #server.R code
        server <- function(input,output){
          data<- reactive({
            input$Item

            })
          output$Itemcorr <- renderTable({
            DF %>% filter(FirstItem == data()) %>% arrange(desc(X.Correlation))
          })
        }

        shinyApp(ui, server)
</code>```

i want to get my data from SQL directly without exporting to excel
 But i have an error when i run my shinyapp (Error in Orders$OtherLangDescription :
  $ operator is invalid for atomic vectors)

答: I Solved this error by replacing sqlExecute with sqlQuery

Body:
I try to get my raw data from SQL Server using (RODBCext) and then deploy my results to my shinyApp
this is my code:

    #loading Packages
        library(RODBC)
        library(shiny)
        library(rsconnect)
        library(dplyr)
        library(RODBCext)
 #global code
        #connect to DB
        Test <- odbcDriverConnect("driver={SQL Server};server=***********;database=*******;uid=*****;pwd=******")
        #build query
        Orders<- sqlExecute(Test,"
                            SELECT
                            WHWorkOrderHeaderId
                            ,OtherLangDescription
                            FROM   Warehouse.WHWorkOrderDetails
                            INNER JOIN Warehouse.WHWorkOrderHeader AS WHH
                            ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = WHH.ID
                            INNER JOIN Warehouse.StockItems
                            ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id
                            WHERE Type = 'IO'
                            ORDER BY OtherLangDescription ASC")
            #close the connection
            odbcClose(Test)
            #return results
            Orders$OtherLangDescription <- as.factor(Orders$OtherLangDescription)
            orderList <- unique(Orders$OtherLangDescription)
            ListId <- lapply(orderList, function(x) subset(Orders, OtherLangDescription == x)$WHWorkOrderHeaderId)
            Initial_Tab <- lapply(ListId, function(x) subset(Orders, WHWorkOrderHeaderId %in% x)$OtherLangDescription)
            Correlation_Tab <- mapply(function(Product, ID) table(Product)/length(ID),Initial_Tab, ListId)
            colnames(Correlation_Tab) <- orderList
            cor_per<- round(Correlation_Tab*100,2)
            DF<-data.frame(row=rownames(cor_per)[row(cor_per)],
            col=colnames(cor_per)[col(cor_per)], corr=c(cor_per))
            DF

 #ui.R code
        ui <- fluidPage(
          titlePanel("Item Correlation"),
          sidebarPanel(
            selectInput("Item","Select Item",choices= DF$FirstItem),
            # ,selectInput("Item","SelectItem",choices= DF$SecondItem),

          ),
          mainPanel(
            tableOutput("Itemcorr")
          )
        )

        #server.R code
        server <- function(input,output){
          data<- reactive({
            input$Item

            })
          output$Itemcorr <- renderTable({
            DF %>% filter(FirstItem == data()) %>% arrange(desc(X.Correlation))
          })
        }

        shinyApp(ui, server)

i want to get my data from SQL directly without exporting to excel
 But i have an error when i run my shinyapp (Error in Orders$OtherLangDescription :
  $ operator is invalid for atomic vectors)