问:
Simplest and understandable example of volatile keyword in Java
I'm reading about volatile keyword in Java and completely understand the theory part of it.

But, what I'm searching for is, a good case example, which shows what would happen if variable wasn't volatile and if it were.

Below code snippet doesn't work as expected (taken from here):

```<code>class Test extends Thread {

    boolean keepRunning = true;

    public void run() {
        while (keepRunning) {
        }

        System.out.println("Thread terminated.");
    }

    public static void main(String[] args) throws InterruptedException {
        Test t = new Test();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println("keepRunning set to false.");
    }
}
</code>```

Ideally, if keepRunning wasn't volatile, thread should keep on running indefinitely. But, it does stop after few seconds.

I've got two basic questions:

Can anyone explain volatile with example? Not with theory from JLS.

Is volatile substitute for synchronization? Does it achieve atomicity?

答:
Variable Volatile: Volatile Keyword is applicable to variables. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

```<code>Access_Modifier volatile DataType Variable_Name;
</code>```

Volatile Field: An indication to the VM that multiple threads may try to access/update the field's value at the same time. To a special kind of instance variables which has to shared among all the threads with Modified value. Similar to Static(Class) variable, Only one copy of volatile value is cached in main memory, So that before doing any ALU Operations each thread has to read the updated value from Main memory after ALU operation it has to write to main memory direclty. (A write to a volatile variable v synchronizes-with all subsequent reads of v by any thread) This means that changes to a volatile variable are always visible to other threads.

Here to a nonvoltaile variable if Thread t1 changes the value in t1's cache, Thread t2 can't access the changed value untill t1 writes, t2 read from main memory for the most recent modified value, which may lead to Data-Inconsistancy.

volatile cannot be cached - assembler

```<code>    +--------------+--------+-------------------------------------+
    |  Flag Name   |  Value | Interpretation                      |
    +--------------+--------+-------------------------------------+
    | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.|
    +--------------+--------+-------------------------------------+
    |ACC_TRANSIENT | 0x0080 | Declared transient; not written or  |
    |              |        | read by a persistent object manager.|
    +--------------+--------+-------------------------------------+
</code>```

Shared Variables:
Memory that can be shared between threads is called shared memory or heap memory. All instance fields, static fields, and array elements are stored in heap memory.

Synchronization: synchronized is applicable to methods, blocks. allows to execute only 1-thread at a time on object. If t1 takes control, then remaining threads has to wait untill it release the control.

Example:

public class VolatileTest implements Runnable {

    private static final int MegaBytes = 10241024;

    private static final Object counterLock = new Object();
    private static int counter = 0;
    private static volatile int counter1 = 0;

