问:
How do I install a signed driver on Windows 10 without getting "Program Compatibility Assistant" message
When I try to install my device driver, I get the

"Program Compatibility Dialog"
A digitally signed driver is required :  Process Detection Driver Cetrus.  Windows blocked the installation of a digitally unsigned driver.  Uninstall the program or device that uses the driver and check the publisher's website for a digitally signed version of the driver.

My driver is signed:

```<code>        Verifying: PDetect64.sys
        Signature Index: 0 (Primary Signature)
        Hash of file (sha1): 039DFBD6C922B86BC9D8E2ABF9AADAB800ABE21E

        Signing Certificate Chain:
            Issued to: AddTrust External CA Root
            Issued by: AddTrust External CA Root
            Expires:   Sat May 30 03:48:38 2020
            SHA1 hash: 02FAF3E291435468607857694DF5E45B68851868

                Issued to: COMODO RSA Certification Authority
                Issued by: AddTrust External CA Root
                Expires:   Sat May 30 03:48:38 2020
                SHA1 hash: F5AD0BCC1AD56CD150725B1C866C30AD92EF21B0

                    Issued to: COMODO RSA Code Signing CA
                    Issued by: COMODO RSA Certification Authority
                    Expires:   Mon May 08 16:59:59 2028
                    SHA1 hash: B69E752BBE88B4458200A7C0F4F5B3CCE6F35B47

                        Issued to: Cetrus LLC
                        Issued by: COMODO RSA Code Signing CA
                        Expires:   Sun May 26 16:59:59 2019
                        SHA1 hash: 647ACC3A5A36302E3A096F05595FD94EF8ED530D

        The signature is timestamped: Fri May 26 10:58:35 2017
        Timestamp Verified by:
            Issued to: UTN-USERFirst-Object
            Issued by: UTN-USERFirst-Object
            Expires:   Tue Jul 09 11:40:36 2019
            SHA1 hash: E12DFB4B41D7D9C32B30514BAC1D81D8385E2D46

                Issued to: COMODO SHA-1 Time Stamping Signer
                Issued by: UTN-USERFirst-Object
                Expires:   Tue Jul 09 11:40:36 2019
                SHA1 hash: 03A5B14663EB12023091B84A6D6A68BC871DE66B

        Cross Certificate Chain:
            Issued to: Microsoft Code Verification Root
            Issued by: Microsoft Code Verification Root
            Expires:   Sat Nov 01 06:54:03 2025
            SHA1 hash: 8FBE4D070EF8AB1BCCAF2A9D5CCAE7282A2C66B3

                Issued to: AddTrust External CA Root
                Issued by: Microsoft Code Verification Root
                Expires:   Tue Aug 15 13:36:30 2023
                SHA1 hash: A75AC657AA7A4CDFE5F9DE393E69EFCAB659D250

                    Issued to: COMODO RSA Certification Authority
                    Issued by: AddTrust External CA Root
                    Expires:   Sat May 30 03:48:38 2020
                    SHA1 hash: F5AD0BCC1AD56CD150725B1C866C30AD92EF21B0

                        Issued to: COMODO RSA Code Signing CA
                        Issued by: COMODO RSA Certification Authority
                        Expires:   Mon May 08 16:59:59 2028
                        SHA1 hash: B69E752BBE88B4458200A7C0F4F5B3CCE6F35B47

                            Issued to: Cetrus LLC
                            Issued by: COMODO RSA Code Signing CA
                            Expires:   Sun May 26 16:59:59 2019
                            SHA1 hash: 647ACC3A5A36302E3A096F05595FD94EF8ED530D

        Successfully verified: PDetect64.sys

        Number of files successfully Verified: 1
        Number of warnings: 0
        Number of errors: 0
</code>```

Can somebody help with how to go about figuring out why Windows 10 thinks this is an unsigned driver?

答: The ONLY way is to sign the driver with an EV code signing certificate.

Body:
When I try to install my device driver, I get the

"Program Compatibility Dialog"
A digitally signed driver is required :  Process Detection Driver Cetrus.  Windows blocked the installation of a digitally unsigned driver.  Uninstall the program or device that uses the driver and check the publisher's website for a digitally signed version of the driver.

My driver is signed:

        Verifying: PDetect64.sys
        Signature Index: 0 (Primary Signature)
        Hash of file (sha1): 039DFBD6C922B86BC9D8E2ABF9AADAB800ABE21E

        Signing Certificate Chain:
            Issued to: AddTrust External CA Root
            Issued by: AddTrust External CA Root
            Expires:   Sat May 30 03:48:38 2020
            SHA1 hash: 02FAF3E291435468607857694DF5E45B68851868

                Issued to: COMODO RSA Certification Authority
                Issued by: AddTrust External CA Root
                Expires:   Sat May 30 03:48:38 2020
                SHA1 hash: F5AD0BCC1AD56CD150725B1C866C30AD92EF21B0

                    Issued to: COMODO RSA Code Signing CA
                    Issued by: COMODO RSA Certification Authority
                    Expires:   Mon May 08 16:59:59 2028
                    SHA1 hash: B69E752BBE88B4458200A7C0F4F5B3CCE6F35B47

                        Issued to: Cetrus LLC
                        Issued by: COMODO RSA Code Signing CA
                        Expires:   Sun May 26 16:59:59 2019
                        SHA1 hash: 647ACC3A5A36302E3A096F05595FD94EF8ED530D

        The signature is timestamped: Fri May 26 10:58:35 2017
        Timestamp Verified by:
            Issued to: UTN-USERFirst-Object
            Issued by: UTN-USERFirst-Object
            Expires:   Tue Jul 09 11:40:36 2019
            SHA1 hash: E12DFB4B41D7D9C32B30514BAC1D81D8385E2D46

                Issued to: COMODO SHA-1 Time Stamping Signer
                Issued by: UTN-USERFirst-Object
                Expires:   Tue Jul 09 11:40:36 2019
                SHA1 hash: 03A5B14663EB12023091B84A6D6A68BC871DE66B

        Cross Certificate Chain:
            Issued to: Microsoft Code Verification Root
            Issued by: Microsoft Code Verification Root
            Expires:   Sat Nov 01 06:54:03 2025
            SHA1 hash: 8FBE4D070EF8AB1BCCAF2A9D5CCAE7282A2C66B3

                Issued to: AddTrust External CA Root
                Issued by: Microsoft Code Verification Root
                Expires:   Tue Aug 15 13:36:30 2023
                SHA1 hash: A75AC657AA7A4CDFE5F9DE393E69EFCAB659D250

                    Issued to: COMODO RSA Certification Authority
                    Issued by: AddTrust External CA Root
                    Expires:   Sat May 30 03:48:38 2020
                    SHA1 hash: F5AD0BCC1AD56CD150725B1C866C30AD92EF21B0

                        Issued to: COMODO RSA Code Signing CA
                        Issued by: COMODO RSA Certification Authority
                        Expires:   Mon May 08 16:59:59 2028
                        SHA1 hash: B69E752BBE88B4458200A7C0F4F5B3CCE6F35B47

                            Issued to: Cetrus LLC
                            Issued by: COMODO RSA Code Signing CA
                            Expires:   Sun May 26 16:59:59 2019
                            SHA1 hash: 647ACC3A5A36302E3A096F05595FD94EF8ED530D

        Successfully verified: PDetect64.sys

        Number of files successfully Verified: 1
        Number of warnings: 0
        Number of errors: 0

Can somebody help with how to go about figuring out why Windows 10 thinks this is an unsigned driver?


来源: stackexchange

问:
Converting XGBoost model to CoreML
I am trying to convert the following XGBoost model to a CoreML File but I get the error.

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-
  packages/coremltools/converters/xgboost/_tree.py", line 48, in convert
return _MLModel(_convert_tree_ensemble(model, feature_names, target))
File "/usr/local/lib/python2.7/dist-
 packages/coremltools/converters/xgboost/_tree_ensemble.py", line 111, in convert_tree_ensemble
xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json')
TypeError: get_dump() got an unexpected keyword argument 'dump_format'
</code>```

I installed xgboost using pip. Why is this occurring?

答: Follow the installation guide. Do not use pip install xgboost or you will get this error with get_dump. See http://xgboost.readthedocs.io/en/latest/build.html for more information.</p>

ContentLicense: CC BY-SA 3.0

Title: Converting XGBoost model to CoreML

Body:
I am trying to convert the following XGBoost model to a CoreML File but I get the error.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-
  packages/coremltools/converters/xgboost/_tree.py", line 48, in convert
return _MLModel(_convert_tree_ensemble(model, feature_names, target))
File "/usr/local/lib/python2.7/dist-
 packages/coremltools/converters/xgboost/_tree_ensemble.py", line 111, in convert_tree_ensemble
xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json')
TypeError: get_dump() got an unexpected keyword argument 'dump_format'

I installed xgboost using pip. Why is this occurring?


问:
Incorrect lookat matrix
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

```<code>Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}
</code>```

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

```<code>void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}
</code>```

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

```<code>gl_Position = projection * view * model * vec4(vertexPosition, 1.0);
</code>```

And this is how my matrix multiplication works:

```<code>Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}
</code>```

Edit: updated picture
Edit: Added a more detailed description

答:
If your positions (position, center) and the up vector are in viewport space, then the Z-Axis of the view matrix is the inverse line of sight and the Y-Axis is the up vector. See the following code:

```<code>Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up)
{
    Matrix4f out(1.0f); // I suppose this initilizes a 4*4 identity matrix

    // Z-Axis is the line of sight
    Vector3f z = position.substract(center).normalize(); // inverse line of sight

    // Y-Axis is the up vector
    Vector3f y = up;

    // X-Axis is the cross product of Y-Axis and Z-Axis
    Vector3f x = y.cross(z).normalize();

    // orthonormalize the Y-Axis
    y = z.cross( x );

    out.mElements[0*4 + 0] = x.x;
    out.mElements[0*4 + 1] = x.y;
    out.mElements[0*4 + 2] = x.z;

    out.mElements[1*4 + 0] = y.x;
    out.mElements[1*4 + 1] = y.y;
    out.mElements[1*4 + 2] = y.z;

    out.mElements[2*4 + 0] = z.x;
    out.mElements[2*4 + 1] = z.y;
    out.mElements[2*4 + 2] = z.z;

    return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
}
</code>```

Title: Incorrect lookat matrix

Body:
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

gl_Position = projection * view * model * vec4(vertexPosition, 1.0);

And this is how my matrix multiplication works:

Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}

Edit: updated picture
Edit: Added a more detailed description

Body:
If your positions (position, center) and the up vector are in viewport space, then the Z-Axis of the view matrix is the inverse line of sight and the Y-Axis is the up vector. See the following code:

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up)
{
    Matrix4f out(1.0f); // I suppose this initilizes a 4*4 identity matrix

    // Z-Axis is the line of sight
    Vector3f z = position.substract(center).normalize(); // inverse line of sight

    // Y-Axis is the up vector
    Vector3f y = up;

    // X-Axis is the cross product of Y-Axis and Z-Axis
    Vector3f x = y.cross(z).normalize();

    // orthonormalize the Y-Axis
    y = z.cross( x );

    out.mElements[0*4 + 0] = x.x;
    out.mElements[0*4 + 1] = x.y;
    out.mElements[0*4 + 2] = x.z;

    out.mElements[1*4 + 0] = y.x;
    out.mElements[1*4 + 1] = y.y;
    out.mElements[1*4 + 2] = y.z;

    out.mElements[2*4 + 0] = z.x;
    out.mElements[2*4 + 1] = z.y;
    out.mElements[2*4 + 2] = z.z;

    return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
}

ContentLicense: CC BY-SA 4.0


问:
Grails 3.2 with Angularjs1.5 List not returning all records
I don't know if this is a grails or angular issue although I suspect the former. Database has 200+ records but list is serving up exactly 100 instead. What am I missing here?

fybkbraEditController.js (Angular 1.5)

```<code>function FybkbraEditController(Fybkbra, $stateParams, $state, Fytrnlt, Fytbank, Stvnatn, $filter) {
var vm = this;
var max = 100000, offset = 0;

vm.fytrnltList = Fytrnlt.list({max: max, offset: offset});
vm.fytbankList = Fytbank.list({max: max, offset: offset});
vm.stvnatnListFilt = Stvnatn.list({max: max, offset: offset}); //200+ records in table but only exactly 100 records are loaded

vm.getCS = function () {

   vm.res01 = ($filter('filter')(vm.stvnatnListFilt, {stvnatncode: vm.fybkbra.fybkbranatncode.toString()}, true));
</code>```

html code

```<code> <div class="fieldcontain">
        <label for="country">Country *</label>
  <select ng-model="vm.fybkbra.fybkbranatncode"
            ng-options="stvnatn.stvnatncode as (stvnatn.id + ':' + stvnatn.stvnatnnation ) for stvnatn in vm.stvnatnList | orderBy:'stvnatnnation' | limitTo:500"
            ng-change="vm.getCS()"
            ng-required="true"
            id="country">

    </select>

</div>
</code>```

答: You haven't shown your controller code (or whatever the controller is invoking to get the records) but because the number of records being returned is an even 100, my guess that your code is doing something like SomeDomainClass.list(max: 100) (which is what the default RestfulController class does... not sure if you are using that).

Body:
I don't know if this is a grails or angular issue although I suspect the former. Database has 200+ records but list is serving up exactly 100 instead. What am I missing here?

fybkbraEditController.js (Angular 1.5)

function FybkbraEditController(Fybkbra, $stateParams, $state, Fytrnlt, Fytbank, Stvnatn, $filter) {
var vm = this;
var max = 100000, offset = 0;

vm.fytrnltList = Fytrnlt.list({max: max, offset: offset});
vm.fytbankList = Fytbank.list({max: max, offset: offset});
vm.stvnatnListFilt = Stvnatn.list({max: max, offset: offset}); //200+ records in table but only exactly 100 records are loaded

vm.getCS = function () {

   vm.res01 = ($filter('filter')(vm.stvnatnListFilt, {stvnatncode: vm.fybkbra.fybkbranatncode.toString()}, true));

html code

        Country *
  <select ng-model="vm.fybkbra.fybkbranatncode"
            ng-options="stvnatn.stvnatncode as (stvnatn.id + ':' + stvnatn.stvnatnnation ) for stvnatn in vm.stvnatnList | orderBy:'stvnatnnation' | limitTo:500"
            ng-change="vm.getCS()"
            ng-required="true"
            id="country">

    </select>


问:
Creating Mutexes with Binary Semaphore
I'm working with a simple system that does NOT have mutexes, but rather a limited array of hardware binary semaphores.  Typically, all multithreading is been done with heavy Semaphore techniques that makes code both poor in performance and difficult to write correctly without deadlocks.

A naive implementation is to use one semaphore globally in order to ensure atomic access to a critical section.  However, this means that unrelated objects (even of different types) will block if any critical section is being accessed.

My current solution to this problem is to use a single global semaphore to ensure atomic access to a guard byte that then ensures atomic access to the particular critical section.  I currently have this so far:

```<code>while (true) {
    while (mutexLock == Mutex::Locked) {
    } //wait on mutex
    Semaphore semaLock(SemaphoreIndex::Mutex); //RAII semaphore object
    if (mutexLock == Mutex::Unlocked) {
        mutexLock = Mutex::Locked;
        break;
    }
} //Semaphore is released by destructor here
// ... atomically safe code
mutexLock = Mutex::Unlocked;
</code>```

I have a few questions:  Is this the best way to approach this problem?  Is this code thread-safe?  Is this the same as a "double checked lock"?  If so, does it suffer from the same problems and therefore need memory barriers?

EDIT:  A few notes on the system this is being implemented on...

It is a RISC 16-bit processor with 32kB RAM.  While it has heavy multithreading capabilities, its memory model is very primitive.  Loads and stores are atomic, there is no caching, no branch prediction or branch target prediction, one core with many threads.  Memory barriers are mostly for the compiler to know it should reload memory into general purpose registers, not for any hardware reason (no cache)

答:
Right now we still don't have that much information about your system (for example, what kind of registers are available for each instruction in parrallel? do you use bank architecture?, how many simultaneous instructions can you actually execute?) but hopefully what I suggest will help you

If I understand your situation you have a piece of hardware that does not have true cores, but simply MIMD ability via a vectorized operation (based on your reply).  with a It is a "RISC 16-bit processor with 32kB RAM" where:

Loads and stores are atomic, there is no caching, no branch prediction or branch target prediction, one core with many threads

The key here is that loads and stores are atomic.  Note you won't be able to do larger than 16bit load and stores atomically, since they will be compiled to two separate atomic instructions (and thus not being atomic itself).

Here is the functionality of a mutex:

attempt to lock

unlock

To lock, you might run into issues if each resource attempts to lock.  For example say in your hardware N = 4 (number of processes to be run in parrallel).  If instruction 1 (I1) and I2 try to lock, they will both be successful in locking.  Since your loads and stores are atomic, both processes see "unlocked" at the same time, and both acquire the lock.

This means you can't do the following:

```<code> if mutex_1 unlocked:
      lock mutex_1
</code>```

which might look like this in an arbitrary assembly language:

```<code> load arithmetic mutex_addr
 or arithmetic immediate(1)  // unlocked = 0000 or 1 = 0001, locked = 0001 or 1 = 0001
 store mutex_addr arithmetic // not putting in conditional label to provide better synchronization.
 jumpifzero MUTEXLABEL arithmetic
</code>```

To get around this you will need to have each "thread" either know if its currently getting a lock some one else is or avoid simultaneous lock access entirely.

I only see one kind of way this can be done on your system (via flag/mutex id checking). Have a mutex id associated with each thread for each mutex it is currently checking, and check for all other threads to see if you can actually acquire a lock. Your binary semaphores don't really help here because you need to associate an individual mutex with a semaphore if you were going to use it (and still have to load the mutex from ram).

A simple implementation of the check every thread unlock and lock, basically each mutex has an ID and a state, in order to avoid race conditions per instruction, the current mutex being handled is identified well before it is actually acquired.   Having the "identify which lock you want to use" and "actually try to get the lock" come in two steps stops accidental acquisition on simultaneous access. With this method you can have 2^16-1 (because 0 is used to say no lock was found) mutexes and your "threads" can exist on any instruction pipe.

```<code>// init to zero
volatile uint16_t CURRENT_LOCK_ATTEMPT[NUM_THREADS]{0};
// make thread id associated with priority
bool tryAcqureLock(uint16_t mutex_id, bool& mutex_lock_state){
    if(mutex_lock_state == false){
        // do not actually attempt to take the lock until checked everything.
        // No race condition can happen now, you won't have actually set the lock
        // if two attempt to acquire the same lock at the same time, you'll both
        // be able to see some one else is as well.
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = mutex_id;
        //checking all lower threads, need some sort of priority
        //predetermined to figure out locking.
        for( int i = 0; i < MY_THREAD_ID; i++ ){
            if((CURRENT_LOCK_ATTEMPT[i] == mutex_id){
                //clearing bit.
                CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
                return false;
            }
        }
        // make sure to lock mutex before clearing which mutex you are currently handling
        mutex_lock_state = true;
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
        return true;
    }
    return false;
}

// its your fault if you didn't make sure you owned the lock in the first place
// if you did own it, theres no race condition, because of atomic store load.
// if you happen to set the state while another instruction is attempting to
// acquire the lock they simply wont get the lock and no race condition occurs
bool unlock(bool& mutex_lock_state){
    mutex_lock_state = false;
}
</code>```

If you want more equal access of resources you could change indexing instead of being based on i = 0 to i < MY_THREAD_ID, you randomly pick a "starting point" to circle around back to MY_THREAD_ID using modulo arithmetic. IE:

```<code>bool tryAcqureLock(uint16_t mutex_id, bool& mutex_lock_state, uint16_t per_mutex_random_seed){
    if(mutex_lock_state == false){

        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = mutex_id;
        //need a per thread linear congruence generator for speed and consistency
        std::minstd_rand0 random(per_mutex_random_seed)
        for(int i = random() % TOTAL_NUM_THREADS; i != MY_THREAD_ID i = (i + 1) % TOTAL_NUM_THREADS)
        {
        //same as before
        }
        // if we actually acquired the lock
        GLOBAL_SEED = global_random() // use another generator to set the next seed to be used
        mutex_lock_state = true;
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
        return true;
    }
    return false;
}
</code>```

In general your lack of test and set ability really throws a wrench into everything, meaning you are forced to use other algorithms for mutexes. For more information on other algorithms that you can use for non test and set architectures check out this SO post, and these wikipedia algorithms which only rely on atomic loads and stores:

Dekker's Algorithm

Eisenberg Mcguire Algorithm

Peterson's Algorithm

Lamport's Algorithm

Szymanski's Algorithm

All of these algorithms basically decompose into checking a set of flags to see if you can access the resource safely by going through every one elses flags.

Title: Creating Mutexes with Binary Semaphore

Body:
I'm working with a simple system that does NOT have mutexes, but rather a limited array of hardware binary semaphores.  Typically, all multithreading is been done with heavy Semaphore techniques that makes code both poor in performance and difficult to write correctly without deadlocks.

A naive implementation is to use one semaphore globally in order to ensure atomic access to a critical section.  However, this means that unrelated objects (even of different types) will block if any critical section is being accessed.

My current solution to this problem is to use a single global semaphore to ensure atomic access to a guard byte that then ensures atomic access to the particular critical section.  I currently have this so far:

while (true) {
    while (mutexLock == Mutex::Locked) {
    } //wait on mutex
    Semaphore semaLock(SemaphoreIndex::Mutex); //RAII semaphore object
    if (mutexLock == Mutex::Unlocked) {
        mutexLock = Mutex::Locked;
        break;
    }
} //Semaphore is released by destructor here
// ... atomically safe code
mutexLock = Mutex::Unlocked;

I have a few questions:  Is this the best way to approach this problem?  Is this code thread-safe?  Is this the same as a "double checked lock"?  If so, does it suffer from the same problems and therefore need memory barriers?

EDIT:  A few notes on the system this is being implemented on...

It is a RISC 16-bit processor with 32kB RAM.  While it has heavy multithreading capabilities, its memory model is very primitive.  Loads and stores are atomic, there is no caching, no branch prediction or branch target prediction, one core with many threads.  Memory barriers are mostly for the compiler to know it should reload memory into general purpose registers, not for any hardware reason (no cache)

Body:
Right now we still don't have that much information about your system (for example, what kind of registers are available for each instruction in parrallel? do you use bank architecture?, how many simultaneous instructions can you actually execute?) but hopefully what I suggest will help you

If I understand your situation you have a piece of hardware that does not have true cores, but simply MIMD ability via a vectorized operation (based on your reply).  with a It is a "RISC 16-bit processor with 32kB RAM" where:

Loads and stores are atomic, there is no caching, no branch prediction or branch target prediction, one core with many threads

The key here is that loads and stores are atomic.  Note you won't be able to do larger than 16bit load and stores atomically, since they will be compiled to two separate atomic instructions (and thus not being atomic itself).

Here is the functionality of a mutex:

attempt to lock

unlock

To lock, you might run into issues if each resource attempts to lock.  For example say in your hardware N = 4 (number of processes to be run in parrallel).  If instruction 1 (I1) and I2 try to lock, they will both be successful in locking.  Since your loads and stores are atomic, both processes see "unlocked" at the same time, and both acquire the lock.

This means you can't do the following:

 if mutex_1 unlocked:
      lock mutex_1

which might look like this in an arbitrary assembly language:

 load arithmetic mutex_addr
 or arithmetic immediate(1)  // unlocked = 0000 or 1 = 0001, locked = 0001 or 1 = 0001
 store mutex_addr arithmetic // not putting in conditional label to provide better synchronization.
 jumpifzero MUTEXLABEL arithmetic

To get around this you will need to have each "thread" either know if its currently getting a lock some one else is or avoid simultaneous lock access entirely.

I only see one kind of way this can be done on your system (via flag/mutex id checking). Have a mutex id associated with each thread for each mutex it is currently checking, and check for all other threads to see if you can actually acquire a lock. Your binary semaphores don't really help here because you need to associate an individual mutex with a semaphore if you were going to use it (and still have to load the mutex from ram).

A simple implementation of the check every thread unlock and lock, basically each mutex has an ID and a state, in order to avoid race conditions per instruction, the current mutex being handled is identified well before it is actually acquired.   Having the "identify which lock you want to use" and "actually try to get the lock" come in two steps stops accidental acquisition on simultaneous access. With this method you can have 2^16-1 (because 0 is used to say no lock was found) mutexes and your "threads" can exist on any instruction pipe.

// init to zero
volatile uint16_t CURRENT_LOCK_ATTEMPT[NUM_THREADS]{0};
// make thread id associated with priority
bool tryAcqureLock(uint16_t mutex_id, bool& mutex_lock_state){
    if(mutex_lock_state == false){
        // do not actually attempt to take the lock until checked everything.
        // No race condition can happen now, you won't have actually set the lock
        // if two attempt to acquire the same lock at the same time, you'll both
        // be able to see some one else is as well.
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = mutex_id;
        //checking all lower threads, need some sort of priority
        //predetermined to figure out locking.
        for( int i = 0; i < MY_THREAD_ID; i++ ){
            if((CURRENT_LOCK_ATTEMPT[i] == mutex_id){
                //clearing bit.
                CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
                return false;
            }
        }
        // make sure to lock mutex before clearing which mutex you are currently handling
        mutex_lock_state = true;
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
        return true;
    }
    return false;
}

// its your fault if you didn't make sure you owned the lock in the first place
// if you did own it, theres no race condition, because of atomic store load.
// if you happen to set the state while another instruction is attempting to
// acquire the lock they simply wont get the lock and no race condition occurs
bool unlock(bool& mutex_lock_state){
    mutex_lock_state = false;
}

If you want more equal access of resources you could change indexing instead of being based on i = 0 to i < MY_THREAD_ID, you randomly pick a "starting point" to circle around back to MY_THREAD_ID using modulo arithmetic. IE:

bool tryAcqureLock(uint16_t mutex_id, bool& mutex_lock_state, uint16_t per_mutex_random_seed){
    if(mutex_lock_state == false){

        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = mutex_id;
        //need a per thread linear congruence generator for speed and consistency
        std::minstd_rand0 random(per_mutex_random_seed)
        for(int i = random() % TOTAL_NUM_THREADS; i != MY_THREAD_ID i = (i + 1) % TOTAL_NUM_THREADS)
        {
        //same as before
        }
        // if we actually acquired the lock
        GLOBAL_SEED = global_random() // use another generator to set the next seed to be used
        mutex_lock_state = true;
        CURRENT_LOCK_ATTEMPT[MY_THREAD_ID] = 0;
        return true;
    }
    return false;
}

In general your lack of test and set ability really throws a wrench into everything, meaning you are forced to use other algorithms for mutexes. For more information on other algorithms that you can use for non test and set architectures check out this SO post, and these wikipedia algorithms which only rely on atomic loads and stores:

Dekker's Algorithm

Eisenberg Mcguire Algorithm

Peterson's Algorithm

Lamport's Algorithm

Szymanski's Algorithm

All of these algorithms basically decompose into checking a set of flags to see if you can access the resource safely by going through every one elses flags.


问:
Mixed Complementarity (MCP) Pyomo
Is it possible to solve an mcp models with pyomo? I would appreciate it if someone could point out an example and the solver i could use, if it's possible of course.</p>

答:
Yes, in principle it is: http://prod.sandia.gov/techlib/access-control.cgi/2015/155584.pdf

You need to install the PATH AMPL Solver from this webpage

pages.cs.wisc.edu/~ferris/path.html

If you make it work, could you see if the munson1.py solves the problems correctly in the examples correctly (munson1.py is a MCP), as I had problems so far

groups.google.com/forum/#!topic/pyomo-forum/DxdtrepaU6I

Title: Mixed Complementarity (MCP) Pyomo


问:
dplyr+purrr: n() refers to map() groups, not local groups?
I have a parent dataset nesting multiple datasets (i.e. a tibble where each cell is a tibble) , where I want for each dataset, to find the number of rows of each group. Standard way, using a single dataset, would simply be to do group_by(var) %>% mutate(nrow=n()).

But now that I do this for multiple datasets with a map() call, it looks like the n() call refers to the (implicit) grouping made by map(), not the explicit grouping within my local dataset made by group_by?

Standard way for one single dataset, n() returns 50:

```<code>iris %>%
  group_by(., Species) %>%
  mutate(nrow=n())
</code>```

Dataset of datasets:

```<code> df <- data_frame(name=c("a", "b"), Data=list(iris, iris))
 df2 <- df %>%
          mutate(Data2=map(Data, ~group_by(., Species) %>%
                 mutate(nrow=n()) %>%
                 ungroup()))
</code>```

but now n() returned 2?

```<code>df2[1,]$Data2[[1]]
</code>```

答:
Another option, available since version 0.7.0 is to use add_count(), which will not conflict with the map(), and anyway simplifies the code:

```<code># standard case:
iris %>%
  add_count(Species)

## df of df:
df2 <- df %>%
  mutate(Data2=map(Data, ~add_count(., Species)))
</code>```

Body:
I have a parent dataset nesting multiple datasets (i.e. a tibble where each cell is a tibble) , where I want for each dataset, to find the number of rows of each group. Standard way, using a single dataset, would simply be to do group_by(var) %>% mutate(nrow=n()).

But now that I do this for multiple datasets with a map() call, it looks like the n() call refers to the (implicit) grouping made by map(), not the explicit grouping within my local dataset made by group_by?

Standard way for one single dataset, n() returns 50:

iris %>%
  group_by(., Species) %>%
  mutate(nrow=n())

Dataset of datasets:

 df <- data_frame(name=c("a", "b"), Data=list(iris, iris))
 df2 <- df %>%
          mutate(Data2=map(Data, ~group_by(., Species) %>%
                 mutate(nrow=n()) %>%
                 ungroup()))

but now n() returned 2?

df2[1,]$Data2[[1]]

Body:
Another option, available since version 0.7.0 is to use add_count(), which will not conflict with the map(), and anyway simplifies the code:

# standard case:
iris %>%
  add_count(Species)

## df of df:
df2 <- df %>%
  mutate(Data2=map(Data, ~add_count(., Species)))


问:
MenuItem bitmaps raises an assert failure …
I am trying to have a nice bitmap of a gear in front of the Preferences menu item. This is how I think it should be coded:

```<code>    menubar = wx.MenuBar()
    fileMenu = wx.Menu()
    preferences = wx.MenuItem(text="Preferences",
                              helpString="Opens preferences dialog.",
                              kind=wx.ITEM_NORMAL)
    gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'gear.png'))
    preferences.SetBitmap(gear)
    self.shcfg = fileMenu.Append(preferences)
</code>```

However, this is wrong as I get a

```<code>Traceback (most recent call last):
  File "gui.py", line 193, in <module>
    GUI(None)
  File "gui.py", line 117, in __init__
    self.InitUI()
  File "gui.py", line 129, in InitUI
    preferences.SetBitmap(gear)
wx._core.wxAssertionError: C++ assertion "Assert failure" failed at /tmp/pip-build-sc_vd1aj/wxPython/ext/wxWidgets/src/gtk/menu.cpp(729) in SetBitmap(): only normal menu items can have bitmaps
</code>```

What am I doing wrong?

答: Have you tried omitting kind=wx.ITEM_NORMAL? It looks like it could be mishandled by wxPython and result in creating a checkable item instead. At least, this is what somehow ends up by happening, according to the assert message.

Body:
I am trying to have a nice bitmap of a gear in front of the Preferences menu item. This is how I think it should be coded:

    menubar = wx.MenuBar()
    fileMenu = wx.Menu()
    preferences = wx.MenuItem(text="Preferences",
                              helpString="Opens preferences dialog.",
                              kind=wx.ITEM_NORMAL)
    gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'gear.png'))
    preferences.SetBitmap(gear)
    self.shcfg = fileMenu.Append(preferences)

However, this is wrong as I get a

Traceback (most recent call last):
  File "gui.py", line 193, in <module>
    GUI(None)
  File "gui.py", line 117, in __init__
    self.InitUI()
  File "gui.py", line 129, in InitUI
    preferences.SetBitmap(gear)
wx._core.wxAssertionError: C++ assertion "Assert failure" failed at /tmp/pip-build-sc_vd1aj/wxPython/ext/wxWidgets/src/gtk/menu.cpp(729) in SetBitmap(): only normal menu items can have bitmaps

What am I doing wrong?


问:
How to round a time down to the nearest 15 minutes in Ruby?
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

```<code>t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
</code>```

答:
You said "round down", so I'm not sure if you're actually looking for the round or the floor, but here's the code to do both.  I think something like this reads really well if you add round_off and floor methods to the Time class.  The added benefit is that you can more easily round by any time partition.

```<code>require 'active_support/core_ext/numeric' # from gem 'activesupport'

class Time
  # Time#round already exists with different meaning in Ruby 1.9
  def round_off(seconds = 60)
    Time.at((self.to_f / seconds).round * seconds).utc
  end

  def floor(seconds = 60)
    Time.at((self.to_f / seconds).floor * seconds).utc
  end
end

t = Time.now                    # => Thu Jan 15 21:26:36 -0500 2009
t.round_off(15.minutes)         # => Thu Jan 15 21:30:00 -0500 2009
t.floor(15.minutes)             # => Thu Jan 15 21:15:00 -0500 2009
</code>```

Note: ActiveSupport was only necessary for the pretty 15.minutes argument.  If you don't want that dependency, use 15 * 60 instead.

OwnerDisplayName: Readonly

ContentLicense: CC BY-SA 2.5

Body:
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)

Body:
You said "round down", so I'm not sure if you're actually looking for the round or the floor, but here's the code to do both.  I think something like this reads really well if you add round_off and floor methods to the Time class.  The added benefit is that you can more easily round by any time partition.

require 'active_support/core_ext/numeric' # from gem 'activesupport'

class Time
  # Time#round already exists with different meaning in Ruby 1.9
  def round_off(seconds = 60)
    Time.at((self.to_f / seconds).round * seconds).utc
  end

  def floor(seconds = 60)
    Time.at((self.to_f / seconds).floor * seconds).utc
  end
end

t = Time.now                    # => Thu Jan 15 21:26:36 -0500 2009
t.round_off(15.minutes)         # => Thu Jan 15 21:30:00 -0500 2009
t.floor(15.minutes)             # => Thu Jan 15 21:15:00 -0500 2009

Note: ActiveSupport was only necessary for the pretty 15.minutes argument.  If you don't want that dependency, use 15 * 60 instead.

OwnerDisplayName: Ryan McGeary

LastEditorDisplayName: Ryan McGeary


问:
Splitting divs into 2 columns
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

```
</div>
</div>
</p>

<p>and I want to transform this 1 lined column into 2 columns like this:</p>

<p><img src="https://i.stack.imgur.com/NKI4c.png" alt="example image"></p>

<p>I already tried to use this code, but is there any different way to split the div?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}</code>```

title1

article1

title2

article2

title3

article3

title4

article4

```

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

