问:
GIT: Add author, date create/modified to a file
I need to create a universal script that will add this information to each file when it is saved, as in such text editors like Atom orWebStorm.

Information for add:

File creation date;

Date of last file update;

Project branch;

Author.

Example of this table

Here is an example of the code I created with the shell.

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

# Abort if any of the commands fail
set -e
# Trace what gets executed. Useful for debugging.
set -x
# If set, the return value of a pipeline is the value of the last (rightmost) command to
#exit with a non-zero status, or zero if all commands in the pipeline exit successfully.
set -o pipefail
# Treat unset variables as an error when performing parameter expansion.
# If expansion is attempted on an unset variable, the shell prints an error message,
# and, if not interactive, exits with a non-zero status.
set -u

 # Created:
DATE=$(date +%Y-%m-%d:%H:%M:%S);
BRANCH=$(git symbolic-ref --short -q HEAD);
GIT_USER=$(git config user.name);
CREATED=$(echo 'created');

# Updated:
DATE_U=$(git log -1 --format=%cd --date=format:%Y-%m-%d:%H:%M:%S);
BRANCH_U=$(git symbolic-ref --short -q HEAD);
GIT_USER_U=$(git config user.name);
UPDATED=$(echo 'updated');

# Find file (js) and add table to file.
echo "Create table in js-file..."
if test -a $(grep created: ./development/*.js); then
  sudo find ./development -name "*.js" -type f -exec sed -i 1i\ "/*flow*/\n/*---------------------------------------------------------\n $CREATED: $DATE | $BRANCH | $GIT_USER \n $UPDATED: $DATE_U | $BRANCH_U | $GIT_USER_U \n---------------------------------------------------------*/" {} \;
  echo "Create table..."
else
  echo "Table already is exist..."
fi

# Find file (scss) and add to file.
echo "Create table in scss-file..."
if test -a $(grep created: ./development/*.scss); then
  sudo find ./development -name "*.scss" -type f -exec sed -i 1i\ "/*---------------------------------------------------------\n $CREATED: $DATE | $BRANCH | $GIT_USER \n $UPDATED: $DATE_U | $BRANCH_U | $GIT_USER_U \n---------------------------------------------------------*/" {} \;
  echo "Create table..."
else
  echo "Table already is exist..."
fi
</code>```

In the commands for adding a table, there is a drawback, after the first addition to the file, this table no longer works on files that were created later or the table in them was deleted.

And the second problem is the dynamic update of information in files.

```<code># Updated
echo "Update date area..."
if test ! -a $DATE_U;
  then
  echo "Date is exist..."
else
  echo "Update date..."
fi

echo "Update branch area..."
if test ! -a $BRANCH_U;
  then
  echo "Branch is exist..."
else
  echo "Update branch..."
fi

echo "Update user area..."
if test ! -a $GIT_USER;
  then
  echo "User is exist..."
else
  echo "Update user..."
fi
</code>```

答:
Do you really need to have those meta-data available in the file?

Having meta-data in file is usually an old habit from old centralized SCMs.

But in git, as you need to clone the whole repo locally, you have direct access to all the meta-data.

So you can simply access them when you need them by doing:

```<code># Data of first commit of file
git log -1 --diff-filter=A --format='%an | %aI | %h' -- path/to/file

# Data of last commit of file
git log -1 --format='%an | %aI | %h' -- path/to/file
</code>```

If you really want to get them in your file, the recommended way is to use keyword-expansion (just like CVS or SVN used to do).

But, it won't solve the necessity to add the placeholders in each files.

If you want to enforce the header creation with placeholders, you will need to use another clean filter to modify files on-the-fly when staging them (see Can you change a file content during git commit?).

But, you will have to deploy and force use of this filter on all git client interacting with your repository.

You can reject publishing commits modifying a file without header by using server-side hooks.

Body:
I need to create a universal script that will add this information to each file when it is saved, as in such text editors like Atom orWebStorm.

Information for add:

File creation date;

Date of last file update;

Project branch;

Author.

Example of this table

Here is an example of the code I created with the shell.

#! /bin/bash

# Abort if any of the commands fail
set -e
# Trace what gets executed. Useful for debugging.
set -x
# If set, the return value of a pipeline is the value of the last (rightmost) command to
#exit with a non-zero status, or zero if all commands in the pipeline exit successfully.
set -o pipefail
# Treat unset variables as an error when performing parameter expansion.
# If expansion is attempted on an unset variable, the shell prints an error message,
# and, if not interactive, exits with a non-zero status.
set -u

 # Created:
DATE=$(date +%Y-%m-%d:%H:%M:%S);
BRANCH=$(git symbolic-ref --short -q HEAD);
GIT_USER=$(git config user.name);
CREATED=$(echo 'created');

# Updated:
DATE_U=$(git log -1 --format=%cd --date=format:%Y-%m-%d:%H:%M:%S);
BRANCH_U=$(git symbolic-ref --short -q HEAD);
GIT_USER_U=$(git config user.name);
UPDATED=$(echo 'updated');

# Find file (js) and add table to file.
echo "Create table in js-file..."
if test -a $(grep created: ./development/*.js); then
  sudo find ./development -name "*.js" -type f -exec sed -i 1i\ "/*flow*/\n/*---------------------------------------------------------\n $CREATED: $DATE | $BRANCH | $GIT_USER \n $UPDATED: $DATE_U | $BRANCH_U | $GIT_USER_U \n---------------------------------------------------------*/" {} \;
  echo "Create table..."
else
  echo "Table already is exist..."
fi

# Find file (scss) and add to file.
echo "Create table in scss-file..."
if test -a $(grep created: ./development/*.scss); then
  sudo find ./development -name "*.scss" -type f -exec sed -i 1i\ "/*---------------------------------------------------------\n $CREATED: $DATE | $BRANCH | $GIT_USER \n $UPDATED: $DATE_U | $BRANCH_U | $GIT_USER_U \n---------------------------------------------------------*/" {} \;
  echo "Create table..."
else
  echo "Table already is exist..."
fi

In the commands for adding a table, there is a drawback, after the first addition to the file, this table no longer works on files that were created later or the table in them was deleted.

And the second problem is the dynamic update of information in files.

# Updated
echo "Update date area..."
if test ! -a $DATE_U;
  then
  echo "Date is exist..."
else
  echo "Update date..."
fi

echo "Update branch area..."
if test ! -a $BRANCH_U;
  then
  echo "Branch is exist..."
else
  echo "Update branch..."
fi

echo "Update user area..."
if test ! -a $GIT_USER;
  then
  echo "User is exist..."
else
  echo "Update user..."
fi

Body:
Do you really need to have those meta-data available in the file?

Having meta-data in file is usually an old habit from old centralized SCMs.

But in git, as you need to clone the whole repo locally, you have direct access to all the meta-data.

So you can simply access them when you need them by doing:

# Data of first commit of file
git log -1 --diff-filter=A --format='%an | %aI | %h' -- path/to/file

# Data of last commit of file
git log -1 --format='%an | %aI | %h' -- path/to/file

If you really want to get them in your file, the recommended way is to use keyword-expansion (just like CVS or SVN used to do).

But, it won't solve the necessity to add the placeholders in each files.

If you want to enforce the header creation with placeholders, you will need to use another clean filter to modify files on-the-fly when staging them (see Can you change a file content during git commit?).

But, you will have to deploy and force use of this filter on all git client interacting with your repository.

You can reject publishing commits modifying a file without header by using server-side hooks.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Generate all possible choices of elements each from a distinct set
Suppose that we have k sets each of which contains q elements. I want to generate all possible sets in which we select exactly 1 element from each set. Assume that the sets are represented as a table where each row is a set and its columns are its elements. Also assume that all elements are indexed row-wise like this

Set 1: 1 2 3

Set 2: 4 5 6

Set 3: 7 8 9

The thing is that k,q may vary so I cannot use nested for loops. I work in C++ and this structure is actually a std::vector of std::vector of int, but I am not asking for code here, just an idea on how to do this.

答:
A hard coded solution would be

```<code>for (int a1 : v[0]) {
  for (int a2 : v[1]) {
    for (int a3 : v[2]) {
      for (int a4 : v[3]) {
        for (int a5 : v[4]) {
            do_job(a1, a2, a3, a4, a5);
        }
      }
    }
  }
}
</code>```

To make it generic, you may do:

```<code>bool increase(const std::vector<std::set<int>>& v,
              std::vector<std::set<int>::iterator>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] == v[index].end()) {
            it[index] = v[index].begin();
        } else {
            return true;
        }
    }
    return false;
}

template <typename F>
void iterate(const std::vector<std::set<int>>& v, F&& do_job)
{
    std::vector<std::set<int>::iterator> its;
    its.reserve(v.size());
    for (auto& s : v) {
        its.push_back(s.begin());
    }

    do {
        do_job(its);
    } while (increase(v, its));
}
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Body:
A hard coded solution would be

for (int a1 : v[0]) {
  for (int a2 : v[1]) {
    for (int a3 : v[2]) {
      for (int a4 : v[3]) {
        for (int a5 : v[4]) {
            do_job(a1, a2, a3, a4, a5);
        }
      }
    }
  }
}

To make it generic, you may do:

bool increase(const std::vector<std::set<int>>& v,
              std::vector<std::set<int>::iterator>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] == v[index].end()) {
            it[index] = v[index].begin();
        } else {
            return true;
        }
    }
    return false;
}

template <typename F>
void iterate(const std::vector<std::set<int>>& v, F&& do_job)
{
    std::vector<std::set<int>::iterator> its;
    its.reserve(v.size());
    for (auto& s : v) {
        its.push_back(s.begin());
    }

    do {
        do_job(its);
    } while (increase(v, its));
}

Demo


问:
How to assign value to directive using javascript code?
Hi I am developing angularjs application. I am doing validation for textbox. I am doing range validation. textbox should accept numbers within the specified range. I have developed directive for this purpose. I am assigning value as range-number="10,4096". Instead of assigning value in this tag i want to assign in angularjs code.

Below is my html.