    private volatile int counter2 = 0;
    private int counter3 = 0;

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            concurrentMethodWrong();
        }

    }

    void addInstanceVolatile() {
        synchronized (counterLock) {
            counter2 = counter2 + 1;
            System.out.println( Thread.currentThread().getName() +"\t\t « InstanceVolatile :: "+ counter2);
        }
    }

    public void concurrentMethodWrong() {
        counter = counter + 1;
        System.out.println( Thread.currentThread().getName() +" « Static :: "+ counter);
        sleepThread( 1/4 );

        counter1 = counter1 + 1;
        System.out.println( Thread.currentThread().getName() +"\t « StaticVolatile :: "+ counter1);
        sleepThread( 1/4 );

        addInstanceVolatile();
        sleepThread( 1/4 );

        counter3 = counter3 + 1;
        sleepThread( 1/4 );
        System.out.println( Thread.currentThread().getName() +"\t\t\t\t\t « Instance :: "+ counter3);
    }
    public static void main(String[] args) throws InterruptedException {
        Runtime runtime = Runtime.getRuntime();

        int availableProcessors = runtime.availableProcessors();
        System.out.println("availableProcessors :: "+availableProcessors);
        System.out.println("MAX JVM will attempt to use : "+ runtime.maxMemory() / MegaBytes );
        System.out.println("JVM totalMemory also equals to initial heap size of JVM : "+ runtime.totalMemory() / MegaBytes );
        System.out.println("Returns the amount of free memory in the JVM : "+ untime.freeMemory() / MegaBytes );
        System.out.println(" ===== ----- ===== ");

        VolatileTest volatileTest = new VolatileTest();
        Thread t1 = new Thread( volatileTest );
        t1.start();

        Thread t2 = new Thread( volatileTest );
        t2.start();

        Thread t3 = new Thread( volatileTest );
        t3.start();

        Thread t4 = new Thread( volatileTest );
        t4.start();

        Thread.sleep( 10 );;

        Thread optimizeation = new Thread() {
            @Override public void run() {
                System.out.println("Thread Start.");

                Integer appendingVal = volatileTest.counter2 + volatileTest.counter2 + volatileTest.counter2;

                System.out.println("End of Thread." + appendingVal);
            }
        };
        optimizeation.start();
    }

    public void sleepThread( long sec ) {
        try {
            Thread.sleep( sec * 1000 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
```

Static[Class Field] vs Volatile[Instance Field] - Both are not cached by threads

Static fields are common to all threads and get stored in Method Area. Static with volatile no use. Static field cant be serialized.

Volatile mainly used with instance variable which get stored in heap area. The main use of volatile is to maintain updated value over all the Threads. instance volatile field can be Serialized.

@see

Volatile Vs Static in java

System with multiple cores sharing an L2 cache

JVM memory model

Body:
I'm reading about volatile keyword in Java and completely understand the theory part of it.

But, what I'm searching for is, a good case example, which shows what would happen if variable wasn't volatile and if it were.

Below code snippet doesn't work as expected (taken from here):

class Test extends Thread {

    boolean keepRunning = true;

    public void run() {
        while (keepRunning) {
        }

        System.out.println("Thread terminated.");
    }

    public static void main(String[] args) throws InterruptedException {
        Test t = new Test();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println("keepRunning set to false.");
    }
}

Ideally, if keepRunning wasn't volatile, thread should keep on running indefinitely. But, it does stop after few seconds.

I've got two basic questions:

Can anyone explain volatile with example? Not with theory from JLS.

Is volatile substitute for synchronization? Does it achieve atomicity?

Body:
Variable Volatile: Volatile Keyword is applicable to variables. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

Access_Modifier volatile DataType Variable_Name;

Volatile Field: An indication to the VM that multiple threads may try to access/update the field's value at the same time. To a special kind of instance variables which has to shared among all the threads with Modified value. Similar to Static(Class) variable, Only one copy of volatile value is cached in main memory, So that before doing any ALU Operations each thread has to read the updated value from Main memory after ALU operation it has to write to main memory direclty. (A write to a volatile variable v synchronizes-with all subsequent reads of v by any thread) This means that changes to a volatile variable are always visible to other threads.

Here to a nonvoltaile variable if Thread t1 changes the value in t1's cache, Thread t2 can't access the changed value untill t1 writes, t2 read from main memory for the most recent modified value, which may lead to Data-Inconsistancy.

volatile cannot be cached - assembler

    +--------------+--------+-------------------------------------+
    |  Flag Name   |  Value | Interpretation                      |
    +--------------+--------+-------------------------------------+
    | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.|
    +--------------+--------+-------------------------------------+
    |ACC_TRANSIENT | 0x0080 | Declared transient; not written or  |
    |              |        | read by a persistent object manager.|
    +--------------+--------+-------------------------------------+

Shared Variables:
Memory that can be shared between threads is called shared memory or heap memory. All instance fields, static fields, and array elements are stored in heap memory.

Synchronization: synchronized is applicable to methods, blocks. allows to execute only 1-thread at a time on object. If t1 takes control, then remaining threads has to wait untill it release the control.

Example:

public class VolatileTest implements Runnable {

    private static final int MegaBytes = 10241024;

    private static final Object counterLock = new Object();
    private static int counter = 0;
    private static volatile int counter1 = 0;

    private volatile int counter2 = 0;
    private int counter3 = 0;

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            concurrentMethodWrong();
        }

    }

    void addInstanceVolatile() {
        synchronized (counterLock) {
            counter2 = counter2 + 1;
            System.out.println( Thread.currentThread().getName() +"\t\t « InstanceVolatile :: "+ counter2);
        }
    }

    public void concurrentMethodWrong() {
        counter = counter + 1;
        System.out.println( Thread.currentThread().getName() +" « Static :: "+ counter);
        sleepThread( 1/4 );

        counter1 = counter1 + 1;
        System.out.println( Thread.currentThread().getName() +"\t « StaticVolatile :: "+ counter1);
        sleepThread( 1/4 );

        addInstanceVolatile();
        sleepThread( 1/4 );

        counter3 = counter3 + 1;
        sleepThread( 1/4 );
        System.out.println( Thread.currentThread().getName() +"\t\t\t\t\t « Instance :: "+ counter3);
    }
    public static void main(String[] args) throws InterruptedException {
        Runtime runtime = Runtime.getRuntime();

        int availableProcessors = runtime.availableProcessors();
        System.out.println("availableProcessors :: "+availableProcessors);
        System.out.println("MAX JVM will attempt to use : "+ runtime.maxMemory() / MegaBytes );
        System.out.println("JVM totalMemory also equals to initial heap size of JVM : "+ runtime.totalMemory() / MegaBytes );
        System.out.println("Returns the amount of free memory in the JVM : "+ untime.freeMemory() / MegaBytes );
        System.out.println(" ===== ----- ===== ");

        VolatileTest volatileTest = new VolatileTest();
        Thread t1 = new Thread( volatileTest );
        t1.start();

        Thread t2 = new Thread( volatileTest );
        t2.start();

        Thread t3 = new Thread( volatileTest );
        t3.start();

        Thread t4 = new Thread( volatileTest );
        t4.start();

        Thread.sleep( 10 );;

        Thread optimizeation = new Thread() {
            @Override public void run() {
                System.out.println("Thread Start.");

                Integer appendingVal = volatileTest.counter2 + volatileTest.counter2 + volatileTest.counter2;

                System.out.println("End of Thread." + appendingVal);
            }
        };
        optimizeation.start();
    }

    public void sleepThread( long sec ) {
        try {
            Thread.sleep( sec * 1000 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Static[Class Field] vs Volatile[Instance Field] - Both are not cached by threads

Static fields are common to all threads and get stored in Method Area. Static with volatile no use. Static field cant be serialized.

Volatile mainly used with instance variable which get stored in heap area. The main use of volatile is to maintain updated value over all the Threads. instance volatile field can be Serialized.

@see

Volatile Vs Static in java

System with multiple cores sharing an L2 cache

JVM memory model


来源: stackexchange

问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答:
Java has hashes, but because of strong typing they're not quite as flexible as hashes in Perl. Multidimensional hashes are harder to work with. In Perl, you can just declare a hash and let autovivification create the nested hashes on demand.

```<code>my %hash;
$hash{a}{b} = 1;
</code>```

In Java, you have to declare it to be a hash-of-hashes up-front.

```<code>Map<String,Map<String,Integer>> hash = new HashMap<String,HashMap<String,Integer>>();
hash.put("a", new HashMap<String, Integer>());
hash.get("a").put("b", new Integer(1));
</code>```

For every extra dimension you need to add another nesting of Map<K,V> to the declaration. Aside from being tedious, this isn't very OO.

ContentLicense: CC BY-SA 3.0

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

Body:
Java has hashes, but because of strong typing they're not quite as flexible as hashes in Perl. Multidimensional hashes are harder to work with. In Perl, you can just declare a hash and let autovivification create the nested hashes on demand.

my %hash;
$hash{a}{b} = 1;

In Java, you have to declare it to be a hash-of-hashes up-front.

Map<String,Map<String,Integer>> hash = new HashMap<String,HashMap<String,Integer>>();
hash.put("a", new HashMap<String, Integer>());
hash.get("a").put("b", new Integer(1));

For every extra dimension you need to add another nesting of Map<K,V> to the declaration. Aside from being tedious, this isn't very OO.

ContentLicense: CC BY-SA 2.5


问:
Select element in the same list as element with "title"
I have the following code:

```<code><div id="filebrowser" class="jstree jstree-1 jstree-grid-cell jstree-default jstree-checkbox-selection" role="tree" aria-multiselectable="true" tabindex="0" aria-activedescendant="-3" aria-busy="false" aria-selected="false">
    <ul class="jstree-container-ul jstree-children" role="group">
        <li role="treeitem" aria-selected="false" aria-level="1" aria-labelledby="-3_anchor" aria-expanded="false" id="-3" class="jstree-node  jstree-last jstree-closed" aria-busy="false">
            <i class="jstree-icon jstree-ocl" role="presentation"></i>
            <a class="jstree-anchor jstree-grid-col-0" href="#" tabindex="-1" id="-3_anchor" title="/">
                <i class="jstree-icon jstree-checkbox" role="presentation"></i>
                <i class="jstree-icon jstree-themeicon glyphicon glyphicon-folder-close jstree-themeicon-custom" role="presentation"></i>/
            </a>
        </li>
    </ul>
</div>
</code>```

Screenshot

For my Selenium testing I need to click on the , which is marked red in the screenshot. I would like to click on this in the list that also has and  element that has a title= attribute. Is that possible?

For the background: I would like to select different files in given jstree and point on these files by setting their names as global values. If I would like to select "/", "etc/", "testdirectory" and then "test_file.txt".

答:
To click on the WebElement represented as  you can use the following line of code :

```<code>driver.find_element_by_xpath("//li[@role='treeitem']/i[@class='jstree-icon jstree-ocl' and @role='presentation']").click()
</code>```

But looking at the HTML seems we may have to invoke click() method on the  tag as follows :

```<code>driver.find_element_by_xpath("//li[@role='treeitem']//a[@class='jstree-anchor jstree-grid-col-0']").click()
</code>```

Body:
I have the following code:

                /

Screenshot

For my Selenium testing I need to click on the , which is marked red in the screenshot. I would like to click on this in the list that also has and  element that has a title= attribute. Is that possible?

For the background: I would like to select different files in given jstree and point on these files by setting their names as global values. If I would like to select "/", "etc/", "testdirectory" and then "test_file.txt".

Body:
To click on the WebElement represented as <i class="jstree-icon jstree-ocl"> you can use the following line of code :

driver.find_element_by_xpath("//li[@role='treeitem']/i[@class='jstree-icon jstree-ocl' and @role='presentation']").click()

But looking at the HTML seems we may have to invoke click() method on the <a> tag as follows :

driver.find_element_by_xpath("//li[@role='treeitem']//a[@class='jstree-anchor jstree-grid-col-0']").click()


问:
Json node get asLocalDate
Good day,

Please assist, I checked Jackson JsonNode  but I can't seem to find what am looking for.

I need to know how to get JsonNode as LocalDate

```<code>// Example : I can get int value like :

ObjectMapper mapper = new ObjectMapper();
final JsonNode data =mapper.readTree(json);
Int myNumberInt = data.get ("ngNumberInt").asInt();
</code>```

How about LocalDate, how do I get it from JsonNode?

In my mind, am wishing there was

```<code>LocalDate dateCreated = data.get ("ngDate").asLocalDate();
</code>```

答:
JsonNode methods will only give you the JSON data types. However you can use your ObjectMapper instance to deserialize a LocalDate.

```<code>objectMapper.readValue(data, LocalDate.class)
</code>```

You will need to include jackson-modules-java8 if you haven't already. This includes a serializer/deserializer for Java's LocalDate.

Title: Json node get asLocalDate

Body:
Good day,

Please assist, I checked Jackson JsonNode  but I can't seem to find what am looking for.

I need to know how to get JsonNode as LocalDate

// Example : I can get int value like :

ObjectMapper mapper = new ObjectMapper();
final JsonNode data =mapper.readTree(json);
Int myNumberInt = data.get ("ngNumberInt").asInt();

How about LocalDate, how do I get it from JsonNode?

In my mind, am wishing there was

LocalDate dateCreated = data.get ("ngDate").asLocalDate();

Body:
JsonNode methods will only give you the JSON data types. However you can use your ObjectMapper instance to deserialize a LocalDate.

objectMapper.readValue(data, LocalDate.class)

You will need to include jackson-modules-java8 if you haven't already. This includes a serializer/deserializer for Java's LocalDate.


问:
How do I get batch to recognise a folder with a . in as a folder?
I have a batch file which needs to rename a folder from Profile.Win7 to Profile.Win7.%currentdate%.

Right now I'm just using the command

```<code>move /y %userprofileaddress%\Profile.Win7 %userprofileaddress%\%backupfolder%
</code>```

which doesn't throw an error (as far as I can see) but just doesn't do anything.

The folder isn't in use, so any ideas?

Edit: It works now... I wasn't running as admin. facepalm

答:
I think that it is easier to obtain answers if you directly describe the corresponding processing and results of the batch file in the question.

Both works well and not work examples. And if there are error messages etc.

According to the contents of the current question, it seems that it renames the folder itself rather than moving or copying the files in the folder.

In that case, if there is a program using the corresponding folder and files and folders in it, you should not be able to rename.

Please check whether such a situation has occurred.

Body:
I have a batch file which needs to rename a folder from Profile.Win7 to Profile.Win7.%currentdate%.

Right now I'm just using the command

move /y %userprofileaddress%\Profile.Win7 %userprofileaddress%\%backupfolder%

which doesn't throw an error (as far as I can see) but just doesn't do anything.

The folder isn't in use, so any ideas?

Edit: It works now... I wasn't running as admin. facepalm


问:
How to update component state on redux state change?
Since I have a component with forms, I need the forms to be connected to the component state. The initial data comes from Redux so try to initialize and update the component by setting the state with the props:

```<code>componentWillMount = () => {
  this.setState({
    language: this.props.language || 'en'
  })
}
</code>```

language is a connected prop and I checked that it is updated in the store.

```<code>const mapStateToProps = state => ({
  language: state.language
})
</code>```

I also tried to use componentWillReceiveProps and componentWillUpdate but it doesn't work. I get the initial state, and even though the store and the connected props change, the component's state doesn't update.

```<code>{this.props.language} // updates
{this.state.language} // doesn't change
</code>```

What is the correct way to manage forms from Redux data?

The render part:

```<code>render () {
  const {classes, theme, web} = this.props

  const language = (
    <CardContent>
      <Typography type="headline">
        Language
      </Typography>
      <Divider/>
      <form className={classes.container} autoComplete="off">
        <FormControl fullWidth margin="normal">
          <InputLabel htmlFor="language">Select Block</InputLabel>
          <Select
            value={this.state.language} // <==================== language
            onChange={this.handleLanguaheChange}
            input={<Input id="language"/>}
          >
            <MenuItem value={'en'}>English</MenuItem>
            <MenuItem value={'he'}>עברית</MenuItem>
          </Select>
        </FormControl>
      </form>
    </CardContent>
  )
  ...

  return (
      <Grid
        container
        spacing={theme.spacing.unit * 3}
        justify={'space-between'}
        className={classes.gridWrap}
      >
        <Grid item xs={6}>
          <Card className={classes.card}>
            {language}
          </Card>
...
</code>```

答:
even though the store and the connected props change, the component's state doesn't update

The way you have it written, the state won't update unless you explicitly update it using setState() (most likely in the componentWillReceiveProps() method).

When you use mapStateToProps() with the Redux connect() HOC, you are mapping your Redux state to your component through its props, so in your case this.props.language will update when the Redux stored updates.

Body:
Since I have a component with forms, I need the forms to be connected to the component state. The initial data comes from Redux so try to initialize and update the component by setting the state with the props:

componentWillMount = () => {
  this.setState({
    language: this.props.language || 'en'
  })
}

language is a connected prop and I checked that it is updated in the store.

const mapStateToProps = state => ({
  language: state.language
})

I also tried to use componentWillReceiveProps and componentWillUpdate but it doesn't work. I get the initial state, and even though the store and the connected props change, the component's state doesn't update.

{this.props.language} // updates
{this.state.language} // doesn't change

What is the correct way to manage forms from Redux data?

The render part:

render () {
  const {classes, theme, web} = this.props

  const language = (
    <CardContent>
      <Typography type="headline">
        Language
      </Typography>
      <Divider/>
      <form className={classes.container} autoComplete="off">
        <FormControl fullWidth margin="normal">
          <InputLabel htmlFor="language">Select Block</InputLabel>
          <Select
            value={this.state.language} // <==================== language
            onChange={this.handleLanguaheChange}
            input={<Input id="language"/>}
          >
            <MenuItem value={'en'}>English</MenuItem>
            <MenuItem value={'he'}>עברית</MenuItem>
          </Select>
        </FormControl>
      </form>
    </CardContent>
  )
  ...

  return (
      <Grid
        container
        spacing={theme.spacing.unit * 3}
        justify={'space-between'}
        className={classes.gridWrap}
      >
        <Grid item xs={6}>
          <Card className={classes.card}>
            {language}
          </Card>
...


问:
Return boolean if one element matches among 2 arrays in postgresql
I have 2 arrays in postgresql and I need to return true if there are at least 1 match of element between these 2 arrays no mather if it is same position.

Follows example below:

```<code>select array(select generate_series(0,10)) =
       any(select array(select generate_series(10,11)))
</code>```

it should return true because I have 10 in both arrays

答:
Go for && operator

like

```<code>SELECT ARRAY['apple','cherry','avocado'] && ARRAY['applea','cherrya','avocado']

SELECT ARRAY[1,4,3] && ARRAY[2,1]
</code>```

https://www.postgresql.org/docs/9.6/static/functions-array.html

Body:
I have 2 arrays in postgresql and I need to return true if there are at least 1 match of element between these 2 arrays no mather if it is same position.

Follows example below:

select array(select generate_series(0,10)) =
       any(select array(select generate_series(10,11)))

it should return true because I have 10 in both arrays

Body:
Go for && operator

like

SELECT ARRAY['apple','cherry','avocado'] && ARRAY['applea','cherrya','avocado']

SELECT ARRAY[1,4,3] && ARRAY[2,1]

https://www.postgresql.org/docs/9.6/static/functions-array.html


问:
Server http:/localhost:8080 requires a user name and a password. The server says: XDB
I am trying to access localhost:8080 but it is showing me I need to enter user name and pass word. I remember messing up with the server some 4 months ago while I was trying to develop a web application and hosting my domain name on my pc, Unfortunately I become unsuccessful. While working with servlets I was tring some security features and till some time i did not see and of these pop up windows asking for authentication.

I tried to enter the password that I was playing with but non of those are working. Is there anyway i could get out of this problem?

答:
give username as admin

and leave the password empty


问:
INSERT FROM syntax
logcat

```<code>    12-07 12:24:30.394 7246-7246/me.jaxbot.appfoodgrab E/SQLiteLog: (1) near "FROM": syntax error
    12-07 12:24:30.396 7246-7246/me.jaxbot.appfoodgrab E/AndroidRuntime: FATAL EXCEPTION: main
 Process: me.jaxbot.appfoodgrab, PID: 7246
 android.database.sqlite.SQLiteException: near "FROM": syntax error (code 1): , while compiling: INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('02','Nasi Goreng','5','6','5');
     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
     at me.jaxbot.appfoodgrab.Database.Database.addToCart(Database.java:61)
     at me.jaxbot.appfoodgrab.FoodDetail$1.onClick(FoodDetail.java:55)
     at android.view.View.performClick(View.java:5610)
     at android.view.View$PerformClick.run(View.java:22265)
     at android.os.Handler.handleCallback(Handler.java:751)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    12-07 12:24:30.420 1589-1839/? E/ActivityManager: Found activity ActivityRecord{dc9c9ab u0 me.jaxbot.appfoodgrab/.MainActivity t99 f} in proc activity list using null instead of expected ProcessRecord{226ea2 7246:me.jaxbot.appfoodgrab/u0a82}
    12-07 12:38:42.780 2368-2922/? E/NetworkScheduler: ignoring stale queue check message
</code>```

My coding

```<code>  public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }
</code>```

答:
Your query is wrong

use INSERT INTO instead of INSERT FROM

Try this

```<code>public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT INTO  OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: INSERT FROM syntax

Body:
logcat

    12-07 12:24:30.394 7246-7246/me.jaxbot.appfoodgrab E/SQLiteLog: (1) near "FROM": syntax error
    12-07 12:24:30.396 7246-7246/me.jaxbot.appfoodgrab E/AndroidRuntime: FATAL EXCEPTION: main
 Process: me.jaxbot.appfoodgrab, PID: 7246
 android.database.sqlite.SQLiteException: near "FROM": syntax error (code 1): , while compiling: INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('02','Nasi Goreng','5','6','5');
     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
     at me.jaxbot.appfoodgrab.Database.Database.addToCart(Database.java:61)
     at me.jaxbot.appfoodgrab.FoodDetail$1.onClick(FoodDetail.java:55)
     at android.view.View.performClick(View.java:5610)
     at android.view.View$PerformClick.run(View.java:22265)
     at android.os.Handler.handleCallback(Handler.java:751)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    12-07 12:24:30.420 1589-1839/? E/ActivityManager: Found activity ActivityRecord{dc9c9ab u0 me.jaxbot.appfoodgrab/.MainActivity t99 f} in proc activity list using null instead of expected ProcessRecord{226ea2 7246:me.jaxbot.appfoodgrab/u0a82}
    12-07 12:38:42.780 2368-2922/? E/NetworkScheduler: ignoring stale queue check message

My coding

  public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }

Body:
Your query is wrong

use INSERT INTO instead of INSERT FROM

Try this

public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT INTO  OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }


问:
Eclipse hangs in building project after each save
This has become so annoying.
Each time I save an Ant build I get Eclipse in rebuilding itself...
I have Java Project which depends from a non-Java project. When I edit a file in the non-Java project, save, build. I get the whole project sync process launched... 1-5 minutes later I get the prompt back.</p>

答:
You could try to turn off automatic building globally in the Project menu. If you do this, the Build project... and Build all options become enabled, allowing you to manually build when necessary.

Another option may be to set the refresh workspace policy of your executed ANT build (granted you are using the Eclipse AntRunner): in the Run configuration on the refresh tab you could manually select only to update the project changed by the ANT build.


问:
(Xamarin.Android) Turn camera picture if the device orientation was landscape
I want to make a Xamarin.Android app where I can capture pictures like the camera...

When I take the picture i have to turn the picture in the correct orientation. So when the orientation was landscape or upside down I want to turn it to portrait...
But I don't know how I can do this.

Here is my code

```<code> private async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        _camera.StopPreview();

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.SetMessage("Search for faces...");
        builder.SetTitle("Warten");

        AlertDialog dialog = builder.Create();

        dialog.Show();

        byte[] imageBytes;

        var image = _textureView.Bitmap;

        using (var imageStream = new MemoryStream())
        {
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
            image.Recycle();
            imageBytes = imageStream.ToArray();
        }

        var base64image = Convert.ToBase64String(imageBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        var result = faceRecognition.SendPhoto(base64image);

        dialog.Hide();

        _camera.StartPreview();
    }
</code>```

答:
To solve the problem you have to update your OnSurfaceTextureUpdated function to this and also alowing screen rotations:

```<code>public void OnSurfaceTextureUpdated(SurfaceTexture surface)
    {
    var display = activity.WindowManager.DefaultDisplay;

    if (display.Rotation == SurfaceOrientation.Rotation0)
    {
        _camera.SetDisplayOrientation(90);
    }

    if (display.Rotation == SurfaceOrientation.Rotation90)
    {
        _camera.SetDisplayOrientation(0);
    }

    if (display.Rotation == SurfaceOrientation.Rotation180)
    {
        _camera.SetDisplayOrientation(180);
    }

    if (display.Rotation == SurfaceOrientation.Rotation270)
    {
        _camera.SetDisplayOrientation(180);
    }
}
</code>```

Body:
I want to make a Xamarin.Android app where I can capture pictures like the camera...

When I take the picture i have to turn the picture in the correct orientation. So when the orientation was landscape or upside down I want to turn it to portrait...
But I don't know how I can do this.

Here is my code

 private async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        _camera.StopPreview();

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.SetMessage("Search for faces...");
        builder.SetTitle("Warten");

        AlertDialog dialog = builder.Create();

        dialog.Show();

        byte[] imageBytes;

        var image = _textureView.Bitmap;

        using (var imageStream = new MemoryStream())
        {
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
            image.Recycle();
            imageBytes = imageStream.ToArray();
        }

        var base64image = Convert.ToBase64String(imageBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        var result = faceRecognition.SendPhoto(base64image);

        dialog.Hide();

        _camera.StartPreview();
    }

Body:
To solve the problem you have to update your OnSurfaceTextureUpdated function to this and also alowing screen rotations:

public void OnSurfaceTextureUpdated(SurfaceTexture surface)
    {
    var display = activity.WindowManager.DefaultDisplay;

    if (display.Rotation == SurfaceOrientation.Rotation0)
    {
        _camera.SetDisplayOrientation(90);
    }

    if (display.Rotation == SurfaceOrientation.Rotation90)
    {
        _camera.SetDisplayOrientation(0);
    }

    if (display.Rotation == SurfaceOrientation.Rotation180)
    {
        _camera.SetDisplayOrientation(180);
    }

    if (display.Rotation == SurfaceOrientation.Rotation270)
    {
        _camera.SetDisplayOrientation(180);
    }
}


问:
Creating a table, dropping it and referencing the results
I'm creating a table using multiple subselects. So I am getting data from multiple places within one SQL Database.

What I want is to 1. Set the above as a table itself and 2. create a new table using the above results.

So I will call the above [table1].

I just want to know how to set this as a (temporary) table so i can then start to add new script which I can use to the data I have now received in my new table to display.

答:
You can just write SELECT YOURCOLUMNS INTO #TEMP FROM XXXXX

And then you can start a new script by writing

Note: You new script has to been in the same session when you make use of temp tables

```<code>DROP TABLE IF EXISTS DBO.TEST --This only works on SQL Server 2016

/* Drop Table */
IF OBJECT_ID('dbo.Test', 'U') IS NOT NULL
DROP TABLE dbo.Test;

Create Table dbo.TEST (
COLUMNS DATATYPE NULL
)

Insert into DBO.TEST
SELECT * FROM #TEMP

DROP TABLE #TEMP
</code>```

Body:
You can just write SELECT YOURCOLUMNS INTO #TEMP FROM XXXXX

And then you can start a new script by writing

Note: You new script has to been in the same session when you make use of temp tables

DROP TABLE IF EXISTS DBO.TEST --This only works on SQL Server 2016

/* Drop Table */
IF OBJECT_ID('dbo.Test', 'U') IS NOT NULL
DROP TABLE dbo.Test;

Create Table dbo.TEST (
COLUMNS DATATYPE NULL
)

Insert into DBO.TEST
SELECT * FROM #TEMP

DROP TABLE #TEMP


问:
Is it possible to get the original URL after a 302 .htaccess RedirectMatch?

Hello guys. I started coding my own "URL shortener". The basic idea is you use example.com/12345 to redirect to another URL. This "matching" is done by using .htaccess to redirect stuff towards a script that does (irrelevant for us now) stuff.

My .htaccess currently looks like this:

```<code>RedirectMatch 302 ^/\w{5}$ /redir.php
</code>```

The redirect matches any string of exactly 5 and sends it toward my PHP script where the actual redirection to the expanded URL take place. The only problem is that I was unable to find a proper way of getting the original URL, the matched one into a variable.

As a sidenote the whole thing happens on a VPS set up by me with minimal knowledge, so if this problem can originate from a missing config ($_SERVER['HTTP_REFERER'] doesn't work), then expect my configs to not be 100% correct and by standards.

EDIT: changed from RedirectMatch to RewriteRule, still doesn't work.

```<code>RewriteRule ^\w{5}$ /redir.php [R,L]
</code>```

答:
you can use the following rule:

```<code>RewriteRule ^(\w{5})$ /redir.php?redir=$1 [R,L]
</code>```

this will send the 5 letter string as querystring param redir. Which you can access in redir.php as:

```<code>$_GET['redir']
</code>```

Edit: Or as @LawrenceCherone have suggested you can use $_SERVER['REQUEST_URI'] in redir.php. But for that you have to use NC flag in .htaccess instead, Like:

```<code>RewriteRule ^(\w{5})$ /redir.php [NC,L]
</code>```

Body:
Hello guys. I started coding my own "URL shortener". The basic idea is you use example.com/12345 to redirect to another URL. This "matching" is done by using .htaccess to redirect stuff towards a script that does (irrelevant for us now) stuff.

My .htaccess currently looks like this:

RedirectMatch 302 ^/\w{5}$ /redir.php

The redirect matches any string of exactly 5 and sends it toward my PHP script where the actual redirection to the expanded URL take place. The only problem is that I was unable to find a proper way of getting the original URL, the matched one into a variable.

As a sidenote the whole thing happens on a VPS set up by me with minimal knowledge, so if this problem can originate from a missing config ($_SERVER['HTTP_REFERER'] doesn't work), then expect my configs to not be 100% correct and by standards.

EDIT: changed from RedirectMatch to RewriteRule, still doesn't work.

RewriteRule ^\w{5}$ /redir.php [R,L]

Body:
you can use the following rule:

RewriteRule ^(\w{5})$ /redir.php?redir=$1 [R,L]

this will send the 5 letter string as querystring param redir. Which you can access in redir.php as:

$_GET['redir']

Edit: Or as @LawrenceCherone have suggested you can use $_SERVER['REQUEST_URI'] in redir.php. But for that you have to use NC flag in .htaccess instead, Like:

RewriteRule ^(\w{5})$ /redir.php [NC,L]


问:
Doesn't Picasso support to download images which uses https protocol
Hello I am using the Picasso library to download the images from URL.

URL : https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/s200x200/1472865_191408954385576_14109897_n.jpg

URL is using https protocol, here it is not working for me to download the images of https protocol using Picasso.

Doesn't it support to download the images which uses https protocol, it worked for me only if I use http proctocol ?

Here I am trying to get bitmap which is using https protocol

```<code>com.squareup.picasso.Target target = new com.squareup.picasso.Target() {

@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom loadedFrom) {
    userProfile.setBitmap(bitmap);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    });
}

@Override
public void onBitmapFailed(Drawable drawable) {
    userProfile.setBitmap(null);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    }).execute();
}

@Override
public void onPrepareLoad(Drawable drawable) {}
};

Picasso.with(getActivity()).load(imgUrl.toString()).into(target);
</code>```

Any idea ?

答:
```<code> final OkHttpClient client = new OkHttpClient.Builder()
                    .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                    .build();

            Picasso picasso = new Picasso.Builder(mContext)
                    .downloader(new OkHttp3Downloader(client))
                    .build();
picasso .with(mContext).load(YOUR_URL).into(YOUR_IMAGEVIEW);
</code>```

<p>Add </p>

```<code>compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
</code>```

Body:
Hello I am using the Picasso library to download the images from URL.

URL : https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/s200x200/1472865_191408954385576_14109897_n.jpg

URL is using https protocol, here it is not working for me to download the images of https protocol using Picasso.

Doesn't it support to download the images which uses https protocol, it worked for me only if I use http proctocol ?

Here I am trying to get bitmap which is using https protocol

com.squareup.picasso.Target target = new com.squareup.picasso.Target() {

@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom loadedFrom) {
    userProfile.setBitmap(bitmap);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    });
}

@Override
public void onBitmapFailed(Drawable drawable) {
    userProfile.setBitmap(null);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    }).execute();
}

