问:
How to combine two regex using AND operator
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

```<code>var url = https://website.com/something-here/page.html?p=null#confirmation?order=123
</code>```

My expected result is:

```<code>/something-here/page.html #confirmation
</code>```

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

```<code>var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);
</code>```

But I would like to have it done as a single regex with the same result.

答:
You can use RegExp's group system to your advantage. Here's a snippet:

```<code>var matches = url.match(/(som[^#]+.html).*?(#[^#]+.tion)/);
console.log(matches[1] + " " + matches[2]); // prints /something-here/page.html #confirmation
</code>```

I combined your two RegExp conditions into one, while enclosing them with parenthesis in the correct areas to create two groups.

That way, you can get the specified group and add a space in between.

Body:
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

var url = https://website.com/something-here/page.html?p=null#confirmation?order=123

My expected result is:

/something-here/page.html #confirmation

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);

But I would like to have it done as a single regex with the same result.

Body:
You can use RegExp's group system to your advantage. Here's a snippet:

var matches = url.match(/(som[^#]+.html).*?(#[^#]+.tion)/);
console.log(matches[1] + " " + matches[2]); // prints /something-here/page.html #confirmation

I combined your two RegExp conditions into one, while enclosing them with parenthesis in the correct areas to create two groups.

That way, you can get the specified group and add a space in between.


来源: stackexchange

问:
Dynamic JavaScript time counter
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

```<code>1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE
</code>```

Here is the code I try to make it work.

```<code><center>
<script>
    var countDownDate = new Date("2017-11-17T20:10:30Z").getTime();
    var x = setInterval(function() {
        var now = new Date().getTime();
        var distance = countDownDate - now;

        // Seconds
        if (distance < 1000){
            document.getElementById("count1").innerHTML = seconds + "s ";
        }
        // Minutes
        if (distance < 60000){
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = minutes + "m " + seconds + "s ";
        }
        // Hours
        if (distance < 3600000){
            var hours = Math.floor(distance / (1000 * 60 * 60 * 1));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
        }
        // Days
        if(distance > 3600001){
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("count1").innerHTML = days + "d " + hours + "h " + minutes + "m " $
        }

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("count1").innerHTML = "You will be redirected now";
        }
    }, 1000);
</script>

<p id="count1"></p>
</center>
</code>```

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

答:
Here is the whole script in working order in case somebody else need it:

The whole script is meant to be reused multiply times in a single page by changing the ID in the $FD['id'] array variable and copy pasting the function that prints/echoing the function content.

PHP FUNCTION INCLUDE FILE (count.php):

```<code><?php
// JS Date format
// 2017-11-14T12:00:00Z

function counter($FD){
$date=$FD['date'];
$id=$FD['id'];
$display_start_1=$FD['display_start_1'];
$display_start_2=$FD['display_start_2'];
$display_end=$FD['display_end'];

echo $counter=<<<a
<center>
<script>

var countDownDate$id = new Date("$date").getTime();
var x$id = setInterval(function () {
        var now$id = new Date().getTime();
        var distance$id = countDownDate$id - now$id;

        var days$id = Math.floor(distance$id / (1000 * 60 * 60 * 24));
        var hours$id = Math.floor((distance$id % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes$id = Math.floor((distance$id % (1000 * 60 * 60)) / (1000 * 60));
        var seconds$id = Math.floor((distance$id % (1000 * 60)) / 1000);

        // Seconds
        if (distance$id <= 60000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + seconds$id + "s " + " $display_start_2";
        }
        // Minutes
        else if (distance$id <= 3600000) {
                document.getElementById("count$id").innerHTML ="$display_start " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        // Hours
        else if (distance$id <= 86400000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        // Days
        else if (distance$id > 86400000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + days$id + "d " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        if (distance$id < 0) {
                clearInterval(x$id);
                document.getElementById("count$id").innerHTML = "$display_end";
        }
}, 1000);
</script>
<p id="count$id"></p>
a;
}
?>
</code>```

PHP DISPLAY FILE (count_display.php):

```<code><?php
$now = time();
// Simulation of utc time (-1 hour +1 minute)
// By modifying the amount of seconds you set/define the amount of seconds that will counted down
$timestamp_new=$now-3600+10;
// Time formattig for JavaScript code
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);

// Include the function file once only
include'count.php';

// Define variables for the first counter
$FD1['date']="$date_new";
$FD1['id']='1';
$FD1['display_start_1']="Please wait for another:<br >";
$FD1['display_start_2']="<br />We are preparing your playground for you.";
$FD1['display_end']="Your Playground is ready at:<br /><a href='http://555.555.555.555'>Game server 01</a>";
counter($FD1);

// Define variables for the second counter
$timestamp_new=$now-3600+15;
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);

// The second count down timer
$FD2['date']="$date_new";
$FD2['id']='2';
$FD2['display_start_1']="Please wait for another:<br >";
$FD2['display_start_2']="<br />We are preparing your playground for you.";
$FD2['display_end']="Your Playground is ready at:<br /><a href='http://100.100.100.100'>Game server 02</a>";
counter($FD2);

// And so on ....

?>
</code>```

Hoping that this will save a lot of time to somebody else ;)
Have a great life (you who can and know how) ;)

ContentLicense: CC BY-SA 3.0

Title: Dynamic JavaScript time counter

Body:
I'm trying to make a dynamic time counter/timer in JavaScript.

Why dynamic? Well I would like to display days/hours/minutes/seconds if the time stamp is bigger enough to display days or hours and so on.

In case the timestamp is less than a day I would like that the script dynamically displays only the hours.

1D 0H 59M 59S
23H 59M 59S
59M 59S
59S
MESSAGE

Here is the code I try to make it work.

I think that my problem is related with math confusion in milliseconds but I can't find out what is wrong.

Body:
Here is the whole script in working order in case somebody else need it:

The whole script is meant to be reused multiply times in a single page by changing the ID in the $FD['id'] array variable and copy pasting the function that prints/echoing the function content.

PHP FUNCTION INCLUDE FILE (count.php):

<?php
// JS Date format
// 2017-11-14T12:00:00Z

function counter($FD){
$date=$FD['date'];
$id=$FD['id'];
$display_start_1=$FD['display_start_1'];
$display_start_2=$FD['display_start_2'];
$display_end=$FD['display_end'];

echo $counter=<<<a
<center>
<script>

var countDownDate$id = new Date("$date").getTime();
var x$id = setInterval(function () {
        var now$id = new Date().getTime();
        var distance$id = countDownDate$id - now$id;

        var days$id = Math.floor(distance$id / (1000 * 60 * 60 * 24));
        var hours$id = Math.floor((distance$id % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes$id = Math.floor((distance$id % (1000 * 60 * 60)) / (1000 * 60));
        var seconds$id = Math.floor((distance$id % (1000 * 60)) / 1000);

        // Seconds
        if (distance$id <= 60000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + seconds$id + "s " + " $display_start_2";
        }
        // Minutes
        else if (distance$id <= 3600000) {
                document.getElementById("count$id").innerHTML ="$display_start " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        // Hours
        else if (distance$id <= 86400000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        // Days
        else if (distance$id > 86400000) {
                document.getElementById("count$id").innerHTML ="$display_start_1 " + days$id + "d " + hours$id + "h " + minutes$id + "m " + seconds$id + "s " + " $display_start_2";
        }
        if (distance$id < 0) {
                clearInterval(x$id);
                document.getElementById("count$id").innerHTML = "$display_end";
        }
}, 1000);
</script>
<p id="count$id"></p>
a;
}
?>

PHP DISPLAY FILE (count_display.php):

<?php
$now = time();
// Simulation of utc time (-1 hour +1 minute)
// By modifying the amount of seconds you set/define the amount of seconds that will counted down
$timestamp_new=$now-3600+10;
// Time formattig for JavaScript code
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);

// Include the function file once only
include'count.php';

// Define variables for the first counter
$FD1['date']="$date_new";
$FD1['id']='1';
$FD1['display_start_1']="Please wait for another:<br >";
$FD1['display_start_2']="<br />We are preparing your playground for you.";
$FD1['display_end']="Your Playground is ready at:<br /><a href='http://555.555.555.555'>Game server 01</a>";
counter($FD1);

// Define variables for the second counter
$timestamp_new=$now-3600+15;
$date_new=date('Y-m-d\TH:i:s\Z', $timestamp_new);

// The second count down timer
$FD2['date']="$date_new";
$FD2['id']='2';
$FD2['display_start_1']="Please wait for another:<br >";
$FD2['display_start_2']="<br />We are preparing your playground for you.";
$FD2['display_end']="Your Playground is ready at:<br /><a href='http://100.100.100.100'>Game server 02</a>";
counter($FD2);

// And so on ....

?>

Hoping that this will save a lot of time to somebody else ;)
Have a great life (you who can and know how) ;)


问:
AngularJS to Angular - NgUpgrade
I have a app running AngularJS 1.5 and I'm trying to use NgUpgrade to start migrating old components to Angular.

My first step it's to have both frameworks running side by side. But when using NgUpgrade, I'm getting the following error:

```<code>Unhandled Promise rejection: [$injector:modulerr] Failed to instantiate module $$UpgradeModule due to:
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module undefined due to:
Error: [ng:areq] Argument 'module' is not a function, got undefined
</code>```

Basically I have an app.module.ts for Angular and app.js for AngularJS.

Following angular documentation, I created a main.ts to bootstrap both frameworks.

```<code>import { AppModule } from './app.module';

import { UpgradeModule } from '@angular/upgrade/static';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
    console.log('Bootstrap both Angular and AngularJS ');
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.body, ['myApp'], {strictDi: true});
});

For creating my bundle, I'm using webpack.
</code>```

答:
This is the current state of our module. Most of the code is irrelevant to bootstrap both framework, since it's related with Redux. First, you need to remove the ng-app from the html and then inside of the constructor of the Module you need to call ngDoBootstrap() to bootstrap angular manually.

upgrade.bootstrap(document.body, ['app'], {strictDi: true}); will take care of bootstrapping your AngularJS application.

export class AppModule {
    constructor(private ngRedux: NgRedux<any>, @Inject(DIGEST_MIDDLEWARE) digestMiddleware: any) {
        const reducer = combineReducers({
            actions: actionsReducer,
            ...coreReducers
        });
        const initialStete = {
            actions: actionsInitialState,
            ...coreState
        };

        // digestMiddleware needs to be last, to support use in AngularJS 1.x
        const store = createStore(reducer, initialStete, applyMiddleware(thunk, logger, digestMiddleware) );
        ngRedux.provideStore(store);
    }
 ngDoBootstrap() {}
}

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
 const upgrade = platformRef.injector.get(UpgradeModule);
 upgrade.bootstrap(document.body, ['app'], {strictDi: true});
});```

Title: AngularJS to Angular - NgUpgrade

Body:
I have a app running AngularJS 1.5 and I'm trying to use NgUpgrade to start migrating old components to Angular.

My first step it's to have both frameworks running side by side. But when using NgUpgrade, I'm getting the following error:

Unhandled Promise rejection: [$injector:modulerr] Failed to instantiate module $$UpgradeModule due to:
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module undefined due to:
Error: [ng:areq] Argument 'module' is not a function, got undefined

Basically I have an app.module.ts for Angular and app.js for AngularJS.

Following angular documentation, I created a main.ts to bootstrap both frameworks.

import { AppModule } from './app.module';

import { UpgradeModule } from '@angular/upgrade/static';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
    console.log('Bootstrap both Angular and AngularJS ');
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.body, ['myApp'], {strictDi: true});
});

For creating my bundle, I'm using webpack.


问:
Why is my list of Tuples vertical?
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

```<code>>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
</code>```

This is my code:

```<code>def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]
</code>```

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

```<code>[[0], 13]
</code>```

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

答:
The question asks you to return a list with the desired structure, so be careful about that. You are just printing one right now.

```<code>def enum(aSequence):
    list1 = []
    for i in range(len(aSequence)):
        b = aSequence[i]
        a = i
        # use append to keep your items in the list to be returned
        list1.append((a, b))
    return list1