```<code>  <div class="inputblock" ng-class="{ 'has-error' : ((form5.$submitted && form5.DownPayment.$invalid )|| (form5.DownPayment.$invalid && form5.DownPayment.$dirty))}">
                        <div>
                            <span class="ang-error" style="color:#fff" ng-show="form5.DownPayment.$dirty && form5.DownPayment.$invalid  && form5.DownPayment.$error.rangeNumber">
                                <span ng-show="form5.DownPayment.$invalid && form5.DownPayment.$dirty">Invalid</span>
                            </span>
                        </div>
                        <input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">
                    </div>
</code>```

Below is my js code.

```<code>app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = attrs.rangeNumber.split(',').map(Number);
            ctrl.$validators.rangeNumber = function (value) {
                return value >= range[0] && value <= range[1];
            };
        }
    };
});
</code>```

May i know how can i do this? Any help would be appreciated. Thank you.

答:
I hope this will solve your problem

```<code>app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = scope.$eval(attrs.rangeNumber);
            range = range.split(',').map(Number);

            ctrl.$parsers.push(function(value) {
              value = +value;
              var isValidRange = !(value >= range[0] && value <= range[1]);
              ctrl.$setValidity('range', isValidRange);

              return value;
          });
        }
    };
});
</code>```

Controller

```<code>$scope.range = '1,4096';
// or you can make it array, but in that case you have to remove split
//and map functions from the directive
$scope.range = [1, 4096];
</code>```

HTML

```<code><input class="" type="text" name="rangeNumber" ng-attr-placeholder="{{ 'DownPayment' }}" ng-model="DownPayment"  range-number="range">
<p ng-show="!sampleForm.rangeNumber.$invalid && sampleForm.rangeNumber.$dirty">Number not in range</p>
</code>```

https://jsfiddle.net/yordan_nikolov/pwejm6de/

Edited

Body:
Hi I am developing angularjs application. I am doing validation for textbox. I am doing range validation. textbox should accept numbers within the specified range. I have developed directive for this purpose. I am assigning value as range-number="10,4096". Instead of assigning value in this tag i want to assign in angularjs code.

Below is my html.

                                Invalid

                        <input class="" type="text" name="DownPayment" placeholder="{{ 'DownPayment' | translate }}" ng-model="DownPayment" required ng-readonly="makereadonlyDownPayment" range-number="range">

Below is my js code.

app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = attrs.rangeNumber.split(',').map(Number);
            ctrl.$validators.rangeNumber = function (value) {
                return value >= range[0] && value <= range[1];
            };
        }
    };
});

May i know how can i do this? Any help would be appreciated. Thank you.

Body:
I hope this will solve your problem

app.directive('rangeNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            var range = scope.$eval(attrs.rangeNumber);
            range = range.split(',').map(Number);

            ctrl.$parsers.push(function(value) {
              value = +value;
              var isValidRange = !(value >= range[0] && value <= range[1]);
              ctrl.$setValidity('range', isValidRange);

              return value;
          });
        }
    };
});

Controller

$scope.range = '1,4096';
// or you can make it array, but in that case you have to remove split
//and map functions from the directive
$scope.range = [1, 4096];

HTML

<input class="" type="text" name="rangeNumber" ng-attr-placeholder="{{ 'DownPayment' }}" ng-model="DownPayment"  range-number="range">
<p ng-show="!sampleForm.rangeNumber.$invalid && sampleForm.rangeNumber.$dirty">Number not in range</p>

https://jsfiddle.net/yordan_nikolov/pwejm6de/

Edited


问:
Android Studio Decryption unsuccessful on newest SDKs (Google API)
i'm trying to run the Android Emulator with new SDKs (Adnroid 7). It was marked with Google API, but when it starts it wants me to enter a password. When i put in something, it shows me "Decryption Unsuccessful". However it doesn't happen with an SDK not marked with "Google API".

答: Probably, you used cyryllic or something other, non Latin characters in your user name. Just rename your user folder and be happy.</p>


问:
Prevent @RabbitListener in spring-rabbit from trying to connect to server during integration test
I want to run some acceptance tests for my services that are using rabbitMq but I want to ignore all that require inter-service communication (amqp).

The problem however is that Spring tries to connect to the (non-exisiting) rabbit host on startup so it can register its consumers. It does that for each method that is annotated with @RabbitListener which can get quite annoying with the long timeout this has if I have more than one listener in my service.

How can I reduce this timeout or even prevent @RabbitListener connection all together?

Our (simplified) Rabbit Config:

```<code>@Configuration
@EnableRabbit
public class RabbitMqConfig {

    public RabbitMqConfig(
            @Value("${rabbitmq.host}") String rabbitHost,
            @Value("${rabbitmq.port}") int rabbitPort,
            @Value("${exchange.name}") String exchange) {
        this.rabbitHost = rabbitHost;
        this.rabbitPort = rabbitPort;
        this.exchange= exchange;
    }

  @Bean
  DirectExchange directExchangeBean() {
    return new DirectExchange(this.exchange, true, false);
  }

  @Bean
  public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitHost);
    connectionFactory.setPort(rabbitPort);
    return connectionFactory;
  }

  @Bean
  public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory());
  }

  @Bean
  public Queue itemDoneQueue() {
    return new Queue(ITEM_DONE_QUEUENAME, true);
  }

  @Bean
  Binding itemDoneBinding() {
    return BindingBuilder.bind(itemDoneQueue()).to(directExchangeBean()).with(ITEM_DONE_KEY);
  }

}
</code>```

Properties

```<code>rabbitmq.host=192.168.42.100
rabbitmq.port=5672
exchange.name=myExchange
</code>```

The Listener:

```<code>  @RabbitListener(queues = ITEM_DONE_QUEUENAME)
  public void receiveMessageFromItemDoneQueue(String message) {
    // do the work
  }
</code>```

