问:
How to recursively merge two objects?
I have the following two objects:

```<code>var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};
</code>```

and I'd like to get:

```<code>var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};
</code>```

答:
I would use lodash’s _.merge method in this case.

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

```<code>var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
</code>```

https://lodash.com/docs/4.17.4#merge

Or if you need it to not be part of a library, then look at the lodash’s implementation.

Title: How to recursively merge two objects?

Body:
I have the following two objects:

var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};

and I'd like to get:

var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};

Body:
I would use lodash’s _.merge method in this case.

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

https://lodash.com/docs/4.17.4#merge

Or if you need it to not be part of a library, then look at the lodash’s implementation.


来源: stackexchange

问:
How do I calculate the temperature in celsius returned in openweathermap.org JSON?
I'm getting the weather for a city using openweathermap.org.

The jsonp call is working and everything is fine but the resulting object contains the temperature in an unknown unit:

```<code>{
    //...
    "main": {
        "temp": 290.38, // What unit of measurement is this?
        "pressure": 1005,
        "humidity": 72,
        "temp_min": 289.25,
        "temp_max": 291.85
    },
    //...
}
</code>```

Here is a demo that console.log's the full object.

I don't think the resulting temperature is in fahrenheit because converting 290.38 fahrenheit to celsius is 143.544.

Does anyone know what temperature unit openweathermap is returning?

答:
You can change the unit to metric.

This is my code.

```<code><head>
    <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
        <style type="text/css">]
        body{
            font-size: 100px;

        }

        #weatherLocation{

            font-size: 40px;
        }
        </style>
        </head>
        <body>
<div id="weatherLocation">Click for weather</div>

<div id="location"><input type="text" name="location"></div>

<div class="showHumidity"></div>

<div class="showTemp"></div>

<script type="text/javascript">
$(document).ready(function() {
  $('#weatherLocation').click(function() {
    var city = $('input:text').val();
    let request = new XMLHttpRequest();
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=[YOUR API KEY HERE]`;

    request.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        let response = JSON.parse(this.responseText);
        getElements(response);
      }
    }

    request.open("GET", url, true);
    request.send();

    getElements = function(response) {
      $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
      $('.showTemp').text(`The temperature in Celcius is ${response.main.temp} degrees.`);
    }
  });
});
</script>

</body>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the weather for a city using openweathermap.org.

The jsonp call is working and everything is fine but the resulting object contains the temperature in an unknown unit:

{
    //...
    "main": {
        "temp": 290.38, // What unit of measurement is this?
        "pressure": 1005,
        "humidity": 72,
        "temp_min": 289.25,
        "temp_max": 291.85
    },
    //...
}

Here is a demo that console.log's the full object.

I don't think the resulting temperature is in fahrenheit because converting 290.38 fahrenheit to celsius is 143.544.

Does anyone know what temperature unit openweathermap is returning?

Body:
You can change the unit to metric.

This is my code.

<head>
    <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
        <style type="text/css">]
        body{
            font-size: 100px;

        }

        #weatherLocation{

            font-size: 40px;
        }
        </style>
        </head>
        <body>
<div id="weatherLocation">Click for weather</div>

<div id="location"><input type="text" name="location"></div>

<div class="showHumidity"></div>

<div class="showTemp"></div>

