问:
Keep the lifespan of variable after multiple function calls?
Assuming:

```<code>def myfunc(x):
    my_list  = []
    list.append(x)
</code>```

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

```<code>def myfunc(x):
    NA listv  = []
    list.append(x)
</code>```

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

答:
There is not a keyword to do this. There are workarounds (such as the mutable default argument), but there are better ways to achieve the same thing.

For exaple you could set the variable as a function attribute:

```<code>def my_func():
    my_func.my_list.append(1)

my_func.my_list = []
</code>```

However this is just a hacky way of doing this:

```<code>class MyFuncFactory:
    def __init__(self):
        self.my_list = []
    def __call__(self):
        self.my_list.append(1)
</code>```

Hence you are probably better of writing a class instead of a function in this case.

Sometimes you could use a nonlocal variable. For example to define a key function which requires state I usually write something like:

```<code>def my_key_builder():
    some_state = 0

    def key_function(arg):
        nonlocal some_state
        some_state += 1
        return some_state % 2
    return key_function

for x in sorted(a_list, key=my_key_builder()):
    print(x)
</code>```

Using a nonlocal instead of a global (or mutable default argument) allows you to use the key function multiple times. However if the function becomes slightly bigger using a class is probably the best option.

Body:
Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

def myfunc(x):
    NA listv  = []
    list.append(x)

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

Body:
There is not a keyword to do this. There are workarounds (such as the mutable default argument), but there are better ways to achieve the same thing.

For exaple you could set the variable as a function attribute:

def my_func():
    my_func.my_list.append(1)

my_func.my_list = []

However this is just a hacky way of doing this:

class MyFuncFactory:
    def __init__(self):
        self.my_list = []
    def __call__(self):
        self.my_list.append(1)

Hence you are probably better of writing a class instead of a function in this case.

Sometimes you could use a nonlocal variable. For example to define a key function which requires state I usually write something like:

def my_key_builder():
    some_state = 0

    def key_function(arg):
        nonlocal some_state
        some_state += 1
        return some_state % 2
    return key_function

for x in sorted(a_list, key=my_key_builder()):
    print(x)

Using a nonlocal instead of a global (or mutable default argument) allows you to use the key function multiple times. However if the function becomes slightly bigger using a class is probably the best option.


来源: stackexchange

问:
Makefile always thinks project is up to date - but files don't even exist
I have the following makefile:

```CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver```

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

``` [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.```

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.

答:
Your have directories with the same name as your targets.

Since your targets don't depend on anything, they'll always be considered up to date.

When specifying a target that isn't linked to a file on disk, you need to use the special target .PHONY:

```<code>.PHONY: adjl adjm
</code>```

You should also do the same for your clean and real_clean targets as well - otherwise they'll break if someone creates a file called "clean".

ContentLicense: CC BY-SA 2.5

Body:
I have the following makefile:

CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

 [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.

Body:
Your have directories with the same name as your targets.

Since your targets don't depend on anything, they'll always be considered up to date.

When specifying a target that isn't linked to a file on disk, you need to use the special target .PHONY:

.PHONY: adjl adjm

You should also do the same for your clean and real_clean targets as well - otherwise they'll break if someone creates a file called "clean".


问:
What does ".UNTIL !ZERO?" mean in x86 asm?
```<code>SENDS PROC NEAR
MOV CX,16
.REPEAT
   .REPEAT
      IN AL,CSTAT
      TEST AL,20H
   .UNTIL !ZERO?
   LODSB
   OUT DATA,AL
.UNTILCXZ

RET
</code>```

This is a x86 asm program for the PC16550D to read 16 bytes. The outer loop repeat 16 times. CSTAT is checked to see whether the data is received.
   In ".UNTIL !ZERO?", does ZERO mean the zero flag?  What does "?" and "!" mean?

答:
This is a post test loop condition that matches when the zero flag is unset.

The .UNTIL directive ends a .REPEAT block and has the syntax: .UNTIL condition

In the situation in question !ZERO? is the condition. This is an expression with 2 operators. The ! operator is a logical negation. The ZERO? operator checks the status of the zero flag. Combined they check for the zero flag being unset.

ContentLicense: CC BY-SA 3.0

Body:
SENDS PROC NEAR
MOV CX,16
.REPEAT
   .REPEAT
      IN AL,CSTAT
      TEST AL,20H
   .UNTIL !ZERO?
   LODSB
   OUT DATA,AL
.UNTILCXZ

RET

This is a x86 asm program for the PC16550D to read 16 bytes. The outer loop repeat 16 times. CSTAT is checked to see whether the data is received.
   In ".UNTIL !ZERO?", does ZERO mean the zero flag?  What does "?" and "!" mean?


问:
Validate ABI JSon (Ethereum)
i've a problem with the following Json :

```<code>[ { constant: false,
inputs: [Object],
    name: 'set',
    outputs: [],
    type: 'function'
}, {
    constant: true,
    inputs: [],
    name: 'get',
    outputs: [Object],
    type: 'function'
}, {
    anonymous: false,
    inputs: [Object],
    name: 'ItBlinks',
    type: 'event'
},
    set: {
        [Function: bound]
        request: [Function: bound],
        call: [Function: bound],
        sendTransaction: [Function: bound],
        estimateGas: [Function: bound],
        getData: [Function: bound],
        uint256: [Circular]
    },
    get: {
        [Function: bound]
        request: [Function: bound],
        call: [Function: bound],
        sendTransaction: [Function: bound],
        estimateGas: [Function: bound],
        getData: [Function: bound],
        '': [Circular]
    },
    allEvents: [Function: bound],
    ItBlinks: {
        [Function: bound] uint256: [Function: bound]
    }
}
</code>```

This JSon is the ABI and this should be add to my contract into my wallet (Ethereum Wallet) to send information (in this case, made a blink event on my raspberry PI)

When I add these line into my contract in my ethereum wallet, it tell me my Json is not correct.

I've try to validate, but it give me an error, and i cannot solve it. (I'm a beginner in JSon)

Somebody can help me to validate the get / set method? to be a valid JSon format?

This is the full return with coinbase (the address and coinbase is modified) :

```<code>coinbase : 0x20408a19c567a475545947600a95130f24f7C123
{ _eth:
   Eth {
     _requestManager: { provider: [Object], polls: {}, timeout: null },
     getBalance: { [Function] request: [Function: bound ], call: 'eth_getBalance' },
     getStorageAt: { [Function] request: [Function: bound ], call: 'eth_getStorageAt' },
     getCode: { [Function] request: [Function: bound ], call: 'eth_getCode' },
     getBlock: { [Function] request: [Function: bound ], call: [Function] },
     getUncle: { [Function] request: [Function: bound ], call: [Function] },
     getCompilers: { [Function] request: [Function: bound ], call: 'eth_getCompilers' },
     getBlockTransactionCount: { [Function] request: [Function: bound ], call: [Function] },
     getBlockUncleCount: { [Function] request: [Function: bound ], call: [Function] },
     getTransaction:
      { [Function]
        request: [Function: bound ],
        call: 'eth_getTransactionByHash' },
     getTransactionFromBlock: { [Function] request: [Function: bound ], call: [Function] },
     getTransactionReceipt:
      { [Function]
        request: [Function: bound ],
        call: 'eth_getTransactionReceipt' },
     getTransactionCount: { [Function] request: [Function: bound ], call: 'eth_getTransactionCount' },
     call: { [Function] request: [Function: bound ], call: 'eth_call' },
     estimateGas: { [Function] request: [Function: bound ], call: 'eth_estimateGas' },
     sendRawTransaction: { [Function] request: [Function: bound ], call: 'eth_sendRawTransaction' },
     signTransaction: { [Function] request: [Function: bound ], call: 'eth_signTransaction' },
     sendTransaction: { [Function] request: [Function: bound ], call: 'eth_sendTransaction' },
     sign: { [Function] request: [Function: bound ], call: 'eth_sign' },
     compile: { solidity: [Object], lll: [Object], serpent: [Object] },
     submitWork: { [Function] request: [Function: bound ], call: 'eth_submitWork' },
     getWork: { [Function] request: [Function: bound ], call: 'eth_getWork' },
     coinbase: [Getter],
     getCoinbase: { [Function] request: [Function: bound ] },
     mining: [Getter],
     getMining: { [Function] request: [Function: bound ] },
     hashrate: [Getter],
     getHashrate: { [Function] request: [Function: bound ] },
     syncing: [Getter],
     getSyncing: { [Function] request: [Function: bound ] },
     gasPrice: [Getter],
     getGasPrice: { [Function] request: [Function: bound ] },
     accounts: [Getter],
     getAccounts: { [Function] request: [Function: bound ] },
     blockNumber: [Getter],
     getBlockNumber: { [Function] request: [Function: bound ] },
     protocolVersion: [Getter],
     getProtocolVersion: { [Function] request: [Function: bound ] },
     iban:
      { [Function]
        fromAddress: [Function],
        fromBban: [Function],
        createIndirect: [Function],
        isValid: [Function] },
     sendIBANTransaction: [Function: bound ] },
  transactionHash: null,
  address: '0x9535eb707582edb3317dfdcdb365ce4186500C123',
  abi:
   [ { constant: false,
       inputs: [Object],
       name: 'set',
       outputs: [],
       type: 'function' },
     { constant: true,
       inputs: [],
       name: 'get',
       outputs: [Object],
       type: 'function' },
     { anonymous: false,
       inputs: [Object],
       name: 'ItBlinks',
       type: 'event' } ],
  set:
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     uint256: [Circular] },
  get:
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     '': [Circular] },
  allEvents: [Function: bound ],
  ItBlinks: { [Function: bound ] uint256: [Function: bound ] }
}
</code>```