答:
Nothing wrong with flexbox for this layout.

There's no need to use a pseudo-element.

.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex: 0 0 50%;
  padding: 10px;
}

* {
  margin: 0;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div></code>```

Title: Splitting divs into 2 columns

Body:
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

and I want to transform this 1 lined column into 2 columns like this:

I already tried to use this code, but is there any different way to split the div?

.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}

title1

article1

title2

article2

title3

article3

title4

article4

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

Body:
Nothing wrong with flexbox for this layout.

There's no need to use a pseudo-element.

.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex: 0 0 50%;
  padding: 10px;
}

* {
  margin: 0;
  box-sizing: border-box;
}

<div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div>


问:
print statements are not appearing in GAE
Running GAE application in dev(dev_appserver.py). Print statements are not showing when I run, statements are showing when I kill (Ctrl+C) the application.

Its a very simple application.

dev_appserver command:

```<code>python dev_appserver.py --skip_sdk_update_check=yes C:\Chaitu\Projects\fb
</code>```

Output: Print statement is not appearing.

```<code>INFO     2017-07-05 10:33:54,759 devappserver2.py:116] Skipping SDK update check.
INFO     2017-07-05 10:33:54,875 api_server.py:297] Starting API server at: http://localhost:53833
INFO     2017-07-05 10:33:54,891 dispatcher.py:209] Starting module "default" running at: http://localhost:8080
INFO     2017-07-05 10:33:54,907 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO     2017-07-05 10:33:59,188 module.py:809] default: "GET /fb/getdim HTTP/1.1" 200 40
</code>```

Calling Function:

```<code>class get_dim(webapp.RequestHandler):

    _apptitle      = None
    _projectid     = None
    _projectnumber = None

    def get(self):
        #bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
        cfg=appsettings()
        self.response.write("Enter into getdim")
        for i in cfg._templates:

            id=int(i['_id'])

            if id == 1:
                self.response.write("Enter into if statement")
                fbutils._getDim(int(i['_id']),i['_app_id'],i['_app_secret'],i['_access_token'],i['_ad_acct'],i['_filename'],i['_gcsbucket'],cfg)