@Override
public void onPrepareLoad(Drawable drawable) {}
};

Picasso.with(getActivity()).load(imgUrl.toString()).into(target);

Any idea ?

Body:
 final OkHttpClient client = new OkHttpClient.Builder()
                    .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                    .build();

            Picasso picasso = new Picasso.Builder(mContext)
                    .downloader(new OkHttp3Downloader(client))
                    .build();
picasso .with(mContext).load(YOUR_URL).into(YOUR_IMAGEVIEW);

Add

compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'


问:
Splitting a large XML file in Python
I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between  and , then save that into a file, then continue on through the rest of the file.

My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"

I'd rather not use sentinel variables. Is there a pythonic way to get this done?

The file is too big to read into memory.

答: You might consider using the ElementTree iterparse function for this situation.</p>

OwnerDisplayName: benjamin

Title: Splitting a large XML file in Python

OwnerDisplayName: Jeff Bauer


问:
How do I specify the Linq OrderBy argument dynamically?
How do I specify the argument passed to orderby using a value I take as a parameter?

Ex:

```<code>List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}
</code>```

Currently implementation:

```<code>List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();
</code>```

Instead of c.Address, how can I take that as a parameter?

Example

```<code> string param = "City";
 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();
</code>```

答:
To expand on the answer by @Icarus: if you want the return type of the extension method to be an IOrderedQueryable instead of an IQueryable, you can simply cast the result as follows: </p>