答:
You do not have valid JSON. JSON has key/value pairs with keys being strings delimited by double quotes. Details of JSON can be found here

From the Ethereum documentation this is an example of JSON in the ABI:

```<code>[{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}]
</code>```

Details of the ethereum contract ABI can be found here

Title: Validate ABI JSon (Ethereum)

Body:
i've a problem with the following Json :

[ { constant: false,
inputs: [Object],
    name: 'set',
    outputs: [],
    type: 'function'
}, {
    constant: true,
    inputs: [],
    name: 'get',
    outputs: [Object],
    type: 'function'
}, {
    anonymous: false,
    inputs: [Object],
    name: 'ItBlinks',
    type: 'event'
},
    set: {
        [Function: bound]
        request: [Function: bound],
        call: [Function: bound],
        sendTransaction: [Function: bound],
        estimateGas: [Function: bound],
        getData: [Function: bound],
        uint256: [Circular]
    },
    get: {
        [Function: bound]
        request: [Function: bound],
        call: [Function: bound],
        sendTransaction: [Function: bound],
        estimateGas: [Function: bound],
        getData: [Function: bound],
        '': [Circular]
    },
    allEvents: [Function: bound],
    ItBlinks: {
        [Function: bound] uint256: [Function: bound]
    }
}

This JSon is the ABI and this should be add to my contract into my wallet (Ethereum Wallet) to send information (in this case, made a blink event on my raspberry PI)

When I add these line into my contract in my ethereum wallet, it tell me my Json is not correct.

I've try to validate, but it give me an error, and i cannot solve it. (I'm a beginner in JSon)

Somebody can help me to validate the get / set method? to be a valid JSon format?

This is the full return with coinbase (the address and coinbase is modified) :

coinbase : 0x20408a19c567a475545947600a95130f24f7C123
{ _eth:
   Eth {
     _requestManager: { provider: [Object], polls: {}, timeout: null },
     getBalance: { [Function] request: [Function: bound ], call: 'eth_getBalance' },
     getStorageAt: { [Function] request: [Function: bound ], call: 'eth_getStorageAt' },
     getCode: { [Function] request: [Function: bound ], call: 'eth_getCode' },
     getBlock: { [Function] request: [Function: bound ], call: [Function] },
     getUncle: { [Function] request: [Function: bound ], call: [Function] },
     getCompilers: { [Function] request: [Function: bound ], call: 'eth_getCompilers' },
     getBlockTransactionCount: { [Function] request: [Function: bound ], call: [Function] },
     getBlockUncleCount: { [Function] request: [Function: bound ], call: [Function] },
     getTransaction:
      { [Function]
        request: [Function: bound ],
        call: 'eth_getTransactionByHash' },
     getTransactionFromBlock: { [Function] request: [Function: bound ], call: [Function] },
     getTransactionReceipt:
      { [Function]
        request: [Function: bound ],
        call: 'eth_getTransactionReceipt' },
     getTransactionCount: { [Function] request: [Function: bound ], call: 'eth_getTransactionCount' },
     call: { [Function] request: [Function: bound ], call: 'eth_call' },
     estimateGas: { [Function] request: [Function: bound ], call: 'eth_estimateGas' },
     sendRawTransaction: { [Function] request: [Function: bound ], call: 'eth_sendRawTransaction' },
     signTransaction: { [Function] request: [Function: bound ], call: 'eth_signTransaction' },
     sendTransaction: { [Function] request: [Function: bound ], call: 'eth_sendTransaction' },
     sign: { [Function] request: [Function: bound ], call: 'eth_sign' },
     compile: { solidity: [Object], lll: [Object], serpent: [Object] },
     submitWork: { [Function] request: [Function: bound ], call: 'eth_submitWork' },
     getWork: { [Function] request: [Function: bound ], call: 'eth_getWork' },
     coinbase: [Getter],
     getCoinbase: { [Function] request: [Function: bound ] },
     mining: [Getter],
     getMining: { [Function] request: [Function: bound ] },
     hashrate: [Getter],
     getHashrate: { [Function] request: [Function: bound ] },
     syncing: [Getter],
     getSyncing: { [Function] request: [Function: bound ] },
     gasPrice: [Getter],
     getGasPrice: { [Function] request: [Function: bound ] },
     accounts: [Getter],
     getAccounts: { [Function] request: [Function: bound ] },
     blockNumber: [Getter],
     getBlockNumber: { [Function] request: [Function: bound ] },
     protocolVersion: [Getter],
     getProtocolVersion: { [Function] request: [Function: bound ] },
     iban:
      { [Function]
        fromAddress: [Function],
        fromBban: [Function],
        createIndirect: [Function],
        isValid: [Function] },
     sendIBANTransaction: [Function: bound ] },
  transactionHash: null,
  address: '0x9535eb707582edb3317dfdcdb365ce4186500C123',
  abi:
   [ { constant: false,
       inputs: [Object],
       name: 'set',
       outputs: [],
       type: 'function' },
     { constant: true,
       inputs: [],
       name: 'get',
       outputs: [Object],
       type: 'function' },
     { anonymous: false,
       inputs: [Object],
       name: 'ItBlinks',
       type: 'event' } ],
  set:
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     uint256: [Circular] },
  get:
   { [Function: bound ]
     request: [Function: bound ],
     call: [Function: bound ],
     sendTransaction: [Function: bound ],
     estimateGas: [Function: bound ],
     getData: [Function: bound ],
     '': [Circular] },
  allEvents: [Function: bound ],
  ItBlinks: { [Function: bound ] uint256: [Function: bound ] }
}

Body:
You do not have valid JSON. JSON has key/value pairs with keys being strings delimited by double quotes. Details of JSON can be found here

From the Ethereum documentation this is an example of JSON in the ABI:

[{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}]

Details of the ethereum contract ABI can be found here


问:
Unresolved reference async in Kotlin
I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?

Unresolved reference: async

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    async() {
        val forecastWeather = ForecastRequest("302015").execute()
        Log.d("Test", forecastWeather.toString())
    }
}
</code>```

ForecastRequest.kt

```<code>class ForecastRequest(val zipcode: String) {
    companion object {
        private val APP_ID = "XYZ"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                    "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }

    fun execute(): ForecastResponse {
        val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
        return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
    }
}
</code>```

Top level build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module level build.gradle

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.williams.thirddemo"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.code.gson:gson:2.8.1'
}
</code>```

答:
Different Kotlin libraries can have different implementations of async that do different things.

If you wanted the general async-await function from the core library, make sure you have a dependency to kotlinx.coroutines

Title: Unresolved reference async in Kotlin

Body:
I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?

Unresolved reference: async

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    async() {
        val forecastWeather = ForecastRequest("302015").execute()
        Log.d("Test", forecastWeather.toString())
    }
}

ForecastRequest.kt

class ForecastRequest(val zipcode: String) {
    companion object {
        private val APP_ID = "XYZ"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                    "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }

    fun execute(): ForecastResponse {
        val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
        return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
    }
}

Top level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module level build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.williams.thirddemo"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.code.gson:gson:2.8.1'
}