</code>```

Actual Function:

```<code>def _getDim(idno,app_id,app_secret,access_token,ad_acct,file_name,bucket_nm,cfg):
  try:
    print "Hi This is test message"
  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
</code>```

答:
The most like cause of this is that your operating system is not flushing the buffer that your print statements are being written to until after dev server process has finished.

Use the logging package to have output produced while the dev server is running.

```<code>import logging

def _getDim(idno,app_id,app_secret,access_token,ad_acct,file_name,bucket_nm,cfg):
  try:
    logging.info("Hi This is test message")
  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logging.exception('Something went wrong.')
</code>```

By default the dev server suppresses log messages with a level less than info, but you can control this by passing the --log_level parameter to the dev server.

```<code>python dev_appserver.py --skip_sdk_update_check=yes --log_level=debug C:\Chaitu\Projects\fb
</code>```

Body:
Running GAE application in dev(dev_appserver.py). Print statements are not showing when I run, statements are showing when I kill (Ctrl+C) the application.

Its a very simple application.

dev_appserver command:

python dev_appserver.py --skip_sdk_update_check=yes C:\Chaitu\Projects\fb

Output: Print statement is not appearing.

INFO     2017-07-05 10:33:54,759 devappserver2.py:116] Skipping SDK update check.
INFO     2017-07-05 10:33:54,875 api_server.py:297] Starting API server at: http://localhost:53833
INFO     2017-07-05 10:33:54,891 dispatcher.py:209] Starting module "default" running at: http://localhost:8080
INFO     2017-07-05 10:33:54,907 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO     2017-07-05 10:33:59,188 module.py:809] default: "GET /fb/getdim HTTP/1.1" 200 40

Calling Function:

class get_dim(webapp.RequestHandler):

    _apptitle      = None
    _projectid     = None
    _projectnumber = None

    def get(self):
        #bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
        cfg=appsettings()
        self.response.write("Enter into getdim")
        for i in cfg._templates:

            id=int(i['_id'])

            if id == 1:
                self.response.write("Enter into if statement")
                fbutils._getDim(int(i['_id']),i['_app_id'],i['_app_secret'],i['_access_token'],i['_ad_acct'],i['_filename'],i['_gcsbucket'],cfg)

Actual Function:

def _getDim(idno,app_id,app_secret,access_token,ad_acct,file_name,bucket_nm,cfg):
  try:
    print "Hi This is test message"
  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()

Body:
The most like cause of this is that your operating system is not flushing the buffer that your print statements are being written to until after dev server process has finished.

Use the logging package to have output produced while the dev server is running.

import logging

def _getDim(idno,app_id,app_secret,access_token,ad_acct,file_name,bucket_nm,cfg):
  try:
    logging.info("Hi This is test message")
  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logging.exception('Something went wrong.')

By default the dev server suppresses log messages with a level less than info, but you can control this by passing the --log_level parameter to the dev server.

python dev_appserver.py --skip_sdk_update_check=yes --log_level=debug C:\Chaitu\Projects\fb


问:
Jekyll For Loop Questions
So I want to setup a for loop in Jekyll that only displays the latest event/item in the collection. (Organised by date)

Currently, this doesn't do much apart from sort the date by weight and cycle through the collection with a limit of one.

```<code>    {% assign sorted_events = site.events | sort: "date" %}
    {% for event in sorted_events limit:1 %}
    <section class="venue-info wow fadeIn" data-wow-duration="1.2s" id="about">
        <div class="upcoming-event">
          <h1>Our Next Event</h1>
        <h2>{{ event.title }}</h2>
        <p>{{ event.description }}</p>
        <a class="btn scroll" href="{{ event.url }}">Learn More</a>
        </div>
    {% endfor %}
