问:
onTouchBegan not working cocos2dx
try to play around with cocos2dx with cpp:

Here is the Header file:

```<code>#ifndef FirstScene_h
#define FirstScene_h

#include "cocos2d.h"
class FirstScene: public cocos2d::Scene
{
public:
    static cocos2d::Scene* createScene();
    virtual bool init();
    void menuCloseCallback(cocos2d::Ref* pSender);
    CREATE_FUNC(FirstScene);

    bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event);
    bool onTouchMoved(cocos2d::Touch *touch, cocos2d::Event * event);
    bool onTouchEnd(cocos2d::Touch *touch, cocos2d::Event *event);

private:
    cocos2d::Label *logLabel;
};
#endif /* FirstScene_h */
</code>```

And here is the cpp file:

```<code>#include "FirstScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
Scene* FirstScene::createScene(){
    return FirstScene::create();
}

bool FirstScene::init(){
    if(!Scene::init()){
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto label = Label::createWithTTF("this is the first scene", "fonts/Marker Felt.ttf", 24);
    label->setPosition(visibleSize.width/2,visibleSize.height/2);

    this->addChild(label,1);

    auto sprite = Sprite::create("HelloWorld.png");
    sprite->setPosition(visibleSize.width/3,visibleSize.height/3);

    logLabel = Label::createWithTTF("Log holder", "fonts/Marker Felt.ttf", 24);

    logLabel->setPosition(visibleSize.width/2 + 10.0f, visibleSize.height/2 + 10.0f);
    this->addChild(logLabel,3);

    this->addChild(sprite,0);

    auto listener = EventListenerTouchOneByOne::create();

    listener->onTouchBegan = CC_CALLBACK_2(FirstScene::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(FirstScene::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(FirstScene::onTouchEnd, this);

    return true;
}

bool FirstScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
    CCLOG("touch at x=%f, y=%f", touch->getLocation().x, touch->getLocation().y);
    std::string s = "";
    s += "touch at x=";
    s += touch->getLocation().x;
    s += "y=";
    s += touch->getLocation().y;
    logLabel->setString(s);
    return true;
}

bool FirstScene::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event) {

    std::string s = "";
    s += "touch moved at x=";
    s += touch->getDelta().x;
    s += " y=";
    s += touch->getDelta().y;
    CCLOG("touch moved at x=%f, y=%f", touch->getDelta().x, touch->getDelta().y);
    logLabel->setString(s);
    return true;
}

bool FirstScene::onTouchEnd(cocos2d::Touch *touch, cocos2d::Event *event) {
    std::string s="";
    s += "touch ended at x=";
    s += touch->getLocation().x;
    s += " y=";
    s += touch->getLocation().y;

    CCLOG("touch ended at x=%f, y=%f", touch->getLocation().x, touch->getLocation().y);
    logLabel->setString(s);
    return true;
}
</code>```

The things I want is when I touch and move on the screen, the log will be showed and the logLabel will show the message, but it seems there is no message saw either in the log window nor the logLabel changed.

What did I missing?

Note

I load this scene by one previous scene by following code if it matters:

```<code>void HelloWorld::menuCloseCallback(Ref* pSender)
{
    auto firstScene = FirstScene::createScene();
    Director::getInstance()->replaceScene(firstScene);
}
</code>```

Really a newbie for cocos2dx and cpp, thanks in advance.

答:
You need to add/register you event listener to event dispatcher :

```<code>Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
</code>```

If you want to add an event listener for a specified event with the priority of scene graph :

```<code>addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)
</code>```

else want add an event listener for a specified event with the fixed priority.

```<code>addEventListenerWithFixedPriority(EventListener* listener, Node* node)
</code>```

Title: onTouchBegan not working cocos2dx

Body:
try to play around with cocos2dx with cpp:

Here is the Header file:

#ifndef FirstScene_h
#define FirstScene_h

#include "cocos2d.h"
class FirstScene: public cocos2d::Scene
{
public:
    static cocos2d::Scene* createScene();
    virtual bool init();
    void menuCloseCallback(cocos2d::Ref* pSender);
    CREATE_FUNC(FirstScene);

    bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event);
    bool onTouchMoved(cocos2d::Touch *touch, cocos2d::Event * event);
    bool onTouchEnd(cocos2d::Touch *touch, cocos2d::Event *event);

private:
    cocos2d::Label *logLabel;
};
#endif /* FirstScene_h */

And here is the cpp file:

#include "FirstScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
Scene* FirstScene::createScene(){
    return FirstScene::create();
}

bool FirstScene::init(){
    if(!Scene::init()){
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto label = Label::createWithTTF("this is the first scene", "fonts/Marker Felt.ttf", 24);
    label->setPosition(visibleSize.width/2,visibleSize.height/2);

    this->addChild(label,1);

    auto sprite = Sprite::create("HelloWorld.png");
    sprite->setPosition(visibleSize.width/3,visibleSize.height/3);

    logLabel = Label::createWithTTF("Log holder", "fonts/Marker Felt.ttf", 24);

    logLabel->setPosition(visibleSize.width/2 + 10.0f, visibleSize.height/2 + 10.0f);
    this->addChild(logLabel,3);

    this->addChild(sprite,0);

    auto listener = EventListenerTouchOneByOne::create();

    listener->onTouchBegan = CC_CALLBACK_2(FirstScene::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(FirstScene::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(FirstScene::onTouchEnd, this);

    return true;
}

bool FirstScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
    CCLOG("touch at x=%f, y=%f", touch->getLocation().x, touch->getLocation().y);
    std::string s = "";
    s += "touch at x=";
    s += touch->getLocation().x;
    s += "y=";
    s += touch->getLocation().y;
    logLabel->setString(s);
    return true;
}

bool FirstScene::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event) {

    std::string s = "";
    s += "touch moved at x=";
    s += touch->getDelta().x;
    s += " y=";
    s += touch->getDelta().y;
    CCLOG("touch moved at x=%f, y=%f", touch->getDelta().x, touch->getDelta().y);
    logLabel->setString(s);
    return true;
}

bool FirstScene::onTouchEnd(cocos2d::Touch *touch, cocos2d::Event *event) {
    std::string s="";
    s += "touch ended at x=";
    s += touch->getLocation().x;
    s += " y=";
    s += touch->getLocation().y;

    CCLOG("touch ended at x=%f, y=%f", touch->getLocation().x, touch->getLocation().y);
    logLabel->setString(s);
    return true;
}

The things I want is when I touch and move on the screen, the log will be showed and the logLabel will show the message, but it seems there is no message saw either in the log window nor the logLabel changed.

What did I missing?

Note

I load this scene by one previous scene by following code if it matters:

void HelloWorld::menuCloseCallback(Ref* pSender)
{
    auto firstScene = FirstScene::createScene();
    Director::getInstance()->replaceScene(firstScene);
}

Really a newbie for cocos2dx and cpp, thanks in advance.

Body:
You need to add/register you event listener to event dispatcher :

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

If you want to add an event listener for a specified event with the priority of scene graph :

addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)

else want add an event listener for a specified event with the fixed priority.

addEventListenerWithFixedPriority(EventListener* listener, Node* node)


来源: stackexchange

问:
making a jar file for console
I have a program without a GUI and I use console! So first I read a line from a user from console

BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));

and then I will write an answer for the user in the console!

System.out.println("Server:"+output);

I want to create a jar file for it ! but how can i show my console in jar file with out using GUI?
please help me thanks.

答: The process of creating a JAR file is same for console as well as GUI based apps. You are definitely not seeing the output of your JAR. Simply execute it from a console then you will see the output. For the ease of use, you can make a batch file (MS-Windows) to run your JAR.</p>

ContentLicense: CC BY-SA 2.5

Title: making a jar file for console


问:
How do I escape %% in a batch file
I'm echoing out line from a batch file into another file. I know that to escape % you need %% but i can't figure out the escape sequence for %%. The following is what I am trying to accomplish

```<code>echo something %%stuff > secondFile.txt
</code>```

Resulting in

```<code>something %%stuff
</code>```

I have tried the following patterns:

%%%%

^%^%

%%%

答:
it's different on command line and in a batchfile.

On commandline: echo some %%stuff

in a batchfile: echo some %%%%stuff