问:
R/ggplot Cumulative Sum in Histogram
I have a dataset with user IDs and the number of objects they created. I drew the histogram using ggplot and now I'm trying to include the cumulative sum of the x-values as a line. The aim is to see much the bins contribute to the total number. I tried the following:

```<code>ggplot(data=userStats,aes(x=Num_Tours)) + geom_histogram(binwidth = 0.2)+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   geom_line(aes(x=Num_Tours, y=cumsum(Num_Tours)/sum(Num_Tours)*3500),color="red")+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./3500, name = "Cummulative percentage of routes [%]"))
</code>```

This does not work because I don't include any bins so the plot

and

```<code>ggplot(data=userStats,aes(x=Num_Tours)) + geom_histogram(binwidth = 0.2)+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   stat_bin(aes(y=cumsum(..count..)),binwidth = 0.2, geom="line",color="red")+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./3500, name = "Cummulative percentage of routes [%]"))
</code>```

Resulting in this:
.

Here the cumsum of the count is considered. What I want is the cumsum of the count * value of the bin. Then it should be normalized, so that it can be displayed in one plot. What I am trying to to is something like that:

I would appreciate any input! Thanks

Edit:
As test data, this should work:

```<code>userID <- c(1:100)
Num_Tours <- sample(1:100,100)
userStats <- data.frame(userID,Num_Tours)
userStats$cumulative <- cumsum(userStats$Num_Tours/sum(userStats$Num_Tours))
</code>```

答:
Here is an illustrative example that could be helpful for you.

```<code>set.seed(111)
userID <- c(1:100)
Num_Tours <- sample(1:100, 100, replace=T)
userStats <- data.frame(userID, Num_Tours)

# Sorting x data
userStats$Num_Tours <- sort(userStats$Num_Tours)
userStats$cumulative <- cumsum(userStats$Num_Tours/sum(userStats$Num_Tours))

library(ggplot2)
# Fix manually the maximum value of y-axis
ymax <- 40
ggplot(data=userStats,aes(x=Num_Tours)) +
   geom_histogram(binwidth = 0.2, col="white")+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   geom_line(aes(x=Num_Tours,y=cumulative*ymax), col="red", lwd=1)+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./ymax,
    name = "Cumulative percentage of routes [%]"))
</code>```

Title: R/ggplot Cumulative Sum in Histogram

Body:
I have a dataset with user IDs and the number of objects they created. I drew the histogram using ggplot and now I'm trying to include the cumulative sum of the x-values as a line. The aim is to see much the bins contribute to the total number. I tried the following:

ggplot(data=userStats,aes(x=Num_Tours)) + geom_histogram(binwidth = 0.2)+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   geom_line(aes(x=Num_Tours, y=cumsum(Num_Tours)/sum(Num_Tours)*3500),color="red")+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./3500, name = "Cummulative percentage of routes [%]"))

This does not work because I don't include any bins so the plot

and

ggplot(data=userStats,aes(x=Num_Tours)) + geom_histogram(binwidth = 0.2)+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   stat_bin(aes(y=cumsum(..count..)),binwidth = 0.2, geom="line",color="red")+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./3500, name = "Cummulative percentage of routes [%]"))

Resulting in this:
.

Here the cumsum of the count is considered. What I want is the cumsum of the count * value of the bin. Then it should be normalized, so that it can be displayed in one plot. What I am trying to to is something like that:

I would appreciate any input! Thanks

Edit:
As test data, this should work:

userID <- c(1:100)
Num_Tours <- sample(1:100,100)
userStats <- data.frame(userID,Num_Tours)
userStats$cumulative <- cumsum(userStats$Num_Tours/sum(userStats$Num_Tours))

Body:
Here is an illustrative example that could be helpful for you.

set.seed(111)
userID <- c(1:100)
Num_Tours <- sample(1:100, 100, replace=T)
userStats <- data.frame(userID, Num_Tours)

# Sorting x data
userStats$Num_Tours <- sort(userStats$Num_Tours)
userStats$cumulative <- cumsum(userStats$Num_Tours/sum(userStats$Num_Tours))

library(ggplot2)
# Fix manually the maximum value of y-axis
ymax <- 40
ggplot(data=userStats,aes(x=Num_Tours)) +
   geom_histogram(binwidth = 0.2, col="white")+
   scale_x_log10(name = 'Number of planned tours',breaks=c(1,5,10,50,100,200))+
   geom_line(aes(x=Num_Tours,y=cumulative*ymax), col="red", lwd=1)+
   scale_y_continuous(name = 'Number of users', sec.axis = sec_axis(~./ymax,
    name = "Cumulative percentage of routes [%]"))


问:
electron browser javascript error
I am very new to node, javascript, and electron. I am just trying to write a simple app that opens a local HTML file in a browser window. The local file has some complex embedded javascript (tiddlywiki). Here is some sample code (I did not use local file in this one, but the result is the same):

```<code>const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})

// and load the index.html of the app.
win.loadURL(url.format({
    pathname: 'tiddlywiki.com',
    protocol: 'http:',
    slashes: true,
    webPreferences: {
      nodeIntegration: false,
 }
 }))
</code>```

When the electron app launches I get the following error in the browser dev tools.

```<code>Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.$tw.boot.startup (tiddlywiki.com/:27506)
    at tiddlywiki.com/:27765
    at Object.$tw.boot.decryptEncryptedTiddlers (tiddlywiki.com/:27053)
    at Object.$tw.boot.boot (tiddlywiki.com/:27763)
    at _boot (tiddlywiki.com/:27772)
    at tiddlywiki.com/:27782
</code>```

I assume this is because of some integration of the node.js object model? Sorry for the lack of understanding. Thanks in advance for the help.

答:
You put the webPreferences into the wrong place.

You have to put it in the initialization for the BrowserWindow and not in url.format:

```<code>win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: false
    }
})
</code>```

Title: electron browser javascript error

Body:
I am very new to node, javascript, and electron. I am just trying to write a simple app that opens a local HTML file in a browser window. The local file has some complex embedded javascript (tiddlywiki). Here is some sample code (I did not use local file in this one, but the result is the same):

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})

// and load the index.html of the app.
win.loadURL(url.format({
    pathname: 'tiddlywiki.com',
    protocol: 'http:',
    slashes: true,
    webPreferences: {
      nodeIntegration: false,
 }
 }))

When the electron app launches I get the following error in the browser dev tools.

Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.$tw.boot.startup (tiddlywiki.com/:27506)
    at tiddlywiki.com/:27765
    at Object.$tw.boot.decryptEncryptedTiddlers (tiddlywiki.com/:27053)
    at Object.$tw.boot.boot (tiddlywiki.com/:27763)
    at _boot (tiddlywiki.com/:27772)
    at tiddlywiki.com/:27782

I assume this is because of some integration of the node.js object model? Sorry for the lack of understanding. Thanks in advance for the help.

Body:
You put the webPreferences into the wrong place.

You have to put it in the initialization for the BrowserWindow and not in url.format:

win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: false
    }
})


问:
Does Object destructing work by reference or it clones the object
I need to copy an object from this.state to change some of its property values.

For example in the following method state is being mutated directly (this.state.errors = {})

```<code>   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };
</code>```

To avoid this, I know that we can use :

a) The object spread operator

```<code>let errors={...this.state.errors};
</code>```

b) Or Object.assign

```<code>let errors=Object.assign({},this.state.errors);
</code>```

But sometimes I've seem some examples in which object destructuring it is used like this:

```<code>authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };
</code>```

So my question is , is it object destructuring equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring ?

答:
No. Object destructuring just assign the same object inside the 'this.state' to a different variable.

```<code>let {errors, author} = this.state;
</code>```

So the new error variable refer to the same error object inside the this.state

However, next line errors = {}; doesn't mutate the this.state. It only rereference the error variable to a new empty object. So the given code still doesn't  do a state mutation. In fact, there is no any meaning of having error in this object destructuring. It's similar to something like this.

```<code>let errors = this.state.errors;
errors = {};
</code>```

Which is essentially no difference from this.

```<code>let errors = {};
</code>```

Body:
I need to copy an object from this.state to change some of its property values.

For example in the following method state is being mutated directly (this.state.errors = {})

   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };

To avoid this, I know that we can use :

a) The object spread operator

let errors={...this.state.errors};

