问:
Storing actively updated fields in the database
I have a database with one of the table storing articles. For every article I need to store the number of times it was viewed. Now, my idea is to store this value in the database and update it every time someone visits the page with that article and I am considering two alternatives now:

Create a column views in the table articles and update it.

Create a separate table view_count with FK pointer to the article and the number views for that article.

My question is: is there any difference between these two approaches in terms of speed and why? Are there any better alternatives?

The database I use is PostgreSQL.

Note, that I am not considering the different ways of accumulating those values in separate files, outside of database and later inserting because i) we do not get as many hits ii) the feature in minor and if it would require such a hassle we would rather abandon it and use some other service for that.

答:
The differences of two proposals are quite subtle, here's how I see them:

Same table

keeping it in the same table will allow you to retrieve it at lower cost

updates might be locking the parts of DB that other queries in the queue need slowing them down

making tables wider increases I/O (it always increase I/O for table scans, but for index lookups it is not so straight forward - when record size becomes bigger then the filesystem's block size then even the index lookups will have to do 2x more I/O; or nx more I/O depending on the record size/block size, if the record size is much less then the block size then the effect for the index lookups depends on the type of query/order of the data on the disk - if choosing records from the same block you will feel the performance hit, if choosing sparse data you will not feel it)

Separate tables

updates will happen on a smaller table so less I/O (locks might still be necessary to check foreign key, depending on isolation level, but should be shorter as there is less I/O)

retrieving data for an article requires a join which will increase I/O

if the view count is a new feature not present on most of your other records you are also saving space and even though join might increase required I/O, this might give better performance

Notes:

The comment apply, but are subtle: record size will probably not get significantly affected to influence all queries. The benefits of less I/O with separate table might not be perceivable.


来源: stackexchange

问:
Laravel attempt to assign property of non-object
I want to allow user to update their profile created on a page however I get an error message saying that i am trying to attempt to assign property of non-object:

But user and twitter do have a value.

In a database field is called twitter_personal and of course id is a id.

Controller:

```<code>function updateProfile(Request $request) {
    $user = Auth::id();
    $twitter = $request->input('twitter');
    $user->twitter_personal = $twitter;
    $user->save();
    if($user->save()) {
    $message = 'Success';
    }else{
    $message = 'Error';
    }
   return redirect()->back()->withInput()->with('message', $message);
</code>```

}

Form:

```<code>            <form class="form-horizontal" role="form" method="POST" action="{{ action('ProfileController@updateProfile') }}">
                {{ csrf_field() }}
                <div class="form-group{{ $errors->has('url') ? ' has-error' : '' }}">
                    <label for="twitter" class="col-md-4 control-label">Twitter</label>
                <div class="col-md-6">
                <input id="twitter" type="text" class="form-control" name="twitter">
                @if ($errors->has('url'))
                <span class="help-block">
                    <strong>{{ $errors->first('url') }}</strong>
                </span>
                @endif
        </div>
    </div>
</code>```

So here's the question, how can I solve it? and is there a better way of doing it? if so please provide an example!

答:
The function Auth::id() will return the identifier of the currently authenticated user.

If you need to user model instead you should user:

```<code> Auth::user()
</code>```

If you instead prefer to not use the Auth facade you can just get the user associated with the current request:

```<code>$request->user()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to allow user to update their profile created on a page however I get an error message saying that i am trying to attempt to assign property of non-object:

But user and twitter do have a value.

In a database field is called twitter_personal and of course id is a id.

Controller:

function updateProfile(Request $request) {
    $user = Auth::id();
    $twitter = $request->input('twitter');
    $user->twitter_personal = $twitter;
    $user->save();
    if($user->save()) {
    $message = 'Success';
    }else{
    $message = 'Error';
    }
   return redirect()->back()->withInput()->with('message', $message);

}

Form:

            <form class="form-horizontal" role="form" method="POST" action="{{ action('ProfileController@updateProfile') }}">
                {{ csrf_field() }}

has('url') ? ' has-error' : '' }}">
                    Twitter

                <input id="twitter" type="text" class="form-control" name="twitter">
                @if ($errors->has('url'))

                    {{ $errors->first('url') }}

                @endif

So here's the question, how can I solve it? and is there a better way of doing it? if so please provide an example!

Body:
The function Auth::id() will return the identifier of the currently authenticated user.

If you need to user model instead you should user:

 Auth::user()

If you instead prefer to not use the Auth facade you can just get the user associated with the current request:

$request->user()


问:
Is it good practice to unit test properties?
I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.</p>

答: Think of TDD and Unit testes as a way to "see ahead", you write the test in a way that you feel would be best for your public signature, of your classes, to be. </p>

ContentLicense: CC BY-SA 2.5


问:
Auto-implement Swift protocol methods in Xcode
I just started with the swift language and coming from java it looks great so far.
But I'm really missing something:

Eclipse had this great feature that when I added "implements XYZ" it provided me a function to automatically implement the necessary function stubs. This is a huge timesaver.

Xcode doesn't seem to have this feature, or am I missing something?

I found the accessorize plugin, but this seems only to work with Objective C..

Is there a solution?

PS. I'm using Xcode 6.1.1

答:
Xcode 9

Xcode 9 now supports conforming to protocol methods via a "fix it". It will automatically fill the missing methods for you. This was announced in WWDC 2017.

Update: This doesn't seem to work for protocols defined by you, unfortunately.

ContentLicense: CC BY-SA 4.0


问:
why int.TryParse cannot initialise multiple variables
I am using int.TryParse to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:

```<code>int min,
    max;
</code>```

using the following conditional statement:

```<code>bool lengthCompatible = int.TryParse(string1, out min) &&
                        int.TryParse(string2, out max);