<script type="text/javascript">
$(document).ready(function() {
  $('#weatherLocation').click(function() {
    var city = $('input:text').val();
    let request = new XMLHttpRequest();
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=[YOUR API KEY HERE]`;

    request.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        let response = JSON.parse(this.responseText);
        getElements(response);
      }
    }

    request.open("GET", url, true);
    request.send();

    getElements = function(response) {
      $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
      $('.showTemp').text(`The temperature in Celcius is ${response.main.temp} degrees.`);
    }
  });
});
</script>

</body>


问:
Uninstall Android APK via AirWatch
I´ve developed an APK which should be remotely managed via AirWatch. My problem is that I can install it successfully but I can´t uninstall it. Using AirWatch I can uninstall all apps in the device but this one. Is there any special permission/configuration I should have in the app to be able to uninstall it?
Thanks!</p>

答: You can remotely manage only "Managed" applications. Check the application's Assignment settings and ensure that you've selected the option to make the app managed.</p>

Title: Uninstall Android APK via AirWatch


问:
pthread_create() and memory leaks
This question seems to be asked a lot.  I had some legacy production code that was seemingly fine, until it started getting many more connections per day.  Each connection kicked off a new thread.  Eventually, it would exhaust memory and crash.

I'm going back over pthread (and C sockets) which I've not dealt with in years.  The tutorial I had was informative, but I'm seeing the same thing when I use top.  All the threads exit, but there's still some virtual memory taken up.  Valgrind tells me there is a possible memory loss when calling pthread_create().  The very basic sample code is below.

The scariest part is that pthread_exit( NULL ) seems to leave about 100m in VIRT unaccounted for when all the threads exit.  If I comment out this line, it's much more liveable, but there is still some there.  On my system it start with about 14k, and ends with 47k.

If I up the thread count to 10,000, VIRT goes up to 70+ gigs, but finishes somewhere around 50k, assuming I comment out pthread_exit( NULL ).  If I use pthread_exit( NULL ) it finishes with about 113m still in VIRT.  Are these acceptable?  Is top not telling me everything?

```<code>void* run_thread( void* id )
{
    int thread_id = *(int*)id;
    int count = 0;
    while ( count < 10 ) {
        sleep( 1 );
        printf( "Thread %d at count %d\n", thread_id, count++ );
    }

    pthread_exit( NULL );
    return 0;
}

int main( int argc, char* argv[] )
{
    sleep( 5 );
    int thread_count    = 0;
    while( thread_count < 10 ) {
        pthread_t my_thread;
        if ( pthread_create( &my_thread, NULL, run_thread, (void*)&thread_count ) < 0 )   {
            perror( "Error making thread...\n" );
            return 1;
        }

        pthread_detach( my_thread );
        thread_count++;
        sleep( 1 );
    }

    pthread_exit( 0 );  // added as per request
    return 0;
}
</code>```

答:
I know this is rather old question, but I hope others wil benefit.
This is indeed a memory leak. The thread is created with default attributes. By default the thread is joinable. A joinable threads keeps its underlying bookkeeping until it is finished... and joined.
If a thread is never joined, set de Detached attribute. All (thread) resources will be freed once the thread terminates.
Here's an example:</p>

```<code>pthread_attr_t attr;
pthread_t thread;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, 1);
pthread_create(&thread, &attr, &threadfunction, NULL);
pthread_attr_destroy(&attr);
</code>```

Title: pthread_create() and memory leaks

Body:
This question seems to be asked a lot.  I had some legacy production code that was seemingly fine, until it started getting many more connections per day.  Each connection kicked off a new thread.  Eventually, it would exhaust memory and crash.

I'm going back over pthread (and C sockets) which I've not dealt with in years.  The tutorial I had was informative, but I'm seeing the same thing when I use top.  All the threads exit, but there's still some virtual memory taken up.  Valgrind tells me there is a possible memory loss when calling pthread_create().  The very basic sample code is below.

The scariest part is that pthread_exit( NULL ) seems to leave about 100m in VIRT unaccounted for when all the threads exit.  If I comment out this line, it's much more liveable, but there is still some there.  On my system it start with about 14k, and ends with 47k.

If I up the thread count to 10,000, VIRT goes up to 70+ gigs, but finishes somewhere around 50k, assuming I comment out pthread_exit( NULL ).  If I use pthread_exit( NULL ) it finishes with about 113m still in VIRT.  Are these acceptable?  Is top not telling me everything?

void* run_thread( void* id )
{
    int thread_id = *(int*)id;
    int count = 0;
    while ( count < 10 ) {
        sleep( 1 );
        printf( "Thread %d at count %d\n", thread_id, count++ );
    }

    pthread_exit( NULL );
    return 0;
}

int main( int argc, char* argv[] )
{
    sleep( 5 );
    int thread_count    = 0;
    while( thread_count < 10 ) {
        pthread_t my_thread;
        if ( pthread_create( &my_thread, NULL, run_thread, (void*)&thread_count ) < 0 )   {
            perror( "Error making thread...\n" );
            return 1;
        }

        pthread_detach( my_thread );
        thread_count++;
        sleep( 1 );
    }

    pthread_exit( 0 );  // added as per request
    return 0;
}

Body:
I know this is rather old question, but I hope others wil benefit.
This is indeed a memory leak. The thread is created with default attributes. By default the thread is joinable. A joinable threads keeps its underlying bookkeeping until it is finished... and joined.
If a thread is never joined, set de Detached attribute. All (thread) resources will be freed once the thread terminates.
Here's an example:

pthread_attr_t attr;
pthread_t thread;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, 1);
pthread_create(&thread, &attr, &threadfunction, NULL);
pthread_attr_destroy(&attr);


问:
How to chain lambdas with all optional values available at the innermost scope without nesting Optional#ifPresent()?
This is an offshoot of my other question: How to chain Optional#ifPresent() in lambda without nesting?

However, the problem now is how to provide a lambda solution where all of the optional values are available at the innermost scope:

```<code>B b = procA().flatMap(this::procB).orElseThrow(SomeException::new);

// Value from procA() is not available.
</code>```

My original code was:

```<code>void SomeMethod() {
    procA().ifPresent(a -> {
       procB(a).ifPresent(b -> {
          // Do something with a and b

          return;
       });
    });

    throw new SomeException();
}
</code>```

I understand that the return at the innermost scope is wrong. The new flatMap example illustrates the correct behavior.

I am using ifPresent() instead of get() to avoid potential runtime exceptions where I might fail to check whether the value of an optional isPresent().

答:
I find this question very interesting as chained calls with potential null returns are a common nuisance, and Optional can shorten the usual null check chain a lot. But the issue there is that the nature of the functional stream methods hides the intermediate values in the mapping functions. Nesting is a way to keep them available, but can also get annoying if the length of the call chain grows, as you have realized.

I cannot think of an easy and lightweight solution, but if the nature of your project leads to these situations regularly, this util class could help:

```<code>public static class ChainedOptional<T>
{
    private final List<Object> intermediates;

    private final Optional<T>  delegate;

    private ChainedOptional(List<Object> previousValues, Optional<T> delegate)
    {
        this.intermediates = new ArrayList<>(previousValues);
        intermediates.add(delegate.orElse(null));
        this.delegate = delegate;
    }

    public static <T> ChainedOptional<T> of(T value)
    {
        return of(Optional.ofNullable(value));
    }

    public static <T> ChainedOptional<T> of(Optional<T> delegate)
    {
        return new ChainedOptional<>(new ArrayList<>(), delegate);
    }

    public <R> ChainedOptional<R> map(Function<T, R> mapper)
    {
        return new ChainedOptional<>(intermediates, delegate.map(mapper));
    }

    public ChainedOptional<T> ifPresent(Consumer<T> consumer)
    {
        delegate.ifPresent(consumer);
        return this;
    }

    public ChainedOptional<T> ifPresent(BiConsumer<List<Object>, T> consumer)
    {
        delegate.ifPresent(value -> consumer.accept(intermediates, value));
        return this;
    }

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
        throws X
    {
        return delegate.orElseThrow(exceptionSupplier);
    }

    public <X extends Throwable> T orElseThrow(Function<List<Object>, X> exceptionSupplier)
        throws X
    {
        return orElseThrow(() -> exceptionSupplier.apply(intermediates));
    }
}
</code>```

You use it by wrapping an Optional or a plain value. When you then use the map method to chain method calls, it will provide a new ChainedOptional while storing the current value in a list. At the end (ifPresent, orElseThrow), you will not only get the last value, but also the list of all intermediate values. Since it is not known how many calls will be chained, I did not find a way to store those values in a type-safe way, though.

See examples here:

```<code>ChainedOptional.of(1)
               .map(s -> s + 1)
               .map(s -> "hello world")
               .map(s -> (String) null)
               .map(String::length)
               .ifPresent((intermediates, result) -> {
                   System.out.println(intermediates);
                   System.out.println("Result: " + result);
               })
               .orElseThrow(intermediates -> {
                   System.err.println(intermediates);
                   return new NoSuchElementException();
               });

// [1, 2, hello world, null, null]
// Exception in thread "main" java.util.NoSuchElementException
//    at ...

ChainedOptional.of(1)
               .map(s -> s + 1)
               .map(s -> "hello world")
               // .map(s -> (String) null)
               .map(String::length)
               .ifPresent((intermediates, result) -> {
                   System.out.println(intermediates);
                   System.out.println("Result: " + result);
               })
               .orElseThrow(intermediates -> {
                   System.err.println(intermediates);
                   return new NoSuchElementException();
               });

// [1, 2, hello world, 11]
// Result: 11
</code>```

Hope this helps. Let me know if you come up with a nicer solution.

Body:
This is an offshoot of my other question: How to chain Optional#ifPresent() in lambda without nesting?

However, the problem now is how to provide a lambda solution where all of the optional values are available at the innermost scope:

B b = procA().flatMap(this::procB).orElseThrow(SomeException::new);

// Value from procA() is not available.

My original code was:

void SomeMethod() {
    procA().ifPresent(a -> {
       procB(a).ifPresent(b -> {
          // Do something with a and b

          return;
       });
    });

    throw new SomeException();
}

I understand that the return at the innermost scope is wrong. The new flatMap example illustrates the correct behavior.

I am using ifPresent() instead of get() to avoid potential runtime exceptions where I might fail to check whether the value of an optional isPresent().

Body:
I find this question very interesting as chained calls with potential null returns are a common nuisance, and Optional can shorten the usual null check chain a lot. But the issue there is that the nature of the functional stream methods hides the intermediate values in the mapping functions. Nesting is a way to keep them available, but can also get annoying if the length of the call chain grows, as you have realized.

I cannot think of an easy and lightweight solution, but if the nature of your project leads to these situations regularly, this util class could help:

public static class ChainedOptional<T>
{
    private final List<Object> intermediates;

    private final Optional<T>  delegate;

    private ChainedOptional(List<Object> previousValues, Optional<T> delegate)
    {
        this.intermediates = new ArrayList<>(previousValues);
        intermediates.add(delegate.orElse(null));
        this.delegate = delegate;
    }

    public static <T> ChainedOptional<T> of(T value)
    {
        return of(Optional.ofNullable(value));
    }

    public static <T> ChainedOptional<T> of(Optional<T> delegate)
    {
        return new ChainedOptional<>(new ArrayList<>(), delegate);
    }

    public <R> ChainedOptional<R> map(Function<T, R> mapper)
    {
        return new ChainedOptional<>(intermediates, delegate.map(mapper));
    }

    public ChainedOptional<T> ifPresent(Consumer<T> consumer)
    {
        delegate.ifPresent(consumer);
        return this;
    }

    public ChainedOptional<T> ifPresent(BiConsumer<List<Object>, T> consumer)
    {
        delegate.ifPresent(value -> consumer.accept(intermediates, value));
        return this;
    }

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
        throws X
    {
        return delegate.orElseThrow(exceptionSupplier);
    }

    public <X extends Throwable> T orElseThrow(Function<List<Object>, X> exceptionSupplier)
        throws X
    {
        return orElseThrow(() -> exceptionSupplier.apply(intermediates));
    }
}

You use it by wrapping an Optional or a plain value. When you then use the map method to chain method calls, it will provide a new ChainedOptional while storing the current value in a list. At the end (ifPresent, orElseThrow), you will not only get the last value, but also the list of all intermediate values. Since it is not known how many calls will be chained, I did not find a way to store those values in a type-safe way, though.

See examples here:

ChainedOptional.of(1)
               .map(s -> s + 1)
               .map(s -> "hello world")
               .map(s -> (String) null)
               .map(String::length)
               .ifPresent((intermediates, result) -> {
                   System.out.println(intermediates);
                   System.out.println("Result: " + result);
               })
               .orElseThrow(intermediates -> {
                   System.err.println(intermediates);
                   return new NoSuchElementException();
               });

// [1, 2, hello world, null, null]
// Exception in thread "main" java.util.NoSuchElementException
//    at ...

ChainedOptional.of(1)
               .map(s -> s + 1)
               .map(s -> "hello world")
               // .map(s -> (String) null)
               .map(String::length)
               .ifPresent((intermediates, result) -> {
                   System.out.println(intermediates);
                   System.out.println("Result: " + result);
               })
               .orElseThrow(intermediates -> {
                   System.err.println(intermediates);
                   return new NoSuchElementException();
               });

// [1, 2, hello world, 11]
// Result: 11

Hope this helps. Let me know if you come up with a nicer solution.


问:
F# Applying Map.filter on Map derived from list of records
I have these records:

```<code>type Name        = string
type PhoneNumber = int
type Sex         = Male | Female
type YearOfBirth = int
type Interests   = string list
type Client      = {name: Name; phone: PhoneNumber; sex: Sex; birth: YearOfBirth; interests: Interests}

let client1 = {name = "Jon"; phone = 37613498; sex = Male; birth = 1980; interests = ["Cars"; "Boats"; "Airplanes"]}
let client2 = {name = "Jonna"; phone = 31852654; sex = Female; birth = 1970; interests = ["Makeup"; "Sewing"; "Bananas"]}
</code>```

Which I put into a list:

```<code>let file1 = [client1;client2]
</code>```

I then attempt to create a function using Map which should be able to filter file1 and only return the client, which has the same birthday as the one given in the function.

Example:

```<code>requestMap 1980
</code>```

Would return map [("Jon", (37613498, Male, 1980, ["Cars"; "Boats"; "Airplanes"]))] in this case.

I've stumbled into a function, but I've got a bit stuck now.

```<code>let requestMap yob =
    Map.ofList [for f in file1 do yield f.name,(f.phone,f.sex,f.birth,f.interests)] |>
    Map.filter (fun key value -> )
</code>```

I have trouble figuring out how I can get to birth in the current map's value? Because as it is right now, it's hidden inside value which is a PhoneNumber * Sex * YearOfBirth * Interests tuple currently.

Any hints?

答:
Here are some more options not mentioned in other answers:

Store the whole Client in the Map value:

```<code>[for f in file1 do yield f.name, f]
|> Map.ofList
|> Map.filter (fun _ f -> f.birth = yob)
</code>```

Do a conditional yield with an if:

```<code>[ for f in file1 do
    if f.birth = yob then
        yield f.name, f ]
|> Map.ofList
</code>```

Body:
I have these records:

type Name        = string
type PhoneNumber = int
type Sex         = Male | Female
type YearOfBirth = int
type Interests   = string list
type Client      = {name: Name; phone: PhoneNumber; sex: Sex; birth: YearOfBirth; interests: Interests}

let client1 = {name = "Jon"; phone = 37613498; sex = Male; birth = 1980; interests = ["Cars"; "Boats"; "Airplanes"]}
let client2 = {name = "Jonna"; phone = 31852654; sex = Female; birth = 1970; interests = ["Makeup"; "Sewing"; "Bananas"]}

Which I put into a list:

let file1 = [client1;client2]

I then attempt to create a function using Map which should be able to filter file1 and only return the client, which has the same birthday as the one given in the function.

Example:

requestMap 1980

Would return map [("Jon", (37613498, Male, 1980, ["Cars"; "Boats"; "Airplanes"]))] in this case.

I've stumbled into a function, but I've got a bit stuck now.

let requestMap yob =
    Map.ofList [for f in file1 do yield f.name,(f.phone,f.sex,f.birth,f.interests)] |>
    Map.filter (fun key value -> )

I have trouble figuring out how I can get to birth in the current map's value? Because as it is right now, it's hidden inside value which is a PhoneNumber * Sex * YearOfBirth * Interests tuple currently.

Any hints?

Body:
Here are some more options not mentioned in other answers:

Store the whole Client in the Map value:

[for f in file1 do yield f.name, f]
|> Map.ofList
|> Map.filter (fun _ f -> f.birth = yob)

Do a conditional yield with an if:

[ for f in file1 do
    if f.birth = yob then
        yield f.name, f ]
|> Map.ofList


问:
Query by several values (Logical "or") on Cloud Firebase's Swift SDK
I am designing an app that returns posts by users I follow, so I would like to query a collection and return documents matching either one of the users I follow (logical OR).

Is there a way to return all posts written by ANY of the users in that array without having to query them individually? I am thinking something like:

```<code>postsRef
    .whereField("user", isEqualTo: "user1 || user2 || user3")
</code>```

This would be the equivalent on MongoDB using $in:

```<code>postsRef.find( { user: { $in: [ user1, user2 ] } } )
</code>```

Thanks.

答:
Unfortunately, I contacted Firebase support about this and this was their answer:

Regarding your question, technically it's not yet supported in Cloud Firestore.

For the meantime, you may find this reference helpful in formulating a workaround.

I found this other link to be more useful, which basically tells people to use an indexing service like "Algolia"

https://firebase.google.com/docs/firestore/solutions/search

Body:
I am designing an app that returns posts by users I follow, so I would like to query a collection and return documents matching either one of the users I follow (logical OR).

Is there a way to return all posts written by ANY of the users in that array without having to query them individually? I am thinking something like:

postsRef
    .whereField("user", isEqualTo: "user1 || user2 || user3")

This would be the equivalent on MongoDB using $in:

postsRef.find( { user: { $in: [ user1, user2 ] } } )

Thanks.


问:
Change class of a element when clicking on a button
To be more specific, i have an div which has an icon in it. I want it to be so when you click on the div the class in a nav changes but i'm new to javascript so i dont know how to set the javascript to however it might work. And internet got me too confused and all of the answers were for changing the class in the same div/element.

Here's my html code:

```<code><div class="nav-container">
            <nav id="navdrop" class="top-bar">

!-- Code in between --!

    <div id="mobileNav" class="mobile-toggle">
      <i class="icon icon_menu"></i>
    </div>
</code>```

Here's my Javascript:

```<code>document.getElementById('mobileNav').onclick = function(){
    var className = '' + navdrop.className + '';
    if ( ~className.indexOf('open-nav') ) {
        this.className = className.replace(' open-nav', '');
    } else {
        this.className += ' open-nav';
    }
}
</code>```

答:
This is what you want. Moreover it's in pure Javascript

function classToggle() {
    document.querySelector('#navdrop').classList.toggle('class1');
    document.querySelector('#navdrop').classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.class1 {
    border: solid 1px;
}

.class2 {
    border: 0;
}</code>```

HTML |
CSS |
JavaScript |
jQuery

click here
```

Body:
To be more specific, i have an div which has an icon in it. I want it to be so when you click on the div the class in a nav changes but i'm new to javascript so i dont know how to set the javascript to however it might work. And internet got me too confused and all of the answers were for changing the class in the same div/element.

Here's my html code:

!-- Code in between --!

Here's my Javascript:

document.getElementById('mobileNav').onclick = function(){
    var className = '' + navdrop.className + '';
    if ( ~className.indexOf('open-nav') ) {
        this.className = className.replace(' open-nav', '');
    } else {
        this.className += ' open-nav';
    }
}

Body:
This is what you want. Moreover it's in pure Javascript

function classToggle() {
    document.querySelector('#navdrop').classList.toggle('class1');
    document.querySelector('#navdrop').classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);

.class1 {
    border: solid 1px;
}

.class2 {
    border: 0;
}

<nav id="navdrop" class="class2">
<a href="#">HTML</a> |
<a href="#">CSS</a> |
<a href="#">JavaScript</a> |
<a href="#">jQuery</a>
</nav>
<br/>

<div id="div" >click here</div>


问:
QML: threading model for WorkerScript
When using a QML WorkerScript, are the requests (sent via postMessage()) queued (and executed on a single handler thread) or is there the possibility/danger that two successive postMessage() will be executed on two threads concurrently?

答:
Short answer

All WorkerScript should execute in the same thread.

Not so short answer

All WorkerScript in a QQmlEngine should execute in the same thread.

Long answer

When you create a WorkerScript in QML you instantiate the QQuickWorkerScript C++ class. This class uses the QQuickWorkerScriptEngine class to handles all the thready things.

Now, if you look at QQuickWorkerScript::engine() and QQmlEnginePrivate::getWorkerScriptEngine() you will see that all WorkerScript objects will share the same QQuickWorkerScriptEngine instance as long as they share the same QQmlEngine.

Also QQuickWorkerScriptEngine is a QThread (public inheritance) and contains a member variable named d of type QQuickWorkerScriptEnginePrivate *. d is running in the thread handled by QQuickWorkerScriptEngine (see d->moveToThread(this) in QQuickWorkerScriptEngine constructor). And it is this d that will effectively run the asynchronous work in QQuickWorkerScriptEnginePrivate::event().

PS

This kind of contradicts Qt documentation that states:

Use WorkerScript to run operations in a new thread.

Which might make you think that each WorkerScript is a new thread.

Title: QML: threading model for WorkerScript


问:
Certificate is not trusted. Application's installer sometimes works correctly and others fails
I have an application in a test environment and when I install it in my computer all work correctly, but when others users installs it some of them works and others fails. When it fails, it displays this error: customized functionality in this application will not work because the certificate used to sign the deployment manifest for appname o its locations is not trusted. Contact your administrators for further assistance.

In addition, I created a test certificate, using visual studio 2015, to sing the application. The application is an add-in using VSTO.

The app is downloaded from a web server into my company, also it uses two web services.

Here is a photo of the error

答:
Get a proper certificate or install the certificate you used onto the computers that you want this app to trust. The whole concept of having to sign the cert is to prevent accidental installations of untrusted applications. In order for that to work the machines you're installing to need to first trust the cert.

You will need a Code Signing certificate and sign the Click-Once package using that cert. You may still need to distribute the trusted cert to the machines somehow (depending on how those are setup).


问:
Putting a CGImageRef on the clipboard
I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard.

However it doesn't work, so two questions:

Is this the correct way to go about this? (ie, is there just a small bug, or am I doing it wrong?)

What type should I make the destination? The source had it as TIFF, but word doesn't seem to know how to deal with that, I changed it to PICT, which at least gave me the "paste" option, but then said it was too big...

Code:

```<code>void copyCGImageRefToPasteboard(CGImageRef ref)
{
    OSStatus err = noErr;
    PasteboardRef theClipboard;

    err = PasteboardCreate( kPasteboardClipboard, &theClipboard );
    err = PasteboardClear( theClipboard );// 1

    CFMutableDataRef url = CFDataCreateMutable(kCFAllocatorDefault, 0);

    CFStringRef type = kUTTypePICT;
    size_t count = 1;
    CFDictionaryRef options = NULL;
    CGImageDestinationRef dest = CGImageDestinationCreateWithData(url, type, count, options);
    CGImageDestinationAddImage(dest, ref, NULL);
    CGImageDestinationFinalize(dest);

    err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, type, url, 0 );
}
</code>```

答:
Ok, I'm answering my own question here, but here's what I've found:

Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have).

So, that's the solution, use PDF, and require Word 2008.

OwnerDisplayName: Brian Postow

ContentLicense: CC BY-SA 2.5

Title: Putting a CGImageRef on the clipboard

Body:
I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard.

However it doesn't work, so two questions:

Is this the correct way to go about this? (ie, is there just a small bug, or am I doing it wrong?)

What type should I make the destination? The source had it as TIFF, but word doesn't seem to know how to deal with that, I changed it to PICT, which at least gave me the "paste" option, but then said it was too big...

Code:

void copyCGImageRefToPasteboard(CGImageRef ref)
{
    OSStatus err = noErr;
    PasteboardRef theClipboard;

    err = PasteboardCreate( kPasteboardClipboard, &theClipboard );
    err = PasteboardClear( theClipboard );// 1

    CFMutableDataRef url = CFDataCreateMutable(kCFAllocatorDefault, 0);

    CFStringRef type = kUTTypePICT;
    size_t count = 1;
    CFDictionaryRef options = NULL;
    CGImageDestinationRef dest = CGImageDestinationCreateWithData(url, type, count, options);
    CGImageDestinationAddImage(dest, ref, NULL);
    CGImageDestinationFinalize(dest);

    err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, type, url, 0 );
}

LastEditorDisplayName: Chris Hanson


问:
single bit manipulation
is it possible to get just one bit of an int in C and then flip it without reading the entire int and writing it back to memory?

context:
trying to avoid too many locks/unlocks in pthread.

答:
Here is how ya do it 50x faster than grandpa mutex (we did tests on this sort of thing).  Use gcc atomic operations. You could also use linux atomic operations if your release included them.

```<code>typedef union _foo {
  struct {
    unsigned int a:1,
                 b:6,
                 q:2;
  } Data;
  unsigned int n32;
} TFoo;

TFoo _GlobalFoo;

SomeFuncThatChangesFoo_A(int fNewA)
{
TFoo Old, New;

  while(1) {
    // get a copy of the current state
    Old.n32 = _GlobalFoo.n32;
    New.n32 = Old.n32;
    New.Data.a = fNewA;
    // compare and swap is the atomic operation.
    // if _GlobalFoo hasn't changed since we copied it to "Old", then change _GlobalFoo to "New".
    // __sync_bool_compare_and_swap works on basic types (8 bit, 16 bit, 32 bit, 64 bit, 128 bit
    // depending upon architecture), which is why there is a union overlaying the 32 bit n32 over
    // the actual data that the program uses, Data.
    if (__sync_bool_compare_and_swap(_GlobalFoo.n32, Old.n32, New.n32))
      break; // successfully changed
    // if we get here, the global was changed by another thread, so we just loop back, get the new value
    // and try again.
  } // concurrency loop
}
</code>```

Astute threaders might think that the line "Old.n32 = _GlobalFoo.n32;" could copy garbage in a race if the compiler chose a non-atomic way to perform the copy.  However, __sync_bool_compare_and_swap would just fail because of the a bad copy of the current state, so there would be no harm done.

cheers.

Title: single bit manipulation

Body:
Here is how ya do it 50x faster than grandpa mutex (we did tests on this sort of thing).  Use gcc atomic operations. You could also use linux atomic operations if your release included them.

typedef union _foo {
  struct {
    unsigned int a:1,
                 b:6,
                 q:2;
  } Data;
  unsigned int n32;
} TFoo;

TFoo _GlobalFoo;

SomeFuncThatChangesFoo_A(int fNewA)
{
TFoo Old, New;

  while(1) {
    // get a copy of the current state
    Old.n32 = _GlobalFoo.n32;
    New.n32 = Old.n32;
    New.Data.a = fNewA;
    // compare and swap is the atomic operation.
    // if _GlobalFoo hasn't changed since we copied it to "Old", then change _GlobalFoo to "New".
    // __sync_bool_compare_and_swap works on basic types (8 bit, 16 bit, 32 bit, 64 bit, 128 bit
    // depending upon architecture), which is why there is a union overlaying the 32 bit n32 over
    // the actual data that the program uses, Data.
    if (__sync_bool_compare_and_swap(_GlobalFoo.n32, Old.n32, New.n32))
      break; // successfully changed
    // if we get here, the global was changed by another thread, so we just loop back, get the new value
    // and try again.
  } // concurrency loop
}

Astute threaders might think that the line "Old.n32 = _GlobalFoo.n32;" could copy garbage in a race if the compiler chose a non-atomic way to perform the copy.  However, __sync_bool_compare_and_swap would just fail because of the a bad copy of the current state, so there would be no harm done.

cheers.


问:
Provide default arguments for subscript operator and function call operator
In the following code, I have provided default arguments for array subscript operator.

```<code>struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};
</code>```

But, compiler generated an error :

```<code>error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)
</code>```

But, If I provide default arguments for function call operator.

```<code>struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};
</code>```

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?

答:
I suppose you are really asking why the standard allows one and not the other. The reason is mainly to do with what people expect, rather than some technical logic that precludes a default in one case but not the other:

It's a matter of what people expect the [] operator to mean. Normally it means "Get the element at [...]" where we use an int or some other type to make a specific query about a member of a collection. We are always interested in asking about a specific member, and we always have a specific query in mind.

Now consider what a default argument means. Often it means "you can specify this, but if not I'll assume this default". This works great for certain functions, and people are used to it.

Changing this would probably make a lot of people scratch their heads when they see int x = vec[]

Body:
In the following code, I have provided default arguments for array subscript operator.

struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};

But, compiler generated an error :

error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)

But, If I provide default arguments for function call operator.

struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?


问:
How to represent a dependency relationship between node and artifact in UML Deployment Diagram?
I have a web application that reads from a file. My application is represented as a node and file as an artifact. Can I use dashed arrow to represent their relationship ?

答:
I never used artifacts as you want but it seems legal.

Artifact (p654) : An Artifact represents some (usually reifiable) item of information that is used or produced by a software development process or by operation of a system. Examples of Artifacts include model files, source files, scripts, executable files, database tables, development deliverables, word-processing documents, and mail messages.

A log file is produced by an operation of the system, I guess. Guys, what do you think ?

And there a stereotype in the standard profile: «Create» : A usage dependency denoting that the client classifier creates instances of the supplier classifier. (p 678)

So if you want to model that your wbe server creates an instance of LogFile, the following schema should do the job.

More remarks:

the web server is an execution environment deployed on a node.

your web application is an artifact running on the execution environment.


问:
Angular: Form fields read-only mode
I have some forms that should be editable only by some users. Other users should only be able to view it.

Currently, for each form control in a form, I'm checking condition and displaying either a form control or a text. Something like,

```<code><div>
    <input type="text" *ngIf="editable">
    <p *ngIf="!editable">{{value}}</p>