</code>```

答:
Taking {{site.post}} as the collection for this example, we sort the collection of posts and then use the last tag to get the last element of the array.

To get the newest post:

```<code>{% assign newest = site.posts | sort: "date" | last  %}

{{newest.title}}
{{newest.date}}
</code>```

oldest post:

```<code>{% assign oldest = site.posts | sort: "date" | first  %}

{{oldest.title}}
{{oldest.date}}
</code>```

It should work for any other collection like site.events as your code refers.

Title: Jekyll For Loop Questions

Body:
So I want to setup a for loop in Jekyll that only displays the latest event/item in the collection. (Organised by date)

Currently, this doesn't do much apart from sort the date by weight and cycle through the collection with a limit of one.

    {% assign sorted_events = site.events | sort: "date" %}
    {% for event in sorted_events limit:1 %}

Our Next Event

{{ event.title }}

{{ event.description }}

        Learn More

    {% endfor %}

Body:
Taking {{site.post}} as the collection for this example, we sort the collection of posts and then use the last tag to get the last element of the array.

To get the newest post:

{% assign newest = site.posts | sort: "date" | last  %}

{{newest.title}}
{{newest.date}}

oldest post:

{% assign oldest = site.posts | sort: "date" | first  %}

{{oldest.title}}
{{oldest.date}}

It should work for any other collection like site.events as your code refers.


问:
Unreal Engine 4 Blueprint
Im new to unreal
I have a problem with the communication from Hud_Blueprint to Level_Blueprint.

I want to have a slider in the Hud which controls the rotation of a cube in the level.

In the Hud_Blueprint i have the slider I made in a Widget_Blueprint.
Works perfect, printline values from 0 to 1.
I tried to use a Interface_Blueprint, like in the following link without success.
https://answers.unrealengine.com/questions/22126/pass-variable-from-hud-blueprint-to-level-blueprin.html

my Blueprints:
<s>https://www.dropbox.com/s/k30ah9fjuwlff6x/zusammen.jpg?dl=0</s> (404 response)

Seems like i have no connection between the Blueprints.

The function works just in the Hud_Blueprint.

答: If you select your cube in the level outliner and drag that into your HUD_BP you can obtain a reference to the object that way. You can then drag a pin off the object reference and call SetActorRotation

Title: Unreal Engine 4 Blueprint


问:
How do I use my rails3 generator in all my projects?
I wrote a generator that I'd like to use in my Rails3 projects using Thor (which I absolutely love).

How would I go about using my generator in all my rails3 projects?
i.e. how do I install it?

If the answer is to make a gem out of it - could you please describe the rails3 process of doing so?

Thanks!

答:
Yep, make a gem!

In terms of loading your generator it's pretty much as simple as putting your generator files in lib/generators/#{generator_name}/ in the gem. See the generators guide for a little more explanation of how they're loaded.

Check out some gems which do this such as rails3-generators gem. rspec-rails, machinist for examples.

In terms of actually building your gem, check out jeweler


问:
How to change style of already loaded points from geojson file?
I created a script which loads in features from a geojson file as so:

```<code>"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [5.53204822887795, 51.609252234043296, 0.0]
    }
}, etc...
</code>```

I then use a style function to create circles with different colors and radius sizes on those points:

```<code>var styleFunction = function(feature) {
var style = new ol.style.Style({
    image: new ol.style.Circle({
        radius: calculateRadius(feature),
        fill: new ol.style.Fill({
            color: 'rgba(255, 0, 0, 0.5)'
        }),
    stroke: null
    })
});

return style;
};
</code>```

I would like to change the styling of those features, but for the life of me I have no way of accessing the style. I can access the coordinates (I guess because they're points), but getting the radius or color seems impossible.

Any tips?

答:
In your style function, try changing return style; to return [style];.

See my post here Style Function example

Since each feature goes through the style function, you can also add properties to your geojson that can be read in your style function.  This is great if you want to do other things like make a square or enlarge a map feature based on a property of the feature.

Body:
I created a script which loads in features from a geojson file as so:

"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [5.53204822887795, 51.609252234043296, 0.0]
    }
}, etc...

I then use a style function to create circles with different colors and radius sizes on those points:

var styleFunction = function(feature) {
var style = new ol.style.Style({
    image: new ol.style.Circle({
        radius: calculateRadius(feature),
        fill: new ol.style.Fill({
            color: 'rgba(255, 0, 0, 0.5)'
        }),
    stroke: null
    })
});

return style;
};

I would like to change the styling of those features, but for the life of me I have no way of accessing the style. I can access the coordinates (I guess because they're points), but getting the radius or color seems impossible.

Any tips?


问:
change the view controller title color in objective c
I want to change the view controller title color like that this one in black!

答:
Title color change for only one view controller:

Use below code in viewWillAppear

```<code>[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor blackColor]}];
</code>```

Title color change for Entire Application:

Use below code in didFinishLaunching

```<code>[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
</code>```

Body:
Title color change for only one view controller:

Use below code in viewWillAppear

[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor blackColor]}];

Title color change for Entire Application:

Use below code in didFinishLaunching

[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];


问:
Using Git describe without tags
I have a repository that gives me only a hash when I run git describe. I did not know until today that it does this because of the --always option (which is what I was using) since that repository has no tags. I have another repository with lots of tags.

How can I use git describe to exclude tags and just give me a hash? I want to have all of the other functionality of git describe in case I need to use the other features, such as dirty marking; I just want to exclude tags. Is this possible, or are tags the central feature of describe?

The help page does seem to indicate that, but I just want to be sure. I use this in an Ant build.xml file, so I'm trying to keep this simple.

答:
Yes, but it's not necessarily a good idea.  There is a --all option, which will search branch names—or in fact, all references—as well, but if you use that, you might also need --long.

Description

The central feature of git describe output is that it starts with a name that is (or should be) human-readable:

```<code>v1.2.3
</code>```

To this, Git will, if necessary, add a suffix indicating that the current (or requested) commit is not quite the one named by this string.  The suffix tells both you and Git how much to deviate from the tag.  If there is no suffix, the tag itself names the commit.  Since tags never1 move, if we have that name, we are guaranteed2 to find the correct commit using that name.

With a repository with no tags and no --always:

```<code>$ git describe
fatal: No names found, cannot describe anything.
</code>```

If we add --all, however, we might get this:

```<code>$ git describe --all
heads/master
</code>```

This is a human-readable name, but there is a problem with it: it does not uniquely identify one particular commit, because branch names do move.  Once I make a new commit in this repository, refs/heads/master now names a different commit.

Since the usual intent of one of these outputs from git describe is to provide a human-readable but exact-commit-specifying ID, a branch name, which is never that exact, is not necessarily a good thing.

You can add --long:

```<code>$ git describe --all --long
heads/master-0-g2cbd83f
</code>```

This now uses the -g... suffix to specify a prefix of the actual hash ID.  Now Git can verify that master itself has not moved, or if it has, you can use the 2cbd83f string to find the commit.

1Well, hardly ever.  See the git-tag documentation on when and why and why not to move a tag.

2Guaranteed to the extent that tags have not moved, anyway.

Title: Using Git describe without tags

Body:
Yes, but it's not necessarily a good idea.  There is a --all option, which will search branch names—or in fact, all references—as well, but if you use that, you might also need --long.

Description

The central feature of git describe output is that it starts with a name that is (or should be) human-readable:

v1.2.3

To this, Git will, if necessary, add a suffix indicating that the current (or requested) commit is not quite the one named by this string.  The suffix tells both you and Git how much to deviate from the tag.  If there is no suffix, the tag itself names the commit.  Since tags never1 move, if we have that name, we are guaranteed2 to find the correct commit using that name.

With a repository with no tags and no --always:

$ git describe
fatal: No names found, cannot describe anything.

If we add --all, however, we might get this:

$ git describe --all
heads/master

This is a human-readable name, but there is a problem with it: it does not uniquely identify one particular commit, because branch names do move.  Once I make a new commit in this repository, refs/heads/master now names a different commit.

Since the usual intent of one of these outputs from git describe is to provide a human-readable but exact-commit-specifying ID, a branch name, which is never that exact, is not necessarily a good thing.

You can add --long:

$ git describe --all --long
heads/master-0-g2cbd83f

This now uses the -g... suffix to specify a prefix of the actual hash ID.  Now Git can verify that master itself has not moved, or if it has, you can use the 2cbd83f string to find the commit.

1Well, hardly ever.  See the git-tag documentation on when and why and why not to move a tag.

2Guaranteed to the extent that tags have not moved, anyway.


问:
Automatically add extension when saving in R
I am using the tcltk package in R to create a GUI, and I am trying to write a function in R that automatically adds a .xlsx extension to the end of a file name when saving.  However, when it calls the Save As window, it doesn't add the extension.  Any help is appreciated, thank you.</p>

```<code>library(openxlsx)
library(tcltk)
saveFile1 <- function(){
  write.xlsx(c, tclvalue(tkgetSaveFile(
    filetypes = "{ {Excel} {*.xlsx} }")))
}
</code>```

答:
I think this should do the trick.</p>

```<code>saveFile1 <- function(c){
  require(tcltk)
  require(openxlsx)

  # Prompt for file
  filepath <- tclvalue(tkgetSaveFile(filetypes = "{ {Excel} {*.xlsx} }", defaultextension = ".xlsx"))

  # Check if file was specified
  if(filepath != ""){
    # Ensure that the last 5 characters are .xlsx
    filepath <- ifelse(substr(filepath, nchar(filepath) - 4, nchar(filepath)) == ".xlsx", filepath, paste0(filepath,".xlsx"))

    # Write the file
    write.xlsx(c, filepath)
  }
}

# Test the function
saveFile1(mtcars)
</code>```

Body:
I am using the tcltk package in R to create a GUI, and I am trying to write a function in R that automatically adds a .xlsx extension to the end of a file name when saving.  However, when it calls the Save As window, it doesn't add the extension.  Any help is appreciated, thank you.

library(openxlsx)
library(tcltk)
saveFile1 <- function(){
  write.xlsx(c, tclvalue(tkgetSaveFile(
    filetypes = "{ {Excel} {*.xlsx} }")))
}

Body:
I think this should do the trick.

saveFile1 <- function(c){
  require(tcltk)
  require(openxlsx)

  # Prompt for file
  filepath <- tclvalue(tkgetSaveFile(filetypes = "{ {Excel} {*.xlsx} }", defaultextension = ".xlsx"))

  # Check if file was specified
  if(filepath != ""){
    # Ensure that the last 5 characters are .xlsx
    filepath <- ifelse(substr(filepath, nchar(filepath) - 4, nchar(filepath)) == ".xlsx", filepath, paste0(filepath,".xlsx"))

    # Write the file
    write.xlsx(c, filepath)
  }
}

# Test the function
saveFile1(mtcars)


问:
Powershell : Sort files by first characer of name
Can anyone help with this home project?

I'm attempting to sort a 500gb+ directory full of random files.

I'd like to sort these files into sub-directories named 'A', 'B', 'C'..., '1', '2', '3'...

```<code>###################################################
# I've created a test directory to try my script against
###################################################
<# Start 7/4/2017 #>

Set-Location 'D:\IT Notes\psroot'

<# Make directories A..Z#>

65..90 | % {md ("{0}" -f [char]$_)}

<# Make a list of 0-9, A-Z, & a-z #>
$chars = [char[]] ([char]'0'..[char]'9' + [char]'A'..[char]'Z' + [char]'a'..[char]'z')

<# Use chars list to create random.txt file#>
(1..100).ForEach({-join (Get-Random $chars -Count 10) | Add-Content random.txt })

<# Save random.txt list to a variable#>
$random = (Get-Content .\random.txt)

<# Create files & add .txt extension #>
New-Item $random -ItemType file | Rename-Item -NewName {$_.name + ".txt"}

###################################################
</code>```

Now how do I sort everything into their respected directory?

Thanks for your help in advance!

答:
This took me all morning but I finally got it to work!

For those who are interested in using powershell to clean up those large and unruly directories, your welcome :]

```<code>##########################
# Create directory A-Z
65..90 | % {md ("{0}" -f [char]$_)}

# Starting value = A
$upcaseN = 65

# Run loop while $upcase less than or equall to 90
while ($upcaseN -le 90) {

# Convert $upcase from int to char
$upcase =  [char]$upcaseN

# Move items to respected directories
Move-Item $upcase* $upcase -ErrorAction SilentlyContinue

# Increase starting value
$upcaseN++

}
###########################

###########################
# Create directory 0-9
0..9 | % {md ("{0}" -f $_)}

# Starting value = 0
$notaletter = 0

while ($notaletter -le 9){
Move-Item $notaletter* $notaletter -ErrorAction SilentlyContinue
$notaletter++
</code>```

}
   ############################

Body:
Can anyone help with this home project?

I'm attempting to sort a 500gb+ directory full of random files.

I'd like to sort these files into sub-directories named 'A', 'B', 'C'..., '1', '2', '3'...

###################################################
# I've created a test directory to try my script against
###################################################
<# Start 7/4/2017 #>

Set-Location 'D:\IT Notes\psroot'

<# Make directories A..Z#>

65..90 | % {md ("{0}" -f [char]$_)}

<# Make a list of 0-9, A-Z, & a-z #>
$chars = [char[]] ([char]'0'..[char]'9' + [char]'A'..[char]'Z' + [char]'a'..[char]'z')

<# Use chars list to create random.txt file#>
(1..100).ForEach({-join (Get-Random $chars -Count 10) | Add-Content random.txt })

<# Save random.txt list to a variable#>
$random = (Get-Content .\random.txt)

<# Create files & add .txt extension #>
New-Item $random -ItemType file | Rename-Item -NewName {$_.name + ".txt"}

###################################################

Now how do I sort everything into their respected directory?

Thanks for your help in advance!

Body:
This took me all morning but I finally got it to work!

For those who are interested in using powershell to clean up those large and unruly directories, your welcome :]

##########################
# Create directory A-Z
65..90 | % {md ("{0}" -f [char]$_)}

# Starting value = A
$upcaseN = 65

# Run loop while $upcase less than or equall to 90
while ($upcaseN -le 90) {

# Convert $upcase from int to char
$upcase =  [char]$upcaseN

# Move items to respected directories
Move-Item $upcase* $upcase -ErrorAction SilentlyContinue

# Increase starting value
$upcaseN++

}
###########################

###########################
# Create directory 0-9
0..9 | % {md ("{0}" -f $_)}

# Starting value = 0
$notaletter = 0

while ($notaletter -le 9){
Move-Item $notaletter* $notaletter -ErrorAction SilentlyContinue
$notaletter++

}
   ############################


问:
How to use laravel's Auth class in different table?
I created a simple login and registration in my page and I also added some new columns in the default users table. Now my problem is I have another table named as admin and the default Laravel's Auth table is users. How can I implement the same functionality in my table?

In the Users model it has the declaration for the table name

```<code>   protected $table = 'users';
</code>```

Can you give me an example how can I use the default laravel's auth class?

Thats all thanks. :-)

答:
Laravel takes default users table for an application.  For a change of laravel authentication different table relevant table name, we need to make a small change in authentication file of config.

Go to

config/auth.php

```<code>'providers' => [
    // 'users' => [
    //     'driver' => 'eloquent',
    //     'model' => App\User::class,
    // ],
     'users' => [
         'driver' => 'database',
         'table' => 'user',
     ],
],
</code>```

Body:
I created a simple login and registration in my page and I also added some new columns in the default users table. Now my problem is I have another table named as admin and the default Laravel's Auth table is users. How can I implement the same functionality in my table?

In the Users model it has the declaration for the table name

   protected $table = 'users';

Can you give me an example how can I use the default laravel's auth class?

Thats all thanks. :-)

Body:
Laravel takes default users table for an application.  For a change of laravel authentication different table relevant table name, we need to make a small change in authentication file of config.

Go to

config/auth.php

'providers' => [
    // 'users' => [
    //     'driver' => 'eloquent',
    //     'model' => App\User::class,
    // ],
     'users' => [
         'driver' => 'database',
         'table' => 'user',
     ],
],


问:
Class Not Found when executing Java Web App
I'm very new to the Java landscape (Eclipse, Spring, etc.) and just walking through some introductory tutorials at the moment.  I just finished a Hello World tutorial for Spring MVC, with a simple page that then posts to another action.  Straightforward enough.

I then went on to tinker a bit with the working result of that tutorial.  My first attempt is to create another project in Eclipse with just some simple packages containing POJOs.  The idea being to have something portable which different applications could use.  (Intended to be the equivalent of a "Class Library" project in the .NET world.)

That project has one package, with one interface (IWorld) and one class (HelloWorld).  In my Spring MVC project I then add the other project to the build path and create an instance of that object in the controller.  The compiler says everything's fine:

```<code>package com.sandbox.application.mvctest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sandbox.domain.models.*;

@Controller
public class HelloWorldController {

    @RequestMapping("/")
    public String hello() {
        IWorld world = new HelloWorld();
        world.speak();
        return "hello";
        //TODO: Return a ModelAndView instead
    }

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi(@RequestParam("name") String name, Model model) {
        String message = "Hi " + name + "!";
        model.addAttribute("message", message);
        return "hi";
    }

}
</code>```

The .speak() method doesn't do anything of note, just returns a value which the controller isn't using yet.  The intent of course is to start building up some features in the models rather than just in the controllers and views, building more of a rich domain model.

Eclipse doesn't complain about the code, everything seems to compile just fine.  But when executing on Tomcat I get an exception:

```<code>Jul 05, 2017 12:36:49 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [springDispatcher]
java.lang.ClassNotFoundException: com.sandbox.domain.models.IWorld
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    [and so on...]
</code>```

My Googling has proved fruitless so far, likely because I don't always understand what I'm finding.  For example, there are some posts which advise to correct something in a pom.xml file.  I have no such file.  Is this related to Spring's dependency injection?  Should I be using that?  I wouldn't have considered this to be an injectable dependency, I'm just creating an instance directly.  But then I'm also approaching this from a deeply dogmatic .NET mindset, so all bets are off.

What am I missing here?

答:
If I understand your question properly then you are expecting the project class-path and the web app class-path to be the same. All the dependencies would not be exported automatically when the web app is deployed. You can check the deployed web-app's WEB-INF/lib folder for your dependencies.

If you are using Tomcat as your servlet container then you can add the dependency jars in Tomcat's lib folder and then it should work.

Body:
I'm very new to the Java landscape (Eclipse, Spring, etc.) and just walking through some introductory tutorials at the moment.  I just finished a Hello World tutorial for Spring MVC, with a simple page that then posts to another action.  Straightforward enough.

I then went on to tinker a bit with the working result of that tutorial.  My first attempt is to create another project in Eclipse with just some simple packages containing POJOs.  The idea being to have something portable which different applications could use.  (Intended to be the equivalent of a "Class Library" project in the .NET world.)

That project has one package, with one interface (IWorld) and one class (HelloWorld).  In my Spring MVC project I then add the other project to the build path and create an instance of that object in the controller.  The compiler says everything's fine:

package com.sandbox.application.mvctest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sandbox.domain.models.*;

@Controller
public class HelloWorldController {

    @RequestMapping("/")
    public String hello() {
        IWorld world = new HelloWorld();
        world.speak();
        return "hello";
        //TODO: Return a ModelAndView instead
    }

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi(@RequestParam("name") String name, Model model) {
        String message = "Hi " + name + "!";
        model.addAttribute("message", message);
        return "hi";
    }

}

The .speak() method doesn't do anything of note, just returns a value which the controller isn't using yet.  The intent of course is to start building up some features in the models rather than just in the controllers and views, building more of a rich domain model.

Eclipse doesn't complain about the code, everything seems to compile just fine.  But when executing on Tomcat I get an exception:

Jul 05, 2017 12:36:49 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet [springDispatcher]
java.lang.ClassNotFoundException: com.sandbox.domain.models.IWorld
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    [and so on...]

My Googling has proved fruitless so far, likely because I don't always understand what I'm finding.  For example, there are some posts which advise to correct something in a pom.xml file.  I have no such file.  Is this related to Spring's dependency injection?  Should I be using that?  I wouldn't have considered this to be an injectable dependency, I'm just creating an instance directly.  But then I'm also approaching this from a deeply dogmatic .NET mindset, so all bets are off.

What am I missing here?


问:
Error while doing lint command on private pod "Encountered an unknown error (no implicit conversion of nil into String) during validation."
I'm creating a private pod depending on another private pod the linter works well when I don't add any dependency but when I add the dependency and run the lint command it gives me that error

```<code>Encountered an unknown error (no implicit conversion of nil into String) during validation.
</code>```

the lint commmand:

```<code>pod spec lint --private --sources=https://github.com/*****/****.git
</code>```

Here is my podSpec what is wrong with it and what should I do to fix that?

```<code>Pod::Spec.new do |s|

s.name         = "****Framework"
s.version      = "1.0.0"
s.summary      = "Summary  ................."
s.homepage     = "https://github.com/****/****Framework"
s.description  = "Description ................."
s.license      = "Simplified BSD license"
s.author       = { "Nahla Mortada" => "nahla.mortada@****.com" }
s.platform     = :ios, "9.0"
s.ios.deployment_target = "9.0"
s.source   = { :git => "https://github.com/****/****Framework.git", :tag => s.version }
s.source_files = "****Framework/*.swift"
s.pod_target_xcconfig =  {
'SWIFT_VERSION' => '3.0',
}
s.requires_arc = true
s.dependency '****'

end
</code>```

Full Error:

```<code>ERROR | [iOS] unknown: Encountered an unknown error (no implicit conversion of nil into String
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `initialize'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `new'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `from_file'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification/set.rb:45:in `specification'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source.rb:265:in `search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `block in search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `select'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:347:in `create_set_from_sources'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:317:in `find_cached_set'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:290:in `specifications_for_dependency'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:108:in `search_for'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:206:in `block in sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `sort_by'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:52:in `block in sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:69:in `with_no_such_dependency_error_handling'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:51:in `sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:446:in `push_state_for_requirements'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:438:in `require_nested_dependencies_for'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:422:in `activate_spec'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:388:in `attempt_to_activate_new_spec'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:319:in `attempt_to_activate'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:137:in `process_topmost_state'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:78:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolver.rb:42:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:62:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:719:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:717:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:76:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:236:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:150:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:149:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `block in download_pod'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `download_pod'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:301:in `block in perform_extensive_analysis'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:295:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:295:in `perform_extensive_analysis'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:79:in `validate'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:64:in `block in run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:53:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:53:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-1.0.1/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `<main>'
) during validation.
</code>```

答:
Try clearing your local CocoaPods cache by running rm -rf ~/.cocoapods and then running pod setup.

Your podspec appears to be valid, if this doesn't help you should try uncommenting your s.dependency und linting it again, because the dependency-pod might also be the one causing this crash.

Body:
I'm creating a private pod depending on another private pod the linter works well when I don't add any dependency but when I add the dependency and run the lint command it gives me that error

Encountered an unknown error (no implicit conversion of nil into String) during validation.

the lint commmand:

pod spec lint --private --sources=https://github.com/*****/****.git

Here is my podSpec what is wrong with it and what should I do to fix that?

Pod::Spec.new do |s|

s.name         = "****Framework"
s.version      = "1.0.0"
s.summary      = "Summary  ................."
s.homepage     = "https://github.com/****/****Framework"
s.description  = "Description ................."
s.license      = "Simplified BSD license"
s.author       = { "Nahla Mortada" => "nahla.mortada@****.com" }
s.platform     = :ios, "9.0"
s.ios.deployment_target = "9.0"
s.source   = { :git => "https://github.com/****/****Framework.git", :tag => s.version }
s.source_files = "****Framework/*.swift"
s.pod_target_xcconfig =  {
'SWIFT_VERSION' => '3.0',
}
s.requires_arc = true
s.dependency '****'

end

Full Error:

ERROR | [iOS] unknown: Encountered an unknown error (no implicit conversion of nil into String
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `initialize'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `new'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification.rb:531:in `from_file'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/specification/set.rb:45:in `specification'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source.rb:265:in `search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `block in search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `select'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-1.2.0/lib/cocoapods-core/source/aggregate.rb:83:in `search'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:347:in `create_set_from_sources'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:317:in `find_cached_set'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:290:in `specifications_for_dependency'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:108:in `search_for'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:206:in `block in sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `sort_by'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:200:in `sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:52:in `block in sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:69:in `with_no_such_dependency_error_handling'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/delegates/specification_provider.rb:51:in `sort_dependencies'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:446:in `push_state_for_requirements'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:438:in `require_nested_dependencies_for'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:422:in `activate_spec'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:388:in `attempt_to_activate_new_spec'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:319:in `attempt_to_activate'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:137:in `process_topmost_state'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolution.rb:78:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/molinillo-0.5.5/lib/molinillo/resolver.rb:42:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/resolver.rb:62:in `resolve'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:719:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:717:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer/analyzer.rb:76:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:236:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:150:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/installer.rb:149:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `block in download_pod'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:405:in `download_pod'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:301:in `block in perform_extensive_analysis'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:295:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:295:in `perform_extensive_analysis'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/validator.rb:79:in `validate'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:64:in `block in run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:53:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command/spec/lint.rb:53:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-1.0.1/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `'
) during validation.


问:
Python: Assigning grouped mean to 1-D array
Suppose that I have 2 arrays:

```<code>x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]
</code>```

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

```<code>x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]
</code>```

(I could use loops to achieve this, but that would be quite inefficient.)

Body:
Suppose that I have 2 arrays:

x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]