ContentLicense: CC BY-SA 3.0

Title: How do I escape %% in a batch file

Body:
I'm echoing out line from a batch file into another file. I know that to escape % you need %% but i can't figure out the escape sequence for %%. The following is what I am trying to accomplish

echo something %%stuff > secondFile.txt

Resulting in

something %%stuff

I have tried the following patterns:

%%%%

^%^%

%%%


问:
C# Alternate Way to Find and Replace Text in Word Document
I am looking for alternate ways to search through the word document for certain text and then replace it with another text. My current works using the Find and Replace method however I was wondering if there are other ways to do this.

One method I tried was to go through paragraph by paragraph and search that for the text, swap it out, then paste that into a new word document and save it. However this made things a lot more complicated when it came to images, textbooks, tables etc. Also the formatting did not get preserved so that was another issue.

My current code is as follows:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;

namespace Test
{
    static class Program
    {
        static void Main()
        {
            //Create a new microsoft word file
            Microsoft.Office.Interop.Word.Application fileOpen = new Microsoft.Office.Interop.Word.Application();
            //Open a already existing word file into the new document created
            Microsoft.Office.Interop.Word.Document document = fileOpen.Documents.Open(@"C:\Users\dpatel\Desktop\Test1.docx", ReadOnly: false);
            //Make the file visible
            fileOpen.Visible = true;
            document.Activate();
            //The FindAndReplace takes the text to find under any formatting and replaces it with the
            //new text with the same exact formmating (e.g red bold text will be replaced with red bold text)
            FindAndReplace(fileOpen, "useless", "very useful");
            //Save the editted file in a specified location
            //Can use SaveAs instead of SaveAs2 and just give it a name to have it saved by default
            //to the documents folder
            document.SaveAs2(@"C:\Users\dpatel\Desktop\NewFile1");
            //Close the file out
            fileOpen.Quit();
        }
        //Method to find and replace the text in the word document. Replaces all instances of it
        static void FindAndReplace(Microsoft.Office.Interop.Word.Application fileOpen, object findText, object replaceWithText)
        {
            object matchCase = false;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;
            //execute find and replace
            fileOpen.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
                ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
                ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
        }
    }
}
</code>```

答: Turns out there is no alternative to finding and replacing text. The only way is to scan a document, extract text, then if it matches, to issue a replacement. Which is essentially the same as "find and replace". There are variations to the method however like choosing to search through textboxes only, tables only etc. </p>

Body:
I am looking for alternate ways to search through the word document for certain text and then replace it with another text. My current works using the Find and Replace method however I was wondering if there are other ways to do this.

One method I tried was to go through paragraph by paragraph and search that for the text, swap it out, then paste that into a new word document and save it. However this made things a lot more complicated when it came to images, textbooks, tables etc. Also the formatting did not get preserved so that was another issue.

My current code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;

namespace Test
{
    static class Program
    {
        static void Main()
        {
            //Create a new microsoft word file
            Microsoft.Office.Interop.Word.Application fileOpen = new Microsoft.Office.Interop.Word.Application();
            //Open a already existing word file into the new document created
            Microsoft.Office.Interop.Word.Document document = fileOpen.Documents.Open(@"C:\Users\dpatel\Desktop\Test1.docx", ReadOnly: false);
            //Make the file visible
            fileOpen.Visible = true;
            document.Activate();
            //The FindAndReplace takes the text to find under any formatting and replaces it with the
            //new text with the same exact formmating (e.g red bold text will be replaced with red bold text)
            FindAndReplace(fileOpen, "useless", "very useful");
            //Save the editted file in a specified location
            //Can use SaveAs instead of SaveAs2 and just give it a name to have it saved by default
            //to the documents folder
            document.SaveAs2(@"C:\Users\dpatel\Desktop\NewFile1");
            //Close the file out
            fileOpen.Quit();
        }
        //Method to find and replace the text in the word document. Replaces all instances of it
        static void FindAndReplace(Microsoft.Office.Interop.Word.Application fileOpen, object findText, object replaceWithText)
        {
            object matchCase = false;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;
            //execute find and replace
            fileOpen.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
                ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
                ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
        }
    }
}


问:
FileReader JS throws The object is busy reading a blobs
I am trying to use filereader to read data of multiple files in an array. But there is an error saying The object is already busy reading Blobs.

```<code>                    flag = 1;
                    var file;
                    var fileRead = [];
                    for (var i = 0, f; f = changeEvent.target.files[i]; i++) {
                        reader.onload = function(loadEvent) {
                            scope.$apply(function() {
                                if (flag == 1) {
                                    fileRead.push(loadEvent.target.result);

                                }
                            });
                        };

                        reader.readAsDataURL(f);
                    }

                    for (i = 0; i < changeEvent.target.files.length; i++) {
                        file = changeEvent.target.files[i];
                        fileName.push(file.name);
                    }
                }
            }
</code>```

i have tried using a loop to see if that operation is done but it ends up in an infinite loop.

答:
Here's a snippet of what worked for me. readAsDataURL is async so you have to wait for the file to read before working on the next one. Make sure you declare the reader within the loop.</p>

```<code>       var files = e.target.files;

       if(files) {
        for (let i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onloadend = function(output){
                console.log('output', output.target.result)
                console.log('fileNamnes', f.name)
            }.bind(this);
            reader.readAsDataURL(f)
        }
       }
</code>```

Body:
I am trying to use filereader to read data of multiple files in an array. But there is an error saying The object is already busy reading Blobs.

                    flag = 1;
                    var file;
                    var fileRead = [];
                    for (var i = 0, f; f = changeEvent.target.files[i]; i++) {
                        reader.onload = function(loadEvent) {
                            scope.$apply(function() {
                                if (flag == 1) {
                                    fileRead.push(loadEvent.target.result);

                                }
                            });
                        };

                        reader.readAsDataURL(f);
                    }

                    for (i = 0; i < changeEvent.target.files.length; i++) {
                        file = changeEvent.target.files[i];
                        fileName.push(file.name);
                    }
                }
            }

i have tried using a loop to see if that operation is done but it ends up in an infinite loop.

Body:
Here's a snippet of what worked for me. readAsDataURL is async so you have to wait for the file to read before working on the next one. Make sure you declare the reader within the loop.

       var files = e.target.files;

       if(files) {
        for (let i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onloadend = function(output){
                console.log('output', output.target.result)
                console.log('fileNamnes', f.name)
            }.bind(this);
            reader.readAsDataURL(f)
        }
       }


问:
Setting vsession.program in java app using hibernate 5 and c3po connection pool
I'm trying to set the session program name from my java app.
I'm using an entity manager passing the connection credentials from user input.

I need to be able to set the program name in the oracle session when connected. Right now it only appears as "JDBC Thin Client". I've attempted setting the entity manager properties in java and tried numerous variations in my persistence.xml.

Java snippet

```<code>            props.put( hibernate.connection.url, "jdbc:oracle:thin:@localhost:1521:XE");
            props.put( "hibernate.connection.username", username );
            props.put( "hibernate.connection.password", password );
            props.put( "v$session.program", "MYPROGRAM" );

            emf = Persistence.createEntityManagerFactory( "MYDB", props );

            em = emf.createEntityManager();
</code>```

Persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?><persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="MYDB">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <!-- Hibernate properties -->
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>
        <property name="hibernate.show_sql" value="false"/>
        <property name="hibernate.cache.use_second_level_cache" value="false"/>
        <!-- Connection Pool -->
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.max_size" value="20" />
        <property name="hibernate.c3p0.min_size" value="5" />
        <property name="hibernate.c3p0.acquire_increment" value="5" />
        <property name="hibernate.c3p0.idle_test_period" value="300" />
        <property name="hibernate.c3p0.max_statements" value="0" />
        <property name="hibernate.c3p0.timeout" value="100" />
        <property name="connectionProperties" value="v$session.program:MYPROGRAM" />
    </properties>
</persistence-unit>
</code>```

I'm limited in what techonologies to use, so I cannot use EclipseLink as suggested here

Is there any other way to set this either in the java app or in the persistence.xml file?

答:
The properties hibernate.connection.X are the connection properties passed to JDBC. The property that you are using is also a JDBC one, so you should try to set as below. It worked for me.

code