b) Or Object.assign

let errors=Object.assign({},this.state.errors);

But sometimes I've seem some examples in which object destructuring it is used like this:

authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };

So my question is , is it object destructuring equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring ?

Body:
No. Object destructuring just assign the same object inside the 'this.state' to a different variable.

let {errors, author} = this.state;

So the new error variable refer to the same error object inside the this.state

However, next line errors = {}; doesn't mutate the this.state. It only rereference the error variable to a new empty object. So the given code still doesn't  do a state mutation. In fact, there is no any meaning of having error in this object destructuring. It's similar to something like this.

let errors = this.state.errors;
errors = {};

Which is essentially no difference from this.

let errors = {};


问:
iteration on keypress
I am trying to make a program in Python that will capture and save a unique screenshot each time I press 'Enter'. I am having problems with assigning unique file names to said screenshots. Here is my code piece concerning capturing a screenshot:

```<code>def on_press(key):
if key == Key.enter:
    x = 1
    bitmap = autopy.bitmap.capture_screen()
    bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
    x += 1
</code>```

As you can see I initialized a variable x that I want to increase in value by 1 each time I press 'Enter'. The sequence of program would be this: press Enter -> capture screenshot 1 -> increase x value by one -> press Enter -> capture screenshot 2 -> increase x value by one (and so forth). I tried to use for loops to change the value of x but the result usually involves capturing multitude of screenshots all at once after I have pressed 'Enter'. How to solve it? Any help is greatly appreciated.

答:
Every time, key is set to Key.enter, you reset the value of x back to 1. Therefore x will always 1, when you save the file. You need to save the state of x outside the function.

```<code>x = 1

def on_press(key):
    global x
    if key == Key.enter:
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1
</code>```

Title: iteration on keypress

Body:
I am trying to make a program in Python that will capture and save a unique screenshot each time I press 'Enter'. I am having problems with assigning unique file names to said screenshots. Here is my code piece concerning capturing a screenshot:

def on_press(key):
if key == Key.enter:
    x = 1
    bitmap = autopy.bitmap.capture_screen()
    bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
    x += 1

As you can see I initialized a variable x that I want to increase in value by 1 each time I press 'Enter'. The sequence of program would be this: press Enter -> capture screenshot 1 -> increase x value by one -> press Enter -> capture screenshot 2 -> increase x value by one (and so forth). I tried to use for loops to change the value of x but the result usually involves capturing multitude of screenshots all at once after I have pressed 'Enter'. How to solve it? Any help is greatly appreciated.

Body:
Every time, key is set to Key.enter, you reset the value of x back to 1. Therefore x will always 1, when you save the file. You need to save the state of x outside the function.

x = 1

def on_press(key):
    global x
    if key == Key.enter:
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1


问:
in python is there a better way to apply a list of functions to a dictionary
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

```<code>def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))
</code>```

Produces expected output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

```<code>def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})
</code>```

This produces the desired output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

答:
reduce (or functools.reduce in Python 3) can be used to compose a list of functions into a single function. This requires you to define a composition function:

```<code>def compose(f, g):
    def _(x):
        return f(g(x))
    return _
</code>```

and an identity function:

```<code>def identity(x):
    return x
</code>```

Using these, you can create a function g that applies each function in order to an initial input.

```<code>g = reduce(compose, [func3, func2, func1], identity)
assert (g({'firstElement': 'good'}) ==
        {'firstElement': 'good', 'foo': 10, 'bar': 100, 'baz': 110})
</code>```

Note this works because func1, func2 and func3 are similar enough to pure functions that you can make use of the function monoid. Loosely speaking, it just means that function composition is associative (compose(f, compose(g, h)) is the same as compose(compose(f, g), h)) and that the identity function is neutral under composition (compose(identity, f) and compose(f, identity) are both the same as f itself).

Your three functions aren't really pure functions; they are more like identity functions with side effects. However, you can treat them as pure functions because you are using them as if they were defined as, for example,

```<code>def func1(h):
    h1 = {}
    h1.update(h)
    h1['foo'] = 10
    return h1
</code>```

Exercise for the reader: determine if my call to reduce actually defines g(x) = func3(func2(func1(x))) or g(x) = func1(func2(func3(x)).

Body:
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))

Produces expected output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})

This produces the desired output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

Body:
reduce (or functools.reduce in Python 3) can be used to compose a list of functions into a single function. This requires you to define a composition function:

def compose(f, g):
    def _(x):
        return f(g(x))
    return _

and an identity function:

def identity(x):
    return x

Using these, you can create a function g that applies each function in order to an initial input.

g = reduce(compose, [func3, func2, func1], identity)
assert (g({'firstElement': 'good'}) ==
        {'firstElement': 'good', 'foo': 10, 'bar': 100, 'baz': 110})

Note this works because func1, func2 and func3 are similar enough to pure functions that you can make use of the function monoid. Loosely speaking, it just means that function composition is associative (compose(f, compose(g, h)) is the same as compose(compose(f, g), h)) and that the identity function is neutral under composition (compose(identity, f) and compose(f, identity) are both the same as f itself).

Your three functions aren't really pure functions; they are more like identity functions with side effects. However, you can treat them as pure functions because you are using them as if they were defined as, for example,

def func1(h):
    h1 = {}
    h1.update(h)
    h1['foo'] = 10
    return h1