</div>
</code>```

This doesn't seem to be an elegant way. Please suggest a cleaner way to achieve this, like doing something at the top level.

答:
Since you are using Angular, it is better to use FormControls and FormGroups. Take a look at this guide.
Using the FormControl API you can enable and disable the input programmatically.

An other way is to use property binding and do something like this:

```<code><div>
   <input type="text" [readonly]="!editable">
</div>
</code>```

Title: Angular: Form fields read-only mode

Body:
I have some forms that should be editable only by some users. Other users should only be able to view it.

Currently, for each form control in a form, I'm checking condition and displaying either a form control or a text. Something like,

    <input type="text" *ngIf="editable">

{{value}}

This doesn't seem to be an elegant way. Please suggest a cleaner way to achieve this, like doing something at the top level.

Body:
Since you are using Angular, it is better to use FormControls and FormGroups. Take a look at this guide.
Using the FormControl API you can enable and disable the input programmatically.

An other way is to use property binding and do something like this:

<div>
   <input type="text" [readonly]="!editable">
</div>


问:
Background execution not allowed. Android O pendingintent
I have a service that schedules a pendingintent which starts my notification. However, since Android O I am getting this error. I did some research, and stumbled upon context.registerReceiver , but that does not seem to fix the problem.

Error:

```<code>W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.PACKAGE_ADDED dat=package:my.great.package flg=0x4000010 (has extras) } to com.google.android.googlequicksearchbox/com.google.android.apps.gsa.googlequicksearchbox.GelStubAppWatcher
</code>```

```</p>