print(enum('hello')) # this should print horizontally like you asked.
</code>```

Regarding the simplest answer to create the list you want, the enumerate function is your friend. The enumerate function unpacks a tuple of the index and the object found at the index for an iterable.

```<code>thing = 'hello there!'

#typical use case for enumerate
for i, item in enumerate(thing):
    print(i, item)
</code>```

So here's an example function that does what you want...

```<code>def enum(iterable):
    # must use list() to cast it as an object or else we return a generator object
    return list(enumerate(iterable))

enum('hello there!')
</code>```

Title: Why is my list of Tuples vertical?

Body:
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

This is my code:

def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

[[0], 13]

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

Body:
The question asks you to return a list with the desired structure, so be careful about that. You are just printing one right now.

def enum(aSequence):
    list1 = []
    for i in range(len(aSequence)):
        b = aSequence[i]
        a = i
        # use append to keep your items in the list to be returned
        list1.append((a, b))
    return list1

print(enum('hello')) # this should print horizontally like you asked.

Regarding the simplest answer to create the list you want, the enumerate function is your friend. The enumerate function unpacks a tuple of the index and the object found at the index for an iterable.

thing = 'hello there!'

#typical use case for enumerate
for i, item in enumerate(thing):
    print(i, item)

So here's an example function that does what you want...

def enum(iterable):
    # must use list() to cast it as an object or else we return a generator object
    return list(enumerate(iterable))

enum('hello there!')


问:
How to test my blocking queue actually blocks
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

```<code>BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();
</code>```

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?

答:
```<code>template<class T>
struct async_queue {
  T pop() {
    auto l = lock();
    ++wait_count;
    cv.wait( l, [&]{ return !data.empty(); } );
    --wait_count;
    auto r = std::move(data.front());
    data.pop_front();
    return r;
  }
  void push(T in) {
    {
      auto l = lock();
      data.push_back( std::move(in) );
    }
    cv.notify_one();
  }
  void push_many(std::initializer_list<T> in) {
    {
      auto l = lock();
      for (auto&& x: in)
        data.push_back( x );
    }
    cv.notify_all();
  }
  std::size_t readers_waiting() {
    return wait_count;
  }
  std::size_t data_waiting() const {
    auto l = lock();
    return data.size();
  }
private:
  std::queue<T> data;
  std::condition_variable cv;
  mutable std::mutex m;
  std::atomic<std::size_t> wait_count{0};
  auto lock() const { return std::unique_lock<std::mutex>(m); }

};
</code>```

or somesuch.

In the push thread, busy wait on readers_waiting until it passes 1.

At which point you have the lock and are within cv.wait before the lock is unlocked.  Do a push.

In theory an infinitely slow reader thread could have gotten into cv.wait and still be evaluating the first lambda by the time you call push, but an infinitely slow reader thread is no different than a blocked one...

This does, however, deal with slow thread startup and the like.

Using readers_waiting and data_waiting for anything other than debugging is usually code smell.

Body:
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?

Body:
template<class T>
struct async_queue {
  T pop() {
    auto l = lock();
    ++wait_count;
    cv.wait( l, [&]{ return !data.empty(); } );
    --wait_count;
    auto r = std::move(data.front());
    data.pop_front();
    return r;
  }
  void push(T in) {
    {
      auto l = lock();
      data.push_back( std::move(in) );
    }
    cv.notify_one();
  }
  void push_many(std::initializer_list<T> in) {
    {
      auto l = lock();
      for (auto&& x: in)
        data.push_back( x );
    }
    cv.notify_all();
  }
  std::size_t readers_waiting() {
    return wait_count;
  }
  std::size_t data_waiting() const {
    auto l = lock();
    return data.size();
  }
private:
  std::queue<T> data;
  std::condition_variable cv;
  mutable std::mutex m;
  std::atomic<std::size_t> wait_count{0};
  auto lock() const { return std::unique_lock<std::mutex>(m); }

};

or somesuch.

In the push thread, busy wait on readers_waiting until it passes 1.

At which point you have the lock and are within cv.wait before the lock is unlocked.  Do a push.

In theory an infinitely slow reader thread could have gotten into cv.wait and still be evaluating the first lambda by the time you call push, but an infinitely slow reader thread is no different than a blocked one...

This does, however, deal with slow thread startup and the like.

Using readers_waiting and data_waiting for anything other than debugging is usually code smell.


问:
Saving String arrays to sharedPreference
I have gone through a lot of articles on the web that tries to analyse how array data could be save for future reuse but it seems as if they can't give me exactly what i want.
I'm creating an android app which contains 30 buttons in one layout.
Each button has it own String array  variable with 4 elements in each array.

```<code>String []mon_course1 ={"","","",""};
String []mon_course2 ={"","","",""};
// up to 30
</code>```

all elements in the array contains different string data which is gotten from different EditText

```<code>mon_course1[0] = (editText1.getText().toString());
mon_course1[1] = (editText2.getText().toString());
mon_course1[2] = (editText3.getText().toString());
mon_course1[3] = (editText4.getText().toString());
</code>```

Deciding which array String the EditText's data should be save to is handled by a switch statement.
I'm able to set the arrays data from the corresponding EditText field
and also get the arrays data and set to TextViews

```<code>textView1.setText(mon_course1[0]);
textView2.setText(mon_course1[1]);
// till textView4
</code>```

Now i want the data for each String array's element to be save in such that  it can be independently set to it corresponding textView
using sharedPreference or any other storage option.
Please anyone that wants to help should clearly express his/her code and also use comment for better understanding because I'm just starting android programming. THANKS

答:
```<code>String[] arr = new String[]{"1", "2", "3"};
Editor edit = mPrefs.edit();
for(String str : arr) {
     edit.putString(str, str);
}
edit.apply();
</code>```

Body:
I have gone through a lot of articles on the web that tries to analyse how array data could be save for future reuse but it seems as if they can't give me exactly what i want.
I'm creating an android app which contains 30 buttons in one layout.
Each button has it own String array  variable with 4 elements in each array.

String []mon_course1 ={"","","",""};
String []mon_course2 ={"","","",""};
// up to 30

all elements in the array contains different string data which is gotten from different EditText

mon_course1[0] = (editText1.getText().toString());
mon_course1[1] = (editText2.getText().toString());
mon_course1[2] = (editText3.getText().toString());
mon_course1[3] = (editText4.getText().toString());

Deciding which array String the EditText's data should be save to is handled by a switch statement.
I'm able to set the arrays data from the corresponding EditText field
and also get the arrays data and set to TextViews

textView1.setText(mon_course1[0]);
textView2.setText(mon_course1[1]);
// till textView4

Now i want the data for each String array's element to be save in such that  it can be independently set to it corresponding textView
using sharedPreference or any other storage option.
Please anyone that wants to help should clearly express his/her code and also use comment for better understanding because I'm just starting android programming. THANKS


问:
In javascript, when to use object literal and when to use array?
Here's a sample. My concern is both seem to do the job. which of them to prefer?

```<code>var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}
</code>```

Also, the following seems to be not valid, Any way of avoiding array notation.

```<code>var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};
</code>```

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

```<code>var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};
</code>```

Thanks again and in advance to those who help me with the query.

答:
A for .. in loop iterates over enumerables. You might want to read up on it.

If you have an array of objects I would suggest a traditional for loop:

```<code>var fooObjs = [ {bar: "blah"}, {bar: "blah2"} ];
for (var i = 0, j = fooObj.length; i < j; i++) {
  console.log(fooObjs[i].bar);
}
</code>```

If you have an object with multiple properties, then you could use the for .. in loop:

```<code>var fooObj = { bar: "blah", baz: "blah2" };
for (var i in fooObj) {
  if (fooObj.hasOwnProperty(i)) { // So you don't log prototype properties
    console.log(fooObj[i]);
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's a sample. My concern is both seem to do the job. which of them to prefer?

var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}

Also, the following seems to be not valid, Any way of avoiding array notation.

var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};