Exercise for the reader: determine if my call to reduce actually defines g(x) = func3(func2(func1(x))) or g(x) = func1(func2(func3(x)).


问:
Change serviceInfo packages dynamically for Accessibility Service
I'm developing an app that launches over other apps. Currently I'm using an AccessibilityService with setServiceInfo to listen to window changes, for specific package names, but I'm unable to change these package names dynamically.

```<code>private void setServiceInfo(String apps[]) {

    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    info.notificationTimeout = 0;
    info.packageNames = apps;
    setServiceInfo(info);
}
</code>```

The above code is how I'm setting the serviceInfo. I'm calling setServiceInfo onServiceConnected to first initialise and onAccessibilityEvents for any changes to the package names.

If accessibility service isn't the way to go about this, please suggest alternatives such as services etc.

答:
Reuse existent AccessibilityServiceInfo object via getServiceInfo() (added in API 16) instead of creating new one:

```<code>     @Override
     protected void onServiceConnected() {
            super.onServiceConnected();
            AccessibilityServiceInfo info = getServiceInfo();
            // your other assignments
            info.packageNames = apps;
            setServiceInfo(info);
        }
</code>```

This worked in my tests.

Body:
I'm developing an app that launches over other apps. Currently I'm using an AccessibilityService with setServiceInfo to listen to window changes, for specific package names, but I'm unable to change these package names dynamically.

private void setServiceInfo(String apps[]) {

    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    info.notificationTimeout = 0;
    info.packageNames = apps;
    setServiceInfo(info);
}

The above code is how I'm setting the serviceInfo. I'm calling setServiceInfo onServiceConnected to first initialise and onAccessibilityEvents for any changes to the package names.

If accessibility service isn't the way to go about this, please suggest alternatives such as services etc.

Body:
Reuse existent AccessibilityServiceInfo object via getServiceInfo() (added in API 16) instead of creating new one:

     @Override
     protected void onServiceConnected() {
            super.onServiceConnected();
            AccessibilityServiceInfo info = getServiceInfo();
            // your other assignments
            info.packageNames = apps;
            setServiceInfo(info);
        }

This worked in my tests.


问:
how to run codeiginter project downloaded from github
i have downloaded zip folder from github , link of github code is here

https://github.com/jekkos/opensourcepos

i have extracted this folder in xampp htdocs folder as POS folder and made database with the name of github_pos in mysql. but when i try to run through local host i get this error.
enter image description here

can someone help me how to run project downloaded from github ?

答:
You are going right way. There is no serious issue with your installation. Your installation step should be:

Step 1: Clone/Download zip from git.

Step 2: Import database to phpMyAdmin (SQL file located in the root/application/config.php)

```<code>$db['default'] = array(
    'dsn'   => '',
    'hostname' => !empty(getenv('MYSQL_HOST_NAME')) ? getenv('MYSQL_HOST_NAME') : 'localhost',
    'username' => !empty(getenv('MYSQL_USERNAME')) ? getenv('MYSQL_USERNAME') : 'root',
    'password' => !empty(getenv('MYSQL_PASSWORD')) ? getenv('MYSQL_PASSWORD') : '',
    'database' => !empty(getenv('MYSQL_DB_NAME')) ? getenv('MYSQL_DB_NAME') : 'open',
    'dbdriver' => 'mysqli',
    'dbprefix' => 'ospos_',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
</code>```

Step:3 Import database.sql file (located in database folder).

```<code>       - Go to localhost/phpmyadmin
       - select your empty(or your database)
       - select "Import" menu option from the top.
       - Click brows button and select your database.sql file.
       - press "go" button bottom of the screen
</code>```

now, within few moment your database will be update(add new tables require in the application.)

Step:4 access your project with localhost/pos/public instead of localhost/pos

Your facing access forbidden issue because you don't have access permission by default you can find configuration in the Apache .htaccess config file. Hope this will help you..!

Greetings!

Body:
You are going right way. There is no serious issue with your installation. Your installation step should be:

Step 1: Clone/Download zip from git.

Step 2: Import database to phpMyAdmin (SQL file located in the root/application/config.php)

$db['default'] = array(
    'dsn'   => '',
    'hostname' => !empty(getenv('MYSQL_HOST_NAME')) ? getenv('MYSQL_HOST_NAME') : 'localhost',
    'username' => !empty(getenv('MYSQL_USERNAME')) ? getenv('MYSQL_USERNAME') : 'root',
    'password' => !empty(getenv('MYSQL_PASSWORD')) ? getenv('MYSQL_PASSWORD') : '',
    'database' => !empty(getenv('MYSQL_DB_NAME')) ? getenv('MYSQL_DB_NAME') : 'open',
    'dbdriver' => 'mysqli',
    'dbprefix' => 'ospos_',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Step:3 Import database.sql file (located in database folder).

       - Go to localhost/phpmyadmin
       - select your empty(or your database)
       - select "Import" menu option from the top.
       - Click brows button and select your database.sql file.
       - press "go" button bottom of the screen

now, within few moment your database will be update(add new tables require in the application.)

Step:4 access your project with localhost/pos/public instead of localhost/pos

Your facing access forbidden issue because you don't have access permission by default you can find configuration in the Apache .htaccess config file. Hope this will help you..!

Greetings!


问:
install curl extension fail
I try to install php curl extension in my win xp environment but failed.
To follow the manual ,I have copied libeay32.dll and ssleay32.dll into %systemroot%/system32 dir ,the ';' in front of 'extension=php_curl.dll' also has been opened
but in the test function phpinfo(), there is still not any clues

but the other extensions like php_gd2.dll,php_pdo.dll can be opened or closed without any problems

any help would be appreciated

答:
use this function to try and load the file itself
http://php.net/manual/en/function.dl.php

then run extension_loaded() to check if it worked.

Then you can test if it is actually a path problem. Sometimes there are multiple extension directories. make sure you are using the right one.

Title: install curl extension fail


问:
Cannot install BeautifulSoup for python 3.6
I have spent the past 45 minutes hopelessly trying to run:

```<code>from bs4 import BeautifulSoup
</code>```

But to no avail. I have tried the commands:

```<code>python -m pip install beautifulsoup4
</code>```

where it says:

```<code>Requirement already satisfied: beautifulsoup4 in c:\python27\lib\site-packages
</code>```

I have tried:

```<code>pip3 install beautifulsoup4
</code>```

where it says the same.

I have tried:

```<code>pip install beautifulsoup4
</code>```

Same thing.

I have looked all over stackoverflow, youtube, I am driving myself insane trying to figure this out. I have no idea what to do, please help me.

When I try to run my program main.py with the following code:

```<code>from bs4 import BeautifulSoup
</code>```

With py -3 main.py, I get the error:

```<code>ModuleNotFoundError: No module named 'bs4'
</code>```

Please please please please help me.

I have tried the method proposed at BeautifulSoup4 can't be installed in python3.5 on Windows7 but to no avail.

答:
Now there is beautifulsoup4 for Python 3.6.
It's the same, am using it this way on my webcrawl project.

Just add the beautifulsoup4 module to the project. Then try the line

```<code>from bs4 import BeautifulSoup
</code>```

Body:
I have spent the past 45 minutes hopelessly trying to run:

from bs4 import BeautifulSoup

But to no avail. I have tried the commands:

python -m pip install beautifulsoup4

where it says:

Requirement already satisfied: beautifulsoup4 in c:\python27\lib\site-packages

I have tried:

pip3 install beautifulsoup4

where it says the same.

I have tried:

pip install beautifulsoup4

Same thing.

I have looked all over stackoverflow, youtube, I am driving myself insane trying to figure this out. I have no idea what to do, please help me.

When I try to run my program main.py with the following code:

from bs4 import BeautifulSoup

With py -3 main.py, I get the error:

ModuleNotFoundError: No module named 'bs4'

Please please please please help me.

I have tried the method proposed at BeautifulSoup4 can't be installed in python3.5 on Windows7 but to no avail.

Body:
Now there is beautifulsoup4 for Python 3.6.
It's the same, am using it this way on my webcrawl project.

Just add the beautifulsoup4 module to the project. Then try the line

from bs4 import BeautifulSoup


问:
Build:Cannot Find type definition file for 'mocha' in tsc file after updating to angular 4
I am updating my current project version to Angular 4. And I am getting error like Build:Cannot Find type definition file for 'mocha' in tsc file

I updated project using below steps.

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save

updated stypescript version to 2.3.1

I am using Visual Studio 2015 Update 3.

This is my package.json file

```<code>{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "build:aot": "ngc -p tsconfig-aot.json && rollup -c rollup-config.js"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/platform-server": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@angular/upgrade": "~4.1.1",
    "angular-in-memory-web-api": "~0.3.2",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "mocha": "^3.1.2",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.1",
    "systemjs": "0.20.12",
    "typescript": "^2.3.1",
    "typings": "^1.5.0",
    "zone.js": "^0.8.10"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^4.0.0",
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "rollup": "^0.41.4",
    "rollup-plugin-commonjs": "^8.0.2",
    "rollup-plugin-node-resolve": "^3.0.0",
    "rollup-plugin-uglify": "^1.0.1",
    "typescript": "^2.2.0-dev.20170207",
    "typings": "^2.1.1"
  }
}
</code>```

答:
I think what you are seeing there is that Visual Studio is trying to build your typescript for you on compile, but doesn't know about your separate build process from your npm scripts.  I think you can safely just disable this feature if you have another compile process like in this article:  http://rostacik.net/2015/08/14/how-to-disable-building-of-typescript-files-in-visual-studio-2015/

The important steps being:
add node

```<code><TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
</code>```

to the first

```<code><PropertyGroup>
</code>```

element in .csproj file.

Body:
I am updating my current project version to Angular 4. And I am getting error like Build:Cannot Find type definition file for 'mocha' in tsc file

I updated project using below steps.

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save

updated stypescript version to 2.3.1

I am using Visual Studio 2015 Update 3.

This is my package.json file

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "build:aot": "ngc -p tsconfig-aot.json && rollup -c rollup-config.js"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/platform-server": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@angular/upgrade": "~4.1.1",
    "angular-in-memory-web-api": "~0.3.2",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "mocha": "^3.1.2",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.1",
    "systemjs": "0.20.12",
    "typescript": "^2.3.1",
    "typings": "^1.5.0",
    "zone.js": "^0.8.10"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^4.0.0",
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "rollup": "^0.41.4",
    "rollup-plugin-commonjs": "^8.0.2",
    "rollup-plugin-node-resolve": "^3.0.0",
    "rollup-plugin-uglify": "^1.0.1",
    "typescript": "^2.2.0-dev.20170207",
    "typings": "^2.1.1"
  }
}

Body:
I think what you are seeing there is that Visual Studio is trying to build your typescript for you on compile, but doesn't know about your separate build process from your npm scripts.  I think you can safely just disable this feature if you have another compile process like in this article:  http://rostacik.net/2015/08/14/how-to-disable-building-of-typescript-files-in-visual-studio-2015/

The important steps being:
add node

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

to the first

<PropertyGroup>

element in .csproj file.


问:
Laravel not storing files from request
I got form with file upload named "image". Form is working and i'm getting image but for some reason it's not stored. this is the code I use to store image:

```<code>$path = $request->image->store('storage/uploads');
</code>```

before that I check

```<code>$request->hasFile('image')
</code>```