(I could use loops to achieve this, but that would be quite inefficient.)

Body:
One option is to use Pandas:

import pandas as pd
x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]
s = pd.Series(x,index=flag)
s.groupby(level=0).transform('mean').tolist()

Output:

[3.25,
 5.333333333333333,
 3.25,
 3.3333333333333335,
 5.333333333333333,
 5.333333333333333,
 3.3333333333333335,
 3.25,
 3.25,
 3.3333333333333335]


问:
JavaScript/jQuery: Setting up IP Geolocation API within CodePen
I am very new to using APIs and am having a difficult time making a GET request to IP Geolocation API. I am not sure if the problem is with my code or with something concerning CodePen (it's probably my code).

I took the JavaScript directly from the example listed on IP Geolocation API page. I was going to modify it after seeing it work in action but I couldn't get it work at all. I tried modifying the URL to include both http:// and https://.

JavaScript:

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

  $.getJSON("http://ip-api.com/json/?callback=?", function(data) {
            var table_body = "";
            $.each(data, function(k, v) {
                table_body += "<tr><td>" + k + "</td><td><b>" + v + "</b></td></tr>";
            });
            $("#GeoResults").html(table_body);
        });

});
</code>```

HTML:

```<code><div class="weather">
  <div class="row title">
    <h1>weather</h2>
  </div>
  <div class="row icon">

  </div>
  <div id = "GeoResults" class="row temp">
    <p class = "city">City here</p>
  </div>