<p>My pendingintent:</p>

```Intent myNotification = new Intent("services.notifications.Notification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) (Math.random() * Integer.MAX_VALUE), myNotification, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager.setExact(AlarmManager.RTC_WAKEUP, day.getTimeInMillis(), pendingIntent);
```

<p>My notification:</p>

```public class Notification extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.registerReceiver(this, new IntentFilter());

        try {
            WakeLock wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(1, "NotificationWakeLock");
            wakeLock.acquire(10000);

            try {
                scheduleNotification(context, intent);
            } finally {
                wakeLock.release();
            }
        } catch (NullPointerException e) {}
    }
}
```

答:
I resolved it by adding a foreground service:

```<code>Intent test = new Intent(this, NotificationService.class);
startForegroundService(test);
</code>```

This will show a notification telling that my app is running on the foreground.

And by adding this in my service's oncreate:

```<code>startForeground(100, new NotificationCompat.Builder(this).build());
</code>```

Body:
I have a service that schedules a pendingintent which starts my notification. However, since Android O I am getting this error. I did some research, and stumbled upon context.registerReceiver , but that does not seem to fix the problem.

Error:

W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.PACKAGE_ADDED dat=package:my.great.package flg=0x4000010 (has extras) } to com.google.android.googlequicksearchbox/com.google.android.apps.gsa.googlequicksearchbox.GelStubAppWatcher