and later I'm saving $path. Path is successfully saved and when i check it it's really storage/uploads/radnomid but there is no file

答:
If your filesystems.php configs were default then

```<code>$path = $request->image->store('storage/uploads');
</code>```

saved your files not in storage/uploads but in storage/app/storage/uploads.

And your current accepted answer is not really good because public_path() intended to be used for storing template files not user uploads. According to official docs uploads should be used in storage/ folder with a symbolic link from public/storage/ but not in public/.

Read more in https://laravel.com/docs/5.4/filesystem#the-public-disk

Title: Laravel not storing files from request

Body:
I got form with file upload named "image". Form is working and i'm getting image but for some reason it's not stored. this is the code I use to store image:

$path = $request->image->store('storage/uploads');

before that I check

$request->hasFile('image')

and later I'm saving $path. Path is successfully saved and when i check it it's really storage/uploads/radnomid but there is no file

Body:
If your filesystems.php configs were default then

$path = $request->image->store('storage/uploads');

saved your files not in storage/uploads but in storage/app/storage/uploads.

And your current accepted answer is not really good because public_path() intended to be used for storing template files not user uploads. According to official docs uploads should be used in storage/ folder with a symbolic link from public/storage/ but not in public/.

Read more in https://laravel.com/docs/5.4/filesystem#the-public-disk


问:
AndroidStudio Failed to Sync Gradle project, Failed to find target Google Inc
How can I resolve the Gradle Sync problem?
I installed the missing SDK versions but the error shown again.

Take a look to the screenshots please...

Screenshot 1
Screenshot 2

Thank you in advance.

答:
You also need to open up "build.gradle" script and change the classpath to latest gradle repository.... mine is 'com.android.tools.build:gradle:3.0.0-alpha3'

Hope this helps everyone


问:
finding cells having superscript and subscript text
I am trying to learn VBA.

I want to mark the cells having superscript/subscript in the cell text. Is this possible using Excel VBA?

答:
If your cells are either

all superscript, or

start with a superscript character (which is quirky - xlPart should find any part of a formatted string)

then this code (setup to look at column B) will be much faster than testing every character in very cell as per the msft link

You would use Application.FindFormat.Font.Superscript = True for superscript

Failing this I would look at more complex solution to parse out these characters which would require exporting the text.

```<code>Sub Test()

    Dim ws As Worksheet
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim FirstAddress As String

    Set ws = ActiveSheet
    Set rng1 = ws.Range("B:B")

    Application.FindFormat.Font.Subscript = True

    With rng1
        Set rng2 = .Cells.Find("*", , xlFormulas, xlPart, xlByRows, xlNext, , , True)

        If rng2 Is Nothing Then
            MsgBox "None found"
        Else
            FirstAddress = rng2.Address
            Set rng3 = rng2
            Do
                Set rng2 = .Cells.Find("*", rng2, xlFormulas, xlPart, xlByRows, xlNext, , , True)
                If rng2.Address = FirstAddress Then
                    Exit Do
                Else
                    Set rng3 = Union(rng3, rng2)
                End If
            Loop
            If Not rng3 Is Nothing Then MsgBox rng3.Address
        End If
    End With
End Sub
</code>```

Body:
If your cells are either

all superscript, or

start with a superscript character (which is quirky - xlPart should find any part of a formatted string)

then this code (setup to look at column B) will be much faster than testing every character in very cell as per the msft link

You would use Application.FindFormat.Font.Superscript = True for superscript

Failing this I would look at more complex solution to parse out these characters which would require exporting the text.

Sub Test()

    Dim ws As Worksheet
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim FirstAddress As String

    Set ws = ActiveSheet
    Set rng1 = ws.Range("B:B")

    Application.FindFormat.Font.Subscript = True

    With rng1
        Set rng2 = .Cells.Find("*", , xlFormulas, xlPart, xlByRows, xlNext, , , True)

        If rng2 Is Nothing Then
            MsgBox "None found"
        Else
            FirstAddress = rng2.Address
            Set rng3 = rng2
            Do
                Set rng2 = .Cells.Find("*", rng2, xlFormulas, xlPart, xlByRows, xlNext, , , True)
                If rng2.Address = FirstAddress Then
                    Exit Do
                Else
                    Set rng3 = Union(rng3, rng2)
                End If
            Loop
            If Not rng3 Is Nothing Then MsgBox rng3.Address
        End If
    End With
End Sub


问:
Android BLE ScanCallback LOW LATENCY
I’m building BLE Android.
My application scan for BLE devices with background service 24/7 (this is essential for my app) with SCAN_MODE_LOW_POWER as settings.
When i find devices that are related to my app i switch to SCAN_MODE_LOW_LATENCY because at this point every 1 second count for my app.
With SCAN_MODE_LOW_LATENCY i'm receiving ScanCallback intensively but at some point like when device in sleep mode i’m receiving like 10-11 callback intensively then a pause of 3-4s then the callbacks again.

This 3-4s delay/pause isn’t helping my app at all.

Is it possible to have  intensive ScanCallback even if the device is in sleep or doze mode?

Thanks.

Log when screen on:

05-25 09:26:27.121 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:27.161 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn
:true

05-25 09:26:27.211 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:27.251 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:27.301 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

...intensive ScanCallback

05-25 09:26:41.101 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.151 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.201 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.251 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.291 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.341 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

05-25 09:26:41.391 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :true

Log when screen off:

05-25 09:26:50.141 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.191 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.221 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.271 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.301 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.351 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.401 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.441 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.501 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.531 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.581 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:50.631 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

---> no Callback 5s

05-25 09:26:55.151 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.201 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.251 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.301 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.341 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.381 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.421 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.481 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.521 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.571 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

05-25 09:26:55.611 14564-14564/? I/TAG_BLE: BLE onScanResult - isScreenOn :false

答: Different manufacturers use different Bluetooth chips. Therefore, such behavior is very possible. Have you tried restarting the scan every second or so? Just starting and stopping it.</p>

Title: Android BLE ScanCallback LOW LATENCY


答:
```<code>def on_press(key):
    if key == Key.enter:
        x = 1
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1
</code>```

The code is not correctly indented in your question. Then, 'x' inside a function is a 'local' variable. It will not have the correct value on the next call. You could define a global instance of x like this:

```<code>x = 1

def on_press(key):
    global x
    if key == Key.enter:
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1
</code>```

Title: iteration on keypress

Body:
def on_press(key):
    if key == Key.enter:
        x = 1
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1

The code is not correctly indented in your question. Then, 'x' inside a function is a 'local' variable. It will not have the correct value on the next call. You could define a global instance of x like this:

x = 1

def on_press(key):
    global x
    if key == Key.enter:
        bitmap = autopy.bitmap.capture_screen()
        bitmap.save('C:\Users\User\Desktop\Folder\Capture{}.png'.format(x))
        x += 1


问:
materializecss mobile navbar is disabled
I'm using MaterializeCSS's navbar for my webpage. After adding the nav element and switching to responsive mode, I can find the collapsed button appearing. On clicking it, I am shown the side nav with the links. However the buttons are disabled (there seems to be an overlay on top of the side nav). On clicking any of the links, the side nav disappears.

This is my navbar code:

```<code><div class="navbar-fixed scrollspy" id="main">
        <nav>
            <div class="container nav-wrapper">
                <a href="#!" class="brand-logo center">SRS Constructions</a>
                <a href="#" data-activates="mobile-menu" class="button-collapse"><i class="fa fa-bars"></i></a>
                <ul class="left hide-on-med-and-down">
                    <li class="active"><a href="#main">Home <span class="sr-only">(current)</span></a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#services">Services</a></li>
                </ul>
                <ul class="right hide-on-med-and-down">
                    <li><a href="#">Our Projects</a></li>
                    <li><a href="#">Why Us</a></li>
                    <li><a href="#">Contact</a></li>
                </ul>
                <ul class="side-nav" id="mobile-menu">
                    <li><a href="#main">Home</a></li>
                    <li><a href="#about">About</a></li>
                    <li><a href="#services">Services</a></li>
                    <li><a href="#">Our Projects</a></li>
                    <li><a href="#">Why Us</a></li>
                    <li><a href="#">Contact</a></li>
                </ul>
            </div>
        </nav>
 </div>
</code>```

This is how it looks when I click on the 3 bars :

I have the full page uploaded to Github here.

答: Try to place your #mobile-menu outside of your navbar div.</p>