Thanks again and in advance to those who help me with the query.

Body:
A for .. in loop iterates over enumerables. You might want to read up on it.

If you have an array of objects I would suggest a traditional for loop:

var fooObjs = [ {bar: "blah"}, {bar: "blah2"} ];
for (var i = 0, j = fooObj.length; i < j; i++) {
  console.log(fooObjs[i].bar);
}

If you have an object with multiple properties, then you could use the for .. in loop:

var fooObj = { bar: "blah", baz: "blah2" };
for (var i in fooObj) {
  if (fooObj.hasOwnProperty(i)) { // So you don't log prototype properties
    console.log(fooObj[i]);
  }
}


问:
What value is selected into parameter in SQL query without where clause
For example, I have this query

```<code>SELECT @param = column from table
</code>```

What value is pulled into @param?

I tried this and can't figure out the value that is being pulled. It is not the old record or newer one.

答:
The documentation states:

the variable is assigned the last value that is returned

But without a WHERE clause that uniquely identifies a row nor an ORDER BY clause that specifies a unique value for ordering, the row chosen for the variable assignment is undefined and not deterministic when the table has more than one row.

You could add ORDER BY to the query to return the last ordered row. A more efficient method to do that would to be use SELECT TOP(1)...ORDER BY...DESC. Conversely, SELECT TOP(1)...ORDER BY...ASC will return the first ordered row. Again, the order by column(s) need to be unique for a deterministic value.

Body:
For example, I have this query

SELECT @param = column from table

What value is pulled into @param?

I tried this and can't figure out the value that is being pulled. It is not the old record or newer one.


问:
Python List to Pandas Dataframe - Concatenate Lists
I'm trying to combine two sets of data that I have in list format, and I'm trying to convert them both to pandas, then merge them, in order to eventually export a CSV. I've been trying to convert them to pandas, but I seem to be unable do so without losing data. A data sample is as follows -

```<code>[[     CAPITL LMP  CENTRL LMP  DUNWOD LMP  GENESE LMP    H Q LMP  HUD VL
LMP  \
Hour
00     33.694545   -2.760000   20.277273   -3.484545  -6.530000   20.450909
01     17.832500   16.915833   17.795833   16.416667  16.032500   17.795833
02     21.685833   20.530833   21.690833   19.920000  19.520833   21.681667
03     26.000000    1.942500   17.254167    1.354167  -0.737500
</code>```

I have tried something like

```<code>df = pd.DataFrame.from_records(sales)
</code>```

but when I do I lose all of the data in each row and I only have the column titles.

```<code>        0            1            2            3         4            5   \
0   CAPITL LMP   CENTRL LMP   DUNWOD LMP   GENESE LMP   H Q LMP   HUD VL LMP
1  CAPITL Loss  CENTRL Loss  DUNWOD Loss  GENESE Loss  H Q Loss  HUD VL Loss
2   CAPITL Con   CENTRL Con   DUNWOD Con   GENESE Con   H Q Con   HUD VL Con
</code>```

I don't understand why this is happening, and any help is greatly appreciated. Sales is the top List of data, and it goes on beyond what I have pasted to include other columns (the titles of which you can see become aggregated above after using the dataframe.from idea...

答: Since I can't comment, I will provide it as an answer. You didn't provide a proper input, so it is hard to answer your question. However, I suspect that perhaps your dataset is not a list- take a look at the diagram of 4 different types of data for creating a DataFrame in this link: http://pbpython.com/pandas-list-dict.html this should work for you

Body:
I'm trying to combine two sets of data that I have in list format, and I'm trying to convert them both to pandas, then merge them, in order to eventually export a CSV. I've been trying to convert them to pandas, but I seem to be unable do so without losing data. A data sample is as follows -