```

My pendingintent:

Intent myNotification = new Intent("services.notifications.Notification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) (Math.random() * Integer.MAX_VALUE), myNotification, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager.setExact(AlarmManager.RTC_WAKEUP, day.getTimeInMillis(), pendingIntent);

My notification:

public class Notification extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.registerReceiver(this, new IntentFilter());

        try {
            WakeLock wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(1, "NotificationWakeLock");
            wakeLock.acquire(10000);

            try {
                scheduleNotification(context, intent);
            } finally {
                wakeLock.release();
            }
        } catch (NullPointerException e) {}
    }
}

Body:
I resolved it by adding a foreground service:

Intent test = new Intent(this, NotificationService.class);
startForegroundService(test);

This will show a notification telling that my app is running on the foreground.

And by adding this in my service's oncreate:

startForeground(100, new NotificationCompat.Builder(this).build());


问:
Why enterprise github can't deliver payload to webhook with ssl secured?
verified the certificate information of https://jenkins.example.com/github-webhook with https://cryptoreport.websecurity.symantec.com/checker/.

Github repeatedly says following

We couldn’t deliver this payload: Peer certificate cannot be authenticated with given CA certificates

here is the screenshot of the message:

答: Its very likely a missing CA cert in the certificate chain. Try the Qualys checker, and compare the CA chain report to the CA certs bundle provided by your cert provider. You may be missing an intermediate.</p>


问:
BigQuery GA360 export - product query
I'm working through the documentation with BigQuery, and I'm stuck on a particular query.

```<code>SELECT hits.item.productName AS other_purchased_products, COUNT(hits.item.productName) AS quantity
FROM [XXXXXXX.ga_sessions_20171101]
WHERE fullVisitorId IN (
  SELECT fullVisitorId
  FROM [XXXXXXXX.ga_sessions_20171101]
  WHERE hits.item.productName CONTAINS 'Product A'
   AND totals.transactions>=1
  GROUP BY fullVisitorId )
 AND hits.item.productName IS NOT NULL
 AND hits.item.productName !='Product A'
GROUP BY other_purchased_products
ORDER BY quantity DESC;
</code>```

This one works fine for an individual day in the dataset, however If I want to use TABLE DATE RANGE it errors.

To use the above query across multiple dates, how do I adjust this?

Thanks

答: With legacy SQL the only way is to use an INNER JOIN on fullvisitorid

Title: BigQuery GA360 export - product query

Body:
I'm working through the documentation with BigQuery, and I'm stuck on a particular query.

SELECT hits.item.productName AS other_purchased_products, COUNT(hits.item.productName) AS quantity
FROM [XXXXXXX.ga_sessions_20171101]
WHERE fullVisitorId IN (
  SELECT fullVisitorId
  FROM [XXXXXXXX.ga_sessions_20171101]
  WHERE hits.item.productName CONTAINS 'Product A'
   AND totals.transactions>=1
  GROUP BY fullVisitorId )
 AND hits.item.productName IS NOT NULL
 AND hits.item.productName !='Product A'
GROUP BY other_purchased_products
ORDER BY quantity DESC;

This one works fine for an individual day in the dataset, however If I want to use TABLE DATE RANGE it errors.

To use the above query across multiple dates, how do I adjust this?

Thanks


问:
Copying Character array into char array
Hi I want to fast copy array of Characters to array of chars I can write a method that copies Character array into char array, by converting every Charater in array to char but is there any ready method which is faster just as Arrays.copyOf for two arrays of same type?

答:
There is method in Apache Commons Lang which does exactly what you need:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive-java.lang.Character:A-</p>

```<code>public static char[] ArrayUtils.toPrimitive(Character[] array)
</code>```

Title: Copying Character array into char array

Body:
There is method in Apache Commons Lang which does exactly what you need:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive-java.lang.Character:A-

public static char[] ArrayUtils.toPrimitive(Character[] array)


问:
Declare a variable and then set to a data type?
Accidental DBA, here. I'm looking at a query that was written by a past DBA who is no longer with the company and I noticed something that I consider to be odd; maybe I'm just ignorant. The SQL is used to gather information about the DBs and provide hyperlinks and file locations. It uses one variable. Below is the bit of code in question and it is the very beginning of the query.

```<code> declare @crlf varchar(2)
 set @crlf = char(13)+char(10)
</code>```

So, to me, it looks like the variable is declared as varchar, but is then set as a concatenation of two char data types? This is confusing to me because:

A) why would he not just set the variable as the data type he wants to begin with?
B) I didn't realize you could SET a variable to a data type and not a value
C) I also didn't know you could concatenate (or add in this case, maybe?) data types together. This just makes no sense to me at all.

Any insight on this?

答:
He is simply setting this to a carriage return (CR) and new line feed (LF) hence the variable name crlf. You could use the same method to set it to two letters...

```<code> declare @crlf varchar(2)
 set @crlf = char(88)+char(89)

 select @crlf
</code>```

RESULTS

```<code>XY
</code>```

As pointed out in the comments, this is calling the CHAR() function versus assigning a data type which would be a string literal. The opposite would be the ASCII() function.

Reference ASCII Table

Body:
Accidental DBA, here. I'm looking at a query that was written by a past DBA who is no longer with the company and I noticed something that I consider to be odd; maybe I'm just ignorant. The SQL is used to gather information about the DBs and provide hyperlinks and file locations. It uses one variable. Below is the bit of code in question and it is the very beginning of the query.

 declare @crlf varchar(2)
 set @crlf = char(13)+char(10)

So, to me, it looks like the variable is declared as varchar, but is then set as a concatenation of two char data types? This is confusing to me because:

A) why would he not just set the variable as the data type he wants to begin with?
B) I didn't realize you could SET a variable to a data type and not a value
C) I also didn't know you could concatenate (or add in this case, maybe?) data types together. This just makes no sense to me at all.

Any insight on this?

Body:
He is simply setting this to a carriage return (CR) and new line feed (LF) hence the variable name crlf. You could use the same method to set it to two letters...

 declare @crlf varchar(2)
 set @crlf = char(88)+char(89)

 select @crlf

RESULTS

XY

As pointed out in the comments, this is calling the CHAR() function versus assigning a data type which would be a string literal. The opposite would be the ASCII() function.

Reference ASCII Table


问:
Copy Files Over SSH to all servers in deployment group
I am trying to setup CI pipeline for .net core app with VSTS.

I am confused with Copy Files Over SSH step. Server is defined not by deployment group but by endpoint host.

How should I copy my deployment artifacts to ALL servers in deployment group with this tool?

Actually, same applies to "SSH" - it also get executed only on host from Endpoint definition.

Any ideas?

答: If you're using deployment groups, you don't need to SSH anything to them. The build artifacts will be automatically downloaded to them, since the build/release agent is already running on them and talking directly to VSTS.</p>


问:
How do I display a random phrase from a list when a button is clicked in a web page?
I am creating a web page where someone can visit it. They type a question in a field and click a button, and a response is passed back to them. (Kind of like a magic 8 ball).

What I'm trying to do is set it up something like this:

http://img585.imageshack.us/img585/997/layoutoi.png

I'm still new to hand-coding things - I have a book on HTML/CSS and one on PHP, which lay still unread, so I'll probably need a step-by-step process. (I have a host and everything, so that's already taken care of.) Thanks in advance!

答:
I know you tagged the question PHP, but you might want to consider using javascript instead.  The advantage is that you won't need to reload the page - for something this simple, there isn't really any advantage to using php.

A javascript solution would look something like this:

```<code><html>
  <head>
    <script type='text/javascript'>
      var answerArray = new Array("yes", "no", "maybe");

      function getAnswer() {
        document.getElementById('answerDiv').innerHTML =
          answerArray[Math.floor(Math.random() * answerArray.length)];
      }
    </script>
  </head>
  <body>
    <input id='questionField' type='text' /><br/>
    <input type='submit' value='Ask Me!' onclick='getAnswer()' />
    <div id='answerDiv'></div>
  </body>
</html>
</code>```

Body:
I know you tagged the question PHP, but you might want to consider using javascript instead.  The advantage is that you won't need to reload the page - for something this simple, there isn't really any advantage to using php.

A javascript solution would look something like this:

<html>
  <head>
    <script type='text/javascript'>
      var answerArray = new Array("yes", "no", "maybe");

      function getAnswer() {
        document.getElementById('answerDiv').innerHTML =
          answerArray[Math.floor(Math.random() * answerArray.length)];
      }
    </script>
  </head>
  <body>
    <input id='questionField' type='text' /><br/>
    <input type='submit' value='Ask Me!' onclick='getAnswer()' />
    <div id='answerDiv'></div>
  </body>
</html>


问:
put numpy array items into "bins"
I have a numpy array with some integers, e.g.,

```<code>a = numpy.array([1, 6, 6, 4, 1, 1, 4])
</code>```

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

```<code>bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }
</code>```

A combination of unique and wheres does the trick,

```<code>uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}
</code>```

but this doesn't seem ideal since the number of unique entries may be large.

答:
Here is one way by utilizing the broadcasting, np.where(), and np.split():

```<code>In [66]: unique = np.unique(a)