<property name="hibernate.connection.v$session.program" value="MYPROGRAM" />

Body:
I'm trying to set the session program name from my java app.
I'm using an entity manager passing the connection credentials from user input.

I need to be able to set the program name in the oracle session when connected. Right now it only appears as "JDBC Thin Client". I've attempted setting the entity manager properties in java and tried numerous variations in my persistence.xml.

Java snippet

            props.put( hibernate.connection.url, "jdbc:oracle:thin:@localhost:1521:XE");
            props.put( "hibernate.connection.username", username );
            props.put( "hibernate.connection.password", password );
            props.put( "v$session.program", "MYPROGRAM" );

            emf = Persistence.createEntityManagerFactory( "MYDB", props );

            em = emf.createEntityManager();

Persistence.xml

<?xml version="1.0" encoding="UTF-8"?><persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="MYDB">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>

        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>
        <property name="hibernate.show_sql" value="false"/>
        <property name="hibernate.cache.use_second_level_cache" value="false"/>

        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.max_size" value="20" />
        <property name="hibernate.c3p0.min_size" value="5" />
        <property name="hibernate.c3p0.acquire_increment" value="5" />
        <property name="hibernate.c3p0.idle_test_period" value="300" />
        <property name="hibernate.c3p0.max_statements" value="0" />
        <property name="hibernate.c3p0.timeout" value="100" />
        <property name="connectionProperties" value="v$session.program:MYPROGRAM" />
    </properties>
</persistence-unit>

I'm limited in what techonologies to use, so I cannot use EclipseLink as suggested here

Is there any other way to set this either in the java app or in the persistence.xml file?


问:
REST CXF and Spring cxf-extension-jaxrs-binding File not found exception?
i'm trynig to develop a REST web service using CXF 2.6.0 and spring 2.5.6 my CXF maven dependancy in the pom.xml  are   :

```<code><dependency>
  <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
  <version>2.6.0</version>
   </dependency>

<dependency>
  <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-search</artifactId>
  <version>2.6.0</version>
</dependency>
</code>```

I'am using Spring 2.5.6 and i have declared my web service in the applicationcontext.xml  spring file :

```<code><jaxrs:server id="restContainer" address="/sav">
    <jaxrs:serviceBeans>
        <ref bean="wssav"/>
    </jaxrs:serviceBeans>
</jaxrs:server>

 <import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
</code>```

And i have declared my Web service into web.xml file by this code :

```<code><servlet>
    <servlet-name>CXFServlet</servlet-name>

    <servlet-class>
        org.apache.cxf.transport.servlet.CXFServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</code>```

when i deploy my project on tomcat i got this exception for the second file of import in applicationcontext.xml file :

```<code>    java.io.FileNotFoundException: class path resource [META-INF/cxf/cxf-extension-jaxrs-binding.xml] cannot be opened because it does not exist
</code>```

答:
In applicationContext.xml, comment out the below imports works for me in cxf 3.1.10.
import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml</p>

Body:
i'm trynig to develop a REST web service using CXF 2.6.0 and spring 2.5.6 my CXF maven dependancy in the pom.xml  are   :

<dependency>
  <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
  <version>2.6.0</version>
   </dependency>

<dependency>
  <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-search</artifactId>
  <version>2.6.0</version>
</dependency>

I'am using Spring 2.5.6 and i have declared my web service in the applicationcontext.xml  spring file :

<jaxrs:server id="restContainer" address="/sav">
    <jaxrs:serviceBeans>
        <ref bean="wssav"/>
    </jaxrs:serviceBeans>
</jaxrs:server>

 <import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

And i have declared my Web service into web.xml file by this code :

<servlet>
    <servlet-name>CXFServlet</servlet-name>

    <servlet-class>
        org.apache.cxf.transport.servlet.CXFServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

when i deploy my project on tomcat i got this exception for the second file of import in applicationcontext.xml file :

    java.io.FileNotFoundException: class path resource [META-INF/cxf/cxf-extension-jaxrs-binding.xml] cannot be opened because it does not exist


问:
How to concatenate an object property to another string or variable in javascript
I want to concatenate an object property to a variable like this,</p>

```<code>var foo = { bar_zen: 0, bar_jj: 0 }

var foo2 = $(this); // this comes from attr of an Id or class on click
if(foo.bar_+foo2+ == 0){ ..// do something }
</code>```

答:
use bracket notation instead of dots:</p>

```<code>if(foo["bar_" + foo2] == 0){ ..// do something }
</code>```

Body:
I want to concatenate an object property to a variable like this,

var foo = { bar_zen: 0, bar_jj: 0 }

var foo2 = $(this); // this comes from attr of an Id or class on click
if(foo.bar_+foo2+ == 0){ ..// do something }

Body:
use bracket notation instead of dots:

if(foo["bar_" + foo2] == 0){ ..// do something }


问:
Use of this in bash script.
What is the if [[ -z $1 ]] statement exactly checks here ?

Whenever I run it outputs like this :

[root@localhost ~]# sh script.sh

No argument is given

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

if [[ -z $1 ]]; then

echo "No argument is given"

elif [ "$1" == "testfile" ] ; then

echo "Right argument is given"

else

echo "Wrong argument is given"

fi
</code>```

答:
See man bash:

```<code>[[ expression ]]
</code>```

Return a status of 0 or 1 depending on the evaluation of the conditional expression

and further below

```<code>-z string
</code>```

True if the length of string is zero.

Title: Use of this in bash script.

Body:
What is the if [[ -z $1 ]] statement exactly checks here ?

Whenever I run it outputs like this :

[root@localhost ~]# sh script.sh

No argument is given

#!/bin/bash

if [[ -z $1 ]]; then

echo "No argument is given"

elif [ "$1" == "testfile" ] ; then

echo "Right argument is given"

else

echo "Wrong argument is given"

fi

Body:
See man bash:

[[ expression ]]

Return a status of 0 or 1 depending on the evaluation of the conditional expression

and further below

-z string

True if the length of string is zero.


问:
Reading between certain lines
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!</p>

```<code># DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

答:
Here is a way to do it:

```<code>#!/usr/bin/perl
use strict;
use warnings;

local $/ = "\n\n\n";
while (<DATA>) {
    print if/Stats1/;
}

__DATA__
Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

Output:

```<code>Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789
</code>```

Title: Reading between certain lines

Body:
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!

# DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Body:
Here is a way to do it:

#!/usr/bin/perl
use strict;
use warnings;

local $/ = "\n\n\n";
while (<DATA>) {
    print if/Stats1/;
}

__DATA__
Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Output:

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789


问:
setImageBitmap() is not working
I have and ImageView and it is supposed to be filled with an image from Gallery with this code:

```<code>Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
            getIntent.setType("image/*");
            Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            pickIntent.setType("image/*");

            Intent chooserIntent = Intent.createChooser(getIntent, "Pick an image.");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

            startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);
</code>```

Now, everything's fine in this part of the code, the problem is in onActivityResult(), exactly in setImageBitmap() because imageView is not adopting the image from Gallery. This is the code from onActivityResult():

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == PICK_IMAGE_REQUEST || resultCode == PromoUpload.RESULT_OK){

        Uri selectedImage = data.getData();
        String[] filepathColumm = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filepathColumm, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filepathColumm[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        imagePromo.setImageBitmap(bitmap);
        pictureFlag = 1;

    }
</code>```

I Toast the picturePath attribute and it's displayed ok, the problem is exactly here:

```<code>Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
    imagePromo.setImageBitmap(bitmap);
</code>```

But I don't know what I'm doing wrong. This is the XML of the ImageView:

```<code><ImageView
        android:id="@+id/imageView_promo"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:padding="1dp" />
</code>```

I also tried selecting images from multiple sizes, but it doesn't seem to work...

答:
Will help this,</p>

```<code>BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath,bmOptions);
imageView.setImageBitmap(bitmap);
</code>```

Title: setImageBitmap() is not working

Body:
I have and ImageView and it is supposed to be filled with an image from Gallery with this code:

Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
            getIntent.setType("image/*");
            Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            pickIntent.setType("image/*");

            Intent chooserIntent = Intent.createChooser(getIntent, "Pick an image.");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

            startActivityForResult(chooserIntent, PICK_IMAGE_REQUEST);

Now, everything's fine in this part of the code, the problem is in onActivityResult(), exactly in setImageBitmap() because imageView is not adopting the image from Gallery. This is the code from onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == PICK_IMAGE_REQUEST || resultCode == PromoUpload.RESULT_OK){

        Uri selectedImage = data.getData();
        String[] filepathColumm = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filepathColumm, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filepathColumm[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        imagePromo.setImageBitmap(bitmap);
        pictureFlag = 1;

    }

I Toast the picturePath attribute and it's displayed ok, the problem is exactly here:

Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
    imagePromo.setImageBitmap(bitmap);

But I don't know what I'm doing wrong. This is the XML of the ImageView:

<ImageView
        android:id="@+id/imageView_promo"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:padding="1dp" />

I also tried selecting images from multiple sizes, but it doesn't seem to work...

Body:
Will help this,

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath,bmOptions);
imageView.setImageBitmap(bitmap);