</code>```

Visual Studio (2015) produces the following code highlighting:

Use of unassigned local variable 'max'

Local variable 'max' might not be initialized before accessing

However, if I use 2 conditional statements:

```<code>bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);
</code>```

I can compile with no errors.

Curiouser and curiouser! Any insight appreciated.

Cheers

答:
This is called shortcut boolean evaluation. This makes sure that boolean expressions are only evaluated until the final result is found.

If the first int.TryParse(string1, out min) already, the second one will not be executed, as the overall result will already be false. So the max variable is not guaranteed to be always initialized.

Body:
I am using int.TryParse to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:

int min,
    max;

using the following conditional statement:

bool lengthCompatible = int.TryParse(string1, out min) &&
                        int.TryParse(string2, out max);

Visual Studio (2015) produces the following code highlighting:

Use of unassigned local variable 'max'

Local variable 'max' might not be initialized before accessing

However, if I use 2 conditional statements:

bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);

I can compile with no errors.

Curiouser and curiouser! Any insight appreciated.

Cheers


问:
unable to fetch the list values from the website
i fetch all the detail from the desire website but unable to get the some specific information please guide me for that.

targeted domain: https://shop.adidas.ae/en/messi-16-3-indoor-boots/BA9855.html

my code isresponse.xpath('//ul[@class="product-size"]//li/text()').extract()

need to fetch data!!!

Thanks!

答:
The data you want to fetch is loaded from a javascript. It is said explicitly in the tag class="js-size-value ".

If you want to get it, you will need to use a rendering service. I suggest you use Splash, it is simple to install and simple to use. You will need docker to install splash.


问:
Creating a transaction through DataSource.getTransaction(def) does not set the currentTransactionStatus to it
We have an application with three databases. Two of them are only very seldomly updated. We tried JPA to create transactions around it and it worked for the databases, but grails then did not work on different places (gsp related I am told). This was tried quite a while ago (and not by me).

Due to delivery pressure we needed a solution that at least works for us, so I created a new aspect for the methods changing data in multiple databases. I got this to work, it is a fairly simple approach.

In the aspect we request to start a transaction for each data source, by calling getTransaction(TransactionDefinition def) with the propagation set to REQUIRES_NEW. We then proceed and finally rollback or commit depending on the outcome of the call.

However, one test flow failed. This is the scenario where the code requests a rollback by calling TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(). Of the three TransactionStatusses obtained initially, none actually returns isRollbackOnly() with true. However calling TransactionAspectSupport.currentTransationStatus().isRollbackOnly() does return true. So this seems to point to a different transaction status.

I have not been able to figure out how to make this work, other than checking this additional status. I could not find a way to change the currentTransactionStatus to the one of created TransactionStatus. Looking at the TransactionTemplate implementation, I seem to do things correctly (it also just calls getTransaction() on the datasource).

The code calling the decorated method has specified @Transactional(propagation=Propagation.NOT_SUPPORTED), so I expected no currentTransactionStatus, but one is there.
However, if it is not there the proxied code will not be able to request a rollback the standard way, which I want to be able to fix.

So the question is, how to start a transaction correctly from an Aspect so that the currentTransactionStatus is set correctly or how to set the currentTransactionStatus to what I think is the correct one.

Regards,
Wim Veldhuis.

答:
I finally figured it out.

@Transactional leads to a different code path, where eventually TransactionAspectSupport.invokeWithinTransaction is invoked. This method will set up the current transaction correctly.

So in order to make my approach working, I needed to derive from TransactionAspectSupport, do a number of cast operations so I could get to the correct values for the invokeWithinTransaction call, and within the guarded function block use getTransaction(def) to obtain txns for the OTHER databases. I have choose the most important database to be the one used for invoke...

To make it work I had also to provide a TransactionAttributeSource, that returned my default transaction attributes.That one is stored into the TransactionAspectSupport base class during initialization.

```<code>    @Around("@annotation(framework.db.MultiDbTransactional)")
public Object multiDbTransaction(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    // Get class and method, needed for parent invocation. We need to cast to the actual
    // implementation
    MethodInvocationProceedingJoinPoint mipJoinPoint = (MethodInvocationProceedingJoinPoint) proceedingJoinPoint;
    MethodSignature signature = (MethodSignature) mipJoinPoint.getSignature();
    Class<?> clazz = mipJoinPoint.getTarget().getClass();
    Method method = signature.getMethod();

    return invokeWithinTransaction(method, clazz, new InvocationCallback() {
        @Override
        public Object proceedWithInvocation() throws Throwable {

            // This class will create the other transactions, not of interest here.
            MultiDbTxnContext ctx = new MultiDbTxnContext();
            ctx.startTransactions();

            /*
             * We have started the transactions, so do the job. We mimic DEFAULT spring behavior
             * regarding exceptions, so runtime exceptions roll back, the rest commits.
             */
            try {
                Object result = proceedingJoinPoint.proceed();
                ctx.finishTransactions();
                return result;
            } catch (Error | RuntimeException re) {
                ctx.rollbackTransactions();
                throw re;
            } catch (Throwable t) {
                ctx.commitTransactions();
                throw t;
            }
        }
    });

}
</code>```

Body:
I finally figured it out.

@Transactional leads to a different code path, where eventually TransactionAspectSupport.invokeWithinTransaction is invoked. This method will set up the current transaction correctly.

So in order to make my approach working, I needed to derive from TransactionAspectSupport, do a number of cast operations so I could get to the correct values for the invokeWithinTransaction call, and within the guarded function block use getTransaction(def) to obtain txns for the OTHER databases. I have choose the most important database to be the one used for invoke...

To make it work I had also to provide a TransactionAttributeSource, that returned my default transaction attributes.That one is stored into the TransactionAspectSupport base class during initialization.

    @Around("@annotation(framework.db.MultiDbTransactional)")
public Object multiDbTransaction(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    // Get class and method, needed for parent invocation. We need to cast to the actual
    // implementation
    MethodInvocationProceedingJoinPoint mipJoinPoint = (MethodInvocationProceedingJoinPoint) proceedingJoinPoint;
    MethodSignature signature = (MethodSignature) mipJoinPoint.getSignature();
    Class<?> clazz = mipJoinPoint.getTarget().getClass();
    Method method = signature.getMethod();

    return invokeWithinTransaction(method, clazz, new InvocationCallback() {
        @Override
        public Object proceedWithInvocation() throws Throwable {

            // This class will create the other transactions, not of interest here.
            MultiDbTxnContext ctx = new MultiDbTxnContext();
            ctx.startTransactions();

            /*
             * We have started the transactions, so do the job. We mimic DEFAULT spring behavior
             * regarding exceptions, so runtime exceptions roll back, the rest commits.
             */
            try {
                Object result = proceedingJoinPoint.proceed();
                ctx.finishTransactions();
                return result;
            } catch (Error | RuntimeException re) {
                ctx.rollbackTransactions();
                throw re;
            } catch (Throwable t) {
                ctx.commitTransactions();
                throw t;
            }
        }
    });

}


问:
woocommerce login form submit with button instead on input
I'm wanting to use a button element rather than input on the woocommerce login form, purely for styling reasons. So rather than

```<code><input type="submit" class="btn btn-outline-primary" name="login" value="Login" />
</code>```

I want to use

```<code><button type="submit" class="btn btn-outline-primary">Login</button>
</code>```

This doesn't work though and I've no idea why.

答:
Just found it out the button element need the value setting the same as the input i.e.</p>

```<code><button type="submit" class="btn btn-outline-primary" name="login" value="Login">Login</button>
</code>```

Body:
I'm wanting to use a button element rather than input on the woocommerce login form, purely for styling reasons. So rather than

<input type="submit" class="btn btn-outline-primary" name="login" value="Login" />

I want to use

<button type="submit" class="btn btn-outline-primary">Login</button>

This doesn't work though and I've no idea why.

Body:
Just found it out the button element need the value setting the same as the input i.e.

<button type="submit" class="btn btn-outline-primary" name="login" value="Login">Login</button>


问:
Xcode 9 beta new build system fails with "unable to build node" error
It seems like Xcode 9 beta does not like "~ipad" in filenames for .xib files. When selecting the new build system (for a project, that is compiling successfully with the old build system), it errors out with:

unable to build node:
  '/Users/dev/Library/Developer/Xcode/DerivedData/proj-aiatvieseyfwjkfqncikqcohpdsn/Build/Products/Debug-iphoneos/proj.app/Controller~ipad.nib'
  (node is produced by multiple commands; e.g.,
  'adf8a93da84709e14beaf35ec6d6d21c02c34dc4669b6bd1e18a027ff75b53b5:CompileXIB
  /Users/dev/git/proj/Resources/Controllers/Controller.xib' and
  'adf8a93da84709e14beaf35ec6d6d21c02c34dc4669b6bd1e18a027ff75b53b5:CompileXIB
  /Users/dev/git/proj/Resources/Controllers/Controller~ipad.xib')

Should I rename them or is there another solution?

答:
It's a known bug in Xcode 9 beta. There is no workaround for the moment.

"XIB and Storyboard files which use platform-specific naming conventions (e.g. “MyView~ipad.xib”) may cause the new build system to emit an “unable to build node” error. (32409101)"

So YES, you can try to remove the "~ipad" and just execute it on iPad simulator.

Open radar: New Build System fails to build project containing universal xib


问:
Tensorflow always predict the same output
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

```<code>df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)
</code>```

out:

(20, 1)
(20, 1)

in:

```<code># Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
</code>```

out:

```<code>Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]
</code>```

in:

```<code>sess.run(y, feed_dict={x: inputX })
</code>```

out:

```<code>array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)
</code>```

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.

答:
The main problem that I see is that you initialize your weights in the W matrix with 0s. The operation that you have in the linear layer is basically Wx + b. Hence the gradient with respect to x is W. If you start now with zeros for W then the gradient is 0 as well and you are not able to learn anything. Try to use random initial values as stated on tensorflow.org</p>

```<code># Create two variables.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
                      name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