In [67]: rows, cols = np.where(unique[:, None] == a)

In [68]: indices = np.split(cols, np.where(np.diff(rows) != 0)[0] + 1)

In [69]: dict(zip(unique, indices))
Out[69]: {1: array([0, 4, 5]), 4: array([3, 6]), 6: array([1, 2])}
</code>```

Title: put numpy array items into "bins"

Body:
I have a numpy array with some integers, e.g.,

a = numpy.array([1, 6, 6, 4, 1, 1, 4])

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }

A combination of unique and wheres does the trick,

uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}

but this doesn't seem ideal since the number of unique entries may be large.

Body:
Here is one way by utilizing the broadcasting, np.where(), and np.split():

In [66]: unique = np.unique(a)

In [67]: rows, cols = np.where(unique[:, None] == a)

In [68]: indices = np.split(cols, np.where(np.diff(rows) != 0)[0] + 1)

In [69]: dict(zip(unique, indices))
Out[69]: {1: array([0, 4, 5]), 4: array([3, 6]), 6: array([1, 2])}


问:
x-robots tag for query string parameter
I want to block a query string url's in .htaccess using x-robots tag. The url's are something like:

```<code>https://www.example.com/test?limit=60
https://www.example.com/test?limit=45
https://www.example.com/test?limit=all
</code>```

I need to block the ?limit=xxx

Ive tried something like this but it doesnt work:

```<code><IfModule mod_headers.c>
<Files "^limit=?$">
Header set X-Robots-Tag "noindex, nofollow"
</Files>
</IfModule>
</code>```

答:
Got it working with this:</p>

```<code><IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} ^limit=([a-zA-Z0-9]*)$
RewriteRule .* - [E=NOINDEX_HEADER:1]
</IfModule>

<IfModule mod_headers.c>
Header set X-Robots-Tag "noindex" env=NOINDEX_HEADER
</IfModule>
</code>```

Title: x-robots tag for query string parameter

Body:
I want to block a query string url's in .htaccess using x-robots tag. The url's are something like:

https://www.example.com/test?limit=60
https://www.example.com/test?limit=45
https://www.example.com/test?limit=all

I need to block the ?limit=xxx

Ive tried something like this but it doesnt work:

<IfModule mod_headers.c>
<Files "^limit=?$">
Header set X-Robots-Tag "noindex, nofollow"
</Files>
</IfModule>

Body:
Got it working with this:

<IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} ^limit=([a-zA-Z0-9]*)$
RewriteRule .* - [E=NOINDEX_HEADER:1]
</IfModule>

<IfModule mod_headers.c>
Header set X-Robots-Tag "noindex" env=NOINDEX_HEADER
</IfModule>


问:
angular ng-repeat track by $index
I'm having some trouble understanding why if I use track by Index in a ng-repeat, after removing a item from a array I get the "wrong" values in the scope of a directive.

As you can see in the below plunker if I remove the first Item in the array tracked by index, the value in the directive scope will not be the initial one.

I was expecting to have after the removal:
2 - b
3 - c

but I get
2 - a
3 - b

If I don't use track by index I get the right values.

This is the Script

```<code>nsTests.controller('nsTestCtrl', ['$rootScope', '$scope', '$filter', '$timeout',
function ($rootScope, $scope, $filter, $timeout) {

    $scope.data = [
     {
         id: 1,
         name: 'a'
     },
     {
         id: 2,
         name: 'b'
     },
     {
         id: 3,
         name: 'c'
     },
    ];

    $scope.data2 = [
     {
         id: 1,
         name: 'a'
     },
     {
         id: 2,
         name: 'b'
     },
     {
         id: 3,
         name: 'c'
     },
    ];

    $scope.removeByIndex = function (index) {
        $scope.data.splice(index, 1);
    }

    $scope.removeByItem = function (item) {
        var index = $scope.data2.indexOf(item);
        if (index !== -1) {
            $scope.data2.splice(index, 1);
        }
    }
}
]);

nsTests.directive('test', function ($compile) {
return {
    restrict: 'E',
    template: '{{value}}',
    scope: {
        data: '='
    },
    controller: function ($scope) {
        $scope.value = $scope.data.name;
    }
};
});
</code>```

Here is a plunker with the problem

答:
using track by index, angular will reuse nodes

This is effectively the issue; the directive is not reinitialised as Angular seems ignore it's value parameters and keep the original data from the index.

E.g.

```<code>var arr = [
  { id: 0, status: "Pass" },
  { id: 1, status: "Fail" }
];
</code>```

If you repeat this data and have a custom directive in the repeat that would display a green dot for pass and a red dot for fail.

Example: https://plnkr.co/edit/ytQ9p6YJOfrDubCGIc2N?p=preview

.pass {
  color: green;
}

.fail {
  color: red
}

.pass,
.fail {
  font-size: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <th>ID</th>
  <th>Status</th>
  <tr>
    <td>1</td>
    <td class="pass">▪</td>
  </tr>
  <tr>
    <td>2</td>
    <td class="fail">▪</td>
  </tr>
</table></code>```

When applying a filter e.g. via $filter on arr that filters out the the object with ID:1

.pass {
  color: green;
}

.fail {
  color: red
}