```<code>public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
{
    string command = desc ? "OrderByDescending" : "OrderBy";
    var type = typeof(TEntity);
    var property = type.GetProperty(orderByProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExpression = Expression.Lambda(propertyAccess, parameter);
    var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
        source.Expression, Expression.Quote(orderByExpression));
    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}
</code>```

Body:
How do I specify the argument passed to orderby using a value I take as a parameter?

Ex:

List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}

Currently implementation:

List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();

Instead of c.Address, how can I take that as a parameter?

Example

 string param = "City";
 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();

Body:
To expand on the answer by @Icarus: if you want the return type of the extension method to be an IOrderedQueryable instead of an IQueryable, you can simply cast the result as follows:

public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
{
    string command = desc ? "OrderByDescending" : "OrderBy";
    var type = typeof(TEntity);
    var property = type.GetProperty(orderByProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExpression = Expression.Lambda(propertyAccess, parameter);
    var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
        source.Expression, Expression.Quote(orderByExpression));
    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}


问:
Using A Mapping's Properties In A Switch Statement
I am trying to create some sort of mapping and construct a switch statement based on this.

The first thing I tried was this:

```<code>public class Class1
{
    public void Test()
    {
        string testString_A = "A";
        string testString_B = null;
        switch (testString)
        {
            case Options.O1.aName:
                testString_B = Options.O1.bName;
                break;
            case Options.O2.aName:
                testString_B = Options.O2.bName;
                break;

        }
    }
}

public static class Options
{
    public static Option O1 = new Option()
    {
        aName = "A1",
        bName = "B1"
    };

    public static Option O2 = new Option()
    {
        aName = "A2",
        bName = "B2"
    };
}

public class Option
{
    public string aName;
    public string bName;
}
</code>```