</code>```

Body:
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)

out:

(20, 1)
(20, 1)

in:

# Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

out:

Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]

in:

sess.run(y, feed_dict={x: inputX })

out:

array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.

Body:
The main problem that I see is that you initialize your weights in the W matrix with 0s. The operation that you have in the linear layer is basically Wx + b. Hence the gradient with respect to x is W. If you start now with zeros for W then the gradient is 0 as well and you are not able to learn anything. Try to use random initial values as stated on tensorflow.org

# Create two variables.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
                      name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")


问:
Show Command Prompt Output with BackgroundWorker.Backgroundworker
I have a program that executes a batch file using an asynchronous background worker. Here is the code:

```<code>public static void Execute(CmdObj obj, bool batch)
{
    CmdObj = obj;

    var theWorker = new BackgroundWorker();
    theWorker.RunWorkerCompleted += WorkerCompleted;
    theWorker.WorkerReportsProgress = true;

    if(batch)
    {
        theWorker.DoWork += WorkerBatchWork;
    }else{
        theWorker.DoWork += WorkerCommandWork;
    }
    theWorker.RunWorkerAsync();

}

private static void WorkerBatchWork(object sender, DoWorkEventArgs e)
{
    RunBatch(CmdObj);
}

private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
    if (temp != null)
        ProgramPath = temp.Substring(6);

    WriteLog(CmdObj.Activity, false);
    WriteLog(CmdObj.Error, true);

    CmdObj.TheButton.Enabled = true;
}

private static void RunBatch(CmdObj obj)
{
    var process = new Process();
    var startInfo = new ProcessStartInfo
                        {
                            FileName = obj.SrcFile,
                            WindowStyle = ProcessWindowStyle.Normal,
                            CreateNoWindow = false,
                            RedirectStandardInput = true,
                            RedirectStandardOutput = false,
                            RedirectStandardError = true,
                            UseShellExecute = false
                        };

    try
    {
        if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
            throw new FileLoadException("Not a valid .bat file",obj.SrcFile);

        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        //obj.Activity = process.StandardOutput.ReadToEnd();
        obj.Error = process.StandardError.ReadToEnd();

    }
    catch (Exception ex)
    {
        obj.Exception = ex;
    }
    finally
    {
        process.Close();
    }
}

class CmdObj
{
    public string Command { get; set; }
    public string SrcFile { get; set; }
    public string Activity { get; set; }
    public string Error { get; set; }
    public Exception Exception { get; set; }
    public Button TheButton { get; set; }
}
</code>```

So when I run this program and choose a batch file to execute, I get a blank CMD window. Is there some way to show the output in the CMD window when my program executes the batch file? Alternatively, if I could have the CMD output sent to a textbox or some other control (in real-time), that would work as well.

Thanks!

答:
Don't you need to call

```<code> process.BeginErrorReadLine();
 process.BeginOutputReadLine();
</code>```

after process starts?
I had some problems without this if I remember right.

Body:
I have a program that executes a batch file using an asynchronous background worker. Here is the code:

public static void Execute(CmdObj obj, bool batch)
{
    CmdObj = obj;

    var theWorker = new BackgroundWorker();
    theWorker.RunWorkerCompleted += WorkerCompleted;
    theWorker.WorkerReportsProgress = true;

    if(batch)
    {
        theWorker.DoWork += WorkerBatchWork;
    }else{
        theWorker.DoWork += WorkerCommandWork;
    }
    theWorker.RunWorkerAsync();

}

private static void WorkerBatchWork(object sender, DoWorkEventArgs e)
{
    RunBatch(CmdObj);
}

private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
    if (temp != null)
        ProgramPath = temp.Substring(6);

    WriteLog(CmdObj.Activity, false);
    WriteLog(CmdObj.Error, true);

    CmdObj.TheButton.Enabled = true;
}

private static void RunBatch(CmdObj obj)
{
    var process = new Process();
    var startInfo = new ProcessStartInfo
                        {
                            FileName = obj.SrcFile,
                            WindowStyle = ProcessWindowStyle.Normal,
                            CreateNoWindow = false,
                            RedirectStandardInput = true,
                            RedirectStandardOutput = false,
                            RedirectStandardError = true,
                            UseShellExecute = false
                        };

    try
    {
        if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
            throw new FileLoadException("Not a valid .bat file",obj.SrcFile);

        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        //obj.Activity = process.StandardOutput.ReadToEnd();
        obj.Error = process.StandardError.ReadToEnd();

    }
    catch (Exception ex)
    {
        obj.Exception = ex;
    }
    finally
    {
        process.Close();
    }
}

class CmdObj
{
    public string Command { get; set; }
    public string SrcFile { get; set; }
    public string Activity { get; set; }
    public string Error { get; set; }
    public Exception Exception { get; set; }
    public Button TheButton { get; set; }
}

So when I run this program and choose a batch file to execute, I get a blank CMD window. Is there some way to show the output in the CMD window when my program executes the batch file? Alternatively, if I could have the CMD output sent to a textbox or some other control (in real-time), that would work as well.

Thanks!

Body:
Don't you need to call

 process.BeginErrorReadLine();
 process.BeginOutputReadLine();

after process starts?
I had some problems without this if I remember right.


问:
Getting Location of Created Object from AspNet WebApi with HttpClient
I got an Service to Post Data and Returning Location of Created Object

```<code> public IHttpActionResult Post([FromBody]ErbrachteLeistung value)
{
  int newLeistungId = service.AddErbrachteLeistung(value);
  return Created($"api/ErbrachteLeistung/{newLeistungId}", value);
}
</code>```

My Client Looks like this

```<code>HttpClientHandler handler = new HttpClientHandler
  {
    UseDefaultCredentials = true,
    AllowAutoRedirect = true
  };

  using (HttpClient client = new HttpClient(handler))
  {
    client.BaseAddress = new Uri(WebApiUri);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = client.PostAsJsonAsync<ErbrachteLeistung>("api/ErbrachteLeistung", erbrachteLeistung).Result;
    response.EnsureSuccessStatusCode();
  }
</code>```

How can I read the Created Location given in the WebService out of the Response?

答:
The 201 Created response stores that value in the Location Header</p>

```<code>//...
response.EnsureSuccessStatusCode();
Uri location = response.Headers.Location;

//...
</code>```

Body:
I got an Service to Post Data and Returning Location of Created Object

 public IHttpActionResult Post([FromBody]ErbrachteLeistung value)
{
  int newLeistungId = service.AddErbrachteLeistung(value);
  return Created($"api/ErbrachteLeistung/{newLeistungId}", value);
}

My Client Looks like this

HttpClientHandler handler = new HttpClientHandler
  {
    UseDefaultCredentials = true,
    AllowAutoRedirect = true
  };

  using (HttpClient client = new HttpClient(handler))
  {
    client.BaseAddress = new Uri(WebApiUri);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = client.PostAsJsonAsync<ErbrachteLeistung>("api/ErbrachteLeistung", erbrachteLeistung).Result;
    response.EnsureSuccessStatusCode();
  }

How can I read the Created Location given in the WebService out of the Response?

Body:
The 201 Created response stores that value in the Location Header

//...
response.EnsureSuccessStatusCode();
Uri location = response.Headers.Location;

//...


问:
How to find month no,name from week number using php
How to find month no,name from week number using php</p>

答:
```<code>echo date('F',strtotime('1 January 2010 +50 weeks'));
</code>```

www.php.net/date

www.php.net/strtotime

Body:
echo date('F',strtotime('1 January 2010 +50 weeks'));

www.php.net/date

www.php.net/strtotime


问:
Java: Printing trailing spaces
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

```<code>4
1 4 3 2
</code>```

The code will need to reverse the second input to the following:

```<code>2 3 4 1
</code>```

My solution is as follow:

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}
</code>```

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

答:
The easy way to reverse a string is using the StringBuilder class:

One option is to remove the spaces at the end of the string eg. remove last char

```<code>package stackoverflow.main;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        StringBuilder sb = new StringBuilder();

        for(int arr_i = 0; arr_i < n; arr_i++){
            sb.append(in.nextInt());
            sb.append(" ");
        }

        sb.deleteCharAt(sb.length() - 1);

        String normal = sb.toString();
        String reversed = sb.reverse().toString();

        System.out.println("normal: " + normal);
        System.out.println("reversed: " + reversed);
    }
}
</code>```

Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space