The Test:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public abstract class RabbitTest {
</code>```

Really nothing special here. Obviously during testing the rabbit host is unavailable. That is fine. I want to ignore the fact. And quickly.

I've tried

```<code>spring.rabbitmq.connection-timeout=1
</code>```

But that didn't change anything.

Using

```<code>spring.rabbitmq.listener.simple.auto-startup=false
</code>```

neither does anything.

Using

```<code>spring.autoconfigure.exclude:org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
</code>```

just kills my application context loading with spring complaining about a NoSuchBeanDefinitionException: No bean named 'rabbitListenerContainerFactory' available

Any ideas?
Thanks!

答:
Thanks for your input Gary.
I already found a solution that works for me. For some reason the connection timeout for the Consumer initialization is not exposed in the CachingConnectionFactory I used nor is the property used that I tried (spring.rabbitmq.connection-timeout).

What I do now is initialize the base ConnectionFactory and pass it to the CachingConnectionFactory (Having of course no clue where the difference is but that is the case most of the time with spring):

```<code>  @Bean
  public ConnectionFactory connectionFactory() {
    com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
    connectionFactory.setConnectionTimeout(this.connectionTimeout);
    connectionFactory.setHost(this.rabbitHost);
    connectionFactory.setPort(this.rabbitPort);
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(
        connectionFactory);
    return cachingConnectionFactory;
  }
</code>```

Now I can set the timeout to 1 during my acceptence tests causing the consumer initialization to fail quickly and to a higher value for deployment.

Body:
I want to run some acceptance tests for my services that are using rabbitMq but I want to ignore all that require inter-service communication (amqp).

The problem however is that Spring tries to connect to the (non-exisiting) rabbit host on startup so it can register its consumers. It does that for each method that is annotated with @RabbitListener which can get quite annoying with the long timeout this has if I have more than one listener in my service.

How can I reduce this timeout or even prevent @RabbitListener connection all together?

Our (simplified) Rabbit Config:

@Configuration
@EnableRabbit
public class RabbitMqConfig {

    public RabbitMqConfig(
            @Value("${rabbitmq.host}") String rabbitHost,
            @Value("${rabbitmq.port}") int rabbitPort,
            @Value("${exchange.name}") String exchange) {
        this.rabbitHost = rabbitHost;
        this.rabbitPort = rabbitPort;
        this.exchange= exchange;
    }

  @Bean
  DirectExchange directExchangeBean() {
    return new DirectExchange(this.exchange, true, false);
  }

  @Bean
  public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitHost);
    connectionFactory.setPort(rabbitPort);
    return connectionFactory;
  }

  @Bean
  public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory());
  }

  @Bean
  public Queue itemDoneQueue() {
    return new Queue(ITEM_DONE_QUEUENAME, true);
  }

  @Bean
  Binding itemDoneBinding() {
    return BindingBuilder.bind(itemDoneQueue()).to(directExchangeBean()).with(ITEM_DONE_KEY);
  }

}

Properties

rabbitmq.host=192.168.42.100
rabbitmq.port=5672
exchange.name=myExchange

The Listener:

  @RabbitListener(queues = ITEM_DONE_QUEUENAME)
  public void receiveMessageFromItemDoneQueue(String message) {
    // do the work
  }

The Test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public abstract class RabbitTest {

Really nothing special here. Obviously during testing the rabbit host is unavailable. That is fine. I want to ignore the fact. And quickly.

I've tried

spring.rabbitmq.connection-timeout=1

But that didn't change anything.

Using

spring.rabbitmq.listener.simple.auto-startup=false

neither does anything.

Using

spring.autoconfigure.exclude:org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration

just kills my application context loading with spring complaining about a NoSuchBeanDefinitionException: No bean named 'rabbitListenerContainerFactory' available

Any ideas?
Thanks!

Body:
Thanks for your input Gary.
I already found a solution that works for me. For some reason the connection timeout for the Consumer initialization is not exposed in the CachingConnectionFactory I used nor is the property used that I tried (spring.rabbitmq.connection-timeout).

What I do now is initialize the base ConnectionFactory and pass it to the CachingConnectionFactory (Having of course no clue where the difference is but that is the case most of the time with spring):

  @Bean
  public ConnectionFactory connectionFactory() {
    com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
    connectionFactory.setConnectionTimeout(this.connectionTimeout);
    connectionFactory.setHost(this.rabbitHost);
    connectionFactory.setPort(this.rabbitPort);
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(
        connectionFactory);
    return cachingConnectionFactory;
  }

Now I can set the timeout to 1 during my acceptence tests causing the consumer initialization to fail quickly and to a higher value for deployment.


问:
tf.trainable_variables returns more than one graph's variable
I'm trying to write my own multi-gpu on one node tensorflow example.

I read the code here: https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py

The core code of mine is:

```<code>vars = tf.trainable_variables()
grads = tf.gradients(cost, vars)
tower_grads.append(grads)
</code>```

But as the program run to the second GPU, tf.trainable_variables() return both the first round of the loop tensorflow varibles and the second round's tensorflow varibles.

By the way, I think this task is that the two GPU use the same variables, but the gradients is different. Is it right?

答:
The problem is that

The variable is named aaa in the first round.

But the variable is named aaa_1 in the second round. Even if I set reuse = True.

The solution is using tf.get_variable instead of tf.Variable

I learn it from https://github.com/normanheckscher/mnist-multi-gpu/blob/master/mnist_multi_gpu_batching_train.py#L356

Body:
I'm trying to write my own multi-gpu on one node tensorflow example.

I read the code here: https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py

The core code of mine is:

vars = tf.trainable_variables()
grads = tf.gradients(cost, vars)
tower_grads.append(grads)

But as the program run to the second GPU, tf.trainable_variables() return both the first round of the loop tensorflow varibles and the second round's tensorflow varibles.

By the way, I think this task is that the two GPU use the same variables, but the gradients is different. Is it right?


问:
Record not showing even the record exist in query using PL SQL
I have written a query to fetch a record using unique SAPID and CandidateID but the record is not getting fetched.

But for the same SAPID and candidateId record exist. Here is my query below

```<code>SELECT VT.*,VTS.STATUS_NAME
        FROM TBL_VSAT_MST_DETAIL VT
        LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
        WHERE VT.SAP_ID = 'I-KA-CTPR-ENB-9016'
        AND VT.CANDIDATE_ID = 'C3';
</code>```

Please suggest where I am wrong

update

```<code>SELECT ENB.SAP_ID AS SAP_ID,CAND.CANDIDATEID AS CANDIDATE_ID,ENB.R4G_STATE AS STATE,ENB.SITE_TYPE AS SITETYPE,CAND.SITENAME AS SITENAME,
CAND.STATUS AS CANDIDATESTATUS ,ENB.SITEID AS SITEID,ENB.PRIORITY_SITE AS PRIORITYSITE,ENB.CIRCLE AS CIRCLE,
DECODE (VTS.STATUS_NAME,null, 'Fill Vendor Survey form', VTS.STATUS_NAME) AS VSATSTATUS,
ENB.LATITUDE, ENB.LONGITUDE, VTS.STATUS_ID
FROM R4G_OSP.ENODEB ENB
INNER JOIN R4G_OSP.CANDIDATE CAND ON ENB.SAP_ID = CAND.SAP_ID
LEFT JOIN TBL_VSAT_MST_DETAIL VT ON ENB.SAP_ID = VT.SAP_ID
LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
WHERE ENB.SCOPE = 'EnodeB-Connected_MW'
AND ENB.SITEBACKHAUL = 'MW'
AND CAND.STATUS = 'Fill Vendor Survey Form'
AND (VT.STATUS_ID IS NULL OR VT.STATUS_ID IN (2,4))
AND ENB.SAP_ID = 'I-KA-CTPR-ENB-9016'
AND CAND.CANDIDATEID = 'C3';
</code>```

答:
I think you already have the query: I derived it from your second query:</p>

```<code>SELECT ENB.SAP_ID AS SAP_ID
    ,CAND.CANDIDATEID AS CANDIDATE_ID
     ,VT.*
     ,VTS.STATUS_NAME
FROM R4G_OSP.ENODEB ENB
INNER JOIN R4G_OSP.CANDIDATE CAND ON ENB.SAP_ID = CAND.SAP_ID
LEFT JOIN TBL_VSAT_MST_DETAIL VT ON ENB.SAP_ID = VT.SAP_ID
LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
WHERE ENB.SCOPE = 'EnodeB-Connected_MW'
    AND ENB.SITEBACKHAUL = 'MW'
    AND CAND.STATUS = 'Fill Vendor Survey Form'
    AND (VT.STATUS_ID IS NULL
        OR VT.STATUS_ID IN (2, 4)
        )
    AND ENB.SAP_ID = 'I-KA-CTPR-ENB-9016'
    AND CAND.CANDIDATEID = 'C3';
</code>```

Body:
I have written a query to fetch a record using unique SAPID and CandidateID but the record is not getting fetched.

But for the same SAPID and candidateId record exist. Here is my query below

SELECT VT.*,VTS.STATUS_NAME
        FROM TBL_VSAT_MST_DETAIL VT
        LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
        WHERE VT.SAP_ID = 'I-KA-CTPR-ENB-9016'
        AND VT.CANDIDATE_ID = 'C3';

Please suggest where I am wrong

update

SELECT ENB.SAP_ID AS SAP_ID,CAND.CANDIDATEID AS CANDIDATE_ID,ENB.R4G_STATE AS STATE,ENB.SITE_TYPE AS SITETYPE,CAND.SITENAME AS SITENAME,
CAND.STATUS AS CANDIDATESTATUS ,ENB.SITEID AS SITEID,ENB.PRIORITY_SITE AS PRIORITYSITE,ENB.CIRCLE AS CIRCLE,
DECODE (VTS.STATUS_NAME,null, 'Fill Vendor Survey form', VTS.STATUS_NAME) AS VSATSTATUS,
ENB.LATITUDE, ENB.LONGITUDE, VTS.STATUS_ID
FROM R4G_OSP.ENODEB ENB
INNER JOIN R4G_OSP.CANDIDATE CAND ON ENB.SAP_ID = CAND.SAP_ID
LEFT JOIN TBL_VSAT_MST_DETAIL VT ON ENB.SAP_ID = VT.SAP_ID
LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
WHERE ENB.SCOPE = 'EnodeB-Connected_MW'
AND ENB.SITEBACKHAUL = 'MW'
AND CAND.STATUS = 'Fill Vendor Survey Form'
AND (VT.STATUS_ID IS NULL OR VT.STATUS_ID IN (2,4))
AND ENB.SAP_ID = 'I-KA-CTPR-ENB-9016'
AND CAND.CANDIDATEID = 'C3';

Body:
I think you already have the query: I derived it from your second query:

SELECT ENB.SAP_ID AS SAP_ID
    ,CAND.CANDIDATEID AS CANDIDATE_ID
     ,VT.*
     ,VTS.STATUS_NAME
FROM R4G_OSP.ENODEB ENB
INNER JOIN R4G_OSP.CANDIDATE CAND ON ENB.SAP_ID = CAND.SAP_ID
LEFT JOIN TBL_VSAT_MST_DETAIL VT ON ENB.SAP_ID = VT.SAP_ID
LEFT JOIN TBL_VSAT_STATUS_MST VTS ON VT.STATUS_ID = VTS.STATUS_ID
WHERE ENB.SCOPE = 'EnodeB-Connected_MW'
    AND ENB.SITEBACKHAUL = 'MW'
    AND CAND.STATUS = 'Fill Vendor Survey Form'
    AND (VT.STATUS_ID IS NULL
        OR VT.STATUS_ID IN (2, 4)
        )
    AND ENB.SAP_ID = 'I-KA-CTPR-ENB-9016'
    AND CAND.CANDIDATEID = 'C3';


问:
Check if there are unfinished task spooler tasks?
How can I check in shellscript (zsh) whether there are any unfinished task-spooler tasks?

I tried already passing ts through grep but am not sure how expandable this would be.

答:
```<code>ts -l | awk '$2 == "queued" || $2 == "running" { print $0 }'
</code>```

This will take the output of the ts -l command and then check that the second piece of each line equals "queued" or "running" If it does, it will print the line.

You could use

```<code>ts -l | grep -E '([[:blank:]]+queued[[:blank:]]+) | ([[:blank:]]+running[[:blank:]]+)'
</code>```

This would search the output for multiple blank spaces then the word queued or running and then multiple blank spaces.

Body:
ts -l | awk '$2 == "queued" || $2 == "running" { print $0 }'

This will take the output of the ts -l command and then check that the second piece of each line equals "queued" or "running" If it does, it will print the line.

You could use

ts -l | grep -E '([[:blank:]]+queued[[:blank:]]+) | ([[:blank:]]+running[[:blank:]]+)'

This would search the output for multiple blank spaces then the word queued or running and then multiple blank spaces.


问:
Htaccess - Rewrite URL with multiple different conditions
I want to make URL friendly with multiple conditions.

I got this: www.example.com/?lang=en&page=test&model=mymodel

I want to have: www.example.com/en/test/mymodel

But I got also this (with other parameters):

www.example.com/?lang=en&otherpage=othertest&othermodel=myothermodel

Must be:

www.example.com/en/othertest/myothermodel

How can I do this for my entire website?

答:
If you're going to use friendly URLs that look like this:

```<code>www.example.com/<language>/<value1>/<value2>
</code>```

then Apache won't be able to distinguish between the first and the second "non-friendly" URLs that you mentioned:

```<code>www.example.com/?lang=en&page=test&model=mymodel
www.example.com/?lang=en&otherpage=othertest&othermodel=myothermodel
</code>```

This is because the parameter names (page and model in the 1st, otherpage and othermodel in the 2nd URL) are not present, and can't be guessed, from the friendly URL.

A possible workaround depends on how many different scenarios you have, that is, how many different parameters you want to handle.

E.g. if you only have a few scenarios, you can add a part to the friendly URL pattern telling Apache which parameter names to use, like so:

```<code>www.example.com/<language>/<parameter_set>/<value1>/<value2>
</code>```

then, tell Apache to use the first parameter set if <parameter_set> equals e.g. 1, the second set if it equals 2 and so on.

A sample rewrite rule set could be:

```<code>RewriteEngine On
RewriteRule ^([\w]+)/1/([\w]+)/([\w]+)$ ./?lang=$1&page=$2&model=$3
RewriteRule ^([\w]+)/2/([\w]+)/([\w]+)$ ./?lang=$1&otherpage=$2&othermodel=$3
</code>```

Please note that 1 and 2 are completely arbitrary (they could be any other string).

Naturally, the official docs are there to help.

Body:
If you're going to use friendly URLs that look like this:

www.example.com/<language>/<value1>/<value2>

then Apache won't be able to distinguish between the first and the second "non-friendly" URLs that you mentioned:

www.example.com/?lang=en&page=test&model=mymodel
www.example.com/?lang=en&otherpage=othertest&othermodel=myothermodel

This is because the parameter names (page and model in the 1st, otherpage and othermodel in the 2nd URL) are not present, and can't be guessed, from the friendly URL.

A possible workaround depends on how many different scenarios you have, that is, how many different parameters you want to handle.

E.g. if you only have a few scenarios, you can add a part to the friendly URL pattern telling Apache which parameter names to use, like so:

www.example.com/<language>/<parameter_set>/<value1>/<value2>

then, tell Apache to use the first parameter set if <parameter_set> equals e.g. 1, the second set if it equals 2 and so on.

A sample rewrite rule set could be:

RewriteEngine On
RewriteRule ^([\w]+)/1/([\w]+)/([\w]+)$ ./?lang=$1&page=$2&model=$3
RewriteRule ^([\w]+)/2/([\w]+)/([\w]+)$ ./?lang=$1&otherpage=$2&othermodel=$3

Please note that 1 and 2 are completely arbitrary (they could be any other string).

Naturally, the official docs are there to help.


问:
Working with block special files/devices to implement a filesystem
I've implemented a basic filesystem using FUSE, with all foreseeable POSIX functionality implemented [naturally I haven't even profiled yet ;)]. Currently I'm able to run the filesystem on a regular file (st_mode & S_IFREG), but the next step in development is to host it on an actual block device. Running my code as is, immediately fails on reading st_size after calling fstat on the device. Of course I don't expect the problems to stop there so:

What changes are required to operate on block devices as opposed to regular files?

What are some special considerations I need to make with regard to performance, limitations, special features and the like?

Are there any tutorials and references with dealing with block special files? Googling has turned up very little useful; I only have background knowledge (ironically from MSDN in my dark past) and some scanty information in the manpages.

Update0

I've pointed out what I mean by "regular file".

I don't want to concentrate on getting the device size, I want general guidelines for differences between regular files and device files with respect to performance and usage.

答:
block devices behave very much like files - tools like dd can operate on them without any special handling.  fstat, though, returns information about the special-file node, not the blockdev it refers to.  you probably want to use the BLKGETSIZE64 ioctl to read the size.

there's no particular reason to use a partition over a raw device, though - a blockdev is a blockdev.  O_DIRECT is good, as well, assuming your workload won't generate repeated accesses.  don't confuse it with a real protocol for ensuring the permanence and atomicity of your filesystem, though (fsync, barriers, etc).

ContentLicense: CC BY-SA 2.5


问:
Border for radio button
I have the code like this, which I can't modify handly (only with css)

```<code><label class="radio">
   <input type="radio" name="showTabs" checked="" value="1"> LABEL 1
</label>

<label class="radio">
   <input type="radio" name="showTabs" value="2"> LABEL 2
</label>
</code>```

How can I add border around for checked radiobutton + label?

答:
Check the below code, hope this is what you expecting

.radio{
   position:relative;
   display:inline-block;
}

.ch-style{
  display:block;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  z-index: 0;
}

input[type="radio"]:checked ~ .ch-style{
   border:1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="radio">
<input type="radio" name="showTabs" value="2"> LABEL 2
<span class="ch-style"><span>
</label></code>```

Title: Border for radio button

Body:
I have the code like this, which I can't modify handly (only with css)

   <input type="radio" name="showTabs" checked="" value="1"> LABEL 1

   <input type="radio" name="showTabs" value="2"> LABEL 2

How can I add border around for checked radiobutton + label?

Body:
Check the below code, hope this is what you expecting

.radio{
   position:relative;
   display:inline-block;
}

.ch-style{
  display:block;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  z-index: 0;
}

input[type="radio"]:checked ~ .ch-style{
   border:1px solid red;
}

<label class="radio">
<input type="radio" name="showTabs" value="2"> LABEL 2
<span class="ch-style"><span>
</label>


问:
What's the difference between Node.js HTTP request and get?
What's the difference between Node.js HTTP request and get?

(and when to use which)

Docs: https://nodejs.org/api/http.html

答:
From the exact docs you linked:

Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically.


问:
Dynamically change ul from horizontal to vertical
Maybe a duplicated question, but I didn't found any solution for this problem...

I have a div element (let's call it master) and don't have control over it.

So, I cannot modify its width or height.

Inside it I have another div (let's call it container), about which I have control.

And inside this div I have 3 ul elements, each with 240px.

What I wish is:

If the master has less than 720px (240px of each ul multiplied by the number of ul's), I want to show the ul elements vertically (one on top over the other).

But if the master has more than 720px, I want to show the ul elements horizontally (side by side).

Besides that, I would like that my container element had the minimum width possible to fit its ul children.

Is this possible using only css/html?

I already tried to use flex, float and tables without success...

I made this fiddle to help.

To illustrate what I wish:

The gray box is the master element.

The red one is the container.

And the green ones are the ul elements.

答:
Updated fiddle: https://jsfiddle.net/qywozaa8/2/.

You can use float:left for ul elements.

Also you have to take care of padding with the width (have reduced it 230px as padding is 5px).

Also have changed container overflow:auto to overflow-y: auto.

Hope this helps.

Updated css:

```<code>div.master {
  background-color: gray;
  width: 720px;  /* I have no control over this. But this value can different (360, 1080 and so on) */
  height: 405px; /* I have no control over this. But this value can different (270, 607 and so on) */
}

div.container {
  background-color: red;
  max-height: 250px;
  overflow: auto;
  display: inline-block;
  min-width: 320px;
  max-width: 760px;
  /* we can add other attributes here */
}

ul.list {
  background-color: green;
  width: 240px; /* I have control over this element, but this value cannot be changed */
  height: 150px; /* I have control over this element, but this value cannot be changed */
  padding: 5px 5px 5px 5px; /* I have control over this element, but this value cannot be changed */
  /* we can add other attributes here */
}
</code>```

Body:
Updated fiddle: https://jsfiddle.net/qywozaa8/2/.

You can use float:left for ul elements.

Also you have to take care of padding with the width (have reduced it 230px as padding is 5px).

Also have changed container overflow:auto to overflow-y: auto.

Hope this helps.

Updated css:

div.master {
  background-color: gray;
  width: 720px;  /* I have no control over this. But this value can different (360, 1080 and so on) */
  height: 405px; /* I have no control over this. But this value can different (270, 607 and so on) */
}

div.container {
  background-color: red;
  max-height: 250px;
  overflow: auto;
  display: inline-block;
  min-width: 320px;
  max-width: 760px;
  /* we can add other attributes here */
}

ul.list {
  background-color: green;
  width: 240px; /* I have control over this element, but this value cannot be changed */
  height: 150px; /* I have control over this element, but this value cannot be changed */
  padding: 5px 5px 5px 5px; /* I have control over this element, but this value cannot be changed */
  /* we can add other attributes here */
}


问:
cap production deploy Don't know how to build task 'start' (see --tasks)
Here is my error

cap production deploy
(Backtrace restricted to imported tasks)
cap aborted!
Don't know how to build task 'start' (see --tasks)

with --trace https://gist.github.com/hmexp/a899739fc39eeb56b20f639965a54b13

Capfile

```<code># Load DSL and Setup Up Stages
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rails/console'
require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'

# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
</code>```

Deploy.rb
https://gist.github.com/hmexp/58ac59bd9af48922835c7fcc73fe7ece

So how can i fix this?

Thanks!

答:
I experienced this issue some weeks ago.

As far as I remember, I solved this by putting my before and after statements outside of namespaces and therefore precising the namespaces in invokations like the following:

```<code>before "deploy:starting", "deploy:setup_maintenance_for_deploy"
before "deploy:starting", "maintenance:enable"
# after 'deploy:migrate', 'deploy:seed'
after 'deploy:publishing', 'deploy:restart'
after "deploy:finished", "maintenance:disable"
</code>```

Your trace seems also to confirm my intuition that the problem is caused by a namespacing issue.

These are the Capfile and deploy.rb I'm using:

Capfile

deploy.rb

Hope this helps.

Body:
Here is my error

cap production deploy
(Backtrace restricted to imported tasks)
cap aborted!
Don't know how to build task 'start' (see --tasks)

with --trace https://gist.github.com/hmexp/a899739fc39eeb56b20f639965a54b13

Capfile

# Load DSL and Setup Up Stages
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rails/console'
require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'

# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

Deploy.rb
https://gist.github.com/hmexp/58ac59bd9af48922835c7fcc73fe7ece

So how can i fix this?

Thanks!

Body:
I experienced this issue some weeks ago.

As far as I remember, I solved this by putting my before and after statements outside of namespaces and therefore precising the namespaces in invokations like the following:

before "deploy:starting", "deploy:setup_maintenance_for_deploy"
before "deploy:starting", "maintenance:enable"
# after 'deploy:migrate', 'deploy:seed'
after 'deploy:publishing', 'deploy:restart'
after "deploy:finished", "maintenance:disable"

Your trace seems also to confirm my intuition that the problem is caused by a namespacing issue.

These are the Capfile and deploy.rb I'm using:

Capfile

deploy.rb

Hope this helps.


问:
How to check if array contains more than one element?
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

```<code>if(array && array.length > 1)
</code>```

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

```<code>if(_.some(array))
</code>```

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

```<code>if(_.several(array))

if(_.many(array))
</code>```

Would I have to write my own extension method or did I just not find the right lodash command, yet?

答:
```<code>_.compact(array).length > 1
</code>```

Compact returns array with falsey values removed (false, null, 0, "", undefined, and NaN).

Body:
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

if(array && array.length > 1)

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

if(_.some(array))

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

if(_.several(array))

if(_.many(array))

Would I have to write my own extension method or did I just not find the right lodash command, yet?

Body:
_.compact(array).length > 1

Compact returns array with falsey values removed (false, null, 0, "", undefined, and NaN).


问:
How to create new variable in java dynamically
Is it possible to create new variables in java dynamically.

```<code>class A {
methodA(String variableName) {

      }
}
</code>```

So if new method is called twice, 2 new variables should be newly added to this class?

Is it possible?

答:
Using a HashMap could be a solution. For example, if we have the following class:

```<code>class Staff {
    private HashMap<String, Object> mylist = new HashMap<String, Object>() ;

    void setNewVar(String s, Object o) {
        mylist .put(s, o);
    }

    HashMap<String, Object> getVar() {
        return mylist;
    }
}
</code>```

I can use it as:

```<code>staff.setNewVar("NumVars",11);
staff.setNewVar("NumBatches",300);
...
</code>```

and then:

```<code>staff.getVar()
</code>```

wherever you need. I use it to convert some variables (the number can change) to JSON, successfully.

Body:
Is it possible to create new variables in java dynamically.

class A {
methodA(String variableName) {

      }
}

So if new method is called twice, 2 new variables should be newly added to this class?

Is it possible?

Body:
Using a HashMap could be a solution. For example, if we have the following class:

class Staff {
    private HashMap<String, Object> mylist = new HashMap<String, Object>() ;

    void setNewVar(String s, Object o) {
        mylist .put(s, o);
    }

    HashMap<String, Object> getVar() {
        return mylist;
    }
}

I can use it as:

staff.setNewVar("NumVars",11);
staff.setNewVar("NumBatches",300);
...

and then:

staff.getVar()

wherever you need. I use it to convert some variables (the number can change) to JSON, successfully.


问:
How to release an iOS App only for members with an external membership?
I am planning to release an iOS App for customers which already have a contract/membership for my services and also pay for it.

I have tried to search for such informations but suffer to find some satisfying answers.

The Point: I know apple wants that the payment goes through them or their store, but I already charge my customers for the services and I just want my services to be available on iOS devices aswell.

Will i get rejected when i try to build an iOS-App with a login without registration/payment on the app itself or in-app?

Same question on android platform..

thanks in advance

答:
If you already have paid user base, then you can identify those transaction ids mapping to their userID/Email/Phone numbers etc. Through which you can create credentials for specific users.
Give registration option for others & show what services you offer within app.Further you can ask for payment within app or through your payment gateway.</p>


问:
How to know when a ListBoxItem comes into view?
Is there an event that tells me when a list box item comes into view?

The problem I have is that I can have several thousand elements that I set as my ListBox.ItemSource. Each element will generate a bitmap (which takes a while) so if I would just put this bitmap generation in the constructor creating the collection would take forever to create. Instead I want to defer the bitmap generation when an item comes into view.

Is there a way to do this? Ideally I would prefer not to loop through all the items and check if they are visible.

答:
Is there an event that tells me when a list box item comes into view?

You could handle the Loaded event of the ListBoxItem container:

```<code><ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="Loaded" Handler="OnItemLoaded" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
</code>```

```<code>private void OnItemLoaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = sender as ListBoxItem;
    object dataItem = lbi.DataContext;
    //...
}
</code>```

Body:
Is there an event that tells me when a list box item comes into view?

You could handle the Loaded event of the ListBoxItem container:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="Loaded" Handler="OnItemLoaded" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

private void OnItemLoaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = sender as ListBoxItem;
    object dataItem = lbi.DataContext;
    //...
}


问:
Eclipse opens class file in an active working set instead of Java file
I have about 20 projects in Eclipse segregated into 5 different working sets. Main projects and dependent artifacts. Some artifacts are included in more than one set.

How do I set up Eclipse so when I control click a Java file, the relevant Java file from the active set is opened? At the moment, Eclipse opens a class file. This is while developing and not debugging.

I have followed every Google result I can find for 'eclipse opens class file instead of java' and nothing has worked.

There are no projects in Properties -> Java Build path -> Libraries (I have JRE System Library and Maven Dependencies)

None of the dependent projects are present in Java Build path-> Source.

My Maven is setup to download sources.

Everything worked as expected before I separated my projects to working sets, but was very confusing given the number of open/closed projects.

答:
It seems that you have disabled Maven workspace resolution.

In my setup, right-click on the project -> Maven -> Enable Workspace Resolution
did the trick.

This way, m2e includes the Eclipse projects of dependent local projects instead of the jar files into the Maven Dependencies Library of a project.


问:
What is equivalent query in yii2
As search filtering is not working when use findbysql in yii2 searchmodel, so I want to write an equivalent query of "SELECT * FROM challan WHERE id IN (SELECT MAX(id) FROM challan GROUP BY sid)" in Yii2

答:
```<code>$query->andWhere(new Expression('id IN (SELECT MAX(id) FROM challan GROUP BY sid)'));
</code>```

Title: What is equivalent query in yii2


问:
Access to an object of my SWT thread from my Swing thread
So I have an SWT thread, an eclipse plugin that consists of a simple view myView, with a JPanel myJPanel and a JTree myJTree embedded into it. With a listener on the Swing thread, when the selection change on my JTree it refresh JPanel into the Swing thread.

Simplified code version of my myView :

```<code> public class myView extends ViewPart {
  public java.awt.Frame myFrame;

     @Override
      public void createPartControl(Composite parent) {
        Composite myComposite = new Composite(parent, SWT.EMBEDDED);
        myFrame = SWT_AWT.new_Frame(myComposite);
        myFrame.add(myJPanel);
        myFrame.repaint();
        myFrame.revalidate();

        //same kind of code for Jtree -> myJTreeFrame
    }
</code>```

What I want to do is to refresh myFrame from the Swing thread, when the listener of myJTree has to refresh myJPanel

I thought about this :

```<code>public void valueChanged(TreeSelectionEvent e) {
// some code that refresh myJPanel

Display.getDefault().asyncExec(
    new Runnable() {
      public void run() {
          try {
            myView view = (viewMap4j)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView( "pluginProject.myView");
          } catch (PartInitException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          view.myFrame.repaint();
          view.myFrame.revalidate();
      }
    });
}
</code>```

But I get this error with librairies : No exception of type PartInitException can be thrown; an exception type must be a subclass of Throwable

My question is : How to access to an object from my SWT thread (here myView) in a Swing thread?
and any ideas to make it work in this specific example?

答:
This did the trick, it gave me access to myView where I could find myFrame to refresh it from the JTree listener  :

```<code>  PlatformUI.getWorkbench().getDisplay().asyncExec(
            new Runnable() {
              public void run() {
                try {
                  myView view =null;
                  view = (myView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("pluginProject.myView");
                  view.reloadMyFrame();
                } catch (CoreException e) {
                  e.printStackTrace();
                }
              }
            });
</code>```

Body:
So I have an SWT thread, an eclipse plugin that consists of a simple view myView, with a JPanel myJPanel and a JTree myJTree embedded into it. With a listener on the Swing thread, when the selection change on my JTree it refresh JPanel into the Swing thread.

Simplified code version of my myView :

 public class myView extends ViewPart {
  public java.awt.Frame myFrame;

     @Override
      public void createPartControl(Composite parent) {
        Composite myComposite = new Composite(parent, SWT.EMBEDDED);
        myFrame = SWT_AWT.new_Frame(myComposite);
        myFrame.add(myJPanel);
        myFrame.repaint();
        myFrame.revalidate();

        //same kind of code for Jtree -> myJTreeFrame
    }

What I want to do is to refresh myFrame from the Swing thread, when the listener of myJTree has to refresh myJPanel

I thought about this :

public void valueChanged(TreeSelectionEvent e) {
// some code that refresh myJPanel

Display.getDefault().asyncExec(
    new Runnable() {
      public void run() {
          try {
            myView view = (viewMap4j)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView( "pluginProject.myView");
          } catch (PartInitException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          view.myFrame.repaint();
          view.myFrame.revalidate();
      }
    });
}

But I get this error with librairies : No exception of type PartInitException can be thrown; an exception type must be a subclass of Throwable

My question is : How to access to an object from my SWT thread (here myView) in a Swing thread?
and any ideas to make it work in this specific example?

Body:
This did the trick, it gave me access to myView where I could find myFrame to refresh it from the JTree listener  :

  PlatformUI.getWorkbench().getDisplay().asyncExec(
            new Runnable() {
              public void run() {
                try {
                  myView view =null;
                  view = (myView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("pluginProject.myView");
                  view.reloadMyFrame();
                } catch (CoreException e) {
                  e.printStackTrace();
                }
              }
            });


问:
Compare columns of two CSV files and delete differences
I would like to compare two huge CSV files with different amount of enties. Just one column contains the same values like they are also exisitng in the other file in the same column, which is much bigger.

So I want to keep the lines in one of the files where a line with the same value in the second file also exists.

Example:

```<code>File a
value1,value2,value3,...
value4,value5,value6,...
value7,value8,value9,...

File b:
value10,value2,value11,...
value12,value13,value14,...
</code>```

In the end file b (or a complete new file) should look like this:

```<code>value10,value2,value11,...
</code>```

I don't believe it's that hard, but at the moment I have no idea how to achieve this. How could I get there with linux tools or a bash/python script?

Thanks for any hint!

答:
In awk:

```<code>$ awk -F, '
NR==FNR {               # hash elements in the first file to a
    for(i=1;i<=NF;i++)
        a[$i]
    next
}
{                       # second file
    for(i=1;i<=NF;i++)  # go thru all elements
        if($i in a) {   # if match
            print       # output
            next        # and skip to next record
        }
    }
' file1 file2
value10,value2,value11
</code>```

This one hashes the first file in the memory. If by huge you mean more-than-your-memory-can-handle, this might not be the solution for you.

Body:
I would like to compare two huge CSV files with different amount of enties. Just one column contains the same values like they are also exisitng in the other file in the same column, which is much bigger.

So I want to keep the lines in one of the files where a line with the same value in the second file also exists.

Example:

File a
value1,value2,value3,...
value4,value5,value6,...
value7,value8,value9,...

File b:
value10,value2,value11,...
value12,value13,value14,...

In the end file b (or a complete new file) should look like this:

value10,value2,value11,...

I don't believe it's that hard, but at the moment I have no idea how to achieve this. How could I get there with linux tools or a bash/python script?

Thanks for any hint!

Body:
In awk:

$ awk -F, '
NR==FNR {               # hash elements in the first file to a
    for(i=1;i<=NF;i++)
        a[$i]
    next
}
{                       # second file
    for(i=1;i<=NF;i++)  # go thru all elements
        if($i in a) {   # if match
            print       # output
            next        # and skip to next record
        }
    }
' file1 file2
value10,value2,value11

This one hashes the first file in the memory. If by huge you mean more-than-your-memory-can-handle, this might not be the solution for you.


问:
How to change the background color of tab bar programatically?
My goal is simple, change the default background color of tab bar to my own color.

For example, the default looks like this

I created my own subclass of UITabBarController, so that I don't need to change the color on every UIViewController

```<code>import UIKit

class MyTabController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBar.backgroundColor = .black
    }
}
</code>```

The result is different from what I expected.

I thought that maybe it's the color, then I changed to a custom UIColor and the color looks exactly the same.

I tried changing the bar tint color as well, but its change the color of the icon when active, not the background

```<code>self.tabBar.tintColor = UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0)
</code>```

The result will be

What did I do wrong?

答:
I had the same problem with my app but I wanted to set up a gradient image in tabbar background and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

```<code>- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
    CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}
</code>```

get the instance of UITabBarController

```<code>UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;
</code>```

set your gradient

```<code>[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];
</code>```

I'm not sure if that's a correct approach but it did work for me.

Body:
My goal is simple, change the default background color of tab bar to my own color.

For example, the default looks like this

I created my own subclass of UITabBarController, so that I don't need to change the color on every UIViewController

import UIKit

class MyTabController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBar.backgroundColor = .black
    }
}

The result is different from what I expected.

I thought that maybe it's the color, then I changed to a custom UIColor and the color looks exactly the same.

I tried changing the bar tint color as well, but its change the color of the icon when active, not the background

self.tabBar.tintColor = UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0)

The result will be

What did I do wrong?

Body:
I had the same problem with my app but I wanted to set up a gradient image in tabbar background and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
    CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}

get the instance of UITabBarController

UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;

set your gradient

[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];

I'm not sure if that's a correct approach but it did work for me.


问:
EachWithIndex groovy statement
I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.

Are each and eachWithIndex actually methods? If so what are the arguments that they take?

In the groovy documentation there is this certain example:

```<code>def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number
</code>```

Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?

I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.

答:
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each and eachWithIndex since they encourage you to modify state within the closure or do things that have side effects.

If possible, you may want to do your operations using other groovy collection methods such as .collect or .inject or findResult etc.

However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex method on the original collection which will transform the collection to a collection of pairs of [element, index]

For example,

println(['a', 'b', 'c'].withIndex())

Title: EachWithIndex groovy statement

Body:
I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.

Are each and eachWithIndex actually methods? If so what are the arguments that they take?

In the groovy documentation there is this certain example:

def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number

Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?

I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.


问:
making a directory and then cd'ing in it directly without a new command
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

```<code>#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep
</code>```

by the way this script is for ios

答:
Update after @dash-o's comment,

Current working directory is a process attribute (like environment variables) each process has it's own, a simple command in a shell starts a new process and waits for termination to update exit status $?variable. Child process have it's own environment variable set inheriting exported variables of parent process.
The current working directory of child process can be changed but will not change parent working directory.
cd is not a program but a shell built-in.

Body:
So I am making a Bash Script to make a timestamp directory but the problem I am facing is that it makes a timestamp directory but doesn't cd's into it here is the code:

#!/bin/bash
now=$(date +"%Y-%m-%d-%S")
mkcd () {
   mkdir "$now"
   cd "$now"
}
mkdir /var/mobile/backup
cd /var/mobile/backup
mkcd /var/mobile/backup/$now
echo yep

by the way this script is for ios


问:
docker-compose doesn't set the proxy in service container
I am trying to set the proxy on a magento-devbox (I asked also on the magento stack, but there seems to be less people: https://magento.stackexchange.com/questions/182414/devbox-with-magento2-2-1-6-doesnt-reach-the-proxy-in-docker-container).

I tried the following:

added an .env file with http_proxy=myip

added the http_proxy=myip directly in the docker-compose.yml under environment section of the service

The strange thing: the installation of the webshop (thing are downloaded) and the containers itself work => at running time the proxy works.

When I ssh in the container and run env the variable is not there. So if I try curl www.google.de will not work. If I set the proxy manually will work again (export http_proxy=myip), but this will be set only for this session and I need to reach the internate from the webshop too.

LE: if I go and run docker-compose exec --user magento2 web env I will see the right http_proxy settings (also as root works). But when I ssh (with putty or in PHPStorm) in the container and I do env, these settings are not there anymore.

Do you have any ideas what can I do more?

答:
I had this problem: everytime when I started a ssh the http_proxy variable was not initiated.

For that I had to change the /etc/profile and add there the export http_proxy = my ip. This should be done each time after creating the container!


问:
scroll to bottom using ref doesn't work
I have no clue why my scroll to bottom using ref doesn't work with my below code

```<code>class myComponent extends Component {

    componentDidMount() {
        console.log('test') // it did triggered
        this.container.scrollTop = -312
    }

    render() {
        return(
            <div className="Panel">
                <div ref={elem => this.container = elem}>
                   {/*... list */}
                </div>
            </div>
        )
    }
}
</code>```

My Panel is not equal to window height, imagine a dashboard app where it's wrapped at the right content area, but why isn't my scrollTop work in this case? componentDidMount did trigger.

答:
As mentioned in the comments, scrollTop cannot be negative. Its value determines the distance scrolled from the top of the element. By default the top of the elements are displayed, and as such it doesn't make sense to have a negative scroll.

Other than that, your code should work fine.

Check the demo below, it automatically scrolls to the bottom of the
:

class MyApp extends React.Component {
  constructor() {
    super();
  }
  componentDidMount() {
    this.container.scrollTop = this.container.scrollHeight
  }
  render() {
    return (

 this.container = elem}>

foo

bar

baz

    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {max-height: 110px;overflow: auto;}
li {height: 100px;background: #ffaaaa;}
li:nth-child(2) {background: #aaffaa;}
li:nth-child(3) {background: #aaaaff;}</code>```

```

Title: scroll to bottom using ref doesn't work

Body:
I have no clue why my scroll to bottom using ref doesn't work with my below code

class myComponent extends Component {

    componentDidMount() {
        console.log('test') // it did triggered
        this.container.scrollTop = -312
    }

    render() {
        return(

 this.container = elem}>
                   {/*... list */}

        )
    }
}

My Panel is not equal to window height, imagine a dashboard app where it's wrapped at the right content area, but why isn't my scrollTop work in this case? componentDidMount did trigger.

Body:
As mentioned in the comments, scrollTop cannot be negative. Its value determines the distance scrolled from the top of the element. By default the top of the elements are displayed, and as such it doesn't make sense to have a negative scroll.

Other than that, your code should work fine.

Check the demo below, it automatically scrolls to the bottom of the <ul>:

class MyApp extends React.Component {
  constructor() {
    super();
  }
  componentDidMount() {
    this.container.scrollTop = this.container.scrollHeight
  }
  render() {
    return (
      <ul ref={elem => this.container = elem}>
        <li>foo</li>
        <li>bar</li>
        <li>baz</li>
      </ul>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

ul {max-height: 110px;overflow: auto;}
li {height: 100px;background: #ffaaaa;}
li:nth-child(2) {background: #aaffaa;}
li:nth-child(3) {background: #aaaaff;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Dynamic Workload Console doesn't work whit Firefox esr 45.5 with IBMCCK 2.3.0 (CCK2)
When monitoring workload with the Dynamic Workload Console, the result table appears to be empty if using Firefox esr 45.5 with IBMCCK 2.3.0 (CCK2). Any idea?</p>

答: To solve this problem, use a different browser or upgrade Firefox to esr 45.</p>


问:
How can I get user_id with access token in laravel passport api?
I am creating mobile application and for login I am using oauth.

For url like http://localhost/darkhwast/public/oauth/token
it gives me output json as below:

```<code>{
  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjIyZWQ5YWFjY2U4MDVjYzc4NzUzMWM5NjVkMjdiZDZkNTIwOTQ5NGYxMTllN2Q3YWYyZDQyYWI5MjRjZjYyNTk0ZjhiNTBjNzMyNWMyYjlkIn0.eyJhdWQiOiIyIiwianRpIjoiMjJlZDlhYWNjZTgwNWNjNzg3NTMxYzk2NWQyN2JkNmQ1MjA5NDk0ZjExOWU3ZDdhZjJkNDJhYjkyNGNmNjI1OTRmOGI1MGM3MzI1YzJiOWQiLCJpYXQiOjE0OTgxMzQ1MjAsIm5iZiI6MTQ5ODEzNDUyMCwiZXhwIjoxNTI5NjcwNTIwLCJzdWIiOiIzIiwic2NvcGVzIjpbIioiXX0.CdhOhJ_6wb_KphCbnQEwI8iw94MmvlwCnG8PGPSEcm-YoXeaw2WoXiYRizbkhiXIP84BReRVIXxI-Rug6GUWwT1W8cjrvJinQT2UghCcUMqQ6nQlBingKUUlqyaww5rbcIj6RNDVuRtGnVhpSl6g1wsBz534GmNJyaY5F7t9ZJlf4Q80Cay9mV_YcLVnlOTZqTfGaujo6OM24pG6EoCiyOEF-4Vyd4Naov5O_AswuouCT7kuFdMbNYwNu6hB9_swf7yek_-shqgPk3AGJsnkavCI5Mgj3xQdhhtxoy6IxFcebBZ1iI6V_yd0-UDzHHsVZf2bVk4Hx0j84vA4ZkXXDkc85Lxqpafd31i51eXGPaW308VH2EPV9QwNOxNwNF9nl6uAlkcvfhfNBnNx_QGMALmyuNQf1CXY_rkA72pYkekTe4LQGX48dpIJUnFgnj8Jwsfjrda1D6_N5JvrnbvJkVZbCCgOD9vhJUGnVw6PyEcXldWHiW7EJZkAX9XYB571vzN__qkbM--UpU1fMY13HvWe6qTRSPt4NdZudg1zmQOCn0TpvonP4FGGeB_ldEA488LASAAtQdwHQryw4oZvcb1BSDrvw7IVpGva5ky8aIoeQIORPn2Ehg_I1X9q1Yy3UI8iBPQBWgAnGnyoPYhtIvXYNWLUQJaaocLe3eE7osU",
  "refresh_token": "Mrd+2d8KbLMMbT9bRbxS4YjGUp2nCB092HLaJAxnNIAabDTDfOncYFNAMiCsp/Lc96cLfF8/nE4vAq4DNnpbM8ITCswQLo4/0cY0+e/wgdAhv5ZguPOXmVsOakRT1vymWVj+DH7m1ZlynwD+hMiwVP439iEP66qS6UZqZQ+k+s4SVfMFOE0MUynEFxb27Z8zgeV8Tbw/wA67QlQxXYWWuRL809QQQsFYnmttL71nYqn23TN12iV3/Fmol8S4Kc4ODk3eSFd8C5UUPbTYSdPDOOUUt+v/yrwJgIuZG5PSybG27iPKKkMbI3JgLQc25cAsJUHtkciAn3BVnEV4K2C6hwRM91vGvljB2siblgGw3RooHdYkfZQgCP8zrBvLY9daDKFEuP1QCk8mfpI1kAhhqe3pgDpbIVDlNau+SQXiGMizcMKg/YhnLJpNlU8eqIksLIEEQmFUBfizPmEpyb+KqqhpbfPciGU4LgmwZknferEuAqLS3yzrfWkML5CGYALVWrmo8r2va/qn7yEWY3lYcpcwSXPQiG3TkNKaupfKPQ/i/+aDRb0MOEc68rRkBrSFcOhR0HUgXg+Ev1mNqwuKyu3oGJwYSEGuGEggu/0Ekd1Qem8t7WZAQ245YEj8DpiJcFLX7E9fL1Bo5yuBn9vzTcqRa+kKC7725ayaX3nzxhY="
}
</code>```

But how can I get user_id in response?

答:
Your OAuth server should have an authenticated API endpoint (using passport), something like /api/user or /api/me. You use the provided access_token to authenticate yourself to retrieve the authenticated user details:

```<code>$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $access_token,
    ],
]);

$body = (string) $response->getBody();
$remoteUser = json_decode($body);
</code>```

Once you've retrieved the user details, you should have enough to register the user account locally within the client app's database (if required).

You should encrypt the tokens before storing them on the user record.

Use encrypt() and decrypt() Laravel's reversible encryption helpers, so it's stored safely but can be decrypted for use later.

Body:
I am creating mobile application and for login I am using oauth.

For url like http://localhost/darkhwast/public/oauth/token
it gives me output json as below:

{
  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjIyZWQ5YWFjY2U4MDVjYzc4NzUzMWM5NjVkMjdiZDZkNTIwOTQ5NGYxMTllN2Q3YWYyZDQyYWI5MjRjZjYyNTk0ZjhiNTBjNzMyNWMyYjlkIn0.eyJhdWQiOiIyIiwianRpIjoiMjJlZDlhYWNjZTgwNWNjNzg3NTMxYzk2NWQyN2JkNmQ1MjA5NDk0ZjExOWU3ZDdhZjJkNDJhYjkyNGNmNjI1OTRmOGI1MGM3MzI1YzJiOWQiLCJpYXQiOjE0OTgxMzQ1MjAsIm5iZiI6MTQ5ODEzNDUyMCwiZXhwIjoxNTI5NjcwNTIwLCJzdWIiOiIzIiwic2NvcGVzIjpbIioiXX0.CdhOhJ_6wb_KphCbnQEwI8iw94MmvlwCnG8PGPSEcm-YoXeaw2WoXiYRizbkhiXIP84BReRVIXxI-Rug6GUWwT1W8cjrvJinQT2UghCcUMqQ6nQlBingKUUlqyaww5rbcIj6RNDVuRtGnVhpSl6g1wsBz534GmNJyaY5F7t9ZJlf4Q80Cay9mV_YcLVnlOTZqTfGaujo6OM24pG6EoCiyOEF-4Vyd4Naov5O_AswuouCT7kuFdMbNYwNu6hB9_swf7yek_-shqgPk3AGJsnkavCI5Mgj3xQdhhtxoy6IxFcebBZ1iI6V_yd0-UDzHHsVZf2bVk4Hx0j84vA4ZkXXDkc85Lxqpafd31i51eXGPaW308VH2EPV9QwNOxNwNF9nl6uAlkcvfhfNBnNx_QGMALmyuNQf1CXY_rkA72pYkekTe4LQGX48dpIJUnFgnj8Jwsfjrda1D6_N5JvrnbvJkVZbCCgOD9vhJUGnVw6PyEcXldWHiW7EJZkAX9XYB571vzN__qkbM--UpU1fMY13HvWe6qTRSPt4NdZudg1zmQOCn0TpvonP4FGGeB_ldEA488LASAAtQdwHQryw4oZvcb1BSDrvw7IVpGva5ky8aIoeQIORPn2Ehg_I1X9q1Yy3UI8iBPQBWgAnGnyoPYhtIvXYNWLUQJaaocLe3eE7osU",
  "refresh_token": "Mrd+2d8KbLMMbT9bRbxS4YjGUp2nCB092HLaJAxnNIAabDTDfOncYFNAMiCsp/Lc96cLfF8/nE4vAq4DNnpbM8ITCswQLo4/0cY0+e/wgdAhv5ZguPOXmVsOakRT1vymWVj+DH7m1ZlynwD+hMiwVP439iEP66qS6UZqZQ+k+s4SVfMFOE0MUynEFxb27Z8zgeV8Tbw/wA67QlQxXYWWuRL809QQQsFYnmttL71nYqn23TN12iV3/Fmol8S4Kc4ODk3eSFd8C5UUPbTYSdPDOOUUt+v/yrwJgIuZG5PSybG27iPKKkMbI3JgLQc25cAsJUHtkciAn3BVnEV4K2C6hwRM91vGvljB2siblgGw3RooHdYkfZQgCP8zrBvLY9daDKFEuP1QCk8mfpI1kAhhqe3pgDpbIVDlNau+SQXiGMizcMKg/YhnLJpNlU8eqIksLIEEQmFUBfizPmEpyb+KqqhpbfPciGU4LgmwZknferEuAqLS3yzrfWkML5CGYALVWrmo8r2va/qn7yEWY3lYcpcwSXPQiG3TkNKaupfKPQ/i/+aDRb0MOEc68rRkBrSFcOhR0HUgXg+Ev1mNqwuKyu3oGJwYSEGuGEggu/0Ekd1Qem8t7WZAQ245YEj8DpiJcFLX7E9fL1Bo5yuBn9vzTcqRa+kKC7725ayaX3nzxhY="
}

But how can I get user_id in response?

Body:
Your OAuth server should have an authenticated API endpoint (using passport), something like /api/user or /api/me. You use the provided access_token to authenticate yourself to retrieve the authenticated user details:

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $access_token,
    ],
]);

$body = (string) $response->getBody();
$remoteUser = json_decode($body);

Once you've retrieved the user details, you should have enough to register the user account locally within the client app's database (if required).

You should encrypt the tokens before storing them on the user record.

Use encrypt() and decrypt() Laravel's reversible encryption helpers, so it's stored safely but can be decrypted for use later.


问:
Docker: cd into directory using regular expressions
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

```<code>WORKDIR myfolder*
</code>```

but the current directory remains /.
How can be solved?

答:
If you know, during the build of the docker image, the name of the folder, use a variable:

```<code>WORKDIR ${workdir}
</code>```

And set the variable value during the build.

Body:
I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that.

I've tried with

WORKDIR myfolder*

but the current directory remains /.
How can be solved?

Body:
If you know, during the build of the docker image, the name of the folder, use a variable:

WORKDIR ${workdir}

And set the variable value during the build.


问:
C++0x: How can I access variadic tuple members by index at runtime?
I have written the following basic Tuple template:

```<code>template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : public Tuple<Tail...> {

    private:
    Head element;

    public:
    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};
</code>```

It works just fine, and I can access elements in array-like fashion by using tuple.Get<Index>() - but I can only do that if I know the index at compile-time.  However, I need to access elements in the tuple by index at runtime, and I won't know at compile-time which index needs to be accessed.  Example:

```<code>int chosenIndex = getUserInput();
void* chosenElement = tuple.Get(chosenIndex);
cout << "The option you chose was: " << ((MyAbstractBaseClass*) chosenElement)->getInfo() << endl;
</code>```

What's the best way to do this?

EDIT:

Hackish solution below:

Okay, I've got an idea.  I already figured out one way of doing this before I even posted this question, but it was hackish and produced warnings.  Since another solution isn't forthcoming right away, maybe you guys could help me improve my hackish one. :-)

The tuple can't normally be accessed like an array because the elements are not all necessarily of the same size.  (Hence array-style multiplication to arrive at the correct offset in the class structure will not help.)  However, I managed to work around this by creating a static table that contains a list of offsets for a tuple.  Here's the complete tuple and related templates:

```<code>#include <cstddef>

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename... T>
struct TupleOffsets;

template <typename Head, typename... Tail>
struct TupleOffsets<Head, Tail...> {

    TupleOffsets() { Init(offsets); }
    static void Init(uintptr_t* offsets);
    uintptr_t const& operator[] (uintptr_t i) const { return offsets[i]; }

    private:
    uintptr_t offsets[sizeof...(Tail) + 1];

};

template <typename Head, typename... Tail>
void TupleOffsets<Head, Tail...>::Init(uintptr_t* offsets) {

    typedef Tuple<Head, Tail...> Type;

    *offsets = offsetof(Type, element);
    TupleOffsets<Tail...>::Init(++offsets);

}

template <>
struct TupleOffsets<> {

    TupleOffsets() {}
    static void Init(uintptr_t* offsets) {}

};

template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : public Tuple<Tail...> {

    private:
    Head element;

    public:
    void* Get(uintptr_t i) {
        return (uint8_t*) this + offsets[i];
    }

    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    static const TupleOffsets<Head, Tail...> offsets;

    friend struct TupleOffsets<Head, Tail...>;
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <typename Head, typename... Tail>
const TupleOffsets<Head, Tail...> Tuple<Head, Tail...>::offsets;

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};
</code>```

In practice it works.  However, the compiler gives me a warning for using offsetof on a non-POD data type, and I'm not sure how portable this solution is.  Anyone know how I might improve this solution?

答:
First of all why are you implementing std::tuple?

Secondly it's not possible to access a tuple at a runtime determined index, the reason being that the return type depends on the index and the function signature must be known at compile time.

You may be able to work around this problem by returning a boost::any.

Body:
I have written the following basic Tuple template:

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename Head, typename... Tail>
class Tuple : public Tuple<Tail...> {

    private:
    Head element;

    public:
    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};

It works just fine, and I can access elements in array-like fashion by using tuple.Get<Index>() - but I can only do that if I know the index at compile-time.  However, I need to access elements in the tuple by index at runtime, and I won't know at compile-time which index needs to be accessed.  Example:

int chosenIndex = getUserInput();
void* chosenElement = tuple.Get(chosenIndex);
cout << "The option you chose was: " << ((MyAbstractBaseClass*) chosenElement)->getInfo() << endl;

What's the best way to do this?

EDIT:

Hackish solution below:

Okay, I've got an idea.  I already figured out one way of doing this before I even posted this question, but it was hackish and produced warnings.  Since another solution isn't forthcoming right away, maybe you guys could help me improve my hackish one. :-)

The tuple can't normally be accessed like an array because the elements are not all necessarily of the same size.  (Hence array-style multiplication to arrive at the correct offset in the class structure will not help.)  However, I managed to work around this by creating a static table that contains a list of offsets for a tuple.  Here's the complete tuple and related templates:

#include <cstddef>

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename... T>
struct TupleOffsets;

template <typename Head, typename... Tail>
struct TupleOffsets {

    TupleOffsets() { Init(offsets); }
    static void Init(uintptr_t* offsets);
    uintptr_t const& operator[] (uintptr_t i) const { return offsets[i]; }

    private:
    uintptr_t offsets[sizeof...(Tail) + 1];

};

template <typename Head, typename... Tail>
void TupleOffsets::Init(uintptr_t* offsets) {

    typedef Tuple Type;

    *offsets = offsetof(Type, element);
    TupleOffsets<Tail...>::Init(++offsets);

}

template <>
struct TupleOffsets<> {

    TupleOffsets() {}
    static void Init(uintptr_t* offsets) {}

};

template <typename Head, typename... Tail>
class Tuple : public Tuple<Tail...> {

    private:
    Head element;

    public:
    void* Get(uintptr_t i) {
        return (uint8_t*) this + offsets[i];
    }

    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    static const TupleOffsets offsets;

    friend struct TupleOffsets;
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <typename Head, typename... Tail>
const TupleOffsets Tuple::offsets;

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};

In practice it works.  However, the compiler gives me a warning for using offsetof on a non-POD data type, and I'm not sure how portable this solution is.  Anyone know how I might improve this solution?


问:
Adding local users not in Active Directory in VisualSVN Server
I am using VisualSVN. I am wondering whether if I use subversion authentication, I can easily link my active directory and also be able to add local users who are not part of the active directory.</p>

答:
Have you considered to create a new local Windows user account on the server computer? You can grant permissions to this account to access the repositories and it should be able to authenticate to VisualSVN Server via Basic Windows authentication. Read more about authentication types in VisualSVN Server in the article KB39: Understanding VisualSVN Server Authentication options.

Single VisualSVN Server instance can be configured to use either Windows/AD-based security or dedicated Subversion accounts. The current VisualSVN Server version do not support mixed-mode authentication on a single server instance.

If you want to use mixed-mode authentication and authorization that implies using Subversion dedicated accounts and Windows accounts altogether, it is possible to deploy 2 VisualSVN Server instances. In other words, you can install 2 instances of VisualSVN Server each using different authentication type.

You could deploy two VisualSVN Server Enterprise Edition instances enabled for Multisite Repository replication feature and configure one server to use Windows authentication and the other one to use Subversion authentication. External users should access the server that has Subversion authentication enabled and your internal users should access the one configured for Windows authentication. In such case you'd be required to maintain user/group list and access rules for non-domain users separately.

Multisite Repository Replication

KB68: Getting started with Multisite Repository Replication


问:
Issue in opening Facebook page via Facebook Application instead of Browser
I need to open Facebook page in my installed Facebook Application. I have called the below function for that :

```<code>private void loadFacebookUrl() {
    if (Constant.isOnline(AboutActivity.this)) {
        try {
            if (appInstalledOrNot(AboutActivity.this, "com.facebook.katana")) {
                this.getPackageManager().getPackageInfo("com.facebook.katana", 0);
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/MyPage/")).setPackage("com.facebook.katana"));
            } else {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.katana")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Constant.displayToast(AboutActivity.this, getResources().getString(R.string.msg_internet));
    }
}
</code>```

But, I am getting the following exception in my Logcat:

```<code>    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://www.facebook.com/... pkg=com.facebook.katana }
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:3978)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:3939)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivity(Activity.java:4262)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivity(Activity.java:4230)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at com.app.thelist.activity.AboutActivity.loadFacebookUrl(AboutActivity.java:98)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at com.app.thelist.activity.AboutActivity.onClick(AboutActivity.java:76)
</code>```

What should I have to do to get the task done? Thanks.

答:
your problem is in the link format... you should use: fb://facewebmodal/f?href=

```<code>Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=https://www.facebook.com/mypage"));
</code>```

check if he has the app, then use the above url format, else redirect him to the browser:

```<code>String pageurl = "https://www.facebook.com/mypage";
boolean hasFacebook = appInstalledOrNot(AboutActivity.this, "com.facebook.katana");
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse((hasFacebook?("fb://facewebmodal/f?href="):"") + pageurl));
startActivity(i);
</code>```

Body:
I need to open Facebook page in my installed Facebook Application. I have called the below function for that :

private void loadFacebookUrl() {
    if (Constant.isOnline(AboutActivity.this)) {
        try {
            if (appInstalledOrNot(AboutActivity.this, "com.facebook.katana")) {
                this.getPackageManager().getPackageInfo("com.facebook.katana", 0);
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/MyPage/")).setPackage("com.facebook.katana"));
            } else {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.katana")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Constant.displayToast(AboutActivity.this, getResources().getString(R.string.msg_internet));
    }
}

But, I am getting the following exception in my Logcat:

    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://www.facebook.com/... pkg=com.facebook.katana }
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:3978)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:3939)
07-07 14:19:24.070 5094-5094/com.app.thelist W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivity(Activity.java:4262)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at android.app.Activity.startActivity(Activity.java:4230)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at com.app.thelist.activity.AboutActivity.loadFacebookUrl(AboutActivity.java:98)
07-07 14:19:24.071 5094-5094/com.app.thelist W/System.err:     at com.app.thelist.activity.AboutActivity.onClick(AboutActivity.java:76)

What should I have to do to get the task done? Thanks.

Body:
your problem is in the link format... you should use: fb://facewebmodal/f?href=

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=https://www.facebook.com/mypage"));

check if he has the app, then use the above url format, else redirect him to the browser:

String pageurl = "https://www.facebook.com/mypage";
boolean hasFacebook = appInstalledOrNot(AboutActivity.this, "com.facebook.katana");
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse((hasFacebook?("fb://facewebmodal/f?href="):"") + pageurl));
startActivity(i);


问:
Flask SQLAlchemy login with postgresql
So I have already created a database using the pgadmin3 in postgresql. I have a set of email-ids and passwords. The passwords which I have stored are hashed, i.e. by using pwd_context.hash(password) from the pass.libs.
I have stored them as shown below in the database. Now I have to create another login form in html to authenticate. I am new to flask, but I have seen something called as flask-login. How to compare the password entered in cleartext with the hashed password in database.

答:
Flask-login provides a set of functions... for user login,logout and so on. More information on Flask-login can be found at https://flask-login.readthedocs.io/en/latest/.

For creating and checking a password hash: When working with Flask often werkzeug security is used to create/hash and check passwords. A snippet in which this is demonstrated can be found here : http://flask.pocoo.org/snippets/54/

Finally an internet search (I have not used any of these tutorial/pages before) retrieved following page: https://blog.miguelgrinberg.com/post/two-factor-authentication-with-flask with a quick browse of the page I found an example of using flask-login and werkzeug for user-login/logout under the title 'The First Factor: Password Authentication'. A quick pointer when using this tutorial is that there have been some changes in naming since the page has come online. For example flask.ext.login has been renamed to flask_login. The tutorial http://blog.sampingchuang.com/setup-user-authentication-in-flask/ also provides more information on flask-login and werkzeug. The pointer on renaming is also valid for this one.

Title: Flask SQLAlchemy login with postgresql


问:
Excel average of values in time values
I have these values, which are time values. However, they are not formatted to time values, so an average will give me 8:82, when it should give 9:03. I can't seem to change the format into hh:mm, the values change to 00:00.

Current format is #0:\00

```<code>8:53    9:11
</code>```

How do I get these recognized as time values?

答:
Assuming that 8:53 is in A1 and 9:11 is in B1 then you can use this formula:

=TEXT(AVERAGE(TIMEVALUE(A1),TIMEVALUE(B1)),"hh:mm")

Which actually gives an average of 9:02.

The Office documentation says:

Returns the decimal number of the time represented by a text string. The decimal number is a value ranging from 0 (zero) to 0.99988426, representing the times from 0:00:00 (12:00:00 AM) to 23:59:59 (11:59:59 P.M.).

So you wouldn't  be able to do something like =TEXT(AVERAGE(TIMEVALUE(A1:D1)),"hh:mm")

Title: Excel average of values in time values

Body:
I have these values, which are time values. However, they are not formatted to time values, so an average will give me 8:82, when it should give 9:03. I can't seem to change the format into hh:mm, the values change to 00:00.

Current format is #0:\00

8:53    9:11

How do I get these recognized as time values?