.pass,
.fail {
  font-size: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <th>ID</th>
  <th>Status</th>
  <tr>
    <td>2</td>
    <td class="pass">▪</td>
  </tr>
</table></code>```

As you can see, 1 was filtered out, but the result is now incorrect. This is because Angular is being a little lazy and not reinitialising the directive that we are using even though the data we passed in is now different.

Title: angular ng-repeat track by $index

Body:
I'm having some trouble understanding why if I use track by Index in a ng-repeat, after removing a item from a array I get the "wrong" values in the scope of a directive.

As you can see in the below plunker if I remove the first Item in the array tracked by index, the value in the directive scope will not be the initial one.

I was expecting to have after the removal:
2 - b
3 - c

but I get
2 - a
3 - b

If I don't use track by index I get the right values.

This is the Script

nsTests.controller('nsTestCtrl', ['$rootScope', '$scope', '$filter', '$timeout',
function ($rootScope, $scope, $filter, $timeout) {

    $scope.data = [
     {
         id: 1,
         name: 'a'
     },
     {
         id: 2,
         name: 'b'
     },
     {
         id: 3,
         name: 'c'
     },
    ];

    $scope.data2 = [
     {
         id: 1,
         name: 'a'
     },
     {
         id: 2,
         name: 'b'
     },
     {
         id: 3,
         name: 'c'
     },
    ];

    $scope.removeByIndex = function (index) {
        $scope.data.splice(index, 1);
    }

    $scope.removeByItem = function (item) {
        var index = $scope.data2.indexOf(item);
        if (index !== -1) {
            $scope.data2.splice(index, 1);
        }
    }
}
]);

nsTests.directive('test', function ($compile) {
return {
    restrict: 'E',
    template: '{{value}}',
    scope: {
        data: '='
    },
    controller: function ($scope) {
        $scope.value = $scope.data.name;
    }
};
});

Here is a plunker with the problem

Body:
using track by index, angular will reuse nodes

This is effectively the issue; the directive is not reinitialised as Angular seems ignore it's value parameters and keep the original data from the index.

E.g.

var arr = [
  { id: 0, status: "Pass" },
  { id: 1, status: "Fail" }
];

If you repeat this data and have a custom directive in the repeat that would display a green dot for pass and a red dot for fail.

Example: https://plnkr.co/edit/ytQ9p6YJOfrDubCGIc2N?p=preview

.pass {
  color: green;
}

.fail {
  color: red
}

.pass,
.fail {
  font-size: 24px;
}

<table>
  <th>ID</th>
  <th>Status</th>
  <tr>
    <td>1</td>
    <td class="pass">&squf;</td>
  </tr>
  <tr>
    <td>2</td>
    <td class="fail">&squf;</td>
  </tr>
</table>

When applying a filter e.g. via $filter on arr that filters out the the object with ID:1

.pass {
  color: green;
}

.fail {
  color: red
}

.pass,
.fail {
  font-size: 24px;
}

<table>
  <th>ID</th>
  <th>Status</th>
  <tr>
    <td>2</td>
    <td class="pass">&squf;</td>
  </tr>
</table>

As you can see, 1 was filtered out, but the result is now incorrect. This is because Angular is being a little lazy and not reinitialising the directive that we are using even though the data we passed in is now different.


问:
Syntax issues in OS detection
I'm working on a script using bash to determine the os being used and print to the screen the version.

The only line giving me issues is this one, could you please help me?:

答:
Put the commands in backticks (``) and the statement will assign the output of the command.</p>

```<code>current_os=`cat /etc/*-release | grep CentOS`
</code>```

Title: Syntax issues in OS detection

Body:
Put the commands in backticks (``) and the statement will assign the output of the command.

current_os=`cat /etc/*-release | grep CentOS`


问:
Fastest way to negate a std::vector
Assume I have a std::vector of double, namely

```<code>std::vector<double> MyVec(N);
</code>```

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

```<code>std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
</code>```

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

答:
As others have mentioned, it completely depends on your use case. Probably the simplest way would be something like this:

```<code> struct MyNegatingVect {
     MyVect data;
     bool negated = false;
     void negate() { negated = !negated; }
     // ... setter and getter need indirection ...
     // ..for example
     MyVect::data_type at(size_t index) { return negated ? - data.at(index) : data.at(index);
 };
</code>```

Whether this additional indirection for each single access is worth transforming the negation into setting a single bool depends, as already mentioned, on your use case (actually I doubt that there is a use case where this would bring any measurable benefit).

Title: Fastest way to negate a std::vector

Body:
Assume I have a std::vector of double, namely

std::vector<double> MyVec(N);

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

Body:
As others have mentioned, it completely depends on your use case. Probably the simplest way would be something like this:

 struct MyNegatingVect {
     MyVect data;
     bool negated = false;
     void negate() { negated = !negated; }
     // ... setter and getter need indirection ...
     // ..for example
     MyVect::data_type at(size_t index) { return negated ? - data.at(index) : data.at(index);
 };

Whether this additional indirection for each single access is worth transforming the negation into setting a single bool depends, as already mentioned, on your use case (actually I doubt that there is a use case where this would bring any measurable benefit).


问:
Converting html to pdf in php?
I know that there is a lot of posts about this problem.But can someone help me to setup this http://www.rustyparts.com/pdf.php script to work on my localhost.I just spent all week on this problem.I have download imagemagic,ghostscript,activeperl,...,everything,but still can't make simple example to work. </p>

答: DocRaptor.com is a good option - it uses Prince XML, so the quality is better than other tools, and it's a web app, so nothing to download. It also works in any language. </p>

Title: Converting html to pdf in php?


问:
function in rootscope, can't access rootscope variable
In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.

I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.

```<code>function getTourTranslation(key){
    console.log("getTourTranslation", key);
    var lang = $rootScope.language;
    var step = _.get(steps, key);
    return step[lang]
}
</code>```

So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?

I also tried as $rootScope.getTourTranslation = function(key) but no luck

edit:

This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.

```<code>$rootScope.changeLanguage = function (langKey) {
    if(langKey){
        if(langKey.length == 2) {
            $translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
            $rootScope.language = langKey;
        } else if(langKey.length == 5) {
            $translate.use(langKey);
            $rootScope.language = langKey.substring(0,2);
        }
    }
};

$rootScope.$on('$translateChangeSuccess', function () {
    if($translate.use()){
        $rootScope.language = $translate.use().substring(0,2);
        if($state.$current && !$state.$current.self.abstract) {
            $state.reload();
        }
    }
});
$rootScope.changeLanguage($translate.use());
</code>```

答:
The problem was, that $rootScope.language was called before it was initialized.

So, I placed the call to the getTourTranslation() function in an function which is called after firing an button. So, the right variables are now only initialized when they are needed instead of always.

So, I fixed two things, and that all based on the comment from @BotanMan

Body:
In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.

I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.

function getTourTranslation(key){
    console.log("getTourTranslation", key);
    var lang = $rootScope.language;
    var step = _.get(steps, key);
    return step[lang]
}

So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?

I also tried as $rootScope.getTourTranslation = function(key) but no luck

edit:

This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.

$rootScope.changeLanguage = function (langKey) {
    if(langKey){
        if(langKey.length == 2) {
            $translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
            $rootScope.language = langKey;
        } else if(langKey.length == 5) {
            $translate.use(langKey);
            $rootScope.language = langKey.substring(0,2);
        }
    }
};

$rootScope.$on('$translateChangeSuccess', function () {
    if($translate.use()){
        $rootScope.language = $translate.use().substring(0,2);
        if($state.$current && !$state.$current.self.abstract) {
            $state.reload();
        }
    }
});
$rootScope.changeLanguage($translate.use());


问:
Sparx EA Jscript Information Flows Realized
How do I retrieve a collection of all the Information Flows Realized by a connector of type Dependency using Jscript please?</p>

答:
First option would be to use the API.

Loop the connectors and check EA.Connector.ConveyedItems

But that will be terribly slow for anything but a trivial model.

So the only sane way is to use EA.Repository.SQLQuery(string SQL) to get a list of connectorID's and then use EA.Repository.GetConnectorByID(int ID) to get the connector objects.

The SQL query you need is something in the nature of

```<code>select *
from ((((t_connector c
inner join t_xref x on (x.Client = c.ea_guid
                    and x.Name = 'MOFProps'
                    and x.Type = 'connector property'
                    and x.Behavior = 'abstraction'))
inner join t_connector cf on x.Description like '%' + cf.ea_guid + '%')
inner join t_xref xf on (xf.Client = cf.ea_guid
                    and xf.Name = 'MOFProps'
                    and xf.Type = 'connector property'
                    and xf.Behavior = 'conveyed'))
inner join t_object o on o.ea_guid like xf.Description)
where c.Connector_Type = 'Dependency'
</code>```

Replace % with * in case you are working on a .eap (MS-Access) file.

I also have an implementation in C#. On class ConnectorWrapper there is this operation to get the information flows from the dependency.

```<code>/// <summary>
/// convenience method to return the information flows that realize this Relationship
/// </summary>
/// <returns>the information flows that realize this Relationship</returns>
public virtual HashSet<UML.InfomationFlows.InformationFlow> getInformationFlows()
{
    HashSet<UML.InfomationFlows.InformationFlow> informationFlows = new HashSet<UML.InfomationFlows.InformationFlow>();
    string sqlGetInformationFlowIDs = @"select x.description
        from (t_connector c
        inner join t_xref x on (x.client = c.ea_guid and x.Name = 'MOFProps'))
        where c.ea_guid = '" + this.guid + "'";
    var queryResult = this.model.SQLQuery(sqlGetInformationFlowIDs);
    var descriptionNode = queryResult.SelectSingleNode(this.model.formatXPath("//description"));
    if (descriptionNode != null)
    {
        foreach (string ifGUID in descriptionNode.InnerText.Split(','))
        {
            var informationFlow = this.model.getRelationByGUID(ifGUID) as UML.InfomationFlows.InformationFlow;
            if (informationFlow != null )
            {
                informationFlows.Add(informationFlow);
            }
        }
    }
    return informationFlows;
}
</code>```

Once you have the InformationFlow this code gets the conveyed items

```<code>public HashSet<UML.Classes.Kernel.Classifier> conveyed
{
    get
    {
        if (_conveyed == null)
        {
            string getXrefDescription = @"select x.Description from t_xref x
                                        where x.Name = 'MOFProps'
                                        and x.Behavior = 'conveyed'
                                        and x.client = '" + this.guid + "'";
            //xrefdescription contains the GUID's of the conveyed elements comma separated
            var xrefDescription = this.model.SQLQuery(getXrefDescription).SelectSingleNode(this.model.formatXPath("//Description"));
            if (xrefDescription != null)
            {
                foreach (string conveyedGUID in xrefDescription.InnerText.Split(','))
                {
                    var conveyedElement = this.model.getElementWrapperByGUID(conveyedGUID) as UML.Classes.Kernel.Classifier;
                    if (conveyedElement != null)
                    {
                        //initialize if needed
                        if (_conveyed == null)
                        {
                            _conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
                        }
                        //add the element
                        _conveyed.Add(conveyedElement);
                    }
                }
            }
        }
        //nothing found, return empty list.
        if (_conveyed == null)
        {
            _conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
        }
        return _conveyed;
    }
}
</code>```

Body:
First option would be to use the API.

Loop the connectors and check EA.Connector.ConveyedItems

But that will be terribly slow for anything but a trivial model.

So the only sane way is to use EA.Repository.SQLQuery(string SQL) to get a list of connectorID's and then use EA.Repository.GetConnectorByID(int ID) to get the connector objects.

The SQL query you need is something in the nature of

select *
from ((((t_connector c
inner join t_xref x on (x.Client = c.ea_guid
                    and x.Name = 'MOFProps'
                    and x.Type = 'connector property'
                    and x.Behavior = 'abstraction'))
inner join t_connector cf on x.Description like '%' + cf.ea_guid + '%')
inner join t_xref xf on (xf.Client = cf.ea_guid
                    and xf.Name = 'MOFProps'
                    and xf.Type = 'connector property'
                    and xf.Behavior = 'conveyed'))
inner join t_object o on o.ea_guid like xf.Description)
where c.Connector_Type = 'Dependency'

Replace % with * in case you are working on a .eap (MS-Access) file.

I also have an implementation in C#. On class ConnectorWrapper there is this operation to get the information flows from the dependency.

/// <summary>
/// convenience method to return the information flows that realize this Relationship
/// </summary>
/// <returns>the information flows that realize this Relationship</returns>
public virtual HashSet<UML.InfomationFlows.InformationFlow> getInformationFlows()
{
    HashSet<UML.InfomationFlows.InformationFlow> informationFlows = new HashSet<UML.InfomationFlows.InformationFlow>();
    string sqlGetInformationFlowIDs = @"select x.description
        from (t_connector c
        inner join t_xref x on (x.client = c.ea_guid and x.Name = 'MOFProps'))
        where c.ea_guid = '" + this.guid + "'";
    var queryResult = this.model.SQLQuery(sqlGetInformationFlowIDs);
    var descriptionNode = queryResult.SelectSingleNode(this.model.formatXPath("//description"));
    if (descriptionNode != null)
    {
        foreach (string ifGUID in descriptionNode.InnerText.Split(','))
        {
            var informationFlow = this.model.getRelationByGUID(ifGUID) as UML.InfomationFlows.InformationFlow;
            if (informationFlow != null )
            {
                informationFlows.Add(informationFlow);
            }
        }
    }
    return informationFlows;
}

Once you have the InformationFlow this code gets the conveyed items

public HashSet<UML.Classes.Kernel.Classifier> conveyed
{
    get
    {
        if (_conveyed == null)
        {
            string getXrefDescription = @"select x.Description from t_xref x
                                        where x.Name = 'MOFProps'
                                        and x.Behavior = 'conveyed'
                                        and x.client = '" + this.guid + "'";
            //xrefdescription contains the GUID's of the conveyed elements comma separated
            var xrefDescription = this.model.SQLQuery(getXrefDescription).SelectSingleNode(this.model.formatXPath("//Description"));
            if (xrefDescription != null)
            {
                foreach (string conveyedGUID in xrefDescription.InnerText.Split(','))
                {
                    var conveyedElement = this.model.getElementWrapperByGUID(conveyedGUID) as UML.Classes.Kernel.Classifier;
                    if (conveyedElement != null)
                    {
                        //initialize if needed
                        if (_conveyed == null)
                        {
                            _conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
                        }
                        //add the element
                        _conveyed.Add(conveyedElement);
                    }
                }
            }
        }
        //nothing found, return empty list.
        if (_conveyed == null)
        {
            _conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
        }
        return _conveyed;
    }
}


问:
How to pass command line arguments to a python file from a script
I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional

For Example.

```<code>.\train.py --counter arg1 --opt optional_arg
</code>```

Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute 'train.py' in 'script.py'

I need to do this as I want to give different set of arguments each time to train.py.

I know we can do this using a shell script. I am curious about how to do it using a python script.

train.py

```<code>import optparse
optparser = optparse.OptionParser()

optparser.add_option(
    "--counter", default = "",
    help = "Counter value"
)

optparser.add_option(
    "--opt", default = "",
    help = "Optinal parameter"
)

'''Do Something'''
</code>```

script.py

```<code>args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    args['--counter'] = counter

    '''run train.py with args as input dictionary'''
</code>```

答:
One way is to use the os module and command line via Python:

script.py

```<code>import os

# define some args
arg1 = '74.2'
optional_arg = 'disable'

os.system("python train.py --counter" + arg1 + "--opt" + optional_arg)
</code>```

Body:
I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional

For Example.

.\train.py --counter arg1 --opt optional_arg

Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute 'train.py' in 'script.py'

I need to do this as I want to give different set of arguments each time to train.py.

I know we can do this using a shell script. I am curious about how to do it using a python script.

train.py

import optparse
optparser = optparse.OptionParser()

optparser.add_option(
    "--counter", default = "",
    help = "Counter value"
)

optparser.add_option(
    "--opt", default = "",
    help = "Optinal parameter"
)

'''Do Something'''

script.py

args = {
    '--counter':''
    '--opts':''
}

lst = [ 1, 2, 3]

for counter in lst:
    '''set command line arguments here in args dictionary'''
    args['--counter'] = counter

    '''run train.py with args as input dictionary'''

Body:
One way is to use the os module and command line via Python:

script.py

import os

# define some args
arg1 = '74.2'
optional_arg = 'disable'

os.system("python train.py --counter" + arg1 + "--opt" + optional_arg)


问:
Alarm Manager keeps firing when Application is open
I have a problem and I'm hoping something could kindly point out why it is occuring. I hard-code the date that I want the alarm to fire, and when running the app for the first time, it does only fire at that instance in time. However, once the alarm has been fired, every time the app is open, the alarm continually fires and displays a notification. This is just a small app test that will be used as part of a bigger application and was hoping someone could help me please</p>

```<code>package com.example.alarmtest;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

     private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          Calendar calendar = Calendar.getInstance();

          calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
          calendar.set(Calendar.YEAR, 2014);
          calendar.set(Calendar.DAY_OF_MONTH, 12);

          calendar.set(Calendar.HOUR_OF_DAY, 2);
          calendar.set(Calendar.MINUTE, 26 );
          calendar.set(Calendar.SECOND, 0);
          calendar.set(Calendar.AM_PM,Calendar.PM);

          Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
          pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

          AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
          alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

    }

}

package com.example.alarmtest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;

import android.content.Intent;
import android.os.IBinder;

public class MyAlarmService extends Service {

    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

        Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
        mManager.notify(0, notification);

        return super.onStartCommand(intent, flags, startId);
    }

     @Override
        public void onDestroy()
        {
            // TODO Auto-generated method stub
            super.onDestroy();
        }

}

package com.example.alarmtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Intent service1 = new Intent(context, MyAlarmService.class);
           context.startService(service1);

    }

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

         <activity
            android:name="com.example.alarmtest.NextActivity"
            android:label="Next Screen">
        </activity>

        <service android:name="com.example.alarmtest.MyAlarmService"
                 android:enabled="true" />

        <receiver android:name=".MyReceiver"/>
    </application>

</manifest>
</code>```

答:
Okay so I had similar situation I will go through possible fixes but first lets examine why this happens.

In my case, when you open app it sets alarm for that day, for eg, if alarm being set is before current time it will be fired immediately after setting. Since I showed notifications in alarm receiver, most of the times when I opened app, morning alarms where popping up. Which verifies above condition.

To stop this, either put a check on setting alarms for only future. Or put this check in the alarm receiver that if alarm time is less than current time, dont fire notification.

I set the alarm time in milliseconds in intent before setting alarm as long extra:

```<code>long timestamp=1111882929;  // your alarm timestamp
alarmIntent.putExtra("timestamp",timestamp);
//... setAlarm...
</code>```

When you receive intent in onRecieve of AlarmReceiver (in your case its a Service class) put a check before showing notifications like this:

```<code>if(intent.getLongExtra("timestamp",0)> System.currentTimeMillis())
{

showNotification(intent);
}
// else do nothing
</code>```

Also, if you set an alarm with same pending request code for eg:

```<code>int CODE=112; // any code
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast( context, CODE, alarmIntent, 0 );
</code>```

This will set alarm with code 112, setting alarm with this code again will override it again.

Body:
I have a problem and I'm hoping something could kindly point out why it is occuring. I hard-code the date that I want the alarm to fire, and when running the app for the first time, it does only fire at that instance in time. However, once the alarm has been fired, every time the app is open, the alarm continually fires and displays a notification. This is just a small app test that will be used as part of a bigger application and was hoping someone could help me please

package com.example.alarmtest;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

     private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          Calendar calendar = Calendar.getInstance();

          calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
          calendar.set(Calendar.YEAR, 2014);
          calendar.set(Calendar.DAY_OF_MONTH, 12);

          calendar.set(Calendar.HOUR_OF_DAY, 2);
          calendar.set(Calendar.MINUTE, 26 );
          calendar.set(Calendar.SECOND, 0);
          calendar.set(Calendar.AM_PM,Calendar.PM);

          Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
          pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

          AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
          alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

    }

}

package com.example.alarmtest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;

import android.content.Intent;
import android.os.IBinder;

public class MyAlarmService extends Service {

    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

        Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
        mManager.notify(0, notification);

        return super.onStartCommand(intent, flags, startId);
    }

     @Override
        public void onDestroy()
        {
            // TODO Auto-generated method stub
            super.onDestroy();
        }

}

package com.example.alarmtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Intent service1 = new Intent(context, MyAlarmService.class);
           context.startService(service1);

    }

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

         <activity
            android:name="com.example.alarmtest.NextActivity"
            android:label="Next Screen">
        </activity>

        <service android:name="com.example.alarmtest.MyAlarmService"
                 android:enabled="true" />

        <receiver android:name=".MyReceiver"/>
    </application>

</manifest>

Body:
Okay so I had similar situation I will go through possible fixes but first lets examine why this happens.

In my case, when you open app it sets alarm for that day, for eg, if alarm being set is before current time it will be fired immediately after setting. Since I showed notifications in alarm receiver, most of the times when I opened app, morning alarms where popping up. Which verifies above condition.

To stop this, either put a check on setting alarms for only future. Or put this check in the alarm receiver that if alarm time is less than current time, dont fire notification.

I set the alarm time in milliseconds in intent before setting alarm as long extra:

long timestamp=1111882929;  // your alarm timestamp
alarmIntent.putExtra("timestamp",timestamp);
//... setAlarm...

When you receive intent in onRecieve of AlarmReceiver (in your case its a Service class) put a check before showing notifications like this:

if(intent.getLongExtra("timestamp",0)> System.currentTimeMillis())
{

showNotification(intent);
}
// else do nothing

Also, if you set an alarm with same pending request code for eg:

int CODE=112; // any code
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast( context, CODE, alarmIntent, 0 );

This will set alarm with code 112, setting alarm with this code again will override it again.