```<code>package stackoverflow.main;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        StringBuilder sb = new StringBuilder();

        for(int arr_i = 0; arr_i < n; arr_i++){
            sb.append(in.nextInt());
            if (arr_i != 3
                sb.append(" ");
        }

        String normal = sb.toString();
        String reversed = sb.reverse().toString();

        System.out.println("normal: " + normal);
        System.out.println("reversed: " + reversed);
    }
}
</code>```

Title: Java: Printing trailing spaces

Body:
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

4
1 4 3 2

The code will need to reverse the second input to the following:

2 3 4 1

My solution is as follow:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

Body:
The easy way to reverse a string is using the StringBuilder class:

One option is to remove the spaces at the end of the string eg. remove last char

package stackoverflow.main;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        StringBuilder sb = new StringBuilder();

        for(int arr_i = 0; arr_i < n; arr_i++){
            sb.append(in.nextInt());
            sb.append(" ");
        }

        sb.deleteCharAt(sb.length() - 1);

        String normal = sb.toString();
        String reversed = sb.reverse().toString();

        System.out.println("normal: " + normal);
        System.out.println("reversed: " + reversed);
    }
}

Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space

package stackoverflow.main;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        StringBuilder sb = new StringBuilder();

        for(int arr_i = 0; arr_i < n; arr_i++){
            sb.append(in.nextInt());
            if (arr_i != 3
                sb.append(" ");
        }

        String normal = sb.toString();
        String reversed = sb.reverse().toString();

        System.out.println("normal: " + normal);
        System.out.println("reversed: " + reversed);
    }
}


问:
Create CGColor from { alpha, red, green, blue } values in Xamarin.iOS
I would like to create a CGColor from ARGB (alpha-RGB) values. Is it possible to do it? How?

答:
You can simply do the following if you have the values to pass in.

```<code>UIColor.FromRGBA(red, green, blue, alpha).CGColor;
</code>```

We use a little helper class for converting hash values to UIColors as well, just incase you need it. Simply pass in a hash values ("#ffffff"). Then call .CGColor on the UIColor that it returns, or alternatively adjust the class accordingly.

```<code>class Colors
    {
        public static UIColor FromHexString(string hexValue, float alpha = 1.0f)
        {
            try
            {
                string colorString = hexValue.Replace("#", "");

                float red, green, blue;

                switch (colorString.Length)
                {
                    case 3: // #RGB
                        {
                            red = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(0, 1)), 16) / 255f;
                            green = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(1, 1)), 16) / 255f;
                            blue = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(2, 1)), 16) / 255f;
                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }
                    case 6: // #RRGGBB
                        {
                            red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
                            green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
                            blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }
                    case 8: // #RRGGBBAA
                        {
                            red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
                            green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
                            blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
                            alpha = Convert.ToInt32(colorString.Substring(6, 2), 16) / 255f;

                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }

                    default:
                        throw new ArgumentOutOfRangeException(string.Format("Invalid color value {0} is invalid. It should be a hex value of the form #RBG, #RRGGBB", hexValue));

                }
            }
            catch (Exception genEx)
            {
                return null;
            }
        }
    }
</code>```

Body:
You can simply do the following if you have the values to pass in.

UIColor.FromRGBA(red, green, blue, alpha).CGColor;

We use a little helper class for converting hash values to UIColors as well, just incase you need it. Simply pass in a hash values ("#ffffff"). Then call .CGColor on the UIColor that it returns, or alternatively adjust the class accordingly.

class Colors
    {
        public static UIColor FromHexString(string hexValue, float alpha = 1.0f)
        {
            try
            {
                string colorString = hexValue.Replace("#", "");

                float red, green, blue;

                switch (colorString.Length)
                {
                    case 3: // #RGB
                        {
                            red = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(0, 1)), 16) / 255f;
                            green = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(1, 1)), 16) / 255f;
                            blue = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(2, 1)), 16) / 255f;
                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }
                    case 6: // #RRGGBB
                        {
                            red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
                            green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
                            blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }
                    case 8: // #RRGGBBAA
                        {
                            red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f;
                            green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f;
                            blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f;
                            alpha = Convert.ToInt32(colorString.Substring(6, 2), 16) / 255f;

                            return UIColor.FromRGBA(red, green, blue, alpha);
                        }

                    default:
                        throw new ArgumentOutOfRangeException(string.Format("Invalid color value {0} is invalid. It should be a hex value of the form #RBG, #RRGGBB", hexValue));

                }
            }
            catch (Exception genEx)
            {
                return null;
            }
        }
    }


问:
android.content.Context.getSystemService(java.lang.String)' on a null object reference
when click  button on 'listview', I want to use Push Notification.
But there is Error..

'ListViewAdapter'

```<code> public class ListViewAdapter extends BaseAdapter{
private Context con;
public ListViewAdapter(Context con) {
        this.con = con;
        getData("http://117.17.158.240/test/GpsSender.php");
    }
....
...
 @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(com.satt.mjbus.R.layout.listview_item, parent, false);

        }
 final ImageButton btn = (ImageButton)convertView.findViewById(com.satt.mjbus.R.id.button);
        btn.setTag(position);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int poss = (Integer) v.getTag();
                int check_num = 0;

                btn.setSelected(true);
                if (check_num == 0) {
                    btn.setSelected(true);
                    check_num = 1;
                } else if (check_num == 1) {
                    btn.setSelected(false);
                    check_num = 0;
                }
                NotificationManager notificationManager = (NotificationManager) con.getSystemService(con.NOTIFICATION_SERVICE);
                Intent intent1 = new Intent(con.getApplicationContext(), ListViewAdapter.class);

                Notification.Builder builder = new Notification.Builder(con.getApplicationContext());
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingNotificationIntent = PendingIntent.getActivity(con, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setSmallIcon(R.drawable.bus)
                        .setTicker("HETT")
                        .setWhen(System.currentTimeMillis())
                        .setNumber(1)
                        .setContentTitle("푸쉬 제목")
                        .setContentText("푸쉬내용")
                        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                        .setContentIntent(pendingNotificationIntent)
                        .setAutoCancel(true)
                        .setOngoing(true);

                notificationManager.notify(1, builder.build());

            }

        });
        btn.setFocusable(false);

....
}
</code>```

And I got error is
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

plz help..

答:
replace             LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
with

LayoutInflater inflater = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Body:
when click  button on 'listview', I want to use Push Notification.
But there is Error..

'ListViewAdapter'

 public class ListViewAdapter extends BaseAdapter{
private Context con;
public ListViewAdapter(Context con) {
        this.con = con;
        getData("http://117.17.158.240/test/GpsSender.php");
    }
....
...
 @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(com.satt.mjbus.R.layout.listview_item, parent, false);

        }
 final ImageButton btn = (ImageButton)convertView.findViewById(com.satt.mjbus.R.id.button);
        btn.setTag(position);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int poss = (Integer) v.getTag();
                int check_num = 0;

                btn.setSelected(true);
                if (check_num == 0) {
                    btn.setSelected(true);
                    check_num = 1;
                } else if (check_num == 1) {
                    btn.setSelected(false);
                    check_num = 0;
                }
                NotificationManager notificationManager = (NotificationManager) con.getSystemService(con.NOTIFICATION_SERVICE);
                Intent intent1 = new Intent(con.getApplicationContext(), ListViewAdapter.class);

                Notification.Builder builder = new Notification.Builder(con.getApplicationContext());
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingNotificationIntent = PendingIntent.getActivity(con, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setSmallIcon(R.drawable.bus)
                        .setTicker("HETT")
                        .setWhen(System.currentTimeMillis())
                        .setNumber(1)
                        .setContentTitle("푸쉬 제목")
                        .setContentText("푸쉬내용")
                        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                        .setContentIntent(pendingNotificationIntent)
                        .setAutoCancel(true)
                        .setOngoing(true);

                notificationManager.notify(1, builder.build());

            }

        });
        btn.setFocusable(false);

....
}

And I got error is
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

plz help..


问:
MVC DateTime validation - UK Date format
I have a simple view with two date fields with ValidationMessageFor controls added for the unobtrusive JavaScript validation.

My issue is I keep getting told my date is invalid, when it is in correct format (dd/MM/yyyy)