In this scenario, compiler complains that a constant value is expected for the switch cases.

So next, I tried the following but it does not work either. The .aName I try to use in the switch statement seems not accessible.

```<code>public Class1()
{

    public void Test()
    {
        string testString = "A1";
        switch (testString)
        {
            case Options.O1.aName:
                ...

        }
    }
}

public static class Options
{
    public static Option_O1 O1 = new Option_O1();
    public static Option_O2 O2 = new Option_O2();
}

public class Option_O1
{
    public const string aName = "A1";
    public const string bName = "B1";
}

public class Option_O2
{
    public const string aName = "A2";
    public const string bName = "B2";
}
</code>```

How can I accomplish what I want?

答:
There's a big difference between a string property / field variable (even if it is static or readonly), and a const string. The switch statement requires either literals, or const values in the case statements.

This explains why your first attempt didn't succeed (Error : "A Constant value is required").

In the second case, although you could obviously do this:

```<code>switch (testString)
{
    case Option_O1.aName:
        return Option_O1.bName;
    case Option_O2.aName:
        return Option_O2.bName;
}
</code>```

but as soon as you try and 'cheat' the constant switch requirement by introducing the static class container, you're back to the same problem, although a more cryptic compiler error:

```<code>case Options.O1.aName: // Cannot be accessed by an instance reference
    return Option_O1.bName;
</code>```