</div>
</code>```

URL to my CodePen: https://codepen.io/mattr8/pen/yXEMRM

API I am trying to use: http://ip-api.com/docs/api:json

答:
Codepen doesn't want to work with ip-api.com because of https.  Because codepen is served over https it will block any requests that are not https.  If you go to http://ip-api.com/json/?callback=? you will see the information you're trying to reach.  If you go to https://ip-api.com/json/?callback=? you will receive an error.

The jsbin example they link to does not use https, so it works fine.

So to fix your issue, create an example on a service or your own machine using http, not https for the request.

Body:
I am very new to using APIs and am having a difficult time making a GET request to IP Geolocation API. I am not sure if the problem is with my code or with something concerning CodePen (it's probably my code).

I took the JavaScript directly from the example listed on IP Geolocation API page. I was going to modify it after seeing it work in action but I couldn't get it work at all. I tried modifying the URL to include both http:// and https://.

JavaScript:

$(document).ready(function() {

  $.getJSON("http://ip-api.com/json/?callback=?", function(data) {
            var table_body = "";
            $.each(data, function(k, v) {
                table_body += "
" + k + "	" + v + "
";
            });
            $("#GeoResults").html(table_body);
        });

});

HTML:

weather

City here

URL to my CodePen: https://codepen.io/mattr8/pen/yXEMRM

API I am trying to use: http://ip-api.com/docs/api:json


问:
Are there code metrics that will cover variable scoping
In trying to get an overview of how difficult some legacy C++ and C# code is to maintain, and the risk of introducing bugs to it, it has been suggested that it would be useful to measure how widely or narrowly variables are scoped. The code uses a lot of globals, or widely scoped variables, where local ones would be better. A common occurrence is to find that these variables are used for 2 or 3 lines of code several scope levels in from where they are declared.

I know static code analysis tools usually try to quantify coupling and cohesion, but is there anything more specifically measuring variable/data scope?

答:
You can try CppDepend and it's CQLinq code query language to detect some global variables used by only one method or maybe one class.</p>

```<code>from f in Fields where f.IsGlobal && f.MethodsUsingMe.Count()==1 select f
</code>```

Body:
You can try CppDepend and it's CQLinq code query language to detect some global variables used by only one method or maybe one class.

from f in Fields where f.IsGlobal && f.MethodsUsingMe.Count()==1 select f


问:
Problem when assigning a pointer to an enum variable in C
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

```<code>//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!
</code>```

答: Because status is a pointer to enum error_type, and the_go_status is a pointer to an int. They are pointers to different types.</p>

Body:
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!


问:
Highlight link if in directory
I have a series of links which currently remain highlighted if on the  current url (using query and css).

My question is, what if I want it to remain highlighted not because of the page but if still within that directory? ie. If I click multi links on the page that is still within that directory for that particular link to remain highlighted. Hope that makes sense.

Jquery:

```<code> <script>
  $(function(){
    $('.section li a').each(function() {
      if ($(this).prop('href') == window.location.href) {
        $(this).addClass('current');
      }
    });
  });
  </script>
</code>```

css

```<code>.section li a.current {
  text-decoration: underline;
}
</code>```

答:
you can read URL if it contains the name of the directory</p>

```<code>if(window.location.href.indexOf("SOMETHING") > -1) {
// HIGHLIGHT
});
</code>```

Title: Highlight link if in directory

Body:
I have a series of links which currently remain highlighted if on the  current url (using query and css).

My question is, what if I want it to remain highlighted not because of the page but if still within that directory? ie. If I click multi links on the page that is still within that directory for that particular link to remain highlighted. Hope that makes sense.

Jquery:

css

.section li a.current {
  text-decoration: underline;
}

Body:
you can read URL if it contains the name of the directory

if(window.location.href.indexOf("SOMETHING") > -1) {
// HIGHLIGHT
});