I have added <globalization culture="en-GB" uiCulture="en-GB"/> to my web.config, and also included [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] on each DateTime property, yet it still won't accept UK format dates.

Is there anything obvious I am missing here?

答:
Try change this direct in jquery.validate.js. Work with $.datpicker</p>

```<code>date: function (value, element) {
    var s = value;

    var ind2 = 3;
    var ind3 = 6;
    var ind4 = 4;

    if (s.substr(6, 1) != "2") {
        ind2 = ind2 + 1;
        ind3 = ind3 + 1;
        ind4 = ind4 + 1;
    }

    var ndan = s.substr(0, 2);
    var nmje = s.substr(ind2, 2);
    var ngod = s.substr(ind3, ind4);

    var ns = ngod + "," + nmje + "," + ndan;

    return this.optional(element) || !/Invalid|NaN/.test(new Date(ns));
</code>```

Body:
Try change this direct in jquery.validate.js. Work with $.datpicker

date: function (value, element) {
    var s = value;

    var ind2 = 3;
    var ind3 = 6;
    var ind4 = 4;

    if (s.substr(6, 1) != "2") {
        ind2 = ind2 + 1;
        ind3 = ind3 + 1;
        ind4 = ind4 + 1;
    }

    var ndan = s.substr(0, 2);
    var nmje = s.substr(ind2, 2);
    var ngod = s.substr(ind3, ind4);

    var ns = ngod + "," + nmje + "," + ndan;

    return this.optional(element) || !/Invalid|NaN/.test(new Date(ns));


问:
Swift 2.2 loop through string and get char & index
I'm trying to loop through a String get get the characters as well as their index. Sounds easy.. but I'm not finding the correct syntax for doing that.

Here is what I was trying:

```<code>let str = "testString"
for (index, char) in str.characters  {
    print(index)
    print(char)
}
</code>```

or

```<code>for (index, char) in enumerate(str.characters)  {...}
</code>```

答:
Swift 4

```<code>let str = "Swift 4"
for (index, element) in str.enumerated() {
    print(index)
    print(element)
}
</code>```

Body:
I'm trying to loop through a String get get the characters as well as their index. Sounds easy.. but I'm not finding the correct syntax for doing that.

Here is what I was trying:

let str = "testString"
for (index, char) in str.characters  {
    print(index)
    print(char)
}

or

for (index, char) in enumerate(str.characters)  {...}

Body:
Swift 4

let str = "Swift 4"
for (index, element) in str.enumerated() {
    print(index)
    print(element)
}


问:
Override copy past functionality of a WPF grid view
I have a WPF DataGrid with one column:

```<code> <DataGrid Name="myGRID">
    <DataGrid.Columns>
        <DataGridTextColumn Header="myHeader Binding="{Binding myObservableCollection}">
            <DataGridTextColumn.HeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Setter Property="HorizontalContentAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.HeaderStyle>
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="HorizontalAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.ElementStyle>
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="{x:Type TextBox}">
                    <EventSetter Event="TextChanged" Handler="tbx_ConcernEnter_TextChanged"/>
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

Now i want to override the paste function of the rows.
When i use:

```<code><DataGrid>
<CommandBinding Command="Paste" Executed="CommandBinding_Executed"/>
</DataGrid>
</code>```

this seems to be the override for the whole GridView but not for a specific row.

Do you know how to override this?

答:
The TextBox in the CellEditingTemplate "swallows" the paste command. But you could handle the Loaded event for the TextBox and hook up a Pasting event handler to it:

```<code><DataGridTextColumn.EditingElementStyle>
    <Style TargetType="{x:Type TextBox}">
        <EventSetter Event="TextChanged" Handler="tbx_ConcernEnter_TextChanged"/>
        <EventSetter Event="Loaded" Handler="TextBox_Loaded" />
    </Style>
</DataGridTextColumn.EditingElementStyle>
</code>```

```<code>private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
    TextBox textBox = sender as TextBox;
    DataObject.AddPastingHandler(textBox, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    //paste detected...
}
</code>```

Body:
I have a WPF DataGrid with one column:

 <DataGrid Name="myGRID">
    <DataGrid.Columns>
        <DataGridTextColumn Header="myHeader Binding="{Binding myObservableCollection}">
            <DataGridTextColumn.HeaderStyle>

            </DataGridTextColumn.HeaderStyle>
            <DataGridTextColumn.ElementStyle>

            </DataGridTextColumn.ElementStyle>
            <DataGridTextColumn.EditingElementStyle>

            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

Now i want to override the paste function of the rows.
When i use:

<DataGrid>
<CommandBinding Command="Paste" Executed="CommandBinding_Executed"/>
</DataGrid>

this seems to be the override for the whole GridView but not for a specific row.

Do you know how to override this?

Body:
The TextBox in the CellEditingTemplate "swallows" the paste command. But you could handle the Loaded event for the TextBox and hook up a Pasting event handler to it:

<DataGridTextColumn.EditingElementStyle>
    <Style TargetType="{x:Type TextBox}">
        <EventSetter Event="TextChanged" Handler="tbx_ConcernEnter_TextChanged"/>
        <EventSetter Event="Loaded" Handler="TextBox_Loaded" />
    </Style>
</DataGridTextColumn.EditingElementStyle>

private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
    TextBox textBox = sender as TextBox;
    DataObject.AddPastingHandler(textBox, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    //paste detected...
}


问:
sonar.Qualitygate is Deprecated in Sonar Qube 5.3. What is the alternative?
Context: In Sonar Qube, there exists a custom Quality Gate which is called say abcd. This is NOT the default quality gate. And in Jenkins, I had configured this SonarQube Quality Gate for a set of APIs by using the parameter
-Dsonar.QualityGate=abcd and it was working fine.

Recently Sonar Qube was upgraded to version 5.3. Since then, the abcd quality gate is not working and the default quality gate is coming into play instead of the abcd quality gate for all the APIs.

On analysis, I came to know that sonar.QualityGate is deprecated in Version 5.3.

Question: Can you please let me know what is the alternative? And how do I make sure that these set of APIs have abcd as the quality gate and not the default quality gate?

I would prefer a solution such that I can configure something on Jenkins as I have access to Jenkins but not to Sonar Qube configurations.

答:
You can still dynamically create an association gate - project via Sonarqube Web API.

From your Sonarqube instance, go to its /web_api URL (e.g. http://my-sonarqube/web_api) and check the list of available operations.

The web_api/api/qualitygates is the set of operations related to quality gates.
The web_api/api/qualitygates/select is the operation you need to associate a gate to a project.

Hence, as replacement of the deprecated sonar.qualitygate, you can use either the manual association via the web UI or a dynamic (and automated) association via web API, recommended. The latter case is the way to go in case of Continous Integration jobs (as you mentioned Jenkins in this context) that would need to create dynamically the link (especially useful for branches management).

As a mandatory step for this operation to work, you need to pass some permissions, e.g. an user token, as recommended approach from official Sonarqube documentation on Web API.

An example of what a CI step may look like just before invoking the sonar:sonar step:

```<code>curl -u ${sonar.password.token}: ${sonar.setqualitygate.url} \
-d "gateId=${sonar.gate.id}&projectKey=${sonar.project.key}:${planRepository.branch}"
</code>```

Where:

sonar.password.token is a token you need to generate from the Sonarqube User management page, for a technical user (e.g. a Jenkins user used to make the connection between the component)

sonar.setqualitygate.url the URL of the REST API endpoint (e.g. http://your.sonarqube.domain/api/qualitygates/select)

sonar.gate.id is the gate id, you can find it easily on the URL of the concerned gate (e.g. http://your.sonarqube.domain/quality_gates/show/<id>)

sonar.project.key and planRepository.branch here we are building dynamically the name of the project for a certain branch as well, you can skip this step if you don't want to handle branches dynamically (e.g. easy to do in Bamboo, a bit more tricky in Jenkins)

Body:
You can still dynamically create an association gate - project via Sonarqube Web API.

From your Sonarqube instance, go to its /web_api URL (e.g. http://my-sonarqube/web_api) and check the list of available operations.

The web_api/api/qualitygates is the set of operations related to quality gates.
The web_api/api/qualitygates/select is the operation you need to associate a gate to a project.

Hence, as replacement of the deprecated sonar.qualitygate, you can use either the manual association via the web UI or a dynamic (and automated) association via web API, recommended. The latter case is the way to go in case of Continous Integration jobs (as you mentioned Jenkins in this context) that would need to create dynamically the link (especially useful for branches management).

As a mandatory step for this operation to work, you need to pass some permissions, e.g. an user token, as recommended approach from official Sonarqube documentation on Web API.

An example of what a CI step may look like just before invoking the sonar:sonar step:

curl -u ${sonar.password.token}: ${sonar.setqualitygate.url} \
-d "gateId=${sonar.gate.id}&projectKey=${sonar.project.key}:${planRepository.branch}"

Where:

sonar.password.token is a token you need to generate from the Sonarqube User management page, for a technical user (e.g. a Jenkins user used to make the connection between the component)

sonar.setqualitygate.url the URL of the REST API endpoint (e.g. http://your.sonarqube.domain/api/qualitygates/select)

sonar.gate.id is the gate id, you can find it easily on the URL of the concerned gate (e.g. http://your.sonarqube.domain/quality_gates/show/<id>)

sonar.project.key and planRepository.branch here we are building dynamically the name of the project for a certain branch as well, you can skip this step if you don't want to handle branches dynamically (e.g. easy to do in Bamboo, a bit more tricky in Jenkins)


问:
Project Job Scheduling: Where are resetPanel and createChart called?
I am working on a Class that takes data from a csv, works with a Scheduler Object, and associates the data with the scheduler's attributes(Project, Job, Allocation, Resource, etc). I was thinking after I got everything down(ProjectList, JobList, AllocationList, ExecutionModeList, Resources) I could just pass the scheduler object into createChart.

However, I am still unsure as to where resetPanel and createChart are called( I understand that the ProjectJobPanel has these functions).

So my 2 questions are:

Where are these functions called?( I couldn't find this information in the documentation)

If i want to display my data, do I need to do anything else other than pass in the scheduler object into the "createChart" function?

答: resetPanel() is called by the example swing dialog when a new dataset is loaded. If updatePanel() isn't overwritten, it's also called when a new best solution is found (so for every best solution changed event).


问:
how to play video in same page(media player)
hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....

this is my screen shot:

if i click thumbnails the video will play another page:
that screen shot:

this is for my coding:

```<code>public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;

protected Context _context;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    _context = getApplicationContext();

    setContentView(R.layout.main);

    //set GridView for gallery
    _gallery = (Gallery) findViewById(R.id.videoGrdVw);
    //set default as external/sdcard uri
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //initialize the videos uri
    //showToast(_contentUri.getPath());
    initVideosId();
    //set gallery adapter
    setGalleryAdapter();
}
private void setGalleryAdapter() {
    _gallery.setAdapter(new VideoGalleryAdapter(_context));
    _gallery.setOnItemClickListener(videogridlistener);
    }