Body:
I'm using MaterializeCSS's navbar for my webpage. After adding the nav element and switching to responsive mode, I can find the collapsed button appearing. On clicking it, I am shown the side nav with the links. However the buttons are disabled (there seems to be an overlay on top of the side nav). On clicking any of the links, the side nav disappears.

This is my navbar code:

                SRS Constructions

Home (current)

About

Services

Our Projects

Why Us

Contact

Home

About

Services

Our Projects

Why Us

Contact

This is how it looks when I click on the 3 bars :

I have the full page uploaded to Github here.


问:
Toggle navbar on each navbar item click except one
I want to toggle navbar when navigating with mobile when the user clicks each one of the navbar items except one which is a dropdown.

I am using this code:

```<code>$('.nav a').on('click', function(){
    $('.navbar-toggle').click();
});
</code>```

The problem is that this code toggles the navbar with each item of the navbar on click. However, when I click the dropdown in the navbar, the navbar toggles and the user cannot see items in the dropdown.

答:
I used this and it worked:</p>

```<code>$('.nav :not(.dropdown) a') .on('click', function(){
    $('.navbar-toggle').click();
    });
</code>```

Body:
I want to toggle navbar when navigating with mobile when the user clicks each one of the navbar items except one which is a dropdown.

I am using this code:

$('.nav a').on('click', function(){
    $('.navbar-toggle').click();
});

The problem is that this code toggles the navbar with each item of the navbar on click. However, when I click the dropdown in the navbar, the navbar toggles and the user cannot see items in the dropdown.

Body:
I used this and it worked:

$('.nav :not(.dropdown) a') .on('click', function(){
    $('.navbar-toggle').click();
    });


问:
How do you invoke a function in a module which is in a package?
I have a project structure of:

```<code>root_dir/
└── app/
    ├── __init__.py
    ├── mymodule.py
</code>```

inside of mymodule.py I have the following function:

```<code>def hello():
    print('hello world')
</code>```

If i call python from inside the root directory I'd like to do the following:

```<code>>>> import app
>>> app.mymodule.hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'app' has no attribute 'mymodule'
</code>```

Is there anyway to invoke the hello function?

答: jonrsharpe comment is right. When you reference a package you are referring to the __init__.py module and this module doesn't contain any reference to mymodule. That's why you cannot do app.mymodule in the first place.

Body:
I have a project structure of:

root_dir/
└── app/
    ├── __init__.py
    ├── mymodule.py

inside of mymodule.py I have the following function:

def hello():
    print('hello world')

If i call python from inside the root directory I'd like to do the following:

>>> import app
>>> app.mymodule.hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'app' has no attribute 'mymodule'

Is there anyway to invoke the hello function?


问:
Check for existence before submitting data to the MySql database
I have a PHP code that submits data to the database, but I want to restrict the data if it already exists. I have tried the below code but always inserts data without checking for existence.</p>

```<code>if(isset($_POST['submit'])){

  $phone = $_POST['phone'];

  $checkDataSql = "SELECT phone FROM lead WHERE phone=$phone" ;
  $run = $conn->query($checkDataSql);

  if ($run->num_rows > 0) {
      header("location:add_lead.php?error=unsuccess");
      }
  else{
      $phone = $_POST['phone'];
   }

  $name = $_POST['name'];
  $email = $_POST['email'];
  $gender = $_POST['gender'];
  $treatment = intval($_POST['treatment']);
  $date = date('Y-m-d');
  $source = intval($_POST['source']);
  $staff = intval($_POST['staff_id']);

$insertLead = "INSERT INTO lead
      (`id`, `name`, `phone`, `email`, `gender_id`, `treatment_id`, `date`, `source_id`, `remark`, `staff_id`)
      VALUES (NULL, '$name', '$phone', '$email', '$gender', '$treatment', '$date', '$source', '', '$staff')";

if ($conn->query($insertLead) === TRUE) {
    echo "New record created successfully";
    header("location:add_lead.php?submitted=successfully");
} else {
    echo "Error: " . $insertLead . "<br>" . $conn->error;
}

}
</code>```

答:
Setting the header to redirect doesn't do the redirect immediately, so you need to add something like

exit;

After both of the header() calls to stop execution at that point.

Additionally, look into SQL injection right now, you're code is totally insecure and you'll be hacked before you know it with it as is.

Body:
I have a PHP code that submits data to the database, but I want to restrict the data if it already exists. I have tried the below code but always inserts data without checking for existence.

if(isset($_POST['submit'])){

  $phone = $_POST['phone'];

  $checkDataSql = "SELECT phone FROM lead WHERE phone=$phone" ;
  $run = $conn->query($checkDataSql);

  if ($run->num_rows > 0) {
      header("location:add_lead.php?error=unsuccess");
      }
  else{
      $phone = $_POST['phone'];
   }

  $name = $_POST['name'];
  $email = $_POST['email'];
  $gender = $_POST['gender'];
  $treatment = intval($_POST['treatment']);
  $date = date('Y-m-d');
  $source = intval($_POST['source']);
  $staff = intval($_POST['staff_id']);

$insertLead = "INSERT INTO lead
      (`id`, `name`, `phone`, `email`, `gender_id`, `treatment_id`, `date`, `source_id`, `remark`, `staff_id`)
      VALUES (NULL, '$name', '$phone', '$email', '$gender', '$treatment', '$date', '$source', '', '$staff')";

if ($conn->query($insertLead) === TRUE) {
    echo "New record created successfully";
    header("location:add_lead.php?submitted=successfully");
} else {
    echo "Error: " . $insertLead . "
" . $conn->error;
}

}


问:
iPhone/Objective C: Can't delete a file
In my application, I let the user record a sound clip and later, if the user chooses, I want him to be able to delete it.

This is the code I use:

```<code>NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSLog(@"File exists: %d", [fileManager fileExistsAtPath:path]);
NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]);
[fileManager removeItemAtPath:path error:&error];
if (error != nil)
{
    NSLog(@"Error: %@", error);
    NSLog(@"Path to file: %@", path);
}
</code>```

The problem is that fileExistsAtPath and isDeletableFileAtPath return null and the removeItemAtPath doesn't work, and throws this error,

Error: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x391b7f0 "Operation could not be completed. (Cocoa error 4.)"

The path has this form:

/Users/andrei/Library/Application%20Support/iPhone%20Simulator/User/Applications/5472B318-FA57-4F8D-AD91-7E06E9609215/Documents/1280913694.caf
```

<p>There is a file there called <code>1280913694.caf</code>, but it doesn't pick it up. Does it have something to do with the way in which the path should be represented?</p>

<p>The path works when playing the audio file with <code>AVAudioPlayer</code>.</p>

<p>I've also changed the <code>%@</code> to <code>%d</code> for <code>fileExistsAtPath</code> and <code>isDeletableFileAtPath</code> and the answer is 0, which I suppose means FALSE.</p>

<p>The name of the file is stored in a database, and the path to the file is retrieved with this method:</p>

```-(NSString *)returnFullPathToDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}
```

<p>After I get this value, I use it in the following code</p>

```NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
```

答:
try to change

```<code>NSFileManager *fileManager = [NSFileManager defaultManager];
</code>```

to:

```<code>NSFileManager *fileManager = [NSFileManager new];
</code>```

Title: iPhone/Objective C: Can't delete a file

Body:
In my application, I let the user record a sound clip and later, if the user chooses, I want him to be able to delete it.

This is the code I use:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSLog(@"File exists: %d", [fileManager fileExistsAtPath:path]);
NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]);
[fileManager removeItemAtPath:path error:&error];
if (error != nil)
{
    NSLog(@"Error: %@", error);
    NSLog(@"Path to file: %@", path);
}

The problem is that fileExistsAtPath and isDeletableFileAtPath return null and the removeItemAtPath doesn't work, and throws this error,

Error: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x391b7f0 "Operation could not be completed. (Cocoa error 4.)"

The path has this form:

/Users/andrei/Library/Application%20Support/iPhone%20Simulator/User/Applications/5472B318-FA57-4F8D-AD91-7E06E9609215/Documents/1280913694.caf

There is a file there called 1280913694.caf, but it doesn't pick it up. Does it have something to do with the way in which the path should be represented?

The path works when playing the audio file with AVAudioPlayer.

I've also changed the %@ to %d for fileExistsAtPath and isDeletableFileAtPath and the answer is 0, which I suppose means FALSE.

The name of the file is stored in a database, and the path to the file is retrieved with this method:

-(NSString *)returnFullPathToDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

After I get this value, I use it in the following code

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

Body:
try to change

NSFileManager *fileManager = [NSFileManager defaultManager];

to:

NSFileManager *fileManager = [NSFileManager new];


问:
PHP: problems with inheritance
I try to do class tree  where each class in tree check own directory for template and use it, but when I call function in inherited class then called parent. How can i do it ?

My code in example below output:

D

  C

  b/1.phtml

but i need to d/1.phtml

```<code><?php