问:
Bring implicit to scope
I have a trait

```<code>trait Tr{
    def logic: Option[() => Unit] = None
    def apply(): Unit = logic match {
         case Some(l) => l()
         case None =>
    }
}

object Tr{
    implicit def procLogic2Opt(processingLogic: () => Unit): Option[() => Unit]
= Some(processingLogic)
}
</code>```

The thing is when subclassing the trait I have to import Tr._ explicitly to bring implicits into a scope. Like this

```<code>import Tr._ //otherwise does not compile

class Trrr extends Tr{
    override def processingLogic = () => println("test")
}
</code>```

Is there a way to do it without importing explicitly? How could I redesign it?

答:
Because the client is supposed to call only apply. I thought it's not necessary for subclassers to know that Option is required

So, why require it?

```<code>trait Tr {
    protected val logic: () => Unit = () => {}
    def apply(): Unit = logic()
}

class Trrr extends Tr{
   override val logic = () => println("test")
}
</code>```

(val logic to avoid recreating it each time.)

Title: Bring implicit to scope

Body:
I have a trait

trait Tr{
    def logic: Option[() => Unit] = None
    def apply(): Unit = logic match {
         case Some(l) => l()
         case None =>
    }
}

object Tr{
    implicit def procLogic2Opt(processingLogic: () => Unit): Option[() => Unit]
= Some(processingLogic)
}

The thing is when subclassing the trait I have to import Tr._ explicitly to bring implicits into a scope. Like this

import Tr._ //otherwise does not compile

class Trrr extends Tr{
    override def processingLogic = () => println("test")
}

Is there a way to do it without importing explicitly? How could I redesign it?

Body:
Because the client is supposed to call only apply. I thought it's not necessary for subclassers to know that Option is required

So, why require it?

trait Tr {
    protected val logic: () => Unit = () => {}
    def apply(): Unit = logic()
}

class Trrr extends Tr{
   override val logic = () => println("test")
}

(val logic to avoid recreating it each time.)


问:
Bandwidth throttling for Apache<2.2 on Windows (mod_throttle?)
Does anyone know of a windows build of mod_throttle for Apache 2.2 or lower?

Or perhaps another means by which to throttle bandwidth. I need to throttle as low as 64k for a local speed test demonstration

Preferably Apache rather than a browser plug-in too.

Thanks!

答: Yo may try mod_bandwith as explained here.</p>

OwnerDisplayName: Supernovah


问:
Execute a script before CMD
As per Docker documentation:
There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.

I wish to execute a simple bash script(which processes docker environment variable) before the CMD command(which is init in my case).

Is there any way to do this?

答:
Dan's answer was correct, but I found it rather confusing to implement. For those in the same situation, here are code examples of how I implemented his explanation of the use of ENTRYPOINT instead of CMD.

Here are the last few lines in my Dockerfile:

```<code>#change directory where the mergeandlaunch script is located.
WORKDIR /home/connextcms
ENTRYPOINT ["./mergeandlaunch", "node", "keystone.js"]
</code>```

Here are the contents of the mergeandlaunch bash shell script:

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

#This script should be edited to execute any merge scripts needed to
#merge plugins and theme files before starting ConnextCMS/KeystoneJS.

echo Running mergeandlaunch script

#Execute merge scripts. Put in path to each merge script you want to run here.
cd ~/theme/rtb4/
./merge-plugin

#Launch KeystoneJS and ConnextCMS
cd ~/myCMS

exec "$@"
</code>```

Here is how the code gets executed:

The ENTRYPOINT command kicks off the mergeandlaunch shell script

The two arguments 'node' and 'keystone.js' are passed along to the shell script.

At the end of the script, the arguments are passed on to the exec command.

The exec command then launched my node program the same way the Docker command CMD would do.

Title: Execute a script before CMD

Body:
Dan's answer was correct, but I found it rather confusing to implement. For those in the same situation, here are code examples of how I implemented his explanation of the use of ENTRYPOINT instead of CMD.

Here are the last few lines in my Dockerfile:

#change directory where the mergeandlaunch script is located.
WORKDIR /home/connextcms
ENTRYPOINT ["./mergeandlaunch", "node", "keystone.js"]

Here are the contents of the mergeandlaunch bash shell script:

#!/bin/bash

#This script should be edited to execute any merge scripts needed to
#merge plugins and theme files before starting ConnextCMS/KeystoneJS.

echo Running mergeandlaunch script

#Execute merge scripts. Put in path to each merge script you want to run here.
cd ~/theme/rtb4/
./merge-plugin

#Launch KeystoneJS and ConnextCMS
cd ~/myCMS

exec "$@"

Here is how the code gets executed:

The ENTRYPOINT command kicks off the mergeandlaunch shell script

The two arguments 'node' and 'keystone.js' are passed along to the shell script.

At the end of the script, the arguments are passed on to the exec command.

The exec command then launched my node program the same way the Docker command CMD would do.


问:
Redis StackExchange Client - Frequently receiving "Timeout exceptions", "Redis connection exception", "No connection available to service"
I am frequently getting the below mentioned errors, the dll version used in the project is - 1.0.488.0

System.TimeoutException: Timeout performing GET

StackExchange.Redis.RedisConnectionException: No connection is available to service this operation: GET

No connection is available to service this operation: EXISTS

Can anyone help me out in figuring what the issue can be?

Have also created an issue on StackExchange's Github repo for the same
Issue created on Github for the same

答: It looks like your connection broke. And when it did, any commands already sent to Redis would have timed out on the client application, even though they could have executed on the server. If you upgrade to a later version of the StackExchange.Redis client, you will get richer diagnostics information about what the state of the threadpool, CPU etc was on the client application side. </p>


问:
Spring Cloud Dataflow - Deploy Stream Without Starting
When deploying an application in PCF, it is possible to deploy the application without starting by running cf push --no-start.

In the same way, is it possible to deploy a Spring Cloud Dataflow stream without starting the underlying applications?

答:
The use-case description would be useful to understand why you'd like to deploy a stream and not start it. A stream is a continuous thing - it is meant to be running all the time.

If you're looking to address on-demand style use-cases, it'd be recommended to run them as Task pipelines instead. In fact, the tasks by default are pushed with --no-start equivalent and upon a launch trigger (e.g., a schedule, manual launch. etc.,), it is actually started then.


问:
Faster Multiplication of double Array values
Hello I have a one dimensional array which represents a two dimensional array. Based on the position of each value will determine the coefficient it is multiplied by.

At the moment I iterate over each value in a for loop, multiply by the correct coefficient and then store the product in another array.

MultiplyEachValue.cs

```<code>internal double[] MultiplyEachValue(double[] oneDimArray, int width, int height, Alignment coeffs)
{
    var toReturn = new double[oneDimArray.Length];
    for (int i = 0; i < oneDimArray.Length; i++)
    {
        double curVal;
        if(isEvenPos(i, width, height) == true)
        {
            curVal = coeffs.Small * oneDimArray[i];
        }
        else if (isOddPos(i, 4, 2) == true)
        {
            curVal = coeffs.Large * oneDimArray[i];
        }
        else if (isOppoPos(i, 4, 2) == true)
        {
            curVal = coeffs.Medium * oneDimArray[i];
        }
        else
        {
            curVal = 1;
        }
        toReturn[i] = curVal;
    }
    return toReturn;
}
</code>```

Any idea how I can make it faster?
I have heard of things like dot multiplication but I do not know if it can be applied here. Any suggestions would be great. Thanks!!!

答:
You should run the app with profiling, ideally with a large input so that it takes longer. Then identify hotspots, then review those to see if they can be improved.

Also be aware that elapsed execution time and CPU consumed time are different things too. Are you seeking to reduce CPU cost or elapsed time?

You should also order your if/else ladder to test for the most common scenario first, for example if most of the data ends up in the last if test, then making that check the first check will improve things.

Having said that, the code looks easy to parallelize and on a multi-core machine you could - in principle - see an 'n' factor speed up with 'n' cores if you parallelize the loop.

Body:
Hello I have a one dimensional array which represents a two dimensional array. Based on the position of each value will determine the coefficient it is multiplied by.

At the moment I iterate over each value in a for loop, multiply by the correct coefficient and then store the product in another array.

MultiplyEachValue.cs

internal double[] MultiplyEachValue(double[] oneDimArray, int width, int height, Alignment coeffs)
{
    var toReturn = new double[oneDimArray.Length];
    for (int i = 0; i < oneDimArray.Length; i++)
    {
        double curVal;
        if(isEvenPos(i, width, height) == true)
        {
            curVal = coeffs.Small * oneDimArray[i];
        }
        else if (isOddPos(i, 4, 2) == true)
        {
            curVal = coeffs.Large * oneDimArray[i];
        }
        else if (isOppoPos(i, 4, 2) == true)
        {
            curVal = coeffs.Medium * oneDimArray[i];
        }
        else
        {
            curVal = 1;
        }
        toReturn[i] = curVal;
    }
    return toReturn;
}

Any idea how I can make it faster?
I have heard of things like dot multiplication but I do not know if it can be applied here. Any suggestions would be great. Thanks!!!


问:
show statusbar and change color
I am trying to get my activity to show my status bar.

without statusbar

The style of my activity is like this:

```<code><resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppBaseTheme" parent="Theme.AppCompat">
</style>

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/ActionBarTheme</item>
    <item name="android:actionMenuTextColor">@color/ifix_gray_dark</item>
    <item name="android:typeface">serif</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="colorControlActivated">@color/white</item>

    <item name="actionBarStyle">@style/ActionBarTheme</item>
    <item name="actionMenuTextColor">@color/ifix_gray_dark</item>