private void initVideosId() {
    try
    {
        //Here we set up a string array of the thumbnail ID column we want to get back
        String [] proj={_ID};
        // Now we create the cursor pointing to the external thumbnail store
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int count= _cursor.getCount();
        System.out.println("total"+_cursor.getCount());
        // We now get the column index of the thumbnail id
        _columnIndex = _cursor.getColumnIndex(_ID);
        //initialize
        _videosId = new int[count];
        //move position to first element
        _cursor.moveToFirst();
        for(int i=0;i<count;i++)
        {
            int id = _cursor.getInt(_columnIndex);
            //

            _videosId[i]= id;
            //
            _cursor.moveToNext();
            //
        }
    }catch(Exception ex)
    {
        showToast(ex.getMessage().toString());
    }

}
protected void showToast(String msg)
{
    Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position,
long id) {
        // Now we want to actually get the data location of the file
        String [] proj={MEDIA_DATA};
        // We request our cursor again
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);
          //System.gc();
         // video_column_index =
           _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
          _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
            // Lets move to the selected item in the cursor
            _cursor.moveToPosition(position);

          String filename = _cursor.getString(_columnIndex);
          Intent intent = new Intent(videothumb.this, ViewVideo.class);
          intent.putExtra("videofilename", filename);
          startActivity(intent);
          showToast(filename);
         // Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();

        }
       };
    private class VideoGalleryAdapter extends BaseAdapter
    {
    public VideoGalleryAdapter(Context c)
    {
        _context = c;

    }
    public int getCount()
    {
        return _videosId.length;
    }
    public Object getItem(int position)
    {
        return position;
    }
    public long getItemId(int position)
    {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imgVw= new ImageView(_context);
        try
        {
            if(convertView!=null)
            {
                imgVw= (ImageView) convertView;
            }
            imgVw.setImageBitmap(getImage(_videosId[position]));
            imgVw.setAdjustViewBounds(true);
            imgVw.setBackgroundColor(Color.WHITE);
            imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imgVw.setPadding(5,5,5,5);
            imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
    }
        catch(Exception ex)
        {
            System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
     "+ ex.getMessage());
        }
        return imgVw;
    }

    // Create the thumbnail on the fly
    private Bitmap getImage(int id) {
    Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
    MediaStore.Video.Thumbnails.MICRO_KIND, null);
    System.out.println("ff"+MediaStore.Video.Thumbnails.
  getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
        return thumb;
       }
      }
     }
</code>```

coding 2:`

```<code>public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(R.layout.main1);
    //setContentView(new Zoom(this));
    Video=(VideoView)findViewById(R.id.VideoView01);
    System.gc();
    Intent i = getIntent();
    Bundle extras = i.getExtras();
    filename = extras.getString("videofilename");
    Video.setVideoPath(filename);

    Video.setMediaController(new MediaController(this));
    Video.requestFocus();
    Video.start();
   }

   }
</code>```

anyone help me...

答:
```
You want to use Videoview

<VideoView android:id="@+id/Videoview1"
    android:layout_marginTop="100px"
    android:layout_marginLeft="10px"
    android:layout_width="20px"
    android:layout_height="200px"/>

and create object in your activity
and play.
videoview.start();
like this.

Hope this will help you
```

Body:
hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....

this is my screen shot:

if i click thumbnails the video will play another page:
that screen shot:

this is for my coding:

public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;

protected Context _context;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    _context = getApplicationContext();

    setContentView(R.layout.main);

    //set GridView for gallery
    _gallery = (Gallery) findViewById(R.id.videoGrdVw);
    //set default as external/sdcard uri
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //initialize the videos uri
    //showToast(_contentUri.getPath());
    initVideosId();
    //set gallery adapter
    setGalleryAdapter();
}
private void setGalleryAdapter() {
    _gallery.setAdapter(new VideoGalleryAdapter(_context));
    _gallery.setOnItemClickListener(videogridlistener);
    }