Alternative to switch

I'm guessing here, but it seems that you need to build a run time mapping function.

Assuming that you always want to return the same data type (a string), I would suggest using a Dictionary keyed by the string you are trying to 'switch' on - this mapping can be built up at run time.

Here's an example of a statically bootstrapped map:

```<code>public static class Options
{
    public static Option O1 = new Option()
    {
        aName = "A1",
        bName = "B1"
    };

    public static Option O2 = new Option()
    {
        aName = "A2",
        bName = "B2"
    };
}

private static IDictionary<string, Option> myOptionMap = new []
{
    Options.O1, Options.O2
}
.ToDictionary(x => x.aName);
</code>```

Which you can use like so:

```<code>public string Test(string someAName)
{
    if (myOptionMap.TryGetValue(someAName, out var myOption))
    {
        return myOption.bName;
    }
    // Oops not found
    return string.Empty;
}
</code>```

Unless there's more to this than your MVP, it's unlikely that you'll want to subclass your options per instance - Option_O1

Body:
I am trying to create some sort of mapping and construct a switch statement based on this.

The first thing I tried was this:

public class Class1
{
    public void Test()
    {
        string testString_A = "A";
        string testString_B = null;
        switch (testString)
        {
            case Options.O1.aName:
                testString_B = Options.O1.bName;
                break;
            case Options.O2.aName:
                testString_B = Options.O2.bName;
                break;

        }
    }
}

public static class Options
{
    public static Option O1 = new Option()
    {
        aName = "A1",
        bName = "B1"
    };

    public static Option O2 = new Option()
    {
        aName = "A2",
        bName = "B2"
    };
}

public class Option
{
    public string aName;
    public string bName;
}

In this scenario, compiler complains that a constant value is expected for the switch cases.

So next, I tried the following but it does not work either. The .aName I try to use in the switch statement seems not accessible.

public Class1()
{

    public void Test()
    {
        string testString = "A1";
        switch (testString)
        {
            case Options.O1.aName:
                ...

        }
    }
}

public static class Options
{
    public static Option_O1 O1 = new Option_O1();
    public static Option_O2 O2 = new Option_O2();
}

public class Option_O1
{
    public const string aName = "A1";
    public const string bName = "B1";
}

public class Option_O2
{
    public const string aName = "A2";
    public const string bName = "B2";
}

How can I accomplish what I want?

Body:
There's a big difference between a string property / field variable (even if it is static or readonly), and a const string. The switch statement requires either literals, or const values in the case statements.

This explains why your first attempt didn't succeed (Error : "A Constant value is required").

In the second case, although you could obviously do this:

switch (testString)
{
    case Option_O1.aName:
        return Option_O1.bName;
    case Option_O2.aName:
        return Option_O2.bName;
}

but as soon as you try and 'cheat' the constant switch requirement by introducing the static class container, you're back to the same problem, although a more cryptic compiler error:

case Options.O1.aName: // Cannot be accessed by an instance reference
    return Option_O1.bName;

Alternative to switch

I'm guessing here, but it seems that you need to build a run time mapping function.

Assuming that you always want to return the same data type (a string), I would suggest using a Dictionary keyed by the string you are trying to 'switch' on - this mapping can be built up at run time.

Here's an example of a statically bootstrapped map:

public static class Options
{
    public static Option O1 = new Option()
    {
        aName = "A1",
        bName = "B1"
    };

    public static Option O2 = new Option()
    {
        aName = "A2",
        bName = "B2"
    };
}

private static IDictionary<string, Option> myOptionMap = new []
{
    Options.O1, Options.O2
}
.ToDictionary(x => x.aName);

Which you can use like so:

public string Test(string someAName)
{
    if (myOptionMap.TryGetValue(someAName, out var myOption))
    {
        return myOption.bName;
    }
    // Oops not found
    return string.Empty;
}

Unless there's more to this than your MVP, it's unlikely that you'll want to subclass your options per instance - Option_O1


问:
Facing issue during hot deploy of kar file
My kar file contains the following bundles:

a)common-bundle(contains hibernate as the JPA provider)

b)client-bundle(accesses the entityManagerFactory present inside common-bundle and execute business logic)

I've a strange problem while executing hot deploy of kar file on karaf container.

If I try to do a normal deploy(i.e. by stopping the karaf container,putting the kar file into deploy folder and re-starting karaf container),both the bundles get up and running without any problem.

However,when I try to hot deploy the kar file on karaf container,it throws me the following exception:

Dec 06 13:50:50 INFO 141 HHH000204: Processing PersistenceUnitInfo [
          name: MyModelClass
          ...]
  Dec 06 13:50:51 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
  Dec 06 13:50:51 ERROR 187 The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
  javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
          at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
          at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
          at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
  Dec 06 13:50:51 WARN 187 Error creating EntityManagerFactory
  java.lang.RuntimeException: The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:87)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
          at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
          at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
  Caused by: javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
          at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
          ... 21 more
  Dec 06 13:50:51 INFO 141 HHH000204: Processing PersistenceUnitInfo [
          name: MyModelClass
          ...]
  Dec 06 13:50:52 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
  Dec 06 13:50:55 INFO 141 HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
  Dec 06 13:50:55 INFO 141 HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
  Dec 06 13:50:55 INFO 141 HHH000397: Using ASTQueryTranslatorFactory
  Dec 06 13:50:56 WARN 141 HHH000008: JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()

Following are the most important contents of the bundles:

common-bundle:

Persistence.xml:

```<code><persistence version="2.0"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name="my-persistent-unit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds)</non-jta-data-source>
    <class>MyModelClass</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</code>```

blueprint.xml:

```<code><cm:property-placeholder persistent-id='my-persistent-id'
                         update-strategy='reload'
                         placeholder-prefix="${"
                         placeholder-suffix="}">
    <cm:default-properties>
        <cm:property name="driver" value="undefined"/>
        <cm:property name="url" value="undefined"/>
        <cm:property name="username" value="undefined"/>
        <cm:property name="password" value="undefined"/>
    </cm:default-properties>
</cm:property-placeholder>

<jasypt:property-placeholder encryptor-ref="encryptor"/>
<reference id="encryptor" interface="org.jasypt.encryption.StringEncryptor" availability="mandatory"/>

<bean id='myDs'
      class="CustomConnection">
    <property name="connectionFactoryClassName" value="oracle.jdbc.pool.OracleDataSource"/>
    <property name="URL" value="${url}"/>
    <property name="user" value="${username}"/>
    <property name="password" value="${password}"/>
    <property name="validateConnectionOnBorrow" value="true"/>
</bean>

<service ref='myDs' interface='javax.sql.DataSource'>
    <service-properties>
        <entry key='osgi.jndi.service.name' value='jdbc/ds'/>
    </service-properties>
</service>
</code>```