</style>

<style name="ActivityBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="actionBarSize">35dp</item>
</style>

<style name="ActionBarTheme" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/actionbar_background</item>
    <item name="android:backgroundStacked">@drawable/actionbar_background</item>
    <item name="android:backgroundSplit">@drawable/actionbar_background</item>

    <item name="background">@drawable/actionbar_background</item>
    <item name="backgroundStacked">@drawable/actionbar_background</item>
    <item name="backgroundSplit">@drawable/actionbar_background</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="buttonTint">@color/rosa_iguana</item>
</style>
</resources>
</code>```

For Style v21 I have it:

```<code> <style name="ActivityBar" parent="Theme.AppTheme.NoActionBar">
    <item name="colorPrimaryDark">@color/black</item>
    <item name="android:statusBarColor">@color/black</item>
</style>
</code>```

I found this code to show my status bar but I painted it white

```<code>@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    hideSystemUI(hasFocus);
}

@TargetApi(Build.VERSION_CODES.KITKAT)
private void hideSystemUI(boolean hasFocus) {
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
    }
}
</code>```

example status bar white here

My Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.projextx">
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />
    <!-- for card.io card scanning -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- Added for MobileAppTracking -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />
    <application
        android:name=".Application"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@drawable/launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.ActivitySelectCountry"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomeActivity"
            android:screenOrientation="portrait"
            android:theme="@style/ActivityBar"
            android:windowSoftInputMode="adjustPan"/>
        <activity
            android:name=".activities.ActivitySegment"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".activities.ActivityProductDetail"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".activities.ActivityPagerPagoOption"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>
</code>```

And I really would like some solution with in the styles because this I have to apply it to 2 more activities.

Thanks for the help.

答:
Here is the code that works totally fine for me

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="actionBarSize">35dp</item>
</style>
</code>```

You can try it or you should also check following:

if color Black code is really black(#000000)

In manifest's activity declaration you have set theme properly

If still not working please post layout of activity and manifest as well

Title: show statusbar and change color

Body:
I am trying to get my activity to show my status bar.

without statusbar

The style of my activity is like this:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

For Style v21 I have it:

I found this code to show my status bar but I painted it white

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    hideSystemUI(hasFocus);
}

@TargetApi(Build.VERSION_CODES.KITKAT)
private void hideSystemUI(boolean hasFocus) {
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
    }
}

example status bar white here

My Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.projextx">
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />
    <application
        android:name=".Application"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@drawable/launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.ActivitySelectCountry"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomeActivity"
            android:screenOrientation="portrait"
            android:theme="@style/ActivityBar"
            android:windowSoftInputMode="adjustPan"/>
        <activity
            android:name=".activities.ActivitySegment"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".activities.ActivityProductDetail"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".activities.ActivityPagerPagoOption"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>

And I really would like some solution with in the styles because this I have to apply it to 2 more activities.

Thanks for the help.

Body:
Here is the code that works totally fine for me

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="actionBarSize">35dp</item>
</style>

You can try it or you should also check following:

if color Black code is really black(#000000)

In manifest's activity declaration you have set theme properly

If still not working please post layout of activity and manifest as well


答:
The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

```<code>if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi
</code>```

Title: Use of this in bash script.

Body:
The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi


问:
Sharing variables across multiple sessions
I know I cannot have a global variable in my backend code (java or php or something else) and have different users (and hence sessions) see the same value. If I need to share some values across these user sessions I need to write them to a DB and read it out every time. This seems awfully wasteful to me.

I understand that an apache process (or the app server) will fork and so having global values will not work but if I am looking at a specialized application is there a web server that lets me do this? This should be possible in a web server that uses threads instead of forking processes. But if I need to share global memory I will need to have some kind of locks to properly access them. I understand that it could (and mostly will) get really buggy but will it degrade performance compared to a DB?

Thoughts?

Pav

答:
I'm not sure that's entirely true. Apache will handle each user connection individually - correct. However, I know that in Java it is possible to have a Singleton object that exists for the life of the application, in which you could potentially store values to be used across all user sessions.

When handling each user connection on the server side, each access to this Singleton will access the same object - therefore the same values.

You might want to do some more research into application scope objects as well. I'm not sure exactly what you're trying to achieve due to lack of a use case, but you may find that Java web apps can do more than you expect in this area.


问:
In xmonad, how to remap CapsLock to Ctrl?
I'm new to xmonad, and trying to remap CapsLock to Ctrl.

I think I can do this by adding a ~/.xmonad/xmonad.hs file as suggested at this xmonad setup tutorial, and it seems that the xmonad.hs file should look something like the example given at the xmonad FAQ page.

```<code>import XMonad

main = xmonad defaultConfig
         { modMask = mod4Mask
         , terminal = "urxvt"
         }