private void initVideosId() {
    try
    {
        //Here we set up a string array of the thumbnail ID column we want to get back
        String [] proj={_ID};
        // Now we create the cursor pointing to the external thumbnail store
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int count= _cursor.getCount();
        System.out.println("total"+_cursor.getCount());
        // We now get the column index of the thumbnail id
        _columnIndex = _cursor.getColumnIndex(_ID);
        //initialize
        _videosId = new int[count];
        //move position to first element
        _cursor.moveToFirst();
        for(int i=0;i<count;i++)
        {
            int id = _cursor.getInt(_columnIndex);
            //

            _videosId[i]= id;
            //
            _cursor.moveToNext();
            //
        }
    }catch(Exception ex)
    {
        showToast(ex.getMessage().toString());
    }

}
protected void showToast(String msg)
{
    Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position,
long id) {
        // Now we want to actually get the data location of the file
        String [] proj={MEDIA_DATA};
        // We request our cursor again
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);
          //System.gc();
         // video_column_index =
           _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
          _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
            // Lets move to the selected item in the cursor
            _cursor.moveToPosition(position);

          String filename = _cursor.getString(_columnIndex);
          Intent intent = new Intent(videothumb.this, ViewVideo.class);
          intent.putExtra("videofilename", filename);
          startActivity(intent);
          showToast(filename);
         // Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();

        }
       };
    private class VideoGalleryAdapter extends BaseAdapter
    {
    public VideoGalleryAdapter(Context c)
    {
        _context = c;

    }
    public int getCount()
    {
        return _videosId.length;
    }
    public Object getItem(int position)
    {
        return position;
    }
    public long getItemId(int position)
    {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imgVw= new ImageView(_context);
        try
        {
            if(convertView!=null)
            {
                imgVw= (ImageView) convertView;
            }
            imgVw.setImageBitmap(getImage(_videosId[position]));
            imgVw.setAdjustViewBounds(true);
            imgVw.setBackgroundColor(Color.WHITE);
            imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imgVw.setPadding(5,5,5,5);
            imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
    }
        catch(Exception ex)
        {
            System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
     "+ ex.getMessage());
        }
        return imgVw;
    }

    // Create the thumbnail on the fly
    private Bitmap getImage(int id) {
    Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
    MediaStore.Video.Thumbnails.MICRO_KIND, null);
    System.out.println("ff"+MediaStore.Video.Thumbnails.
  getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
        return thumb;
       }
      }
     }

coding 2:`

public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(R.layout.main1);
    //setContentView(new Zoom(this));
    Video=(VideoView)findViewById(R.id.VideoView01);
    System.gc();
    Intent i = getIntent();
    Bundle extras = i.getExtras();
    filename = extras.getString("videofilename");
    Video.setVideoPath(filename);

    Video.setMediaController(new MediaController(this));
    Video.requestFocus();
    Video.start();
   }

   }

anyone help me...


问:
Two Frameworks use the name for a property
SwifterSwift has a property name cornerRadius.
It's an extension to UIView.

While the DropDown framework has a property name cornerRadius.
DropDown (the class) is a subclass of UIView.

It seems like xCode doesn't know which property I'm referring to.
I only imported one framework to my file but SwifterSwift's extension still takes effect.

I modified the DropDown framework and everything worked fine but then I reverted because it's not allowed and I wouldn't know how to debug any future problems.

I also tried creating a function in an extension to somehow get around this problem.
It turns out that I can't directly access DropDown's table (which is the view that we round).

I cant remove the SwifterSwift framework because it has already been used in the project that I'm working on. Although that might be the best option.

Is there a solution to this problem ?

答:
Please follow the steps in this issue

Or upvote for adding prefix to all SwifterSwift extensions here


问:
open new activity with button
here is the code of my xml.

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>
</code>```

and here is my code of java.

```<code> public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}
</code>```

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

答:
Activity is the most basic Android components is also the most common use of the four components (Activity, Service, Content Provider, BroadcastReceiver).

The steps to create an Activity:

Create a new Java class And extends the Activity

Add in the AndroidManifest

```<code><activity android:name=".ActivityClassName"/>
</code>```

If is to start the interface

```<code><activity android:name=".ActivityClassName">
   <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER"/>
   </intent-filter>
</activity>
</code>```

Override the onCreate() function and load layout

Note: The Activity of the Java classes generally ends in Activity

Title: open new activity with button

Body:
here is the code of my xml.

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>

and here is my code of java.

 public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

Body:
Activity is the most basic Android components is also the most common use of the four components (Activity, Service, Content Provider, BroadcastReceiver).

The steps to create an Activity:

Create a new Java class And extends the Activity

Add in the AndroidManifest

<activity android:name=".ActivityClassName"/>

If is to start the interface

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

Override the onCreate() function and load layout

Note: The Activity of the Java classes generally ends in Activity


问:
Querying rows with coupled conditions
I've got an SQLite table where I store user settings with the following schema :

```<code>CREATE TABLE settings (
  [id] varchar(50) NOT NULL,
  [token] varchar(20) NOT NULL,
  [value] varchar(40) NOT NULL,
  [created] datetime NOT NULL,
  [user_id] INT(10) NOT NULL,
  PRIMARY KEY (id)
);
</code>```

The name of the setting is [token].
The value of the setting is [value].

I'd like to SELECT users who have 2 specific settings (both) :

english speaking users ([token]='language' AND [value]='en'),

subscribed to the newsletter ([token]='newsletter' AND [value]='1'),

So I tried :

```<code>SELECT user_id FROM settings
WHERE
        (token = 'language' AND value = 'en')
    OR  (token = 'newsletter' AND value = 1)
)
GROUP BY user_id
</code>```

But it doesn't work as I get users which ONLY have one of the 2 conditions (I want both).
How can I do?

答:
Please try This query :

```<code>SELECT user_id
FROM settings
WHERE  (token = 'language' AND value = 'en')
        OR  (token = 'newsletter' AND value = '1')
</code>```

There is no use of Group By clause

Title: Querying rows with coupled conditions

Body:
I've got an SQLite table where I store user settings with the following schema :

CREATE TABLE settings (
  [id] varchar(50) NOT NULL,
  [token] varchar(20) NOT NULL,
  [value] varchar(40) NOT NULL,
  [created] datetime NOT NULL,
  [user_id] INT(10) NOT NULL,
  PRIMARY KEY (id)
);

The name of the setting is [token].
The value of the setting is [value].

I'd like to SELECT users who have 2 specific settings (both) :

english speaking users ([token]='language' AND [value]='en'),

subscribed to the newsletter ([token]='newsletter' AND [value]='1'),

So I tried :

SELECT user_id FROM settings
WHERE
        (token = 'language' AND value = 'en')
    OR  (token = 'newsletter' AND value = 1)
)
GROUP BY user_id

But it doesn't work as I get users which ONLY have one of the 2 conditions (I want both).
How can I do?

Body:
Please try This query :

SELECT user_id
FROM settings
WHERE  (token = 'language' AND value = 'en')
        OR  (token = 'newsletter' AND value = '1')

There is no use of Group By clause


问:
check string valid or not in PHP
How to know which word has valid id card with criterion? If id card has 10 characters or more then id card is valid otherwise it is not valid.

example of sentences :

```<code>$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";

$String_2 = "i'm ananda ramadina and my id card 9090909889 my favorite team YYYYYYYYYY.";

$String_3 = "i'm dinda rahayu and my id card 909 my favorite team RRRRRRRR.";
</code>```

答:
You can use this </p>

```<code>$id = filter_var($str, FILTER_SANITIZE_NUMBER_INT);

// compare the length for $id
if (strlen($id) < 10) // not valid
</code>```

Title: check string valid or not in PHP

Body:
How to know which word has valid id card with criterion? If id card has 10 characters or more then id card is valid otherwise it is not valid.

example of sentences :

$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";

$String_2 = "i'm ananda ramadina and my id card 9090909889 my favorite team YYYYYYYYYY.";

$String_3 = "i'm dinda rahayu and my id card 909 my favorite team RRRRRRRR.";

Body:
You can use this

$id = filter_var($str, FILTER_SANITIZE_NUMBER_INT);

// compare the length for $id
if (strlen($id) < 10) // not valid


问:
Style paper-slider editable input
I am trying to add some customized style to the editable text in paper-slider. I know I can style the box of this input by

```<code><paper-slider value="0" id="myslider" editable></paper-slider>
</code>```

css

```<code>#myslider{
    --paper-slider-input: {
        position:absolute;
        top: 50px;
        width: 100px;
        ...
    }
}
</code>```

But how can I style the actual text?

I tried

```<code>#myslider{
    --paper-slider-input: {
        position:absolute;
        top: 50px;
        width: 100px;
        --paper-input-container-input: {
            font-size: 20px;
            color: red;
        }
    }
}
</code>```

That is not working. Also, if I want to show a % (percentage mark) after the text number, what should I do?

I found this post as a reference, but the way they tried to hide the arrows after the text did not work on mine. So what is the correct way to hide arrows?

I did actually ask three questions about styling. Any answer with either one or more of them would help. Thank you!

答:
unfortunately, I am not aware of any way, how to style paper-input. If you look into source code, you can see class .slider-input which is the only one applied to paper-input and it doesn't support any mixins.