[[     CAPITL LMP  CENTRL LMP  DUNWOD LMP  GENESE LMP    H Q LMP  HUD VL
LMP  \
Hour
00     33.694545   -2.760000   20.277273   -3.484545  -6.530000   20.450909
01     17.832500   16.915833   17.795833   16.416667  16.032500   17.795833
02     21.685833   20.530833   21.690833   19.920000  19.520833   21.681667
03     26.000000    1.942500   17.254167    1.354167  -0.737500

I have tried something like

df = pd.DataFrame.from_records(sales)

but when I do I lose all of the data in each row and I only have the column titles.

        0            1            2            3         4            5   \
0   CAPITL LMP   CENTRL LMP   DUNWOD LMP   GENESE LMP   H Q LMP   HUD VL LMP
1  CAPITL Loss  CENTRL Loss  DUNWOD Loss  GENESE Loss  H Q Loss  HUD VL Loss
2   CAPITL Con   CENTRL Con   DUNWOD Con   GENESE Con   H Q Con   HUD VL Con

I don't understand why this is happening, and any help is greatly appreciated. Sales is the top List of data, and it goes on beyond what I have pasted to include other columns (the titles of which you can see become aggregated above after using the dataframe.from idea...


问:
Dropdown Menu Slow Response and Disappearing on Hover
I'm having issues with my dropdown navigation for just this page. The response times on the navigation are extremely slow, and the dropdown menu will show momentarily on hover, but quickly disappears. I'm unsure if it has to do with the main element below, or not. If you have any insight or help, it would be great. I'm a graphic major, not web, so this isn't my forte.

body{
 background-color: white;
}

#page-wrapper{
 margin-left: auto;
 margin-right: auto;
 width: 960px;
 height: auto;
 background-image: url(Images/brick-wall-2209991.jpg);
 background-repeat: repeat-y;
}

li {
 text-align: center;
 display: inline;
}

a {
    text-decoration: none;
}

.span01,.span02,.span03,.span04,.span05,.span06,.span07,.span08,.span09,.span10,.span11,.span12
{
 display: inline;
 float: left;
 margin-left: 10px;
 margin-right: 10px;
}

.first-child{
 margin-left: 0;
}

.last-child{
 margin-right: 0;
}

.span01 {
 width: 60px;
}

.span02 {
 width: 140px;
}

.span03 {
width: 220px;
}

.span04 {
width: 300px;
}

.span05 {
width: 380px;
}

.span06 {
width: 460px;
}

.span07 {
width: 540px;
}

.span08 {
width: 620px;
}

.span09 {
width: 700px;
}

.span10 {
width: 780px;
}

.span11 {
width: 860px;
}

.span12 {
width: 940px;
}

.reset{
 clear: both;
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0px;
}

.header {height: 115px;
   background-color: #1e241b;
  width: 960px;
}

/********Navigation********/

ul { margin-right: 20px;}

li {text-align: center;
 display: inline;
 font-family: 'Josefin Sans', sans-serif;
 font-size: 14pt;
 text-transform: uppercase;
 font-weight: bold;
 letter-spacing: 1px;
 color: #d98a79;

    }
li a:link {color: #d98a79;}

li a:visited {
    color: #d98a79;
}

li a:hover {
 text-decoration-color: white;
 color: white;

}

li a:active {
    color: white;
}

nav {text-align: center;
 padding-left: 110px;
 margin-top: 30px;
 float: right;
 margin-right: 70px;
 }
nav ul ul {
 display: none;
 position: absolute;
 top: 100%;
}

nav ul ul li {
 float: none;
 position: relative;
 text-align: left;
}

nav ul ul li a {
 padding-top: 15px;
 margin-top: 0px;
 padding-bottom: 15px;
 margin-left: -10px;
 margin-right: 15px;
 text-align: left;

}

nav ul li:hover > ul {
 display: block;
}

nav ul {
 background-color: #1e241b;
 list-style: none;
 position: relative;
 display: inline-table;
}

nav ul:after {
 content: "";
 clear: both;
 display: block;
}

nav ul li {
 float: left;
}

nav ul li a{
 display: block;
 padding: 10px 8px;

}
.bar {height: 190px;
 background-color: rgba(0,0,0,0.75);
 position: relative;
 margin-top: 20px;
}

h1 {
 font-family: 'Josefin Sans', sans-serif;
 text-align: right;
 text-transform: uppercase;
 color: white;
 font-size: 90pt;
 position: relative;
 top:-140px;
 left: -40px;
 margin-bottom: -140px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta charset="UTF-8">
<title>Sous Vide - About</title>
<link href="secondary.css" rel="stylesheet" type="text/css">
<style>
@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');
@import url('https://fonts.googleapis.com/css?family=Barlow+Semi+Condensed');
</style>
</head>

<body>

<div id="page-wrapper">

 <header class="span12 header first-child last-child">

  <nav class="span12">

   <ul>
    <li>Home</li>
    <li>About Us
     <ul>
      <li>About Us</li>
      <li>FAQ</li>
     </ul>
    </li>
    <li>Menus
     <ul>
      <li>Seasonal Menu</li>
      <li>Breakfast Menu</li>
      <li>Lunch Menu</li>
     </ul>
    </li>
    <li>Catering</li>
    <li>Gallery</li>
    <li>Locations</li>
    </ul>

  </nav>
     </header>
<div class="reset"></div>

 <main class="bar span12"></main>
  <h1>About Us</h1>

<div class="reset"></div></code>```

答:
You should put the h1 element to a div container and style it with CSS.

Example:

```<code><div id="DIVNAME">
    <h1>About Us</h1>
</div>
</code>```

in css:

```<code>#DIVNAME { height: 100px; width 100px; }
</code>```

Body:
I'm having issues with my dropdown navigation for just this page. The response times on the navigation are extremely slow, and the dropdown menu will show momentarily on hover, but quickly disappears. I'm unsure if it has to do with the main element below, or not. If you have any insight or help, it would be great. I'm a graphic major, not web, so this isn't my forte.

body{
 background-color: white;
}

#page-wrapper{
 margin-left: auto;
 margin-right: auto;
 width: 960px;
 height: auto;
 background-image: url(Images/brick-wall-2209991.jpg);
 background-repeat: repeat-y;
}

li {
 text-align: center;
 display: inline;
}

a {
    text-decoration: none;
}

.span01,.span02,.span03,.span04,.span05,.span06,.span07,.span08,.span09,.span10,.span11,.span12
{
 display: inline;
 float: left;
 margin-left: 10px;
 margin-right: 10px;
}

.first-child{
 margin-left: 0;
}

.last-child{
 margin-right: 0;
}

.span01 {
 width: 60px;
}

.span02 {
 width: 140px;
}

.span03 {
width: 220px;
}

.span04 {
width: 300px;
}

.span05 {
width: 380px;
}

.span06 {
width: 460px;
}

.span07 {
width: 540px;
}

.span08 {
width: 620px;
}

.span09 {
width: 700px;
}

.span10 {
width: 780px;
}

.span11 {
width: 860px;
}

.span12 {
width: 940px;
}

.reset{
 clear: both;
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0px;
}

.header {height: 115px;
   background-color: #1e241b;
  width: 960px;
}

/********Navigation********/

ul { margin-right: 20px;}

li {text-align: center;
 display: inline;
 font-family: 'Josefin Sans', sans-serif;
 font-size: 14pt;
 text-transform: uppercase;
 font-weight: bold;
 letter-spacing: 1px;
 color: #d98a79;

    }
li a:link {color: #d98a79;}

li a:visited {
    color: #d98a79;
}

li a:hover {
 text-decoration-color: white;
 color: white;

}

li a:active {
    color: white;
}

nav {text-align: center;
 padding-left: 110px;
 margin-top: 30px;
 float: right;
 margin-right: 70px;
 }
nav ul ul {
 display: none;
 position: absolute;
 top: 100%;
}

nav ul ul li {
 float: none;
 position: relative;
 text-align: left;
}

nav ul ul li a {
 padding-top: 15px;
 margin-top: 0px;
 padding-bottom: 15px;
 margin-left: -10px;
 margin-right: 15px;
 text-align: left;

}

nav ul li:hover > ul {
 display: block;
}

nav ul {
 background-color: #1e241b;
 list-style: none;
 position: relative;
 display: inline-table;
}

nav ul:after {
 content: "";
 clear: both;
 display: block;
}

nav ul li {
 float: left;
}

nav ul li a{
 display: block;
 padding: 10px 8px;

}
.bar {height: 190px;
 background-color: rgba(0,0,0,0.75);
 position: relative;
 margin-top: 20px;
}

h1 {
 font-family: 'Josefin Sans', sans-serif;
 text-align: right;
 text-transform: uppercase;
 color: white;
 font-size: 90pt;
 position: relative;
 top:-140px;
 left: -40px;
 margin-bottom: -140px;
}

<meta charset="UTF-8">
<title>Sous Vide - About</title>
<link href="secondary.css" rel="stylesheet" type="text/css">

Home

About Us

About Us

FAQ

Menus

Seasonal Menu

Breakfast Menu

Lunch Menu

Catering

Gallery

Locations

About Us

Body:
You should put the h1 element to a div container and style it with CSS.

Example:

<div id="DIVNAME">
    <h1>About Us</h1>
</div>

in css:

#DIVNAME { height: 100px; width 100px; }


问:
VirtualHost problem with passenger (mod_rails)
I'm at my wit's end here with virtual hosting. I'm trying to install redmine and it works with the webrick test server, but when I tried to use passenger (mod_rails) to host and go to the address I specified when in the virtualhost part of my apache config file nothing happens. Here is the relavent section of /etc/httpd/conf/httpd.conf where I try to set up the virtual host:

```<code><VirtualHost *:80>

SetEnv RAILS_ENV production
ServerName redmine.MYSITE.com:80
DocumentRoot /opt/redmine-1.0.5/public/
<Directory /opt/redmine-1.0.5/public/>
    Options -MultiViews
    Allow from all
    AllowOverride none
</Directory>
</code>```

However, when I got to redmine.MYSITE.com:80 nothing happens, I just get our normal home page. I have no idea what the problem is, any help our guidance would be greatly appreciated. If you need any other information, please tell me and I'll provide it.

答:
It took me a while to get Redmine running under Passenger. This is what I have

Install passenger:

```<code>passenger-install-apache2-module
</code>```

Edit Apache confg file:

```<code>LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.11/ext/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.11
PassengerRuby /usr/bin/ruby
</code>```

Create a new directory in the default server:

```<code><Directory>
/webserver_root/html/redmine
RailsBaseURI /redmine
AllowOverride all
Options -MultiViews
</Directory>
</code>```

Lastly, make a link to the physical directory where your ruby apps live (ie NOT under /html or whatever directory you serve most Apache pages from. This MUST be a link to redmine's public subdirectory)

```<code>ln -s /webserver_root/ruby_apps/redmine/public /webserver_root/html/redmine
</code>```

So Apache now tries to show all the public pages as normal, but all other pages get routed through passenger. You access it as a subfolder - eg. http://mywebserver/redmine

Body:
I'm at my wit's end here with virtual hosting. I'm trying to install redmine and it works with the webrick test server, but when I tried to use passenger (mod_rails) to host and go to the address I specified when in the virtualhost part of my apache config file nothing happens. Here is the relavent section of /etc/httpd/conf/httpd.conf where I try to set up the virtual host:

<VirtualHost *:80>

SetEnv RAILS_ENV production
ServerName redmine.MYSITE.com:80
DocumentRoot /opt/redmine-1.0.5/public/
<Directory /opt/redmine-1.0.5/public/>
    Options -MultiViews
    Allow from all
    AllowOverride none
</Directory>

However, when I got to redmine.MYSITE.com:80 nothing happens, I just get our normal home page. I have no idea what the problem is, any help our guidance would be greatly appreciated. If you need any other information, please tell me and I'll provide it.

Body:
It took me a while to get Redmine running under Passenger. This is what I have

Install passenger:

passenger-install-apache2-module

Edit Apache confg file:

LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.11/ext/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.11
PassengerRuby /usr/bin/ruby

Create a new directory in the default server:

<Directory>
/webserver_root/html/redmine
RailsBaseURI /redmine
AllowOverride all
Options -MultiViews
</Directory>

Lastly, make a link to the physical directory where your ruby apps live (ie NOT under /html or whatever directory you serve most Apache pages from. This MUST be a link to redmine's public subdirectory)

ln -s /webserver_root/ruby_apps/redmine/public /webserver_root/html/redmine

So Apache now tries to show all the public pages as normal, but all other pages get routed through passenger. You access it as a subfolder - eg. http://mywebserver/redmine


问:
When is it acceptable to call db.SaveChanges() twice?
I have a controller when I am getting a users credentials from AD and saving it into a Profiles table. I also want to set some user preferences, however, in order to do this I need the Id from Profile I just saved to place it in the Preference table.

```<code>var Profile = new Profile
{
    //Id is auto increment
    EmpId = viewmodel.EmployeeId;
    //....
};
db.Profiles.Add(Profile);
db.SaveChanges();
</code>```

Preferences Save:

```<code>var user = User.Identity.Name;
var getUser = (from gu in db.Profiles where user == gu.EmployeeId select gu.Id).Single();
var Preference = new Preference
{
    UserId = getUser,
    //...
};
db.Preferences.Add(Preference);
db.SaveChanges();
</code>```

In this case, is this acceptable?

答:
It looks like your variable getUser (please rename this variable) ends up as the newly saved profile Id.. although you havent shown us where you define uc.

anyway let me show you the magic of entity framework.

```<code>var profile = new Profile
{
    //Id is auto increment
    EmpId = viewmodel.EmployeeId;
    //....
};
var preference = new Preference
{
    //...
};

profile.Preferences.Add(preference;)
db.Profiles.Add(profile);
db.SaveChanges();
</code>```

So as you can see you used more than 1 SaveChanges unnecessarily. There are times that you need to have more than one SaveChanges. like lets say you SaveChanges, post an id to an api, retrieve some values and save changes again. I never had to do that actually but i have had times that I need more than 1 save changes. For example I had to copy x amount of database records including x amount of related records into new records in a loop.

Body:
I have a controller when I am getting a users credentials from AD and saving it into a Profiles table. I also want to set some user preferences, however, in order to do this I need the Id from Profile I just saved to place it in the Preference table.

var Profile = new Profile
{
    //Id is auto increment
    EmpId = viewmodel.EmployeeId;
    //....
};
db.Profiles.Add(Profile);
db.SaveChanges();

Preferences Save:

var user = User.Identity.Name;
var getUser = (from gu in db.Profiles where user == gu.EmployeeId select gu.Id).Single();
var Preference = new Preference
{
    UserId = getUser,
    //...
};
db.Preferences.Add(Preference);
db.SaveChanges();

In this case, is this acceptable?

Body:
It looks like your variable getUser (please rename this variable) ends up as the newly saved profile Id.. although you havent shown us where you define uc.

anyway let me show you the magic of entity framework.

var profile = new Profile
{
    //Id is auto increment
    EmpId = viewmodel.EmployeeId;
    //....
};
var preference = new Preference
{
    //...
};

profile.Preferences.Add(preference;)
db.Profiles.Add(profile);
db.SaveChanges();

So as you can see you used more than 1 SaveChanges unnecessarily. There are times that you need to have more than one SaveChanges. like lets say you SaveChanges, post an id to an api, retrieve some values and save changes again. I never had to do that actually but i have had times that I need more than 1 save changes. For example I had to copy x amount of database records including x amount of related records into new records in a loop.


问:
fast way find to files in millions of files
I had a huge amount of data, about 50*50*10000 files with total file size 3TB. The file structure looks like:

/myhdd/Experiment_{id}/Run_{id}/Filename

Now given a filename, I want to locate where it is; however a straightforward find /myhdd -name "filename" is super inefficient. It need to look up the entire harddisk to find one file. Is there a better way to do this, like somehow build an index of my file structure to accelerate find?

答:
If locate or various find calls are still slow for your case, you can create and use for searching a file with the paths, as already commented.

You create that "index" file with

```<code>find . -type f > myindex
</code>```

And you can update it periodically either using -ctime to append new files, or from the beginning, it has just the time cost of your search now.

Then you can find the path searching for any filename. This is probably fast enough:

```<code>fname="myfilename"; awk -F/ -v f="$fname" '$NF==f' myindex
</code>```

Here some more information related to your issue.

Body:
If locate or various find calls are still slow for your case, you can create and use for searching a file with the paths, as already commented.

You create that "index" file with

find . -type f > myindex

And you can update it periodically either using -ctime to append new files, or from the beginning, it has just the time cost of your search now.

Then you can find the path searching for any filename. This is probably fast enough:

fname="myfilename"; awk -F/ -v f="$fname" '$NF==f' myindex

Here some more information related to your issue.


答: This is the value in the column referenced. It seems like it should have a TOP 1 in it, with a WHERE Clause designed to fetch 1 row only.</p>

Title: What value is selected into parameter in SQL query without where clause


问:
Running find from a C program to print file name given inode number?
I am trying to print the file name given the inode number. I am using the execlp system call to run the find command. My code is shown below:

```<code> #include <sys/mman.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main(int argc,char *argv[])
 {
    char str[8];
    char *ptr;
    ptr=str;
    long x=9306140;
    snprintf(str,8,"%ld", x);
    execlp("find"," ","~"," ","-inum"," ",str,NULL);

 }
</code>```

But I get an error: Invalid argument '9306140' to -inum.
Could someone please help?

答:
As noted in comments, you don't want the " " (space) arguments in the execlp() argument list.  The shell takes a string with spaces separating the arguments, but it treats what's between the spaces as words that are passed to the command; it doesn't ordinarily pass the spaces to the command.  (That's a simple and sufficient explanation for this exercise; there are caveats and weasel-words galore that could be added.)

The shell also expands ~ to match the value in the $HOME environment variable (in contrast to ~user which gets the home directory of user from the password file — they're usually, but not necessarily, the same).

You also have little margin for error in the size of string you've allocated for the number.  Frankly, though, you should simply use a string.  All these changes lead to:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    const char *home = getenv("HOME");
    const char inode[] = "9306140";
    execlp("find", "find", home, "-inum", inode, (char *)NULL);
    fprintf(stderr, "failed to execute 'find' command\n");
    return(EXIT_FAILURE);
}
</code>```

Note the repeated "find"; the first is the name of the file to be executed after searching along the path; the second is the value to be provided as argv[0].  You could put "hypochondriac" as the second occurrence and it is likely that find would work the same, at worst reporting its error messages as coming from the program 'hypochondriac'.

The next step would be to take the inode number from a command line argument:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc != 2)
    {
         fprintf(stderr, "Usage: %s inode\n", argv[0]);
         exit(EXIT_FAILURE);
    }
    const char *home = getenv("HOME");
    const char *inode = argv[1];
    execlp("find", "find", home, "-inum", inode, (char *)NULL);
    fprintf(stderr, "%s: failed to execute 'find' command\n", argv[0]);
    return(EXIT_FAILURE);
}
</code>```

The step after that would be to handle multiple inode values; at that point, you use execvp() instead of execlp(), though (or, if you're desparate and lazy, you loop and fork() and execlp() once per inode number, but that's slamming your system for no good reason at all).

Body:
I am trying to print the file name given the inode number. I am using the execlp system call to run the find command. My code is shown below:

 #include <sys/mman.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main(int argc,char *argv[])
 {
    char str[8];
    char *ptr;
    ptr=str;
    long x=9306140;
    snprintf(str,8,"%ld", x);
    execlp("find"," ","~"," ","-inum"," ",str,NULL);

 }

But I get an error: Invalid argument '9306140' to -inum.
Could someone please help?

Body:
As noted in comments, you don't want the " " (space) arguments in the execlp() argument list.  The shell takes a string with spaces separating the arguments, but it treats what's between the spaces as words that are passed to the command; it doesn't ordinarily pass the spaces to the command.  (That's a simple and sufficient explanation for this exercise; there are caveats and weasel-words galore that could be added.)

The shell also expands ~ to match the value in the $HOME environment variable (in contrast to ~user which gets the home directory of user from the password file — they're usually, but not necessarily, the same).

You also have little margin for error in the size of string you've allocated for the number.  Frankly, though, you should simply use a string.  All these changes lead to:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    const char *home = getenv("HOME");
    const char inode[] = "9306140";
    execlp("find", "find", home, "-inum", inode, (char *)NULL);
    fprintf(stderr, "failed to execute 'find' command\n");
    return(EXIT_FAILURE);
}

Note the repeated "find"; the first is the name of the file to be executed after searching along the path; the second is the value to be provided as argv[0].  You could put "hypochondriac" as the second occurrence and it is likely that find would work the same, at worst reporting its error messages as coming from the program 'hypochondriac'.

The next step would be to take the inode number from a command line argument:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc != 2)
    {
         fprintf(stderr, "Usage: %s inode\n", argv[0]);
         exit(EXIT_FAILURE);
    }
    const char *home = getenv("HOME");
    const char *inode = argv[1];
    execlp("find", "find", home, "-inum", inode, (char *)NULL);
    fprintf(stderr, "%s: failed to execute 'find' command\n", argv[0]);
    return(EXIT_FAILURE);
}

The step after that would be to handle multiple inode values; at that point, you use execvp() instead of execlp(), though (or, if you're desparate and lazy, you loop and fork() and execlp() once per inode number, but that's slamming your system for no good reason at all).


问:
SSRS Multi Groups Using Parameter in Expression
In Report Builder, I have a report with many parameters, three of the parameters are @DateFrom, @DateTo, @Check

The query from the Main dataset gives this result with 3 columns: Name, Check, ExpiryDate.

```<code>Name    Check   ExpiryDate
A        Y      05/01/2016
B        N      06/10/2017
C        Y      08/15/2017
D        N      08/20/2017
E        Y      09/05/2017
F        N      10/20/2018
</code>```

I need to group the report into 3 groups based on the parameter values,
For example, the user runs the report would enter: @DateFrom = 08/1/2017  @DateTo: 08/31/2017
=> The report should look like below:

Group Current Range ExpiryDate  [(ExpiryDate >= @DateFrom and ExpiryDate <=@DateTo)  and Check = @Check ]

```<code>C        Y      08/15/2017
D        N      08/20/2017
</code>```

Group Before Range ExpiryDate and Check = 'Y'  [(ExpiryDate <= @DateFrom) and Check = 'Y']

```<code>A        Y      05/01/2016
</code>```

Group After Range ExpiryDate and Check = 'Y' [(ExpiryDate >= @DateTo) and Check = 'Y']

```<code>E       Y       09/05/2017
</code>```

In the tablix using the Main dataset (only one tablix in the report), there is one RowGroup named 'Details'

I read lots of arcticles and I tried many ways, but nothing worked as I could not find the right way I guess.  Will you be able to help?

答:
The easiest way to create another group is to modify the SQL and add another column with your grouping logic.

```<code>SELECT
  ....,
  CASE
    WHEN ExpiryDate BETWEEN @DateFrom AND @DateTo AND Check = @Check
    THEN 'Current'
    WHEN ExpiryDate <= @DateFrom AND Check = 'Y'
    THEN 'Before'
    WHEN ExpiryDate >= @DateTo AND Check = 'Y'
    THEN 'After'
  END as MyGroup,
  ...
FROM ...
</code>```

so that you can create a parent group inside your tablix with the new custom grouping field.

OR if the SQL is very complex or you are using a shared dataset/stored procedure, then add a group to the SSRS tablix and specify a custom expression with similar logic using the SWITCH construct.

Edit, adding parameters to the SQL CASE

```<code>CASE
  WHEN expirydate BETWEEN @DateFrom AND @DateTo AND [check] IN @check
  THEN 'Current'
  WHEN expirydate <= @FromDate AND [check] = 'Y'
  THEN 'Before'
  WHEN expirydate >= @FromDate and [check] = 'Y'
  THEN 'After'
END as MyGroup
</code>```

Note that check is only surrounded by square brackets because it's a reserved SQL keyword.

Body:
In Report Builder, I have a report with many parameters, three of the parameters are @DateFrom, @DateTo, @Check

The query from the Main dataset gives this result with 3 columns: Name, Check, ExpiryDate.

Name    Check   ExpiryDate
A        Y      05/01/2016
B        N      06/10/2017
C        Y      08/15/2017
D        N      08/20/2017
E        Y      09/05/2017
F        N      10/20/2018

I need to group the report into 3 groups based on the parameter values,
For example, the user runs the report would enter: @DateFrom = 08/1/2017  @DateTo: 08/31/2017
=> The report should look like below:

Group Current Range ExpiryDate  [(ExpiryDate >= @DateFrom and ExpiryDate <=@DateTo)  and Check = @Check ]

C        Y      08/15/2017
D        N      08/20/2017

Group Before Range ExpiryDate and Check = 'Y'  [(ExpiryDate <= @DateFrom) and Check = 'Y']

A        Y      05/01/2016

Group After Range ExpiryDate and Check = 'Y' [(ExpiryDate >= @DateTo) and Check = 'Y']

E       Y       09/05/2017

In the tablix using the Main dataset (only one tablix in the report), there is one RowGroup named 'Details'

I read lots of arcticles and I tried many ways, but nothing worked as I could not find the right way I guess.  Will you be able to help?

Body:
The easiest way to create another group is to modify the SQL and add another column with your grouping logic.

SELECT
  ....,
  CASE
    WHEN ExpiryDate BETWEEN @DateFrom AND @DateTo AND Check = @Check
    THEN 'Current'
    WHEN ExpiryDate <= @DateFrom AND Check = 'Y'
    THEN 'Before'
    WHEN ExpiryDate >= @DateTo AND Check = 'Y'
    THEN 'After'
  END as MyGroup,
  ...
FROM ...

so that you can create a parent group inside your tablix with the new custom grouping field.

OR if the SQL is very complex or you are using a shared dataset/stored procedure, then add a group to the SSRS tablix and specify a custom expression with similar logic using the SWITCH construct.

Edit, adding parameters to the SQL CASE

CASE
  WHEN expirydate BETWEEN @DateFrom AND @DateTo AND [check] IN @check
  THEN 'Current'
  WHEN expirydate <= @FromDate AND [check] = 'Y'
  THEN 'Before'
  WHEN expirydate >= @FromDate and [check] = 'Y'
  THEN 'After'
END as MyGroup

Note that check is only surrounded by square brackets because it's a reserved SQL keyword.


问:
SAS Macros for plotting
I'm trying to make some plots. I need to make 19 scatter plots with the names in verf_typ_nmes substituted into the data and proc steps one at a time then executed. I've researched Google and thought I copied correctly but no good.

Errors I'm getting:
"Expected %TO not found in %DO statement"
 ERROR: A dummy macro will be compiled.

```<code>%macro Multiplot();
  %do verf_typ_nmes =  BDPREP, BRCODE, CONTNT, COPAL, CURSRY,
                       DFTEST,DOCPST,DSMS,LABEL,MAILING,
                       MAILPC,MERLIN,MMS,MPCV,PRESRT,PVDS,
                       SHPAID,TAP,WEIGHT;
   data &verf_typ_nmes;
     set vol_verfns_prime;
     where verif_type="&verf_typ_nmes";
   RUN;
   proc sgscatter data=&verf_typ_nmes;
     plot verif_pstg*(t_v tfev mlgs fsp avpm);
   run;
   %end;
 %mend;
</code>```

答:
The %DO statement is not as powerful as the DO statement.

Why not just use a BY statement?

```<code>proc sgscatter data=vol_verfns_prime;
  by verif_type ;
  where verif_type in ('BDPREP' 'BRCODE' ..... );
  plot verif_pstg*(t_v tfev mlgs fsp avpm);
run;
</code>```

If you do need to loop over a list of names then put the list in a macro variable and use %scan() to pull out the values one by one.

```<code>%let list=
   BDPREP BRCODE CONTNT COPAL CURSRY DFTEST DOCPST DSMS LABEL
   MAILING MAILPC MERLIN MMS MPCV PRESRT PVDS SHPAID TAP WEIGHT
;
%do i=1 %to %sysfunc(countw(&list));
  ...
   where verif_type="%scan(&list,&i)";
  ...
%end;
</code>```

Don't use comma as your delimiter in lists if you can avoid it. Commas will make it harder to use your list in function and macro calls.

Title: SAS Macros for plotting

Body:
I'm trying to make some plots. I need to make 19 scatter plots with the names in verf_typ_nmes substituted into the data and proc steps one at a time then executed. I've researched Google and thought I copied correctly but no good.

Errors I'm getting:
"Expected %TO not found in %DO statement"
 ERROR: A dummy macro will be compiled.

%macro Multiplot();
  %do verf_typ_nmes =  BDPREP, BRCODE, CONTNT, COPAL, CURSRY,
                       DFTEST,DOCPST,DSMS,LABEL,MAILING,
                       MAILPC,MERLIN,MMS,MPCV,PRESRT,PVDS,
                       SHPAID,TAP,WEIGHT;
   data &verf_typ_nmes;
     set vol_verfns_prime;
     where verif_type="&verf_typ_nmes";
   RUN;
   proc sgscatter data=&verf_typ_nmes;
     plot verif_pstg*(t_v tfev mlgs fsp avpm);
   run;
   %end;
 %mend;

Body:
The %DO statement is not as powerful as the DO statement.

Why not just use a BY statement?

proc sgscatter data=vol_verfns_prime;
  by verif_type ;
  where verif_type in ('BDPREP' 'BRCODE' ..... );
  plot verif_pstg*(t_v tfev mlgs fsp avpm);
run;

If you do need to loop over a list of names then put the list in a macro variable and use %scan() to pull out the values one by one.

%let list=
   BDPREP BRCODE CONTNT COPAL CURSRY DFTEST DOCPST DSMS LABEL
   MAILING MAILPC MERLIN MMS MPCV PRESRT PVDS SHPAID TAP WEIGHT
;
%do i=1 %to %sysfunc(countw(&list));
  ...
   where verif_type="%scan(&list,&i)";
  ...
%end;

Don't use comma as your delimiter in lists if you can avoid it. Commas will make it harder to use your list in function and macro calls.


问:
Order a column based on another column
I want to order Column A based on the values of Column B.

In Google Sheets that is simply: =SORT(A1:A100,B1:B100,TRUE)

How to do that in Excel?

答: This is the manual method in an animated form:

ContentLicense: CC BY-SA 4.0

Title: Order a column based on another column


问:
JavaScript regular expression check number only
I want a regular expression for the following values:

```<code>1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.
</code>```

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

答:
you were puting the dot in the wrong place this should work </p>

```<code>[\+\-]?[0-9]+(\.[0-9]+(?:[Ee][\+\-]?[0-9]+)?)?
</code>```

Body:
I want a regular expression for the following values:

1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

Body:
you were puting the dot in the wrong place this should work

[\+\-]?[0-9]+(\.[0-9]+(?:[Ee][\+\-]?[0-9]+)?)?


问:
mongoldb compare time with now and delete some
I have the following data.

```<code>id:27199997
condition:"in_progress"
date:2017-11-17 19:06:36.820

id:27199998
condition:"in_progress"
date:2017-11-17 20:07:36.820

id:27199999
condition:"in_progress"
date:2017-11-17 21:09:36.820
</code>```

From this I want to delete dates with date > 1 hour from now

I've tried like db.collection.find_one({"condition": "in_progress", "date":{ "$gt": last }})

btw

```<code>now = datetime.datetime.now()

last = datetime.datetime.now() + datetime.timedelta(days=0, hours=1)
</code>```

答:
As far as I understood your question, you should have used lt instead of gt and - instead of +</p>

```<code>last = datetime.datetime.now() - datetime.timedelta(days=0, hours=1)
db.collection.find_one({"condition": "in_progress", "date":{ "$lt": last }})
</code>```

Body:
I have the following data.

id:27199997
condition:"in_progress"
date:2017-11-17 19:06:36.820

id:27199998
condition:"in_progress"
date:2017-11-17 20:07:36.820

id:27199999
condition:"in_progress"
date:2017-11-17 21:09:36.820

From this I want to delete dates with date > 1 hour from now

I've tried like db.collection.find_one({"condition": "in_progress", "date":{ "$gt": last }})

btw

now = datetime.datetime.now()

last = datetime.datetime.now() + datetime.timedelta(days=0, hours=1)

Body:
As far as I understood your question, you should have used lt instead of gt and - instead of +

last = datetime.datetime.now() - datetime.timedelta(days=0, hours=1)
db.collection.find_one({"condition": "in_progress", "date":{ "$lt": last }})


问:
How do I apply code to all files within a folder?
I'm relatively new to programming, but created a c script to rotate images and create a copy of them. However, I was hoping to apply it to a large number of files, so I was wondering if there was a way to apply a program / function to all images within a specific folder. Thanks!</p>

答:
If the program gets the filenames to process in its command line arguments (the argv parameter to main()), you can use a wildcard in the command line when you run it:

```<code>yourprogram /path/to/directory/*
</code>```

The program should simply loop through all the filenames in argv.

If it can only process one file at a time, you can use a shell loop:

for file in /path/to/directory/*
do
    yourprogram "$file"
done
```

Body:
If the program gets the filenames to process in its command line arguments (the argv parameter to main()), you can use a wildcard in the command line when you run it:

yourprogram /path/to/directory/*

The program should simply loop through all the filenames in argv.

If it can only process one file at a time, you can use a shell loop:

for file in /path/to/directory/*
do
    yourprogram "$file"
done


问:
Querying JSON nested array object in SQL
I have the following JSON and i need to query only the name property values.

```<code>DECLARE @j NVARCHAR(4000) = N'{
   "ArrayValue":[
        {
            "name": "XXX",
            "value": 10
        },
        {
            "name": "Memory123",
            "value": 20
        }
    ]
}'
</code>```

Following is what i get with OPENJSON()

```<code>SELECT value as Name
FROM OPENJSON(@j, '$.ArrayValue')
</code>```

Whcih will get the following output.

```<code>Name
---------------------------------------------------
{              "name": "Memory"          }
{              "name": "Memory123"          }
</code>```

However I need the output in the following format.

```<code>Name
-----
Memory
Memory123
</code>```

Is there any simpler way without using replace?

答:
You can define ArrayValue as a JSON column, then use CROSS APPLY to get the name values. Here's an example:</p>

```<code>DECLARE @j NVARCHAR(4000) = N'{
   "ArrayValue":[
        {
            "name": "XXX",
            "value": 10
        },
        {
            "name": "Memory123",
            "value": 20
        }
    ]
}'
SELECT b.name
FROM OPENJSON(@j)
WITH (ArrayValue NVARCHAR(MAX) AS JSON) AS a
CROSS APPLY OPENJSON(a.ArrayValue)
WITH ([name] NVARCHAR(100)) AS b
</code>```

Body:
I have the following JSON and i need to query only the name property values.

DECLARE @j NVARCHAR(4000) = N'{
   "ArrayValue":[
        {
            "name": "XXX",
            "value": 10
        },
        {
            "name": "Memory123",
            "value": 20
        }
    ]
}'

Following is what i get with OPENJSON()

SELECT value as Name
FROM OPENJSON(@j, '$.ArrayValue')

Whcih will get the following output.

Name
---------------------------------------------------
{              "name": "Memory"          }
{              "name": "Memory123"          }

However I need the output in the following format.

Name
-----
Memory
Memory123

Is there any simpler way without using replace?

Body:
You can define ArrayValue as a JSON column, then use CROSS APPLY to get the name values. Here's an example:

DECLARE @j NVARCHAR(4000) = N'{
   "ArrayValue":[
        {
            "name": "XXX",
            "value": 10
        },
        {
            "name": "Memory123",
            "value": 20
        }
    ]
}'
SELECT b.name
FROM OPENJSON(@j)
WITH (ArrayValue NVARCHAR(MAX) AS JSON) AS a
CROSS APPLY OPENJSON(a.ArrayValue)
WITH ([name] NVARCHAR(100)) AS b


问:
Output of a PowerShell command doesn't show result until after Write-Host and Read-Host
Code will not return the results of the Get-ADUser command until after I hit a carriage return at the end of the code

```<code>    Write-Host "Please enter the user account name. Ex. jsmith1" -ForegroundColor Yellow -BackgroundColor Black
$Username = Read-Host
"`n"

Write-Host "Is this the correct username?  $Username" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue1 = Read-Host

IF ($Continue1 -eq 1)
{
  Get-ADUser -Server "contoso.com" -filter * -Properties * | Where {$_.SamAccountName -match $Username} | Select DisplayName, SamAccountName, EmployeeID, EmployeeNumber
}
ELSE
{}

Write-Host "Would you like to update the Employee ID and the Employee Number?" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue2 = Read-Host
</code>```

What am I missing here?

答:
The Write-Host items are immediately displayed during the execution of your command.

The Get-ADUser results are on the output pipeline.

Normally this allows you to return the value into another script, for example, for further processing.  Since you don't assign it or capture the output, it simply goes to a default formatter and displays after everything else before the execution ends.

If you really and truly just want to display the output, you can add | Write-Host to the end of your Get-ADUser call.  If you ever want to connect this to another script, you can capture the value to a variable, then both Write-Host, and then Write-Output to add it back on the pipeline.

See also: Understanding the Windows PowerShell Pipeline

Body:
Code will not return the results of the Get-ADUser command until after I hit a carriage return at the end of the code

    Write-Host "Please enter the user account name. Ex. jsmith1" -ForegroundColor Yellow -BackgroundColor Black
$Username = Read-Host
"`n"

Write-Host "Is this the correct username?  $Username" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue1 = Read-Host

IF ($Continue1 -eq 1)
{
  Get-ADUser -Server "contoso.com" -filter * -Properties * | Where {$_.SamAccountName -match $Username} | Select DisplayName, SamAccountName, EmployeeID, EmployeeNumber
}
ELSE
{}

Write-Host "Would you like to update the Employee ID and the Employee Number?" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue2 = Read-Host

What am I missing here?


问:
google app engine load balancing
I have a paid app on google app engine. As you all know, google will charge you for your instance hours.

The only thing I was not able to understand is, what is the logic that causes google to warm another instance, or how do they decide how to load balancing the traffic between those instances.

As you can see from the screenshot of the appengine instances screen (sorry for the link, I am new to stackoverflow, and was not allowed to post an actual image), in order to make sure that my users won't suffer from a long load request, I have one instance resident at all times.

The funny thing about it is, that it appears that none of the traffic is getting to the resident instance, all the traffic is actually going to one of the dynamic instances. Moreover, let's assume that according to their load balancing algorithm that dynamic instance is overwhelmed, instead of directing traffic to the resident instance, they warmed up another dynamic instance which appears to not get that much traffic either.

If I was not paying for the tripple instance hours, I wouldn't care. Unfortunately, I need to pay for these hours :)

I will appreciate it if anyone can share some more light regarding the following:

1. How does the load balancing of GAE works?

2. What can I do to get a better distribution of the traffic on my instances (and by that reduce the amount of dynamic instances at a given time)

Thanks for the help!

答:
This documentation page explains how the App Engine scheduler works. And this other page teaches what parameters can be changed to control performances.

However we are working on improving the scheduling behavior. Stay tuned by following the Google Cloud Platform blog. (I work on App Engine)

Title: google app engine load balancing


问:
How to check if a uiimage is blank? (empty, transparent)
which is the best way to check whether a UIImage is blank?

I have this painting editor which returns a UIImage; I don't want to save this image if there's nothing on it.

答:
One idea would be to call UIImagePNGRepresentation to get an NSData object then compare it with a pre-defined 'empty' version - ie: call:

```<code>- (BOOL)isEqualToData:(NSData *)otherData
</code>```

to test?

Not tried this on large data; might want to check performance, if your image data is quite large, otherwise if it's small it is probably just like calling memcmp() in C.

Body:
One idea would be to call UIImagePNGRepresentation to get an NSData object then compare it with a pre-defined 'empty' version - ie: call:

- (BOOL)isEqualToData:(NSData *)otherData

to test?

Not tried this on large data; might want to check performance, if your image data is quite large, otherwise if it's small it is probably just like calling memcmp() in C.


问:
CSS wrap behaviour white-space
I have the following:

I don't want to break the tags, so I specified the white-space: nowrap option to the span. However, now I have the following problem: the line doesn't break at all.

How can I fix this?

Relevant HTML:

   test ....
	```

答:
Add the following style to .library-tags:

.library-tags {
  display: inline-block;
  float: left
}
```

Title: CSS wrap behaviour white-space


问:
How to determine the type of credit card?
For a school assignment I'm trying to determine the type of credit card a user has when they type in their card number. A master card starts with 51-55. Extra zeros in front of that number would be considered valid. I've reviewed other threads on how to integrate this into python and although I could just copy and paste the code I still don't really understand whats going on or how they bypass the zeroes in front?

Heres an example of the Master card code to do this:

```<code>^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$
</code>```

Could anyone explain to me what is going on? Thank you for your time.

答:
What you posted is regex, not python.

Intro:

Regex is a sequence of characters that specify a search patter. The string can be used by various searching algorithms to perform find, find and replace, or match operations on strings.

Major languages all have ways to evaluate regex.
For python see: https://docs.pytho.org/3/howto/regex.html

Understanding that regex

Some basic regex rules that would help someone understand the given pattern:

[] marks a list of characters, one of which must be present in that position for a match to be made.  Ex: 'asdf[a-fz]'  would match 'asdfe' or 'asdfz' but not 'asdfg'

The pipe "|" marks as others said "a branch".  It basically means "or".  Ex: 'I (am|was) happy' would match 'I am happy' and 'I was happy' but not 'I am not happy' or "I be happy".

Lastly {} is a quantifier.  It means, "there must be between X and Y occurances of the previous character".  So "[0-9]{2,4}" would match "12" and "1234" but not "1", "12345", or "cats".  If you don't specify the right number, ex {3,} it means there's no limit.  So "[0-9]{3,}" would match "12341234123412341234123412341234".

So the expression is basically intended to check a lot of things, among which, that the number starts with 5, 222, 22, 2, 27, or 2720.  As stated in comments it doesn't properly check that it "starts" with those numbers because there isn't a ^ after each "|"(or), so it just says "Does it start with 5, or contain 222, 22, 2, 27, or 2720.".

Results of expression:

See: http://regexr.com/3h78i
Or see:

Correction

This expression has many fewer false positives:

```<code>^(5[1-5][0-9]{5,5}|222[1-9][0-9]{3,3}|22[3-9][0-9]{4,4}|2[3-6][0-9]{5,5}|27[01][0-9]{4,4}|2720[0-9]{3,3})\d{9}$
</code>```

See: http://regexr.com/3h78l or:

Edit: My correction assumes credit cards are 16 digits. If this is a problem you can fix this by changing the {}'s back, and removing the \d{9} from the end.  Or just by changing \d{9} to \d+.

Alternative

My personal choice of method for determining credit card type is pycard: https://github.com/orokusaki/pycard

This is one of those things where I'd rather not personally be responsible for maintaining a list of rules that may potentially change and ensuring accurate detection.  The linked library is open source, and the guy who made it has been has been active in merging pull requests made by people suggesting improvements to the library up until the time or writing.  If it ever were to become stale and you needed a change you could just fork it.

Body:
For a school assignment I'm trying to determine the type of credit card a user has when they type in their card number. A master card starts with 51-55. Extra zeros in front of that number would be considered valid. I've reviewed other threads on how to integrate this into python and although I could just copy and paste the code I still don't really understand whats going on or how they bypass the zeroes in front?

Heres an example of the Master card code to do this:

^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$

Could anyone explain to me what is going on? Thank you for your time.

Body:
What you posted is regex, not python.

Intro:

Regex is a sequence of characters that specify a search patter. The string can be used by various searching algorithms to perform find, find and replace, or match operations on strings.

Major languages all have ways to evaluate regex.
For python see: https://docs.pytho.org/3/howto/regex.html

Understanding that regex

Some basic regex rules that would help someone understand the given pattern:

[] marks a list of characters, one of which must be present in that position for a match to be made.  Ex: 'asdf[a-fz]'  would match 'asdfe' or 'asdfz' but not 'asdfg'

The pipe "|" marks as others said "a branch".  It basically means "or".  Ex: 'I (am|was) happy' would match 'I am happy' and 'I was happy' but not 'I am not happy' or "I be happy".

Lastly {} is a quantifier.  It means, "there must be between X and Y occurances of the previous character".  So "[0-9]{2,4}" would match "12" and "1234" but not "1", "12345", or "cats".  If you don't specify the right number, ex {3,} it means there's no limit.  So "[0-9]{3,}" would match "12341234123412341234123412341234".

So the expression is basically intended to check a lot of things, among which, that the number starts with 5, 222, 22, 2, 27, or 2720.  As stated in comments it doesn't properly check that it "starts" with those numbers because there isn't a ^ after each "|"(or), so it just says "Does it start with 5, or contain 222, 22, 2, 27, or 2720.".

Results of expression:

See: http://regexr.com/3h78i
Or see:

Correction

This expression has many fewer false positives:

^(5[1-5][0-9]{5,5}|222[1-9][0-9]{3,3}|22[3-9][0-9]{4,4}|2[3-6][0-9]{5,5}|27[01][0-9]{4,4}|2720[0-9]{3,3})\d{9}$

See: http://regexr.com/3h78l or:

Edit: My correction assumes credit cards are 16 digits. If this is a problem you can fix this by changing the {}'s back, and removing the \d{9} from the end.  Or just by changing \d{9} to \d+.

Alternative

My personal choice of method for determining credit card type is pycard: https://github.com/orokusaki/pycard

This is one of those things where I'd rather not personally be responsible for maintaining a list of rules that may potentially change and ensuring accurate detection.  The linked library is open source, and the guy who made it has been has been active in merging pull requests made by people suggesting improvements to the library up until the time or writing.  If it ever were to become stale and you needed a change you could just fork it.


问:
Not opening IDE as Admin causes FileStream throw access to the path is denied exception
As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.</p>

```<code> try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

           //The following line causes an exception.

                using (var stream = new FileStream(path,
                    FileMode.CreateNew, FileAccess.Write).Encrypt())
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
                        jsonWriter.Formatting = Formatting.Indented;
                        protocolJObject.WriteTo(jsonWriter);
                    }
                }
                return ReturnCodes.Success;
            }
            catch (UnauthorizedAccessException ex)
            {
                SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
                returnValue = ReturnCodes.FileAccessDenied;
            }
</code>```

答:
Your user account doesn't have permission to write to the C:\ drive of your computer but admin does.

You can give yourself permission by right clicking on the C:\ drive in windows explorer, select properties and then the security tab and give your account write access.

Alternatively, use a better location

Body:
As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.

 try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

           //The following line causes an exception.

                using (var stream = new FileStream(path,
                    FileMode.CreateNew, FileAccess.Write).Encrypt())
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
                        jsonWriter.Formatting = Formatting.Indented;
                        protocolJObject.WriteTo(jsonWriter);
                    }
                }
                return ReturnCodes.Success;
            }
            catch (UnauthorizedAccessException ex)
            {
                SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
                returnValue = ReturnCodes.FileAccessDenied;
            }


问:
Finding number of dlopen calls of an ELF binary in C
I would like to analyze an ELF binary file and figure out how many calls to dlopen() it makes in C, are there any libraries that can do this? Or how would I go about finding the count?</p>

答:
You could simply use ltrace:

Example:

```<code>#include <dlfcn.h>
#include <stdio.h>
int main(int C, char **V)
{
    char **a = V+1;
    while(*a){
        void *h;
        if(0==(h=dlopen(*a++, RTLD_LAZY)))
            fprintf(stderr, "%s\n", dlerror());
    }

}
</code>```

Compile it:

```<code>$ gcc example.c -fpic -pie
</code>```

Invoke it on self and count dlopen calls:

```<code>$ ltrace -o /dev/fd/3 \
  ./a.out ./a.out ./a.out ./a.out 3>&1 >/dev/null| \
  grep ^dlopen\( -c
3
</code>```

Body:
You could simply use ltrace:

Example:

#include <dlfcn.h>
#include <stdio.h>
int main(int C, char **V)
{
    char **a = V+1;
    while(*a){
        void *h;
        if(0==(h=dlopen(*a++, RTLD_LAZY)))
            fprintf(stderr, "%s\n", dlerror());
    }

}

Compile it:

$ gcc example.c -fpic -pie

Invoke it on self and count dlopen calls:

$ ltrace -o /dev/fd/3 \
  ./a.out ./a.out ./a.out ./a.out 3>&1 >/dev/null| \
  grep ^dlopen\( -c
3


问:
Pass data to TabBar Controller
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

```<code>import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Second ViewController:

```<code>import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

答:
I'm not recommending that you do it this way.  This is an explanation for understanding.

The viewControllers in a tabBarController know their tabBarController.  You can access it with self.tabBarController.

The secondViewController is the second one in the list of viewControllers so let second = tabBarController.viewControllers?[1] as? SecondViewController.

If you haven't visited the secondViewController yet, its view will not have loaded, so the outlets will still be nil.  You can force the view to load with _ = second.view.

If you want to switch to the second tab, then you need to use tabBarController.selectedIndex = 1.

```<code>@IBAction func enter(_ sender: Any) {
    if textField.text != "" {
        if let tabBarController = self.tabBarController as? UITabBarController, let second = tabBarController.viewControllers?[1] as? SecondViewController {
            // make sure view has loaded
            _ = second.view

            second.label.text = textField.text

            // change to second tab
            tabBarController.selectedIndex = 1
        }
    }
}
</code>```

A better way...

Instead of setting the outlet directly, you should instead pass the string to a property of the SecondViewController:

```<code>second.myString = textField.text ?? ""
</code>```

and then assign that string to the label in an override of viewWillAppear.

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    label.text = myString
}
</code>```

The reason to set it in viewWillAppear is that viewWillAppear will run every time before the view is displayed.  viewDidLoad will only run once when the view is first loaded.  Since you want the functionality to work multiple times, viewWillAppear is the correct override.

Title: Pass data to TabBar Controller

Body:
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Second ViewController:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Body:
I'm not recommending that you do it this way.  This is an explanation for understanding.

The viewControllers in a tabBarController know their tabBarController.  You can access it with self.tabBarController.

The secondViewController is the second one in the list of viewControllers so let second = tabBarController.viewControllers?[1] as? SecondViewController.

If you haven't visited the secondViewController yet, its view will not have loaded, so the outlets will still be nil.  You can force the view to load with _ = second.view.

If you want to switch to the second tab, then you need to use tabBarController.selectedIndex = 1.

@IBAction func enter(_ sender: Any) {
    if textField.text != "" {
        if let tabBarController = self.tabBarController as? UITabBarController, let second = tabBarController.viewControllers?[1] as? SecondViewController {
            // make sure view has loaded
            _ = second.view

            second.label.text = textField.text

            // change to second tab
            tabBarController.selectedIndex = 1
        }
    }
}

A better way...

Instead of setting the outlet directly, you should instead pass the string to a property of the SecondViewController:

second.myString = textField.text ?? ""

and then assign that string to the label in an override of viewWillAppear.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    label.text = myString
}

The reason to set it in viewWillAppear is that viewWillAppear will run every time before the view is displayed.  viewDidLoad will only run once when the view is first loaded.  Since you want the functionality to work multiple times, viewWillAppear is the correct override.


问:
Vim iskeyword doesn't work
my iskeyword is iskeyword=@,48-57,_,192-255,(,),=,[,],<,>,:
 but when i'm using ctrl+arrows vim jumps only to spaces, but not others symbols.

答:
Actually, I think you want brackets or parentheses excluded from word selection.

So what you want to do, is removing ( ) { } from iskeyword.

I have tried the following in my .vimrc and it seems to work (wor * does not include ():

set iskeyword-={,},[,],(,)

(The important character here is -which means these characters should be removed fromiskeyword)

By default iskeyword only includes digit and letters so it should not be necessary to remove them explicitly but a plugin might be messing iskeyword definition.

Title: Vim iskeyword doesn't work