</code>```

I'm not sure exactly how the various fields there modMask, mod4Mask, terminal, and "urxvt" represent keyboard keys, or what field to use to represent my CapsLock and Ctrl keys.

How exactly do I remap my CapsLock to Ctrl?

Is there documentation somewhere describing the field associated with each key, CapsLock, Ctrl, etc.?

P.S. As a side-note this mailing list item also says something about xmonad keymay rebinding, but it does not appear to be haskell.

答:
@melpomene's comment led me to seek something other than xmonad for performing the keybinding remap.

Instead I used xmodmap following the instructions described at this blog, Changing your caps lock into Ctrl in X.

Body:
I'm new to xmonad, and trying to remap CapsLock to Ctrl.

I think I can do this by adding a ~/.xmonad/xmonad.hs file as suggested at this xmonad setup tutorial, and it seems that the xmonad.hs file should look something like the example given at the xmonad FAQ page.

import XMonad

main = xmonad defaultConfig
         { modMask = mod4Mask
         , terminal = "urxvt"
         }

I'm not sure exactly how the various fields there modMask, mod4Mask, terminal, and "urxvt" represent keyboard keys, or what field to use to represent my CapsLock and Ctrl keys.

How exactly do I remap my CapsLock to Ctrl?

Is there documentation somewhere describing the field associated with each key, CapsLock, Ctrl, etc.?

P.S. As a side-note this mailing list item also says something about xmonad keymay rebinding, but it does not appear to be haskell.


问:
Can I validate business data during an Azure AD B2C custom sign up process?
We are looking into Azure AD B2C as a general identity management solution for our SaaS services.

One scenario we need to support is around distribution of pre-paid (stored value) payment cards, sold in stores or offered by other 3rd parties to customers. The customer gets the card with a PIN or one time registration code, and with that they can sign up to the cardholder portal, a web application / native app that allows them to view card history, balances and so on.

The sign up process needs to eventually identify the card as a custom claim, but also needs to validate the supplied code right there and then. The user needs to be able to go to the cardholder portal, click 'sign up' and be presented with input fields for the basic info plus the PIN/ reg code. On submit, the PIN/reg code needs to be validated.

Can Azure AD B2C support this type of scenario? Can the UI be completely custom? Are there any pricing implications to this? Also....is there anyway of having the native version of the app have a completely native version of the UI?

答:
I believe you can configure this type of validation for new users signing up using Azure AD B2C Custom Policies.  Custom policies allow you to define your own policy rather than using the built-in set.  Specifically for your case, you'll be able to validate user data given at sign up with your own API.

Fair warning, custom policies can be complex to configure properly.


问:
Source control intellij code style settings
We have a project being managed by more than 20 developers and most of them use intellij.
I was wondering if we can source an xml file somehow so that every developer doesn't have to import code style settings manually.

How to properly import Java code style settings with IntelliJ?
This thread suggests that we have to manually import the xml file and only then we will see those settings will come into effect. Is there a setting that can import the code styles automatically?

答:
```<code><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectCodeStyleSettingsManager">
    <option name="PER_PROJECT_SETTINGS">
      <value>
        <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
        <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="15" />
        <option name="IMPORT_LAYOUT_TABLE">
          <value>
            <package name="" withSubpackages="true" static="true" />
            <emptyLine />
            <package name="java" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="javax" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="org" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="com" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="" withSubpackages="true" static="false" />
          </value>
        </option>
        <codeStyleSettings language="JAVA">
            <option name="KEEP_LINE_BREAKS" value="false" />
            <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        </codeStyleSettings>
      </value>
    </option>
    <option name="USE_PER_PROJECT_SETTINGS" value="true" />
  </component>
</project>
</code>```

The above settings in .idea/codestyleSettings.xml did the trick.

Body:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectCodeStyleSettingsManager">
    <option name="PER_PROJECT_SETTINGS">
      <value>
        <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
        <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="15" />
        <option name="IMPORT_LAYOUT_TABLE">
          <value>
            <package name="" withSubpackages="true" static="true" />
            <emptyLine />
            <package name="java" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="javax" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="org" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="com" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="" withSubpackages="true" static="false" />
          </value>
        </option>
        <codeStyleSettings language="JAVA">
            <option name="KEEP_LINE_BREAKS" value="false" />
            <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        </codeStyleSettings>
      </value>
    </option>
    <option name="USE_PER_PROJECT_SETTINGS" value="true" />
  </component>
</project>

The above settings in .idea/codestyleSettings.xml did the trick.


问:
import webkit fails with an ImportError
When I import webkit on Ubuntu 10.04 I get the following error:

```<code>Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import webkit
  File "/usr/lib/pymodules/python2.6/webkit/__init__.py", line 19, in <module>
    import webkit
ImportError: /usr/lib/pymodules/python2.6/webkit/webkit.so: undefined symbol: webkit_web_frame_get_global_context
</code>```

I think all the packages I need are installed. Does anyone have an idea of why this is failing?

答: Your /usr/lib/pymodules/python2.6/webkit/webkit.so is probably linked against an older version of libwebkit. In that case you'll need to install the correct versions of both software packages.

Title: import webkit fails with an ImportError

Body:
When I import webkit on Ubuntu 10.04 I get the following error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import webkit
  File "/usr/lib/pymodules/python2.6/webkit/__init__.py", line 19, in <module>
    import webkit
ImportError: /usr/lib/pymodules/python2.6/webkit/webkit.so: undefined symbol: webkit_web_frame_get_global_context

I think all the packages I need are installed. Does anyone have an idea of why this is failing?


问:
Aggregate cells of worldclim geographically to estimate standard deviation of 10min resolution by using 30s resolution
I have to estimate topographic information of certain areas. Here a want to use data of worldclim. I need to estimate the the standard deviation of elevation for each 30s cell, that occurs within a 10min cell. However, I really do not know how to this. I somehow have to aggregate the cells geographically...

I first extract the required data of worldclim, elevations for 10min and for 30s (here I just picked a random number for lon and lat). I also provide one of my coordinates I use.

```<code>alt <- getData("worldclim",var="alt",res=10)

alt05_1 <- getData('worldclim', var='alt', res=0.5, lon=5, lat=45)

lats <- c(46.06667, 46.60134)

lons <- c(7.600000, 9.965973)

coords <- data.frame(x=lons,y=lats)

points_alt <- SpatialPoints(coords, proj4string = alt@crs)

values_alt <- extract(alt,points_alt)

altitude <- cbind.data.frame(coordinates(points_alt),values_alt)
</code>```

So with this, I am of course able to extract the elevation for both relosutions, however, how am I able to extract all mean elevations from every 30s cell that occur in the 10min cell of e. g. the first coordinate?

答:
The data you get are with a Raster format. So, you should use functions of library(raster). You can directly calculate the standard deviation through the aggregate function. Parameter fact is the size of the aggregation, here from 0.5 to 10, fact=10/0.5:

```<code>alt05_1 <- getData('worldclim', var='alt', res=0.5, lon=5, lat=45)
sd_alt05 <- aggregate(alt05_1, fact = 10/0.5, fun = sd)
</code>```

To get the mean, you may use the same function. mean is the default by the way:

```<code>mean_alt05 <- aggregate(alt05_1, fact = 10/0.5, fun = mean)
</code>```

Body:
I have to estimate topographic information of certain areas. Here a want to use data of worldclim. I need to estimate the the standard deviation of elevation for each 30s cell, that occurs within a 10min cell. However, I really do not know how to this. I somehow have to aggregate the cells geographically...

I first extract the required data of worldclim, elevations for 10min and for 30s (here I just picked a random number for lon and lat). I also provide one of my coordinates I use.

alt <- getData("worldclim",var="alt",res=10)

alt05_1 <- getData('worldclim', var='alt', res=0.5, lon=5, lat=45)

lats <- c(46.06667, 46.60134)

lons <- c(7.600000, 9.965973)

coords <- data.frame(x=lons,y=lats)

points_alt <- SpatialPoints(coords, proj4string = alt@crs)

values_alt <- extract(alt,points_alt)

altitude <- cbind.data.frame(coordinates(points_alt),values_alt)

So with this, I am of course able to extract the elevation for both relosutions, however, how am I able to extract all mean elevations from every 30s cell that occur in the 10min cell of e. g. the first coordinate?

Body:
The data you get are with a Raster format. So, you should use functions of library(raster). You can directly calculate the standard deviation through the aggregate function. Parameter fact is the size of the aggregation, here from 0.5 to 10, fact=10/0.5:

alt05_1 <- getData('worldclim', var='alt', res=0.5, lon=5, lat=45)
sd_alt05 <- aggregate(alt05_1, fact = 10/0.5, fun = sd)

To get the mean, you may use the same function. mean is the default by the way:

mean_alt05 <- aggregate(alt05_1, fact = 10/0.5, fun = mean)


问:
Starting Celery: AttributeError: 'module' object has no attribute 'celery'
I try to start a Celery worker server from a command line:

```<code>celery -A tasks worker --loglevel=info
</code>```

The code in tasks.py:

```<code>import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"

from celery import task

@task()
def add_photos_task( lad_id ):
...
</code>```

I get the next error:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/celery", line 8, in <module>
    load_entry_point('celery==3.0.12', 'console_scripts', 'celery')()
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/__main__.py", line 14, in main
    main()
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 946, in main
    cmd.execute_from_commandline(argv)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 890, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 177, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 295, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 313, in find_app
    return sym.celery
AttributeError: 'module' object has no attribute 'celery'
</code>```