client-bundle:

blueprint.xml

```<code><bean id="myController"
      class="MyController">
    <argument ref="entityManagerFactory"/>
</bean>
<reference id="entityManagerFactory"
           interface="javax.persistence.EntityManagerFactory"
           filter="(osgi.unit.name=my-persistent-unit)"
           availability="mandatory"/>
</code>```

Please help.

答:
Apparently every bundle is using a datasource but no one is creating it.

javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"

You need to create this datasource, for example by dropping a simple XML file into deploy dir:

```<code><?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/yourdb"/>
        <property name="username" value="XXX"/>
        <property name="password" value="XXX"/>
    </bean>

    <service interface="javax.sql.DataSource" ref="dataSource">
        <service-properties>
            <entry key="osgi.jndi.service.name" value="jdbc/ds"/>
        </service-properties>
    </service>
</blueprint>
</code>```

You will need jdbc and jndi features installed.

Body:
My kar file contains the following bundles:

a)common-bundle(contains hibernate as the JPA provider)

b)client-bundle(accesses the entityManagerFactory present inside common-bundle and execute business logic)

I've a strange problem while executing hot deploy of kar file on karaf container.

If I try to do a normal deploy(i.e. by stopping the karaf container,putting the kar file into deploy folder and re-starting karaf container),both the bundles get up and running without any problem.

However,when I try to hot deploy the kar file on karaf container,it throws me the following exception:

Dec 06 13:50:50 INFO 141 HHH000204: Processing PersistenceUnitInfo [
          name: MyModelClass
          ...]
  Dec 06 13:50:51 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
  Dec 06 13:50:51 ERROR 187 The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
  javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
          at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
          at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
          at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
  Dec 06 13:50:51 WARN 187 Error creating EntityManagerFactory
  java.lang.RuntimeException: The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:87)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
          at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
          at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
          at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
          at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
          at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
  Caused by: javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
          at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
          at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
          at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
          ... 21 more
  Dec 06 13:50:51 INFO 141 HHH000204: Processing PersistenceUnitInfo [
          name: MyModelClass
          ...]
  Dec 06 13:50:52 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
  Dec 06 13:50:55 INFO 141 HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
  Dec 06 13:50:55 INFO 141 HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
  Dec 06 13:50:55 INFO 141 HHH000397: Using ASTQueryTranslatorFactory
  Dec 06 13:50:56 WARN 141 HHH000008: JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()

Following are the most important contents of the bundles:

common-bundle:

Persistence.xml:

<persistence version="2.0"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name="my-persistent-unit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds)</non-jta-data-source>
    <class>MyModelClass</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>

blueprint.xml:

<cm:property-placeholder persistent-id='my-persistent-id'
                         update-strategy='reload'
                         placeholder-prefix="${"
                         placeholder-suffix="}">
    <cm:default-properties>
        <cm:property name="driver" value="undefined"/>
        <cm:property name="url" value="undefined"/>
        <cm:property name="username" value="undefined"/>
        <cm:property name="password" value="undefined"/>
    </cm:default-properties>
</cm:property-placeholder>

<jasypt:property-placeholder encryptor-ref="encryptor"/>
<reference id="encryptor" interface="org.jasypt.encryption.StringEncryptor" availability="mandatory"/>

<bean id='myDs'
      class="CustomConnection">
    <property name="connectionFactoryClassName" value="oracle.jdbc.pool.OracleDataSource"/>
    <property name="URL" value="${url}"/>
    <property name="user" value="${username}"/>
    <property name="password" value="${password}"/>
    <property name="validateConnectionOnBorrow" value="true"/>
</bean>

<service ref='myDs' interface='javax.sql.DataSource'>
    <service-properties>
        <entry key='osgi.jndi.service.name' value='jdbc/ds'/>
    </service-properties>
</service>

client-bundle:

blueprint.xml

<bean id="myController"
      class="MyController">
    <argument ref="entityManagerFactory"/>
</bean>
<reference id="entityManagerFactory"
           interface="javax.persistence.EntityManagerFactory"
           filter="(osgi.unit.name=my-persistent-unit)"
           availability="mandatory"/>

Please help.

Body:
Apparently every bundle is using a datasource but no one is creating it.

javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"

You need to create this datasource, for example by dropping a simple XML file into deploy dir:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/yourdb"/>
        <property name="username" value="XXX"/>
        <property name="password" value="XXX"/>
    </bean>

    <service interface="javax.sql.DataSource" ref="dataSource">
        <service-properties>
            <entry key="osgi.jndi.service.name" value="jdbc/ds"/>
        </service-properties>
    </service>
</blueprint>

You will need jdbc and jndi features installed.


问:
Converting a string HEX to color in Windows Phone Runtime c#
I am working on a windows phone game, and I got stuck when I wanted to convert a HEX string into Color. On windows phone 8 silverlight it is not a problem but I cannot find a solution in runtime because it doesn't include Color.FromArgb, or Color.FromName functions.

Does somebody have a function that converts string HEX to Color?

Thanks.

答:
generete a file namely: ColorUtils.cs

```<code>using Windows.UI.Xaml.Markup;
....
 static class ColorUtils
    {
        public static Color GetColorFromHex(string hexString)
        {
            Color x =(Color)XamlBindingHelper.ConvertValue(typeof(Color), hexString);
            return x;
        }
    }
</code>```

and use it something like

```<code>var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#F24C27")):
</code>```

or with alpha

```<code>var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#4CF24C27")):
</code>```

Body:
generete a file namely: ColorUtils.cs

using Windows.UI.Xaml.Markup;
....
 static class ColorUtils
    {
        public static Color GetColorFromHex(string hexString)
        {
            Color x =(Color)XamlBindingHelper.ConvertValue(typeof(Color), hexString);
            return x;
        }
    }

and use it something like

var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#F24C27")):

or with alpha

var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#4CF24C27")):


问:
Execute custom Javascript function on button click in Angular 4
I am beginner in Angular 4 and writing a login component in Angular 4. On click of a Forgot password I want to flip the controls on page to show Reset password elements. I have a javascript function created called rotateCard(this) which I want to call on button click. It is inline javascript in html. I have added html in component.html. below is the code.

but it is giving error as "ReferenceError: rotateCard is not defined"

```<code><form (ngSubmit)="doLoginUser()" #login="ngForm" >

    <div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card-container manual-flip">
                <div class="card">
                    <div class="front">
                        <div class="content">
                            <div class="main">
                                <img src="../../../../images/logo.png" class="crm-logo" width="139" height="43" />
                                <form>
                                    <div class="form-group">
                                        <input type="text" class="form-control crm-field" placeholder="Email"
                                        id="inputEmail" name="username" ngControl="username" required
                                        autofocus [(ngModel)]="username">
                                    </div>
                                    <div class="form-group">
                                        <input type="password" class="form-control crm-field" name="password" placeholder="Password"
                                        id="inputPassword" ngControl="password" required [(ngModel)]="password">
                                    </div>
                                    <button type="button" class="btn btn-primary btn-block orange-btn">LOGIN</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Forgot Password
                                </button>
                            </div>
                        </div>
                    </div> <!-- end login -->
                    <div class="back">
                        <div class="content">
                            <div class="main">
                                <img src="../../../../images/logo.png" class="crm-logo" width="139" height="43" />
                                <p class="title">Forgot Password</p>
                                <form>
                                    <div class="form-group">
                                        <input type="text" class="form-control crm-field" name="email" placeholder="Email">
                                    </div>
                                    <button type="button" class="btn btn-primary btn-block orange-btn">RESET PASSWORD</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Login
                                </button>
                            </div>
                        </div>
                    </div> <!-- end forgot password -->
                </div> <!-- end card -->
            </div> <!-- end card-container -->
        </div> <!-- end col md 5 -->
    </div> <!-- end row -->
    <div class="space-200"></div>
    </div>

</form>

<script src="../../../../js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="../../../../js/bootstrap.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function rotateCard(btn){
        var $card = $(btn).closest('.card-container');
        console.log($card);
        if($card.hasClass('hover')){
            $card.removeClass('hover');
        } else {
            $card.addClass('hover');
        }
    }
</script>
</code>```