class A {
    private $templates_dir = 'a';
}

class B extends A {

    private $templates_dir = 'b';

    public function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
// idea  - if (!file_exists($file)) return parent::check_template($file);
// method call each class while template will be found
// how do it?

    }

}

class C extends B {

    private $templates_dir = 'c';

}

class D extends C {

    private $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');
</code>```

答:
I would just make $templates_dir protected:

```<code>class A {
   protected $templates_dir = 'a';
}
</code>```

and adjust the extending classes to do the same.

That will then cause templates_dir() to return whatever $templates_dir is set to.

Title: PHP: problems with inheritance

Body:
I try to do class tree  where each class in tree check own directory for template and use it, but when I call function in inherited class then called parent. How can i do it ?

My code in example below output:

D

  C

  b/1.phtml

but i need to d/1.phtml

<?php

class A {
    private $templates_dir = 'a';
}

class B extends A {

    private $templates_dir = 'b';

    public function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
// idea  - if (!file_exists($file)) return parent::check_template($file);
// method call each class while template will be found
// how do it?

    }

}

class C extends B {

    private $templates_dir = 'c';

}

class D extends C {

    private $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');

Body:
I would just make $templates_dir protected:

class A {
   protected $templates_dir = 'a';
}

and adjust the extending classes to do the same.

That will then cause templates_dir() to return whatever $templates_dir is set to.


问:
SQL - Create view with one column from two table depending on condition
I need to create a view with one column from two table ... As you will show in the next image.
The squares are table and the rounded corner square is the view and the condition between them.

How to apply this condition to create that view ?

答:
Use a CASE expression like

```<code>create view myview as
select
    case when (b.Embossied is not null or b.Embossied <> 0)
    then b.Embossied else b1.UniversityId end as alias_name
from Badge b join Badgeldw b1 on b.Embossied = b1.UniversityId;
</code>```

Body:
Use a CASE expression like

create view myview as
select
    case when (b.Embossied is not null or b.Embossied <> 0)
    then b.Embossied else b1.UniversityId end as alias_name
from Badge b join Badgeldw b1 on b.Embossied = b1.UniversityId;


问:
Android GPS is returning null location
I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value.  Below is my code

```<code>   public void getValue() {
    LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    System.out.println("GPS IS "+gpsEnabled);
    if (!gpsEnabled) {
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }
    SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
    try {
        getBatteryLevel();
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
        Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        mLocation = location;
        if (location != null) {
            lat = location.getLatitude();
            lon = location.getLongitude();
            address = getAddress();
            alt = location.getAltitude();
            if (meterFootFlag) {
                diameter = location.getAccuracy();
            } else
                diameter = location.getAccuracy() / 3.28084;
        } else {
            lat = 0.0;
            lon = 0.0;
            alt = 0.0;
        }

    } catch (Exception e) {
        lat = 0.0;
        lon = 0.0;
        alt = 0.0;
    }
</code>```

Also I have added permission in manifest file

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</code>```

but I am getting a null value for the location.

Any ideas on how I can get the location?

答:
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute</p>

Title: Android GPS is returning null location

Body:
I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value.  Below is my code

   public void getValue() {
    LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    System.out.println("GPS IS "+gpsEnabled);
    if (!gpsEnabled) {
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }
    SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
    try {
        getBatteryLevel();
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
        Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        mLocation = location;
        if (location != null) {
            lat = location.getLatitude();
            lon = location.getLongitude();
            address = getAddress();
            alt = location.getAltitude();
            if (meterFootFlag) {
                diameter = location.getAccuracy();
            } else
                diameter = location.getAccuracy() / 3.28084;
        } else {
            lat = 0.0;
            lon = 0.0;
            alt = 0.0;
        }

    } catch (Exception e) {
        lat = 0.0;
        lon = 0.0;
        alt = 0.0;
    }

Also I have added permission in manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

but I am getting a null value for the location.

Any ideas on how I can get the location?


问:
How do I make a vertical toolbar in landscape mode that rotates to become horizontal in portrait mode?
I am creating an app for designing model railroad layouts.  I want to have a toolbar on the bottom and possibly on the top of the screen in portrait mode, and then when the user rotates their device to landscape, have the toolbars stay in the same place on the screen so that they are on the left and right sides of the screen and have the icons rotate, just like the toolbars in the built in camera app on iOS.  How can I do this?  Can I do this in interface builder in Xcode?  If not, what is the specific code?  Also, I am using Swift.  Thanks.</p>

答:
In order to make the toolbar not rotate, here is the code:

```<code>import UIKit

class MainNavigationController: UINavigationController {

override var shouldAutorotate: Bool {
   return false
   }
}

class MainViewController: UIViewController {

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Hide the navigation bar on the this view controller
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

override func viewDidLoad() {
    super.viewDidLoad()

    }
}
</code>```

Basically, you have to embed a navigation controller into the view you want to not rotate, change the navigation controller's class to MainNavigationController and then hide the navigation bar, if desired.

Body:
In order to make the toolbar not rotate, here is the code:

import UIKit

class MainNavigationController: UINavigationController {

override var shouldAutorotate: Bool {
   return false
   }
}

class MainViewController: UIViewController {

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Hide the navigation bar on the this view controller
    self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

override func viewDidLoad() {
    super.viewDidLoad()

    }
}

Basically, you have to embed a navigation controller into the view you want to not rotate, change the navigation controller's class to MainNavigationController and then hide the navigation bar, if desired.

ContentLicense: CC BY-SA 4.0


问:
A program interpretation in C
I am new to c and sometimes I get confused by things I see.
I have the following code:

```<code>int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}
</code>```

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.

答:
& does not refer to address-of in this case like you probably are confusing it with, but bitwise AND.

The bitwise AND operation takes one left hand side parameter and one right hand side parameter, compares them at the bit level (i.e. the 1s and 0s) and returns a value representing which positions in the LHS and the RHS both have a 1.  For example, comparing 6 (binary 0110) and and 3 (binary 0011) would give us binary (0010), which is 2 in base 10.

Showing our work:

```<code>0110
0011
----
0010
</code>```

The second-rightmost position is the only place where the two values have a 1 in common, so that's the only place where we get a 1 after bitwise-ANDing them.

Since the right-hand side of that operation is 0x00000fff, what that operation is doing is taking the parameter ourtime and only returning the least significant 12 bits (since 0xF is 1111 in base 2).

Showing our work again:

```<code>(ourtime has unknown 0s and 1s.)
00000000000000000000111111111111
</code>```

Since the most significant 20 bits of the right hand side are zeroes, and the least significant 12 bits are all ones, the return value is obviously whatever was in the least significant 12 bits of ourtime.

Title: A program interpretation in C

Body:
I am new to c and sometimes I get confused by things I see.
I have the following code:

int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.

Body:
& does not refer to address-of in this case like you probably are confusing it with, but bitwise AND.

The bitwise AND operation takes one left hand side parameter and one right hand side parameter, compares them at the bit level (i.e. the 1s and 0s) and returns a value representing which positions in the LHS and the RHS both have a 1.  For example, comparing 6 (binary 0110) and and 3 (binary 0011) would give us binary (0010), which is 2 in base 10.

Showing our work:

0110
0011
----
0010

The second-rightmost position is the only place where the two values have a 1 in common, so that's the only place where we get a 1 after bitwise-ANDing them.

Since the right-hand side of that operation is 0x00000fff, what that operation is doing is taking the parameter ourtime and only returning the least significant 12 bits (since 0xF is 1111 in base 2).

Showing our work again:

(ourtime has unknown 0s and 1s.)
00000000000000000000111111111111

Since the most significant 20 bits of the right hand side are zeroes, and the least significant 12 bits are all ones, the return value is obviously whatever was in the least significant 12 bits of ourtime.