Does anybody know why the 'celery' attribute cannot be found? Thank you for help.

The operating system is Linux Debian 5.

Edit. May be the clue. Could anyone explain me the next comment to a function (why we must be sure that it finds modules in the current directory)?

```<code># from celery/utils/imports.py
def import_from_cwd(module, imp=None, package=None):
    """Import module, but make sure it finds modules
    located in the current directory.

    Modules located in the current directory has
    precedence over modules located in `sys.path`.
    """
    if imp is None:
        imp = importlib.import_module
    with cwd_in_path():
        return imp(module, package=package)
</code>```

答: For anyone who is getting the same error message for an apparently different reason, note that if any of the imports in your initialization file fail, your app will raise this totally ambiguous AttributeError rather than the exception that initially caused it.

Body:
I try to start a Celery worker server from a command line:

celery -A tasks worker --loglevel=info

The code in tasks.py:

import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"

from celery import task

@task()
def add_photos_task( lad_id ):
...

I get the next error:

Traceback (most recent call last):
  File "/usr/local/bin/celery", line 8, in <module>
    load_entry_point('celery==3.0.12', 'console_scripts', 'celery')()
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/__main__.py", line 14, in main
    main()
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 946, in main
    cmd.execute_from_commandline(argv)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 890, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 177, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 295, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 313, in find_app
    return sym.celery
AttributeError: 'module' object has no attribute 'celery'

Does anybody know why the 'celery' attribute cannot be found? Thank you for help.

The operating system is Linux Debian 5.

Edit. May be the clue. Could anyone explain me the next comment to a function (why we must be sure that it finds modules in the current directory)?

# from celery/utils/imports.py
def import_from_cwd(module, imp=None, package=None):
    """Import module, but make sure it finds modules
    located in the current directory.

    Modules located in the current directory has
    precedence over modules located in `sys.path`.
    """
    if imp is None:
        imp = importlib.import_module
    with cwd_in_path():
        return imp(module, package=package)


问:
Turning off Stellar.js on by using browser detection for IE and Safari
I'm still learning jQuery, and I'm trying to figure out why this script isn't working.

The goal is to turn off Stellar.js parallax for mobile, which I've done by detecting a specific CSS class. I'm also trying to turn it off on Safari and IE because of jumpy performance when using a mousewheel to scroll. Any assistance troubleshooting, since I know the code is syntatically valid, would be awesome.

(It's wrapped in the "jQuery(document).ready(function($)" to function well in WordPress.)

```<code> jQuery(document).ready(function($) {
   $(document).ready(function() {
   // run test on initial page load
   checkSize();

   // run test on resize of the window
   $(window).resize(checkSize);
   });

   //Function to the css rule
   function checkSize(){
   if ($(".parallax").css("background-attachment") == "inherit" ){
      $(function () {
      $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
     });
   });
   }
   if ($(".parallax").css("background-attachment") == "fixed" ){
      $(function () {
      $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
      });
   });
   }
   }

   // Opera 8.0+
   var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

   // Firefox 1.0+
   var isFirefox = typeof InstallTrigger !== 'undefined';

   // Safari 3.0+ "[object HTMLElementConstructor]"
   var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

   // Internet Explorer 6-11
   var isIE = /*@cc_on!@*/false || !!document.documentMode;

   // Edge 20+
   var isEdge = !isIE && !!window.StyleMedia;

   // Chrome 1+
   var isChrome = !!window.chrome && !!window.chrome.webstore;

   // Blink engine detection
   var isBlink = (isChrome || isOpera) && !!window.CSS;

   // check if Safari or IE and disable parallax
   if(!isSafari || !isIE)
   {
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
       });
    }

});
</code>```

Update: I cleaned this up, but now I'm getting an error when I inspect that isFirefox, isChrome, etc., are not defined. Is that because I'm calling the variables incorrectly?

```<code>jQuery(document).ready(function($) {
   $(document).ready(function() {

   // hella browser checks
   // Opera 8.0+
   var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

   // Firefox 1.0+
   var isFirefox = typeof InstallTrigger !== 'undefined';

   // Safari 3.0+ "[object HTMLElementConstructor]"
   var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

   // Internet Explorer 6-11
   var isIE = /*@cc_on!@*/false || !!document.documentMode;

   // Edge 20+
   var isEdge = !isIE && !!window.StyleMedia;

   // Chrome 1+
   var isChrome = !!window.chrome && !!window.chrome.webstore;

   // Blink engine detection
   var isBlink = (isChrome || isOpera) && !!window.CSS;

   // run test on initial page load
   checkSize();

   // run test on resize of the window
   $(window).resize(checkSize);
});

   //Function to the css rule
   function checkSize(){
     if ($(".parallax").css("background-attachment") == "inherit" ){
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
       });
     });
    }
    if ( ($(".parallax").css("background-attachment") == "fixed" ) && (!isFirefox || !isChrome || !isBlink || !isOpera) ) {
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
       });
    });
   }
   }
});
</code>```

答:
This resolves it. Turns out I had to do it within the first function and I needed to call the variables within the screen size check. I hope this is helpful to someone else!</p>

```<code>jQuery(document).ready(function($) {
$(document).ready(function() {

// run test on initial page load
checkSize();

// run test on resize of the window
$(window).resize(checkSize);
});

// hella browser checks
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';

// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;

// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;

// Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;

// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;

//Function to the css rule
function checkSize(){
if ($(".parallax").css("background-attachment") == "inherit" ){
    $(function () {
    $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
    });
});
}
if ( ($(".parallax").css("background-attachment") == "fixed" ) && (isFirefox || isChrome || isBlink || isOpera) ) {
    $(function () {
    $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
    });
});
}
}
});
</code>```

Body:
I'm still learning jQuery, and I'm trying to figure out why this script isn't working.

The goal is to turn off Stellar.js parallax for mobile, which I've done by detecting a specific CSS class. I'm also trying to turn it off on Safari and IE because of jumpy performance when using a mousewheel to scroll. Any assistance troubleshooting, since I know the code is syntatically valid, would be awesome.

(It's wrapped in the "jQuery(document).ready(function($)" to function well in WordPress.)

 jQuery(document).ready(function($) {
   $(document).ready(function() {
   // run test on initial page load
   checkSize();

   // run test on resize of the window
   $(window).resize(checkSize);
   });

   //Function to the css rule
   function checkSize(){
   if ($(".parallax").css("background-attachment") == "inherit" ){
      $(function () {
      $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
     });
   });
   }
   if ($(".parallax").css("background-attachment") == "fixed" ){
      $(function () {
      $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
      });
   });
   }
   }

   // Opera 8.0+
   var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

   // Firefox 1.0+
   var isFirefox = typeof InstallTrigger !== 'undefined';

   // Safari 3.0+ "[object HTMLElementConstructor]"
   var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

   // Internet Explorer 6-11
   var isIE = /*@cc_on!@*/false || !!document.documentMode;

   // Edge 20+
   var isEdge = !isIE && !!window.StyleMedia;

   // Chrome 1+
   var isChrome = !!window.chrome && !!window.chrome.webstore;

   // Blink engine detection
   var isBlink = (isChrome || isOpera) && !!window.CSS;

   // check if Safari or IE and disable parallax
   if(!isSafari || !isIE)
   {
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
       });
    }

});

Update: I cleaned this up, but now I'm getting an error when I inspect that isFirefox, isChrome, etc., are not defined. Is that because I'm calling the variables incorrectly?

jQuery(document).ready(function($) {
   $(document).ready(function() {

   // hella browser checks
   // Opera 8.0+
   var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

   // Firefox 1.0+
   var isFirefox = typeof InstallTrigger !== 'undefined';

   // Safari 3.0+ "[object HTMLElementConstructor]"
   var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

   // Internet Explorer 6-11
   var isIE = /*@cc_on!@*/false || !!document.documentMode;

   // Edge 20+
   var isEdge = !isIE && !!window.StyleMedia;

   // Chrome 1+
   var isChrome = !!window.chrome && !!window.chrome.webstore;

   // Blink engine detection
   var isBlink = (isChrome || isOpera) && !!window.CSS;

   // run test on initial page load
   checkSize();

   // run test on resize of the window
   $(window).resize(checkSize);
});

   //Function to the css rule
   function checkSize(){
     if ($(".parallax").css("background-attachment") == "inherit" ){
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
       });
     });
    }
    if ( ($(".parallax").css("background-attachment") == "fixed" ) && (!isFirefox || !isChrome || !isBlink || !isOpera) ) {
       $(function () {
       $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
       });
    });
   }
   }
});