Maybe, there is some way how to propagate some mixin inside custom element and deeper.

Maybe, and i don't much about it, is to use deep selector. But I saw somewhere it's deprecated.

About your percentage, i can say only the same.. it doesn't support prefix or suffix. Again, you can look into source code and you will see, that inside <paper-input> definition, there isn't slot for such things.. Of course that editing source code would solve all these problems, but there have to be some reason why developers didn't do that.

Title: Style paper-slider editable input

Body:
I am trying to add some customized style to the editable text in paper-slider. I know I can style the box of this input by

<paper-slider value="0" id="myslider" editable></paper-slider>

css

#myslider{
    --paper-slider-input: {
        position:absolute;
        top: 50px;
        width: 100px;
        ...
    }
}

But how can I style the actual text?

I tried

#myslider{
    --paper-slider-input: {
        position:absolute;
        top: 50px;
        width: 100px;
        --paper-input-container-input: {
            font-size: 20px;
            color: red;
        }
    }
}

That is not working. Also, if I want to show a % (percentage mark) after the text number, what should I do?

I found this post as a reference, but the way they tried to hide the arrows after the text did not work on mine. So what is the correct way to hide arrows?

I did actually ask three questions about styling. Any answer with either one or more of them would help. Thank you!


问:
Docker Push Fails
My docker pushes with the latest version appear to be failing almost all the time.

This is what happens with gcloud docker -- push

The push refers to a repository [us.gcr.io/rndb-140315/dream_closet]

80a8fcd2cfa1: Layer already exists

3bca4b8aadf9: Layer already exists

1f3202a15537: Layer already exists

5549f40f950c: Layer already exists

5f70bf18a086: Layer already exists

34d126c63186: Layer already exists

52b4a81ec16b: Layer already exists

6db3819d35cd: Layer already exists

46ecc6c4543a: Layer already exists

dial tcp 108.177.9.82:443: i/o timeout

Here is the docker log:

"Calling POST /v1.24/images/us.gcr.io/rndb-140315/dream_closet/push?tag="
16-11-15T00:44:46.219497295Z" level=debug msg="hostDir:
/etc/docker/certs.d/us.gcr.io"

16-11-15T00:44:46.250418329Z" level=debug msg="hostDir: /etc/docker/certs.d/us.gcr.io"

16-11-15T00:44:46.250519209Z" level=debug msg="Trying to push us.gcr.io/rndb-140315/dream_closet to https://us.gcr.io v2"
16-11-15T00:44:46.446481694Z" level=debug msg="Pushing repository: us.gcr.io/rndb-140315/dream_closet:latest"

16-11-15T00:45:16.709508684Z" level=error msg="Upload failed, retrying: dial tcp 108.177.10.82:443: i/o timeout"

16-11-15T00:45:16.709791097Z" level=error msg="Upload failed, retrying: dial tcp 108.177.10.82:443: i/o timeout"

16-11-15T00:45:16.710004220Z" level=error msg="Upload failed, retrying: dial tcp 108.177.10.82:443: i/o timeout"

16-11-15T00:45:51.711554093Z" level=error msg="Upload failed, retrying: dial tcp 108.177.10.82:443: i/o timeout"

16-11-15T00:46:31.712779966Z" level=error msg="Upload failed, retrying: dial tcp 108.177.10.82:443: i/o timeout"

16-11-15T00:47:17.355180162Z" level=error msg="Attempting next endpoint for push after error: Post https://us.gcr.io/v2/rndb-140315/dream_clos
16-11-15T00:47:17.355302561Z" level=debug msg="Skipping v1 endpoint https://us.gcr.io because v2 registry was detected"

Any ideas on how to resolve?  This worked on a previous version.

答:
I've just had this same problem, which was caused by a network problem.

I had been using a VPN, it seemed that the specific VPN node through which I was connected couldn't cope with the bandwidth I was pushing at it.

When I disconnected from the VPN, it worked fine.

Title: Docker Push Fails


问:
LINQ & Lambda Expressions equivalent of SQL In
Is there a lambda equivalent of IN?  I will like to select all the funds with ids either 4, 5 or 6.  One way of writing it is:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();

However, that quickly becomes unmanageable if I need it to match say 100 different fundIds.  Can I do something like:

List
  fundHistoricalPrices =
  lionContext.FundHistoricalPrices.Where(fhp
  => fhp.Fund.FundId in(5,6,7)).ToList();

答:
You can use the Contains() method on a collection to get the equivalent to in.

```<code>var fundIds = new [] { 5, 6, 7 };

var fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fundIds.Contains(fhp.Fund.FundId)).ToList();
</code>```

Body:
You can use the Contains() method on a collection to get the equivalent to in.

var fundIds = new [] { 5, 6, 7 };

var fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fundIds.Contains(fhp.Fund.FundId)).ToList();


问:
Monitoring files in linux
How to build a tool in Ubuntu 16.04 that can monitor a given folder/directory in every 5 minutes (or specified time) and can check if it contains any file or not (file can be of any format)? What things I need to learn for doing this task? Can I do this with the help of python script or am I required to learn shell scripting.</p>

答:
With python i would try to use watchdog. Used it several times to listen for events in large directory trees and its awesome and easy:

```<code>import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":

    path = '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
</code>```

With this snippet, you will get everything that happens within the defined path as event. To do more with them, dive into the documentation of watchdog.

Title: Monitoring files in linux

Body:
With python i would try to use watchdog. Used it several times to listen for events in large directory trees and its awesome and easy:

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":

    path = '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

With this snippet, you will get everything that happens within the defined path as event. To do more with them, dive into the documentation of watchdog.


问:
SQL Server constraint
I want to delete the path if status is equal to 'y'. but it is not working.</p>

```<code>create table example
(
    [status] varchar(1) not null check([status] in ('y', 'n')),
    [path] varchar(70) not null
    if([status] == 'y') {
        [path] == null;
    }
)
</code>```

答:
As I wrote in my comment, I would not set the existing value to null. Instead, a computed column seems like a better option to me.
Also, varchar(1) is the second worst data type you can choose (nvarchar(1) is even worst).  First, if you know you only ever going to have a fixed length string, use char or nchar. Second, if it's only to specify y or n, You better simply use bit, what only holds values of 0 or 1.

```<code>CREATE TABLE Example
(
    [status] bit not null, -- 0 for `n`, 1 for `y`
    [originalPath] varchar(70) not null, -- keeps the original value. Think write only.
    [path] as (case when status = 1 then
                   null
               else
                   originalPath
               end) -- computed column to use in select statements. This is read only.
)
</code>```

Title: SQL Server constraint

Body:
I want to delete the path if status is equal to 'y'. but it is not working.

create table example
(
    [status] varchar(1) not null check([status] in ('y', 'n')),
    [path] varchar(70) not null
    if([status] == 'y') {
        [path] == null;
    }
)

Body:
As I wrote in my comment, I would not set the existing value to null. Instead, a computed column seems like a better option to me.
Also, varchar(1) is the second worst data type you can choose (nvarchar(1) is even worst).  First, if you know you only ever going to have a fixed length string, use char or nchar. Second, if it's only to specify y or n, You better simply use bit, what only holds values of 0 or 1.

CREATE TABLE Example
(
    [status] bit not null, -- 0 for `n`, 1 for `y`
    [originalPath] varchar(70) not null, -- keeps the original value. Think write only.
    [path] as (case when status = 1 then
                   null
               else
                   originalPath
               end) -- computed column to use in select statements. This is read only.
)


问:
spring data @query 'cached' table?
App entity

```<code>@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}
</code>```

I try to write my own query as such.

```<code>@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);
</code>```

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.

答: Try to replace FROM allowedusers by FROM app.allowedusers

Title: spring data @query 'cached' table?

Body:
App entity

@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}

I try to write my own query as such.

@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.


问:
spring file upload
Is any body know how to upload files using jupload in spring frame work.how to handle the jupload request in spring?</p>

答:
It shouldn't matter which client you use to do the file upload, the server-side logic should be the same.

Spring's File Upload handling is documented here.

Title: spring file upload