答:
I was able to resolve this in 3 steps.

I changed binding to (click)="rotateCard(this).

Added type="button" property to button.

Installed jquery through npm install and added those in to angular-cli.json

This helped loading the jquery and now the inner method written in component.ts is getting called.

Thank you everyone for responding.

Body:
I am beginner in Angular 4 and writing a login component in Angular 4. On click of a Forgot password I want to flip the controls on page to show Reset password elements. I have a javascript function created called rotateCard(this) which I want to call on button click. It is inline javascript in html. I have added html in component.html. below is the code.

but it is giving error as "ReferenceError: rotateCard is not defined"

<form (ngSubmit)="doLoginUser()" #login="ngForm" >

                                <form>

                                        <input type="text" class="form-control crm-field" placeholder="Email"
                                        id="inputEmail" name="username" ngControl="username" required
                                        autofocus [(ngModel)]="username">

                                        <input type="password" class="form-control crm-field" name="password" placeholder="Password"
                                        id="inputPassword" ngControl="password" required [(ngModel)]="password">

                                    <button type="button" class="btn btn-primary btn-block orange-btn">LOGIN</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Forgot Password
                                </button>

Forgot Password

                                <form>

                                        <input type="text" class="form-control crm-field" name="email" placeholder="Email">

                                    <button type="button" class="btn btn-primary btn-block orange-btn">RESET PASSWORD</button>
                                </form>
                                <button class="btn btn-simple login-link" onClick="rotateCard(this)">
                                    Login
                                </button>

</form>


问:
Appname having dots at last of appname
I am having application name as "MYApplication" but it showing me as "MYApplica..." below app icon in mobile.

Now i want to show that fullname as application name, please give me any solution to fix this issue

Note : I have already set appname as "MYApplication" in info.plist (Bundle name)

Thank you.

答:
Your app name is getting truncate trail.

You can keep max 13 or 14 characters only. Depending on character width. “I” takes less width while “B” makes much width. So think about appropriate name of app and set it. In iOS we can not keep 2 line app name like Android device has option.

Title: Appname having dots at last of appname


问:
adb hangs when trying to start or stop server
(This question definitely is related to ADB is not starting (no error message) but there is no clear explanation what fixed the issue and reinstalling over and over again doesn't convince me.)

When I run my usual

```<code>$ sudo adb kill-server && sudo  adb start-server
</code>```

I have to CTRL-C it.

the suggested adb_trace álà the other question yields this:

```<code># export ADB_TRACE=all
# adb start-server
system/core/adb/adb.c::main():Handling commandline()
system/core/adb/adb_client.c::_adb_connect():_adb_connect: host:version
system/core/adb/transport.c::writex():writex: fd=3 len=4: 30303063 000c
system/core/adb/transport.c::writex():writex: fd=3 len=12: 686f73743a76657273696f6e host:version
system/core/adb/transport.c::readx():readx: fd=3 wanted=4 <---- freezes here
</code>```

strace is slightly more verbose and I get this:

```<code># strace /home/leo/Downloads/android-sdk-linux/platform-tools/adb start-server
... many
... many
... lines
futex(0xffab8474, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 1, NULL, f742a700) = -1 EAGAIN (Resource temporarily unavailable)
rt_sigaction(SIGRTMIN, {0xf77525f0, [], SA_SIGINFO}, NULL, 8) = 0
rt_sigaction(SIGRT_1, {0xf7752680, [], SA_RESTART|SA_SIGINFO}, NULL, 8) = 0
rt_sigprocmask(SIG_UNBLOCK, [RTMIN RT_1], NULL, 8) = 0
getrlimit(RLIMIT_STACK, {rlim_cur=-4286578688, rlim_max=-9223372032703125888}) = 0
uname({sys="Linux", node="donleo", ...}) = 0
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(5037), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
write(3, "000c", 4)                     = 4
write(3, "host:version", 12)            = 12
read(3, <---- freezes here
</code>```

So, what next?

Another observation when trying to fix this issue was that updating the sdk via the sdk manager failed. It tells me that I have Android SDK Platform-tools 16.0.2 and wants to update to 17. Clicking install just hangs forever without doing anything. I assume that both actions indefinitely wait for an answer from the same component. [Update: ] Deleting the component worked. Installing it now showed an issue (in contrast to update which did not show any "red" line in the log) saying that stopping adb does not worked. After killing the adb the update went through but adb still refuses to work.

Update: The suspicion that my installation of adb itself might be broken can be ruled out I guess. I'm using the manual download of the SDK and just tried the adb from the ubuntu repository (4.2.2+git20130218-3ubuntu1) and this hangs at exactly the same spot.

答:
Following the answer by giszmo,  my adb was blocked,  but not by another program,  but by a connect for an IPv6 socket [that was never going to bind].

```<code>ipv6.disable_ipv6=1
</code>```

On my kernel resolved the issue,  but probably isn't a permanent solution.

Body:
(This question definitely is related to ADB is not starting (no error message) but there is no clear explanation what fixed the issue and reinstalling over and over again doesn't convince me.)

When I run my usual

$ sudo adb kill-server && sudo  adb start-server

I have to CTRL-C it.

the suggested adb_trace álà the other question yields this:

# export ADB_TRACE=all
# adb start-server
system/core/adb/adb.c::main():Handling commandline()
system/core/adb/adb_client.c::_adb_connect():_adb_connect: host:version
system/core/adb/transport.c::writex():writex: fd=3 len=4: 30303063 000c
system/core/adb/transport.c::writex():writex: fd=3 len=12: 686f73743a76657273696f6e host:version
system/core/adb/transport.c::readx():readx: fd=3 wanted=4 <---- freezes here

strace is slightly more verbose and I get this:

# strace /home/leo/Downloads/android-sdk-linux/platform-tools/adb start-server
... many
... many
... lines
futex(0xffab8474, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 1, NULL, f742a700) = -1 EAGAIN (Resource temporarily unavailable)
rt_sigaction(SIGRTMIN, {0xf77525f0, [], SA_SIGINFO}, NULL, 8) = 0
rt_sigaction(SIGRT_1, {0xf7752680, [], SA_RESTART|SA_SIGINFO}, NULL, 8) = 0
rt_sigprocmask(SIG_UNBLOCK, [RTMIN RT_1], NULL, 8) = 0
getrlimit(RLIMIT_STACK, {rlim_cur=-4286578688, rlim_max=-9223372032703125888}) = 0
uname({sys="Linux", node="donleo", ...}) = 0
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(5037), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
write(3, "000c", 4)                     = 4
write(3, "host:version", 12)            = 12
read(3, <---- freezes here

So, what next?

Another observation when trying to fix this issue was that updating the sdk via the sdk manager failed. It tells me that I have Android SDK Platform-tools 16.0.2 and wants to update to 17. Clicking install just hangs forever without doing anything. I assume that both actions indefinitely wait for an answer from the same component. [Update: ] Deleting the component worked. Installing it now showed an issue (in contrast to update which did not show any "red" line in the log) saying that stopping adb does not worked. After killing the adb the update went through but adb still refuses to work.

Update: The suspicion that my installation of adb itself might be broken can be ruled out I guess. I'm using the manual download of the SDK and just tried the adb from the ubuntu repository (4.2.2+git20130218-3ubuntu1) and this hangs at exactly the same spot.

Body:
Following the answer by giszmo,  my adb was blocked,  but not by another program,  but by a connect for an IPv6 socket [that was never going to bind].

ipv6.disable_ipv6=1

On my kernel resolved the issue,  but probably isn't a permanent solution.