Body:
This resolves it. Turns out I had to do it within the first function and I needed to call the variables within the screen size check. I hope this is helpful to someone else!

jQuery(document).ready(function($) {
$(document).ready(function() {

// run test on initial page load
checkSize();

// run test on resize of the window
$(window).resize(checkSize);
});

// hella browser checks
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';

// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;

// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;

// Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;

// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;

//Function to the css rule
function checkSize(){
if ($(".parallax").css("background-attachment") == "inherit" ){
    $(function () {
    $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: false,
    });
});
}
if ( ($(".parallax").css("background-attachment") == "fixed" ) && (isFirefox || isChrome || isBlink || isOpera) ) {
    $(function () {
    $.stellar({
        horizontalScrolling: false,
        responsive: true,
        parallaxBackgrounds: true,
    });
});
}
}
});


问:
Convert JSON DATA to useable variables in Swift 3
I currently have code that will take the json data I give it and parse it however I have everything wrapped in a for loop and I don't know how to take it out.

JSON data:

```<code>[
{
"id": 1,
"displayName": "Jacob Blacksten",
"department": "DF",
"mamager": "San",
"office": "NYC",
"util": 2
}
]
</code>```

Working code:

```<code>do {
   let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

      guard let array = json as? [Any] else {return}

      for user in array {
          guard let userDict = user as? [String: Any] else {return}
          guard let id = userDict["id"] as? Int else { return }
          guard let name = userDict["displayName"] as? String else { return}
          guard let department = userDict["department"] as? String else {return}
          guard let manager = userDict["mamager"] as? String else {return}
          guard let office = userDict["office"] as? String else {return}
          guard let util = userDict["util"] as? Int else {return}

                print(id)
                print(name)
                print(department)
                print(manager)
                print(office)
                print(util)
            }

        } catch{
           print(error)
        }
</code>```

You will notice everything is inside a for loop creating an array of all "users". However I only have one user and I want to be able to pull out say "id" and use it as a variable to later print it out in a label in my app. I hope this makes sense. I basically just want to manipulate this JSON data so that way I can use it and print them in labels in my app.

答:
If you're trying to use your variables elsewhere, you just need to save them to something outside of the scope of your loop. I would suggest creating a User class and saving the values from the json to an instance of User.

```<code>// User.swift
class User {
    // Identifier
    let id: Int

    // Instance variables
    var name: String?
    var department: String?
    var manager: String?
    var office: String?
    var util: Int?

    init(withId id: Int) {
        self.id = id
    }
}
</code>```

Then, you can just change your loop to be something like this.

```<code>var user: User?

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

    guard let array = json as? [Any],
      let userDict = array[0] as? [String: Any],
      let id = userDict["id"] as? Int,
      let name = userDict["displayName"] as? String,
      let department = userDict["department"] as? String,
      let manager = userDict["manager"] as? String,
      let office = userDict["office"] as? String,
      let util = userDict["util"] as? Int else {
        return
    }

    user = User(withId: id)

    user.name = name
    user.department = department
    user.manager = manager
    user.office = office
    user.util = util

} catch{
    print(error)
}

 // Here, the user variable has all the updated info
 userIdLabel?.text = "\(user?.id)"
</code>```

Note: Did this all in browser, didn't test

Body:
I currently have code that will take the json data I give it and parse it however I have everything wrapped in a for loop and I don't know how to take it out.

JSON data:

[
{
"id": 1,
"displayName": "Jacob Blacksten",
"department": "DF",
"mamager": "San",
"office": "NYC",
"util": 2
}
]

Working code:

do {
   let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

      guard let array = json as? [Any] else {return}

      for user in array {
          guard let userDict = user as? [String: Any] else {return}
          guard let id = userDict["id"] as? Int else { return }
          guard let name = userDict["displayName"] as? String else { return}
          guard let department = userDict["department"] as? String else {return}
          guard let manager = userDict["mamager"] as? String else {return}
          guard let office = userDict["office"] as? String else {return}
          guard let util = userDict["util"] as? Int else {return}

                print(id)
                print(name)
                print(department)
                print(manager)
                print(office)
                print(util)
            }

        } catch{
           print(error)
        }

You will notice everything is inside a for loop creating an array of all "users". However I only have one user and I want to be able to pull out say "id" and use it as a variable to later print it out in a label in my app. I hope this makes sense. I basically just want to manipulate this JSON data so that way I can use it and print them in labels in my app.

Body:
If you're trying to use your variables elsewhere, you just need to save them to something outside of the scope of your loop. I would suggest creating a User class and saving the values from the json to an instance of User.

// User.swift
class User {
    // Identifier
    let id: Int

    // Instance variables
    var name: String?
    var department: String?
    var manager: String?
    var office: String?
    var util: Int?

    init(withId id: Int) {
        self.id = id
    }
}

Then, you can just change your loop to be something like this.

var user: User?

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

    guard let array = json as? [Any],
      let userDict = array[0] as? [String: Any],
      let id = userDict["id"] as? Int,
      let name = userDict["displayName"] as? String,
      let department = userDict["department"] as? String,
      let manager = userDict["manager"] as? String,
      let office = userDict["office"] as? String,
      let util = userDict["util"] as? Int else {
        return
    }

    user = User(withId: id)

    user.name = name
    user.department = department
    user.manager = manager
    user.office = office
    user.util = util

} catch{
    print(error)
}

 // Here, the user variable has all the updated info
 userIdLabel?.text = "\(user?.id)"

Note: Did this all in browser, didn't test


问:
DevExpress master detail row cell style
I want to changing my gridview's master detail rows style according to some conditoion. My code like this ;

```<code>        GridView newDetailView = grdLog.CreateView("GridView") as GridView;
        GridView View = sender as GridView;
        gvLog.MasterRowGetLevelDefaultView += (s, e2) =>
        {
            if (e.RowHandle >= 0)
            {
                for (int i = 0; i < gvLog.Columns.Count - 15; i++)
                {
                    string strTimeKey1 = View.GetRowCellDisplayText(e.RowHandle, View.Columns[i]);
                    string strTimeKey2 = View.GetRowCellDisplayText(View.FocusedRowHandle, View.Columns[i]);
                    if (!strTimeKey1.Equals(strTimeKey2))
                    {
                        e.Appearance.BackColor = Color.Red;
                    }
                }

            }
        };
</code>```

My parent row and detail row have same columns , It must be like If detail row' column value is different from parent row's column value , cell color will be red.

答:
From:How To Dynamically Format Columns For A Detail View

Columns are already created, when the MasterRowExpanded event
  occurs. Please try to use this event to customize them as you require,
  and let me know whether this solution meets your needs.

Refer these DevExpress threads:

Style conditions conditional formatting for master and detail views

How to set row style of Detail grid records after data binded to xtragrid master-detail data
Master/Detail grid with StyleFormatCondition

Title: DevExpress master detail row cell style

Body:
I want to changing my gridview's master detail rows style according to some conditoion. My code like this ;

        GridView newDetailView = grdLog.CreateView("GridView") as GridView;
        GridView View = sender as GridView;
        gvLog.MasterRowGetLevelDefaultView += (s, e2) =>
        {
            if (e.RowHandle >= 0)
            {
                for (int i = 0; i < gvLog.Columns.Count - 15; i++)
                {
                    string strTimeKey1 = View.GetRowCellDisplayText(e.RowHandle, View.Columns[i]);
                    string strTimeKey2 = View.GetRowCellDisplayText(View.FocusedRowHandle, View.Columns[i]);
                    if (!strTimeKey1.Equals(strTimeKey2))
                    {
                        e.Appearance.BackColor = Color.Red;
                    }
                }

            }
        };

My parent row and detail row have same columns , It must be like If detail row' column value is different from parent row's column value , cell color will be red.