问:
changing the href of anchor inside ajax return but then it is overwritten
Hello all i have a problem i have a table with a link in one of the columns
on the click of that link i send it to a function that uses ajax to get a different link for it to direct to.
inside the ajax function it is being changed correctly but then after it finishes the ajax it still redirects to the original page.
if i change it outside of the ajax return it works correctly and redirects to a different site

this is my code:

the php function for building the table

```<code>function populate()
{
$link = connectToDB();
$query = 'Select value1, value2
         from table1';
$data = read($query, $link);
$table = '<div id="table"><table id="links">
            <tr>
            <th>value1</th>
            <th>value2</th>
          </tr>';

$num =0;
while ($row = $data->fetch_assoc()) {
    $table .= '<tr>';
    $table .= '<td>' . $row['value1'] . '</td>';
    $table .= '<td><a id="redirection'.$num.'" onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '>' . $row['value1'] .'</td>';
    $table .= '</tr>';
    $num++;
}
$table .= '</table></div>';
mysqli_close($link);
return $table;
}
</code>```

the javascript to change the href

```<code>function redirect(num){
    var url = $("#redirection"+num).attr("href");
    var sub = url.split('?');
    var val1= sub[2];
    var test = "";
    $.ajax({
        url: 'getNewUrl.php',
        type:'POST',
        dataType: 'json',
        data: { name: val1},
        success: function(table){
            alert(table.val2);
            $("#redirection"+num).attr("href",table.val2);
            var check =$("#redirection"+num);
        },
        error: function () {
            alert("No value with that name");
        }
    });
}
</code>```

when i am alerting the value retured it is the correct one, and when i am checking the href value of check in debugger it is being changed correctly but then i am still redirected to the wrong site

thanks for the help

答:
i think the problem is in href=”/? and wrong doublequote and miss close quote and remove "?" after =/

```<code>onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '
</code>```

it's sould be like this.

```<code>onclick="redirect('.$num.')" href="/redirection.php?' . $row['value2'] .'"
</code>```

hope this help.

Body:
Hello all i have a problem i have a table with a link in one of the columns
on the click of that link i send it to a function that uses ajax to get a different link for it to direct to.
inside the ajax function it is being changed correctly but then after it finishes the ajax it still redirects to the original page.
if i change it outside of the ajax return it works correctly and redirects to a different site

this is my code:

the php function for building the table

function populate()
{
$link = connectToDB();
$query = 'Select value1, value2
         from table1';
$data = read($query, $link);
$table = '

            value1
            value2

';

$num =0;
while ($row = $data->fetch_assoc()) {
    $table .= '
';
    $table .= '' . $row['value1'] . '	';
    $table .= '' . $row['value1'] .'	';
    $table .= '
';
    $num++;
}
$table .= '

';
mysqli_close($link);
return $table;
}

the javascript to change the href

function redirect(num){
    var url = $("#redirection"+num).attr("href");
    var sub = url.split('?');
    var val1= sub[2];
    var test = "";
    $.ajax({
        url: 'getNewUrl.php',
        type:'POST',
        dataType: 'json',
        data: { name: val1},
        success: function(table){
            alert(table.val2);
            $("#redirection"+num).attr("href",table.val2);
            var check =$("#redirection"+num);
        },
        error: function () {
            alert("No value with that name");
        }
    });
}

when i am alerting the value retured it is the correct one, and when i am checking the href value of check in debugger it is being changed correctly but then i am still redirected to the wrong site

thanks for the help

Body:
i think the problem is in href=”/? and wrong doublequote and miss close quote and remove "?" after =/

onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '

it's sould be like this.

onclick="redirect('.$num.')" href="/redirection.php?' . $row['value2'] .'"

hope this help.


来源: stackexchange

问:
Working with subdomain in google app engine
How can I work with sub domain in google app engine (python).

I wanna get first domain part and take some action (handler).

Example:

     product.example.com  -> send it to products handler

     user.example.com     -> send it to users handler

Actually, using virtual path I have this code:

```<code>  application = webapp.WSGIApplication(
    [('/', IndexHandler),
     ('/product/(.*)', ProductHandler),
     ('/user/(.*)', UserHandler)
  ]
</code>```

答:
I liked the idea from Nick but I had a slightly different issue.  I wanted to match one specific subdomain to handle it a bit different, but all other sub domains should be handled the same.  So here is my example.</p>

```<code>import os

def main():
   if (os.environ['HTTP_HOST'] == "sub.example.com"):
      application = webapp.WSGIApplication([('/(.*)', OtherMainHandler)], debug=True)
   else:
      application = webapp.WSGIApplication([('/', MainHandler),], debug=True)

   run_wsgi_app(application)

if __name__ == '__main__':
   main()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I work with sub domain in google app engine (python).

I wanna get first domain part and take some action (handler).

Example:

     product.example.com  -> send it to products handler

     user.example.com     -> send it to users handler

Actually, using virtual path I have this code:

  application = webapp.WSGIApplication(
    [('/', IndexHandler),
     ('/product/(.*)', ProductHandler),
     ('/user/(.*)', UserHandler)
  ]

Body:
I liked the idea from Nick but I had a slightly different issue.  I wanted to match one specific subdomain to handle it a bit different, but all other sub domains should be handled the same.  So here is my example.

import os

def main():
   if (os.environ['HTTP_HOST'] == "sub.example.com"):
      application = webapp.WSGIApplication([('/(.*)', OtherMainHandler)], debug=True)
   else:
      application = webapp.WSGIApplication([('/', MainHandler),], debug=True)

   run_wsgi_app(application)

if __name__ == '__main__':
   main()

ContentLicense: CC BY-SA 2.5


问:
CSS: How to make a background-image appear within a div without setting a fixed height
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.

答:
You can use one transparent image like below:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.header img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="columns small-12 header">
    <img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAGQBAMAAACkCxkHAAAAGFBMVEUAAAD///+TlJWcnp+Ji4yIiouVlZaSk5OelJf9AAAAAXRSTlMAQObYZgAAANVJREFUeF7tzTEVgEAMBbB/HZivDhCBBAQgBf8TLngdEgNJZw6qszMGV1YG4X6OHxYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIA3g1DZGYSVPjMG1R9lOgHLp7M9BAAAAABJRU5ErkJggg=="
    />
  </div>
</div></code>```

You can change window size here:
https://jsfiddle.net/gcejf26t/

If you noticed images are showed weird, because they are just like that! nothing to do with CSS (of course transparent image ratio can be equal to your image's ratio).

You can find smaller base64 coded image in comparison with that I've used and also better ratio as you desire.

But why you should do this? I don't know! Use  for simplicity.

Body:
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.

Body:
You can use one transparent image like below:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.header img {
  width: 100%;
}

<div class="row">
  <div class="columns small-12 header">
    <img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAGQBAMAAACkCxkHAAAAGFBMVEUAAAD///+TlJWcnp+Ji4yIiouVlZaSk5OelJf9AAAAAXRSTlMAQObYZgAAANVJREFUeF7tzTEVgEAMBbB/HZivDhCBBAQgBf8TLngdEgNJZw6qszMGV1YG4X6OHxYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIA3g1DZGYSVPjMG1R9lOgHLp7M9BAAAAABJRU5ErkJggg=="
    />
  </div>
</div>

You can change window size here:
https://jsfiddle.net/gcejf26t/

If you noticed images are showed weird, because they are just like that! nothing to do with CSS (of course transparent image ratio can be equal to your image's ratio).

You can find smaller base64 coded image in comparison with that I've used and also better ratio as you desire.

But why you should do this? I don't know! Use <img> for simplicity.


问:
Any component/API in React Native to handle Email and Phone Number links
LinkingIOS says the following:

* The iOS simulator does not support the mailto: and tel: schemas
 * because the Mail and Phone apps are not installed - you will need to test
 * them on a device.

What can I use in my React Native app to link to the native Mail app when an email address is clicked on? And similarly, how do I give the option to call or text-message when a telephone number is clicked on?

答:
react-native-communications very nice react native npm module. which supports phone call, sms, email, and urls.

Open a web address, easily call, email, text, iMessage (iOS only)
  someone in React Native

```<code><View style={styles.container}>
        <TouchableOpacity onPress={() => Communications.phonecall('0123456789', true)}>
          <View style={styles.holder}>
            <Text style={styles.text}>Make phonecall</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.email(['emailAddress1', 'emailAddress2'],null,null,'My Subject','My body text')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Send an email</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.text('0123456789')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Send a text/iMessage</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.web('https://github.com/facebook/react-native')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Open react-native repo on Github</Text>
          </View>
        </TouchableOpacity>
      </View>
</code>```

Body:
react-native-communications very nice react native npm module. which supports phone call, sms, email, and urls.

Open a web address, easily call, email, text, iMessage (iOS only)
  someone in React Native

<View style={styles.container}>
        <TouchableOpacity onPress={() => Communications.phonecall('0123456789', true)}>
          <View style={styles.holder}>
            <Text style={styles.text}>Make phonecall</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.email(['emailAddress1', 'emailAddress2'],null,null,'My Subject','My body text')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Send an email</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.text('0123456789')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Send a text/iMessage</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => Communications.web('https://github.com/facebook/react-native')}>
          <View style={styles.holder}>
            <Text style={styles.text}>Open react-native repo on Github</Text>
          </View>
        </TouchableOpacity>
      </View>


问:
onRequestPermissionsResult not being called in dialog fragment
I have started to work on Android M runtime permission. Here I am facing the issue that if requestPermissions is called from Dialog Fragment class then onRequestPermissionsResult not getting called in the same Dialog fragment class. But if requestPermissions is called from Activity class or Fragment class then onRequestPermissionsResult method get called in the same class.

Here is my sample code:

```<code>public class ContactPickerDialog extends DialogFragment {
    private static final int READ_CONTACTS_REQUEST_CODE = 12;
    private Context mContext;

    private void loadContact() {
        if(hasPermission(mContext, Manifest.permission.READ_CONTACTS)){
            new ContactSyncTask().execute();
        } else {
            this.requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, READ_CONTACTS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Logger.d("TAG", "dialog onRequestPermissionsResult");
        switch (requestCode) {
            case READ_CONTACTS_REQUEST_CODE:
                // Check Permissions Granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    new ContactSyncTask().execute();
                } else {
                    // Permission Denied
                    Toast.makeText(getActivity(), "Read contact permission is denied", Toast.LENGTH_SHORT).show();
                }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private static boolean hasPermission(Context context, String permission){
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

}
</code>```

Here in the code I am calling requestPermissions method of Dialog Fragment class. So I am expecting to get result in same class.

Any help is appreciated. Thanks in advance!

EDIT:
Here I am adding more detail, so that it will be more helpful to others.
Previously I have used getChildFragmentManager() to show the DialogFragment.

```<code>ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getChildFragmentManager(), "Contact Picker");
</code>```

But As @CommonWare asked me to use activity to show the DialogFragment. I have made following changes and it works.

```<code>ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getActivity().getSupportFragmentManager(), "Contact Picker");
</code>```

答:
I got it done like this

```<code>public class DialogFragmentSMS extends DialogFragment implements View.OnClickListener {

public static DialogFragmentSMS frag;
private static View view;
private static ViewGroup parent;
private EditText editTextMensagem;
private String celular;

private final static int SMS_REQUEST = 20;

public DialogFragmentSMS() {

}
public static DialogFragmentSMS newInstance(String celular)
{

    Bundle args = new Bundle();
    args.putString("celular", celular);
    frag = new DialogFragmentSMS();
    frag.setArguments(args);
    return frag;
}

@Override
public void onCreate(Bundle saveInstaceState)
{
    super.onCreate(saveInstaceState);
}

    @Override
public void onClick(View v) {
    if (!PermissaoUtils.hasPermission(getActivity(), Manifest.permission.SEND_SMS)) {
        //PermissaoUtils.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, SMS_REQUEST);
        frag.requestPermissions(new String[]{Manifest.permission.SEND_SMS}, SMS_REQUEST);
    }else{
        if (validaCampos()) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage("0" + celular, null, editTextMensagem.getText().toString(), null, null);
            Toast.makeText(getActivity(), R.string.sms_enviado, Toast.LENGTH_SHORT).show();
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            frag.dismiss();
        }
    }
}
</code>```

My Class Permission

```<code>public class PermissaoUtils
{
    public static boolean useRunTimePermissions() {
        return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
    }

    public static boolean hasPermission(Activity activity, String permission) {
        if (useRunTimePermissions()) {
            return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    public static void requestPermissions(Activity activity, String[] permission, int requestCode) {
        if (useRunTimePermissions()) {
            activity.requestPermissions(permission, requestCode);
        }
    }
}
</code>```

Body:
I have started to work on Android M runtime permission. Here I am facing the issue that if requestPermissions is called from Dialog Fragment class then onRequestPermissionsResult not getting called in the same Dialog fragment class. But if requestPermissions is called from Activity class or Fragment class then onRequestPermissionsResult method get called in the same class.

Here is my sample code:

public class ContactPickerDialog extends DialogFragment {
    private static final int READ_CONTACTS_REQUEST_CODE = 12;
    private Context mContext;

    private void loadContact() {
        if(hasPermission(mContext, Manifest.permission.READ_CONTACTS)){
            new ContactSyncTask().execute();
        } else {
            this.requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, READ_CONTACTS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Logger.d("TAG", "dialog onRequestPermissionsResult");
        switch (requestCode) {
            case READ_CONTACTS_REQUEST_CODE:
                // Check Permissions Granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    new ContactSyncTask().execute();
                } else {
                    // Permission Denied
                    Toast.makeText(getActivity(), "Read contact permission is denied", Toast.LENGTH_SHORT).show();
                }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private static boolean hasPermission(Context context, String permission){
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

}

Here in the code I am calling requestPermissions method of Dialog Fragment class. So I am expecting to get result in same class.

Any help is appreciated. Thanks in advance!

EDIT:
Here I am adding more detail, so that it will be more helpful to others.
Previously I have used getChildFragmentManager() to show the DialogFragment.

ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getChildFragmentManager(), "Contact Picker");

But As @CommonWare asked me to use activity to show the DialogFragment. I have made following changes and it works.

ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getActivity().getSupportFragmentManager(), "Contact Picker");

Body:
I got it done like this

public class DialogFragmentSMS extends DialogFragment implements View.OnClickListener {

public static DialogFragmentSMS frag;
private static View view;
private static ViewGroup parent;
private EditText editTextMensagem;
private String celular;

private final static int SMS_REQUEST = 20;

public DialogFragmentSMS() {

}
public static DialogFragmentSMS newInstance(String celular)
{

    Bundle args = new Bundle();
    args.putString("celular", celular);
    frag = new DialogFragmentSMS();
    frag.setArguments(args);
    return frag;
}

@Override
public void onCreate(Bundle saveInstaceState)
{
    super.onCreate(saveInstaceState);
}

    @Override
public void onClick(View v) {
    if (!PermissaoUtils.hasPermission(getActivity(), Manifest.permission.SEND_SMS)) {
        //PermissaoUtils.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, SMS_REQUEST);
        frag.requestPermissions(new String[]{Manifest.permission.SEND_SMS}, SMS_REQUEST);
    }else{
        if (validaCampos()) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage("0" + celular, null, editTextMensagem.getText().toString(), null, null);
            Toast.makeText(getActivity(), R.string.sms_enviado, Toast.LENGTH_SHORT).show();
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            frag.dismiss();
        }
    }
}

My Class Permission

public class PermissaoUtils
{
    public static boolean useRunTimePermissions() {
        return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
    }

    public static boolean hasPermission(Activity activity, String permission) {
        if (useRunTimePermissions()) {
            return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    public static void requestPermissions(Activity activity, String[] permission, int requestCode) {
        if (useRunTimePermissions()) {
            activity.requestPermissions(permission, requestCode);
        }
    }
}


问:
How to move a dictionary with object instances to another instance of its parent class in VB.NET
Perhaps I have the terminology wrong here, so this might have caused me not to have found an answer yet.

Here's the situation: I have an instance of the class clsSbkReach called FromReach. This instance has a dictionary that contains multiple instances of clsReachObject.

Now I want to move all existing reachobjects on FromReach to another instance of clsSbkReach, which is called ToReach. How can I achieve this? Here's what I do right now, but it seems to destroy all instances of clsSbkReachObject.

```<code>For Each myObject As clsSbkReachObject In FromReach.ReachObjects.Values
    ToReach.ReachObjects.ReachObjects.Add(myObject.ID.Trim.ToUpper, myObject)   'add the objects to the new reach
Next myObject
FromReach.ReachObjects.ReachObjects.clear
</code>```

I really need to move the existing instances, not copy or clone.

答:
You can move items from one Dictionary to another like this:

```<code>For Each key In sourceDictionary.Keys
    destinationDictionary.Add(key, destinationDictionary(key))
Next

sourceDictionary.Clear()
</code>```

Body:
Perhaps I have the terminology wrong here, so this might have caused me not to have found an answer yet.

Here's the situation: I have an instance of the class clsSbkReach called FromReach. This instance has a dictionary that contains multiple instances of clsReachObject.

Now I want to move all existing reachobjects on FromReach to another instance of clsSbkReach, which is called ToReach. How can I achieve this? Here's what I do right now, but it seems to destroy all instances of clsSbkReachObject.

For Each myObject As clsSbkReachObject In FromReach.ReachObjects.Values
    ToReach.ReachObjects.ReachObjects.Add(myObject.ID.Trim.ToUpper, myObject)   'add the objects to the new reach
Next myObject
FromReach.ReachObjects.ReachObjects.clear

I really need to move the existing instances, not copy or clone.

Body:
You can move items from one Dictionary to another like this:

For Each key In sourceDictionary.Keys
    destinationDictionary.Add(key, destinationDictionary(key))
Next

sourceDictionary.Clear()


问:
PhotoViewer not known as ionic-native
I installed the PhotoViewer as explained in: https://github.com/sarriaroman/photoviewer

When I add import like this the project:
import {PhotoViewer} from 'ionic-native';

it doesn't compile and it says that PhotoViewer is not part of 'ionic-native'

Anyone knows why?

答:
import { PhotoViewer } from '@ionic-native/photo-viewer'

http://ionicframework.com/docs/native/photo-viewer/

Fix your import. Just 'ionic-native' won't work.

Title: PhotoViewer not known as ionic-native


问:
html form post is not sending variable data
After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".

The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.

I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.

PHP Code:

```<code>#delete vendor
require('includes/mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array(); //array to collect errors

    //check to ensure fields are filled out
    if (!empty($_POST['vendor'])) {
        $vendor = trim($_POST['vendor']);
    }
    else {
        $errors[] = "<p>You forgot to select a vendor to delete</p>";
    }

    if (empty($errors)) {
        //insert information into appt table
        $query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
        $result = mysqli_query($dbc, $query);
        if($result){
            echo '<div class="alert alert-success" role="alert">';
            echo '<h2>Thank you!</h2>';
            echo '<p> Your request to delete vendorID ' . $customerID . 'has been completed </p></div>';
        } else {
            echo "Error updating record: " . mysqli_error($dbc);
        }
    } else{
        echo '<div class="alert alert-danger" role="alert"><br>';
        echo '<h2>Errors Detected</h2>';
        echo '<p>The following errors occured:<br/>';
        foreach ($errors as $msg) {
            echo "$msg<br/>\n";
        }
        echo '</p><p>Please try again. </p></div>';
    }

}
</code>```

HTML Code

```<code><div class="container standout" >
    <div class="col-lg-12">
        <h2>Delete a vendor</h2>
        <p> Please select a vendor to delete.</p>
    </div>
    <div class="row">
        <form action="index.php?pagelet=deletevendor" method="post">
            <div class="form-group col-md-4">
                <label for="vendor">Vendors</label>
                <select name="vendor" class="form-control">
                    <option name="vendor" selected disabled>Choose here</option>
                    <?php
                        $query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
                        $result = mysqli_query($dbc, $query);

                        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                            echo '<option name="vendor" value="'.$row['vendorID'].'">'
                                    .$row['vendorID'].' '.$row['businessName']
                                    .' '.$row['contactFname'].' '.$row['contactLname']
                                .'</option>';
                        }?>
                </select>
                <br>
                <br>
                <input class="btn btn-primary" id="submit" type="submit" value="Delete">
            </div>
        </div>
    </form>
</div>
</code>```

答:
removing name="vendor" from options & removing selected both work.

After removing name="vendor" - I added selected back and it still works.
 Thank you!!

Body:
After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".

The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.

I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.

PHP Code:

#delete vendor
require('includes/mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array(); //array to collect errors

    //check to ensure fields are filled out
    if (!empty($_POST['vendor'])) {
        $vendor = trim($_POST['vendor']);
    }
    else {
        $errors[] = "
You forgot to select a vendor to delete
";
    }

    if (empty($errors)) {
        //insert information into appt table
        $query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
        $result = mysqli_query($dbc, $query);
        if($result){
            echo '
';
            echo '
Thank you!
';
            echo '
 Your request to delete vendorID ' . $customerID . 'has been completed

';
        } else {
            echo "Error updating record: " . mysqli_error($dbc);
        }
    } else{
        echo '

';
        echo '
Errors Detected
';
        echo '
The following errors occured:
';
        foreach ($errors as $msg) {
            echo "$msg
\n";
        }
        echo '

Please try again.

';
    }

}

HTML Code

Delete a vendor

 Please select a vendor to delete.

        <form action="index.php?pagelet=deletevendor" method="post">

                Vendors
                <select name="vendor" class="form-control">
                    <option name="vendor" selected disabled>Choose here</option>
                    <?php
                        $query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
                        $result = mysqli_query($dbc, $query);

                        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                            echo '<option name="vendor" value="'.$row['vendorID'].'">'
                                    .$row['vendorID'].' '.$row['businessName']
                                    .' '.$row['contactFname'].' '.$row['contactLname']
                                .'</option>';
                        }?>
                </select>

                <input class="btn btn-primary" id="submit" type="submit" value="Delete">

    </form>


问:
How to get the list of process location only running on my windows computer
Referred: SO Q1 and SO Q2

What I have tried?
In the former link given in the question and I have tried executing it and I get Process Name,Process Locations and process ID. And I referred the internet and modified the script given in the popular answer of SO Q1 and modified like this

```<code>class GetProcess:
def __init__(self):
    cmd = 'WMIC PROCESS get Commandline'
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    for line in proc.stdout:
        print(line)
</code>```

when I am executing the script I get locations with weird data like this

b'"C:\Program Files\WindowsApps\Microsoft.Windows.Photos_17.214.10010.0_x64__8wekyb3d8bbwe\Microsoft.Photos.exe" -ServerName:App.AppXzst44mncqdg84v7sv6p7yznqwssy6f7f.mca

Is there any way to get the location alone instead of getting what is running what?

I can see that this can be done using with some third party libraries but I need to know whether there is any solution which I can get the process without any third party library

答:
You want to take the command lines such as this:

```<code>b'"C:\\Program Files\\WindowsApps\\Microsoft.Windows.Photos_17.214.10010.0_x64__8wekyb3d8bbwe\\Microsoft.Photos.exe" -ServerName:App.AppXzst44mncqdg84v7sv6p7yznqwssy6f7f.mca
</code>```

And extra only the executable path, which is the first part.  It seems like you just need to parse it by looking for the first (possibly quoted) string, which you can do using re, the regular expression module in Python.

The b'...' wrapper you see around the string indicates it is of the bytes type in Python 3, as opposed to Unicode.  That's normal for the output of Popen().

By the way, subprocess.check_output() is probably better suited and safer for your task.

Body:
Referred: SO Q1 and SO Q2

What I have tried?
In the former link given in the question and I have tried executing it and I get Process Name,Process Locations and process ID. And I referred the internet and modified the script given in the popular answer of SO Q1 and modified like this

class GetProcess:
def __init__(self):
    cmd = 'WMIC PROCESS get Commandline'
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    for line in proc.stdout:
        print(line)

when I am executing the script I get locations with weird data like this

b'"C:\Program Files\WindowsApps\Microsoft.Windows.Photos_17.214.10010.0_x64__8wekyb3d8bbwe\Microsoft.Photos.exe" -ServerName:App.AppXzst44mncqdg84v7sv6p7yznqwssy6f7f.mca

Is there any way to get the location alone instead of getting what is running what?

I can see that this can be done using with some third party libraries but I need to know whether there is any solution which I can get the process without any third party library

Body:
You want to take the command lines such as this:

b'"C:\\Program Files\\WindowsApps\\Microsoft.Windows.Photos_17.214.10010.0_x64__8wekyb3d8bbwe\\Microsoft.Photos.exe" -ServerName:App.AppXzst44mncqdg84v7sv6p7yznqwssy6f7f.mca

And extra only the executable path, which is the first part.  It seems like you just need to parse it by looking for the first (possibly quoted) string, which you can do using re, the regular expression module in Python.

The b'...' wrapper you see around the string indicates it is of the bytes type in Python 3, as opposed to Unicode.  That's normal for the output of Popen().

By the way, subprocess.check_output() is probably better suited and safer for your task.


问:
C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?
Sorry for the long title, but I couldn't think of another way to put it.

I have this:

```<code>    private void textBoxToSubmit_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSubmit_Click((object)sender, (EventArgs)e);
        }
    }
</code>```

... in order to make pressing enter in the text box trigger the "submit" button. However, this also prevents shortcuts from going through. (not quite sure what it has to do with that, maybe only multi-key combos?)

ShortcutsEnabled is set to true.

Thanks in advance!

答:
You do not need any client side code if doing this is ASP.NET.
The example below  is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular
 tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

```<code><asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>
</code>```

Body:
Sorry for the long title, but I couldn't think of another way to put it.

I have this:

    private void textBoxToSubmit_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSubmit_Click((object)sender, (EventArgs)e);
        }
    }

... in order to make pressing enter in the text box trigger the "submit" button. However, this also prevents shortcuts from going through. (not quite sure what it has to do with that, maybe only multi-key combos?)

ShortcutsEnabled is set to true.

Thanks in advance!

Body:
You do not need any client side code if doing this is ASP.NET.
The example below  is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>


问:
time() function to (l jS \of F Y \a\t G:i:s A) format
```<code>function test()
 {
     echo time();
     echo "<hr>";
     echo $this->get_date(time());
}
</code>```

and another function

```<code>function get_date($timestamp)
{
  $the_date = date('l jS \of F Y \a\t G:i:s A', $timestamp);
  return $the_date;
}
</code>```

when i use the test function the time() function provides a valid result but the generated timestamp is off by 2 hours
eg. if time() is 1491118740 then the timestamp format should be Sunday 2nd of April 2017 at 7:39:00 AM but i am getting Sunday 2nd of April 2017 at 9:39:00 AM how to fix this?? Please help.. And thanks in advance...
 PS. to check the timestamp value you can use this site http://www.unixtimestamp.com/index.php

答:
Update timezone used by your script using date_default_timezone_set()

Example:

```<code>// check your default timezone first
echo date_default_timezone_get();

// change the timezone: I use 'Africa/Lagos' for example
date_default_timezone_set('Africa/Lagos');

// make sure it's changed
echo date_default_timezone_get();

// now use your function
echo date('l jS \of F Y \a\t G:i:s A');
</code>```

Further reading here

Body:
function test()
 {
     echo time();
     echo "
";
     echo $this->get_date(time());
}

and another function

function get_date($timestamp)
{
  $the_date = date('l jS \of F Y \a\t G:i:s A', $timestamp);
  return $the_date;
}

when i use the test function the time() function provides a valid result but the generated timestamp is off by 2 hours
eg. if time() is 1491118740 then the timestamp format should be Sunday 2nd of April 2017 at 7:39:00 AM but i am getting Sunday 2nd of April 2017 at 9:39:00 AM how to fix this?? Please help.. And thanks in advance...
 PS. to check the timestamp value you can use this site http://www.unixtimestamp.com/index.php

Body:
Update timezone used by your script using date_default_timezone_set()

Example:

// check your default timezone first
echo date_default_timezone_get();

// change the timezone: I use 'Africa/Lagos' for example
date_default_timezone_set('Africa/Lagos');

// make sure it's changed
echo date_default_timezone_get();

// now use your function
echo date('l jS \of F Y \a\t G:i:s A');

Further reading here


问:
Compare the column values and update another column in Oracle
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null
</code>```

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2
</code>```

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

答:
Please try...

```<code>UPDATE tableName
SET LoginID = ( RANK MOD 2 ) + 1;
</code>```

Note : This assumes that the lesser LoginID will always correspond with the lesser RANK for each TestID.

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_mod

Body:
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

Body:
Please try...

UPDATE tableName
SET LoginID = ( RANK MOD 2 ) + 1;

Note : This assumes that the lesser LoginID will always correspond with the lesser RANK for each TestID.

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_mod


问:
How to install maven on redhat linux
Note: When originally posted I was trying to install maven2. Since the main answer is for maven3 I have updated the title. The rest of the question remains as it was originally posted.

I'm trying to install maven2 on a redhat linux box using the command

```<code> yum install maven2
</code>```

but yum doesn't seem to be able to find maven2.

```<code>No package maven2 available
</code>```

I've run across other posts about this topic, but the answer to the following post suggests to add repos. I add said repos, but run into errors after adding them.

How to install Maven into Red Hat Enterprise Linux 6?

I can only access this box via command line so simply downloading maven from their website is difficult for me.

答:
I made the following script:</p>

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

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to install maven on redhat linux

Body:
Note: When originally posted I was trying to install maven2. Since the main answer is for maven3 I have updated the title. The rest of the question remains as it was originally posted.

I'm trying to install maven2 on a redhat linux box using the command

 yum install maven2

but yum doesn't seem to be able to find maven2.

No package maven2 available

I've run across other posts about this topic, but the answer to the following post suggests to add repos. I add said repos, but run into errors after adding them.

How to install Maven into Red Hat Enterprise Linux 6?

I can only access this box via command line so simply downloading maven from their website is difficult for me.

Body:
I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi


问:
How Rails handles database connection in the background?
I am trying show controller specific pages in my rails app when the database connection goes away. I do this by catching the Mysql::Error in the rescue_action method and rendering appropriate pages. When the mysql service alone is stopped , i get the Mysql::Error exception really quickly and i could render the pages without any delay.

But when the server itself is shut down, rails takes 3 mins to throw the Mysql::Error and after 5-6 request the whole website becomes unresponsive.

I tried to figure out, which method in rails framework takes such a long time , when the mysql server is shut down. It was a method connection.real_connect (in the active record mysql_adapter file),which took 3 mins to return with an exception.

so i decided to timeout out this method using systemTimer gem. This monkey patch worked perfectly, when i start the website with database connection and immediately shutdown the database server.

But when i start the website with database, and access the website for sometime and then shut down the database server, it doest work at all. and the whole website becomes unresponsive as before. I wonder what is the difference between the two scenarios.

I think i need to know more in detail about how rails handle database connection . how it reacts when the database connection goes off. so that i could identify exact places where i can put monkey patches and make it work for my spefic requirement. I havent seen any relevant article explaining this.

Any help will be very useful for me

Thanks,

答:
I've not tried this, but you can add connect_timeout as one of the specified options (along with port, host, etc) for the MySQL connection in the database.yml file. That value is passed to the real_connect call to establish the connection to MySQL.

Furthermore, since you are experiencing a delay after the initial connection is made and the DB is shutdown, you may need to use the read_timeout config option.


问:
Transition on box-shadow on-off?
http://lucasdebelder.be/googledoodle/
Here is a live version.

So as you can see on the portals there's a glow around it which is the box-shadow; I want to have it going on and off so it kinda feels more real, I've added  transition: box-shadow ease-in-out; but it only does it at the start, after the page is loaded, and then just keeps glowing on.

Here's the relevant code. (portaal_links means portal left, and rechts means right, it's dutch)

HTML:

```<code><div class="portaal portaal_links"></div>
<div class="portaal portaal_rechts"></div>
</code>```

CSS:

```<code>/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
}
</code>```

答:
Use animation instead of transition.

Keyframes: https://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp

Animation: https://www.w3schools.com/css/css3_animations.asp

.test {
  background: red;
  border-radius: 50%;
  width: 100px;
  height: 200px;
  animation: testing 3s linear infinite; }

@keyframes testing {
  25% {
    box-shadow: 0 0 55px rgba(0,0,0,0.9); }
  75% {
    box-shadow: 0 0 0 transparent; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

Title: Transition on box-shadow on-off?

Body:
http://lucasdebelder.be/googledoodle/
Here is a live version.

So as you can see on the portals there's a glow around it which is the box-shadow; I want to have it going on and off so it kinda feels more real, I've added  transition: box-shadow ease-in-out; but it only does it at the start, after the page is loaded, and then just keeps glowing on.

Here's the relevant code. (portaal_links means portal left, and rechts means right, it's dutch)

HTML:

CSS:

/*portaal general*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}

/*portaal left*/
.portaal_links {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    transition: box-shadow ease-in-out;
    transition-delay: 1s;
    transition-duration: 1s;
    box-shadow: 0 0 55px #57B6FF;
    opacity: 0.75;
    left: 50px;
}

.portaal_rechts {
    background: radial-gradient(ellipse at center, rgba(243,197,189,1) 0%,rgba(232,108,87,1) 50%,rgba(234,40,3,1) 51%,rgba(255,102,0,1) 75%,rgba(199,34,0,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    box-shadow: 0 0 55px #FF6600;
    opacity: 0.55;
    left: 750px;
}

Body:
Use animation instead of transition.

Keyframes: https://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp

Animation: https://www.w3schools.com/css/css3_animations.asp

.test {
  background: red;
  border-radius: 50%;
  width: 100px;
  height: 200px;
  animation: testing 3s linear infinite; }

@keyframes testing {
  25% {
    box-shadow: 0 0 55px rgba(0,0,0,0.9); }
  75% {
    box-shadow: 0 0 0 transparent; }
}

<div class="test"></div>


问:
Displaying Vector Value
I'm trying to add all of the values of my vectors together and get the average, but im receiving error messages.

Here's my directions fo the assignment so you guys could better understand

1)      Accept 15 grades into the vector from the user

EXTRA ADVANCED challenge and requirements:

Accept the number if and only if it is greater than 0.00. Accept the number if and only if, it is a valid type double. That is you are doing validation in this manner each time before populating the values into the vector?

2)      After the numbers are accepted into the vector, calculate and display the average of the 15 entered numbers.

3)      Using Bubble Sort (or another method/algorithm native to vectors), sort the 15 numbers in the array from Greatest to Least. Hint: does not a vector have a built-in sorting method? How do we get the vector to sort descending as required here rather than the standard acending?

4)      Display the sorted gradesVector

Here's the error messages:

```<code>main.cpp:43:10: error: use of undeclared identifier 'sum'
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     ^
main.cpp:43:42: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                      ~~~~~~~~~~~~~~~^~~~~~
main.cpp:43:67: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                                               ~~~~~~~~~~~~~~~^~~~
main.cpp:44:10: error: use of undeclared identifier 'average'
     average = sum/15;
     ^
main.cpp:44:20: error: use of undeclared identifier 'sum'
     average = sum/15;
               ^
main.cpp:46:18: error: use of undeclared identifier 'average'
     cout << average;
</code>```

Here's the code:

```<code>vector<double> gradesVector;
gradesVector.reserve(15);

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;
do
  {

    if(c!=0)

      cout << "Invalid Rage. Please Enter Range 0-100:\n";
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     average = sum/15;

     cout << average;

        }
</code>```

答:
This is the answer

I forgot to use #include <numeric>

the code now reads

```<code>vector<double> gradesVector(15);
double sum;
double average;

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;
do
  {

    if(c!=0)

      cout << "Invalid Rage. Please Enter Range 0-100:\n";
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
</code>```

This line of code uses #include <numeric> I also changed gradesVector[i].begin()andgradesVector[i].end()
    to gradesVector.begin() and gradesVector.end()

```<code>     sum = accumulate(gradesVector.begin(), gradesVector.end(), 0);
     average = sum/15;

        }
cout << average;
</code>```

Title: Displaying Vector Value

Body:
I'm trying to add all of the values of my vectors together and get the average, but im receiving error messages.

Here's my directions fo the assignment so you guys could better understand

1)      Accept 15 grades into the vector from the user

EXTRA ADVANCED challenge and requirements:

Accept the number if and only if it is greater than 0.00. Accept the number if and only if, it is a valid type double. That is you are doing validation in this manner each time before populating the values into the vector?

2)      After the numbers are accepted into the vector, calculate and display the average of the 15 entered numbers.

3)      Using Bubble Sort (or another method/algorithm native to vectors), sort the 15 numbers in the array from Greatest to Least. Hint: does not a vector have a built-in sorting method? How do we get the vector to sort descending as required here rather than the standard acending?

4)      Display the sorted gradesVector

Here's the error messages:

main.cpp:43:10: error: use of undeclared identifier 'sum'
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     ^
main.cpp:43:42: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                      ~~~~~~~~~~~~~~~^~~~~~
main.cpp:43:67: error: member reference base type 'value_type' (aka 'double') is not a structure or union
     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
                                               ~~~~~~~~~~~~~~~^~~~
main.cpp:44:10: error: use of undeclared identifier 'average'
     average = sum/15;
     ^
main.cpp:44:20: error: use of undeclared identifier 'sum'
     average = sum/15;
               ^
main.cpp:46:18: error: use of undeclared identifier 'average'
     cout << average;

Here's the code:

vector<double> gradesVector;
gradesVector.reserve(15);

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;
do
  {

    if(c!=0)

      cout << "Invalid Rage. Please Enter Range 0-100:\n";
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

     sum = accumulate(gradesVector[i].begin(), gradesVector[i].end(), 0);
     average = sum/15;

     cout << average;

        }

Body:
This is the answer

I forgot to use #include <numeric>

the code now reads

vector<double> gradesVector(15);
double sum;
double average;

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    int c=0;
do
  {

    if(c!=0)

      cout << "Invalid Rage. Please Enter Range 0-100:\n";
      cout << "Please Enter Grade "<< i + 1 <<": " << flush;
      cin >> gradesVector[i];
      c++;
  }
    while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

This line of code uses #include <numeric> I also changed gradesVector[i].begin()andgradesVector[i].end()
    to gradesVector.begin() and gradesVector.end()

     sum = accumulate(gradesVector.begin(), gradesVector.end(), 0);
     average = sum/15;

        }
cout << average;


问:
Extract information from web streams
Is it possible to extract information from websites that provide streaming of data? For example, the web page https://www.lightstreamer.com shows a demo where prices keep changing.

Using Google Chrome Developer (F12, Network, WS, Reload page with F5, Select name "lightstreamer") , I found out that the stream is being sent from wss://push.lightstreamer.com/lightstreamer.

答:
You can find an example of client with full source on github.

The following line shows how to target a demo server

```<code>var lsClient = new LightstreamerClient(protocolToUse+"//localhost:"+portToUse,"DEMO");
</code>```

Another example - this in .NET - is here and it's based on a connection listener

```<code>using Lightstreamer.DotNet.Client;

namespace DotNetStockListDemo
{

    class StocklistConnectionListener : IConnectionListener
</code>```

You can read also that this

HelloWorldAdapter class implements the IDataProvider interface
  (which is the .NET remote equivalent of the Java DataProvider
  interface).

and find more implementation details in the docs there.

Title: Extract information from web streams

Body:
You can find an example of client with full source on github.

The following line shows how to target a demo server

var lsClient = new LightstreamerClient(protocolToUse+"//localhost:"+portToUse,"DEMO");

Another example - this in .NET - is here and it's based on a connection listener

using Lightstreamer.DotNet.Client;

namespace DotNetStockListDemo
{

    class StocklistConnectionListener : IConnectionListener

You can read also that this

HelloWorldAdapter class implements the IDataProvider interface
  (which is the .NET remote equivalent of the Java DataProvider
  interface).

and find more implementation details in the docs there.


问:
Xamarin - Visual Studio stuck at zipalign.exe
When trying to deploy an app in Android Device, VS is stuck here:

1>C:\Users\George\AppData\Local\Android\android-sdk\build-tools\23.0.1\zipalign.exe
  4 "C:\Users\George\Documents\Visual Studio
  2015\Projects\SGUotA-Xamarin\BBXamarin\BBXamarin\BBXamarin.Droid\bin\Debug\BBXamarin.Droid-Signed-Unaligned.apk"
  "bin\Debug\BBXamarin.Droid-Signed.apk"

Can anyone propose a solution for this?
screenshot of the problem

答: When I want install Visual Studio 2017, I remove Visual Studio 2015 first then install Visual Studio 2017 and have a same problem even in emulator, to resolve this problem, I uninstall Visual Studio 2017, then removed Xamarin and Android SDK, NDK completely from my computer, then install Visual Studio 2017 again and my problem resolved.</p>


问:
PHP Imagick's setFont method take too long time to execute
I got a very weird problem in my PHP environment using Imagick:

My environment is like this:

```<code>Darwin 16.4.0 Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64

PHP 7.0.16 (cli) (built: Feb 16 2017 22:57:49) ( NTS )

imagick module version => 3.4.3RC4
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel
Imagick compiled with ImageMagick version => ImageMagick 6.9.7-6 Q16 x86_64 2017-02-01 http://www.imagemagick.org
Imagick using ImageMagick library version => ImageMagick 6.9.7-7 Q16 x86_64 2017-02-09 http://www.imagemagick.org
</code>```

And the method setFont of Imagick will cost too long to execute(and even get the default 30 second timeout in execution).

The code is just like this:

```<code><?php
    $img = new Imagick();
    $img->setFont("./SpicyRice.ttf");
    echo "Done";
</code>```

And the code $img->setFont("./SpicyRice.ttf") will get stuck.

No error is thrown, PHP just hang at that method, and timeout the default 30 seconds of execution.

Is there anyone have any thoughts about this? This is the font file that I used.

答:
With the help by @Danack, I resolve the problem and fix it finally.

The problem is so simple, but is really hard to identify at the first time, I think.

The problem for this is that I installed many new fonts into the font library, and didn't rebuild the font config cache.

So, each time when Imagick initing, it try to get the font config and the font config trying to read every font in my font folder to write the font cache.

But, since PHP has a 30 seconds timeout, so the PHP process will fail before the font cache is rebuilt. So, this is endless problem, unless I run the fc-cache command in the command line, and generate the font cache, then, next time when I call this php, the Imagick plugin will use the system's font cache instead to generate all the informations for the font.

And this explains why this works in my command line, because I'm the user of the system, and the system will create font cache for me only.

So, when I run the PHP using command line, it will work, since it has the right font cache, but for the server, since it is httpd and running using system's font cache, it won't work.

So, for now, PHP's imagick is working like normal.

Thank you again, @Danack. Without your help, I won't know the problem like this. :)

Body:
I got a very weird problem in my PHP environment using Imagick:

My environment is like this:

Darwin 16.4.0 Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64

PHP 7.0.16 (cli) (built: Feb 16 2017 22:57:49) ( NTS )

imagick module version => 3.4.3RC4
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel
Imagick compiled with ImageMagick version => ImageMagick 6.9.7-6 Q16 x86_64 2017-02-01 http://www.imagemagick.org
Imagick using ImageMagick library version => ImageMagick 6.9.7-7 Q16 x86_64 2017-02-09 http://www.imagemagick.org

And the method setFont of Imagick will cost too long to execute(and even get the default 30 second timeout in execution).

The code is just like this:

<?php
    $img = new Imagick();
    $img->setFont("./SpicyRice.ttf");
    echo "Done";

And the code $img->setFont("./SpicyRice.ttf") will get stuck.

No error is thrown, PHP just hang at that method, and timeout the default 30 seconds of execution.

Is there anyone have any thoughts about this? This is the font file that I used.


问:
DSAL query for Unread mail in the filter for Outlook using Inbox.Items.Restrict
I am writing a code for automatically downloading an attachment from unread mail containing several keywords in the subject for example "training" but when I tried using SQL query for unread mail, it's giving me an error.

```<code>  Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND " & _
               Chr(34) & "urn:schemas:httpmail:hasattachment" & _
               Chr(34) & "=1"
  Set Items = Inbox.Items.Restrict(Filter) 'No error while running this code
</code>```

```<code> Filter = "@SQL=" & Chr(34) & "& Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND" & _
                    Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                    Chr(34) & "= 1" & Chr(34) & "AND" & _
                    Chr(34) & "urn:schemas:httpmail:read" & _
                    Chr(34) & "= 0"

Set Items = Inbox.Items.Restrict(Filter)
' Now here it is giving me runtime error '-2147352567(800200009)'
</code>```

All the help will be appreciated. Thanks in Advance

答:
You almost got it,

The Error is coming from here Chr(34) & "= 1" & Chr(34) & "AND" & _

It Should be Chr(34) & "=1 AND " & _

Example

```<code>Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
                   Chr(34) & " Like '%Training%' AND " & _
                   Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                   Chr(34) & "=1 AND " & _
                   Chr(34) & "urn:schemas:httpmail:read" & _
                   Chr(34) & "=0"
</code>```

Filtering Items Using a String Comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching. Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.

Body:
I am writing a code for automatically downloading an attachment from unread mail containing several keywords in the subject for example "training" but when I tried using SQL query for unread mail, it's giving me an error.

  Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND " & _
               Chr(34) & "urn:schemas:httpmail:hasattachment" & _
               Chr(34) & "=1"
  Set Items = Inbox.Items.Restrict(Filter) 'No error while running this code

 Filter = "@SQL=" & Chr(34) & "& Chr(34) & "urn:schemas:httpmail:subject" & _
               Chr(34) & " Like '%Training%' AND" & _
                    Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                    Chr(34) & "= 1" & Chr(34) & "AND" & _
                    Chr(34) & "urn:schemas:httpmail:read" & _
                    Chr(34) & "= 0"

Set Items = Inbox.Items.Restrict(Filter)
' Now here it is giving me runtime error '-2147352567(800200009)'

All the help will be appreciated. Thanks in Advance

Body:
You almost got it,

The Error is coming from here Chr(34) & "= 1" & Chr(34) & "AND" & _

It Should be Chr(34) & "=1 AND " & _

Example

Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
                   Chr(34) & " Like '%Training%' AND " & _
                   Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                   Chr(34) & "=1 AND " & _
                   Chr(34) & "urn:schemas:httpmail:read" & _
                   Chr(34) & "=0"

Filtering Items Using a String Comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching. Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.


问:
Pointing out Location of Error from StackTrace-Multiple Threads
I have the following code to catch unhandled Exceptions withing the Program.cs file in a winforms Applications

```<code> private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
            MessageBox.Show(e.Exception.StackTrace.ToString());
            MessageBox.Show(e.Exception.TargetSite.ToString());
            Application.Exit();
        }
</code>```

I'm working with images.I keep getting this Exception

Object is Currently in use elsewhere

The applications uses 2 background workers at the same time.
I have been trying to point out the exact location/line number from the error.

From the stacktrace this is what i get

How can i locate the exact location of the error? so that i can take appropriate measures to correct this issue.

答:
You need to use Windows debugging tools, like Adplus,Windbg or a MemoScope.Net, a relatively new Graphical tool which internally use clrmd. Idea remains, issues like Crash, Hang, which are systems issues, especially in multi user / multi thread environment occurring due to synchronization, data structure / memory corruption, need to be debugged by creating a snapshot / dump at the run-time, which needs to be analyzed using the correct Pdb files (Program Debug Database), so that thread stacks can be reviewed, where exception / deadlock is happening and thus a corrective measure can be invoked.

Just by looking at the information provided by you, it is very difficult to guess, what might have gone wrong, but my guess is as you have multiple background workers doing the processing, therefore the access to the resource need to be Synchronized, using a lock or similar construct, thus more than one thread doesn't tries to access it at same time.

Another question remains, why Background worker in current day, why not Async Await, that would be much cleaner implementation and would not have the challenge of multiple threads, as it doesn't dispatch the call on a separate thread.

Body:
I have the following code to catch unhandled Exceptions withing the Program.cs file in a winforms Applications

 private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
            MessageBox.Show(e.Exception.StackTrace.ToString());
            MessageBox.Show(e.Exception.TargetSite.ToString());
            Application.Exit();
        }

I'm working with images.I keep getting this Exception

Object is Currently in use elsewhere

The applications uses 2 background workers at the same time.
I have been trying to point out the exact location/line number from the error.

From the stacktrace this is what i get

How can i locate the exact location of the error? so that i can take appropriate measures to correct this issue.


问:
Backtesting stock returns for Moving Average rule in r
I am trying to backtest stock returns given a 10 month moving average rule. The rule being, if the price is above the 10mnth average - buy, if it is below the 10mnth average - hold the value constant.

I know how to do this in excel very easily, but I am having trouble in R.

Below is my approach in R:

```<code>#Downloand financial data
library(Quandl)

SPY <- Quandl("YAHOO/INDEX_GSPC", type = "xts", collapse = "monthly")
head(SPY)

#Calculate log returns
SPY$log_ret <- diff(log(SPY$Close))

#Calculate moving average for Closing price
SPY$MA.10 <- rollapply(SPY$Close, width = 10, FUN = mean)

#Create binary rule to determine when to buy and when to hold
#1 = Buy
SPY$Action <- ifelse(SPY$MA.10 < SPY$Close, 1, 0)

#Create default value in a new column to backtest returns
SPY$Hit <- 100

#Calculate cumulative returns
SPY$Hit <-ifelse(SPY$Action == 1, SPY[2:n, "Hit"] *
                (1 + SPY$log_ret), lag.xts(SPY$Hit, k=1))
</code>```

Returns do get calculated correctly for an Action of 1, but when the Action is not 1, I find that SPY$Hit only lags 1 time, then defaults to the 100 value, while I would like it to hold the value from the last Action == 1 time.

This formula works very well in MS Excel and is very easy to implement, but it seems that the issue in R is that I cannot keep the value constant from the last Action == 1, how can I do this so that I can see how well this simple trading strategy would work?

Please let me know if I can clarify this further, thank you.

```<code>Sample of the desired output:
      Action Return    Answer
 [1,]      0   0.00 100.00000
 [2,]      1   0.09 109.00000
 [3,]      1   0.08 117.72000
 [4,]      1  -0.05 111.83400
 [5,]      1  -0.03 108.47898
 [6,]      0  -0.02 108.47898
 [7,]      0   0.01 108.47898
 [8,]      0   0.06 108.47898
 [9,]      1  -0.03 105.22461
[10,]      0   0.10 105.22461
[11,]      1  -0.05  99.96338
</code>```

答:
In Excel there are 2 ways to attain it,
1. Go to the Data command find Data Analysis, find Moving Average,,
In the dialog box you need to put Input data range, Interval (in yur case 10), then output cell addresses.
After finding Result write this formula,

=if(A2 >B2, "Buy", "Hold")
Where A2 hold Price, B2 holds 10 months Moving Average value.

Any where in sheet number cells horizontally 1 to 10 (month number).
Below row put month's value 1 to 10.
Below row calculate 10 months Average.

And finally write the Above written formula to find Buy or hold.

Body:
I am trying to backtest stock returns given a 10 month moving average rule. The rule being, if the price is above the 10mnth average - buy, if it is below the 10mnth average - hold the value constant.

I know how to do this in excel very easily, but I am having trouble in R.

Below is my approach in R:

#Downloand financial data
library(Quandl)

SPY <- Quandl("YAHOO/INDEX_GSPC", type = "xts", collapse = "monthly")
head(SPY)

#Calculate log returns
SPY$log_ret <- diff(log(SPY$Close))

#Calculate moving average for Closing price
SPY$MA.10 <- rollapply(SPY$Close, width = 10, FUN = mean)

#Create binary rule to determine when to buy and when to hold
#1 = Buy
SPY$Action <- ifelse(SPY$MA.10 < SPY$Close, 1, 0)

#Create default value in a new column to backtest returns
SPY$Hit <- 100

#Calculate cumulative returns
SPY$Hit <-ifelse(SPY$Action == 1, SPY[2:n, "Hit"] *
                (1 + SPY$log_ret), lag.xts(SPY$Hit, k=1))

Returns do get calculated correctly for an Action of 1, but when the Action is not 1, I find that SPY$Hit only lags 1 time, then defaults to the 100 value, while I would like it to hold the value from the last Action == 1 time.

This formula works very well in MS Excel and is very easy to implement, but it seems that the issue in R is that I cannot keep the value constant from the last Action == 1, how can I do this so that I can see how well this simple trading strategy would work?

Please let me know if I can clarify this further, thank you.

Sample of the desired output:
      Action Return    Answer
 [1,]      0   0.00 100.00000
 [2,]      1   0.09 109.00000
 [3,]      1   0.08 117.72000
 [4,]      1  -0.05 111.83400
 [5,]      1  -0.03 108.47898
 [6,]      0  -0.02 108.47898
 [7,]      0   0.01 108.47898
 [8,]      0   0.06 108.47898
 [9,]      1  -0.03 105.22461
[10,]      0   0.10 105.22461
[11,]      1  -0.05  99.96338


问:
Image not displaying when using paper clip
This problem i have been trying to solve with the help of stack over websites. But unfortunately i can't do so. So i decided to ask a helping hand instead.

I have tried all those links to solve this problem. But none of them work.

```<code>    http://stackoverflow.com/questions/25934465/rails-paperclip-not-showing-image
    http://stackoverflow.com/questions/9170335/paperclip-images-not-displaying-in-rails-app
    http://stackoverflow.com/questions/23971226/rails-image-not-showing-up-with-paperclip
    http://stackoverflow.com/questions/31348628/paperclip-not-showing-image-even-though-url-images-in-correct-places
    http://stackoverflow.com/questions/7425001/specifying-missing-png-in-paperclip
    http://stackoverflow.com/questions/25249252/paperclip-where-to-place-the-
    missing-png-default-image
    http://stackoverflow.com/questions/38734116/ruby-paperclip-how-to-get-missing-png-to-work
</code>```

Now my problem is that it's always displaying a square image saying missing.

Below is my code

Recipe.rb

```<code> class Recipe < ApplicationRecord

        has_attached_file :image, styles: { medium:  "400x400#" },
       :path => ":rails_root/public/system/:attachment/:id/:style/:filename",
       :url => "/system/:attachment/:id/:style/:filename"

      validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

      end
</code>```

Recipe's show.html.haml

```<code>= image_tag @recipe.image.url(:medium, class: "recipe_image")
</code>```

Recipe's new.html.haml

```<code>= simple_form_for @recipe, html: { multipart: true } do |f|
  - if @recipe.errors.any?
    #errors
      %p
        = @recipe.errors.count
        Prevented this recipe froms saving
      %ul
        - @recipe.errors.full_messages.each do |msg|
          %li= msg
  .panel-body
    = f.input :title, input_html: { class: 'form-control' }
    = f.input :description, input_html: { class: 'form-control' }
    = f.input :image, input_html: { class: 'form-control' }

    = f.button :submit, class: "btn btn-primary"
</code>```

答:
been having the same problem for a while but fixed it myself just now.

what i did:

look through your site folder to see where the images are saved. i.e. mine were saving in a different path to what was showing in my post.rb file.
troubleshoot it is all i can suggest. right click and inspect element on the broken image and compare

i adjusted accordingly and it works fine now :)

Body:
This problem i have been trying to solve with the help of stack over websites. But unfortunately i can't do so. So i decided to ask a helping hand instead.

I have tried all those links to solve this problem. But none of them work.

    http://stackoverflow.com/questions/25934465/rails-paperclip-not-showing-image
    http://stackoverflow.com/questions/9170335/paperclip-images-not-displaying-in-rails-app
    http://stackoverflow.com/questions/23971226/rails-image-not-showing-up-with-paperclip
    http://stackoverflow.com/questions/31348628/paperclip-not-showing-image-even-though-url-images-in-correct-places
    http://stackoverflow.com/questions/7425001/specifying-missing-png-in-paperclip
    http://stackoverflow.com/questions/25249252/paperclip-where-to-place-the-
    missing-png-default-image
    http://stackoverflow.com/questions/38734116/ruby-paperclip-how-to-get-missing-png-to-work

Now my problem is that it's always displaying a square image saying missing.

Below is my code

Recipe.rb

 class Recipe < ApplicationRecord

        has_attached_file :image, styles: { medium:  "400x400#" },
       :path => ":rails_root/public/system/:attachment/:id/:style/:filename",
       :url => "/system/:attachment/:id/:style/:filename"

      validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

      end

Recipe's show.html.haml

= image_tag @recipe.image.url(:medium, class: "recipe_image")

Recipe's new.html.haml

= simple_form_for @recipe, html: { multipart: true } do |f|
  - if @recipe.errors.any?
    #errors
      %p
        = @recipe.errors.count
        Prevented this recipe froms saving
      %ul
        - @recipe.errors.full_messages.each do |msg|
          %li= msg
  .panel-body
    = f.input :title, input_html: { class: 'form-control' }
    = f.input :description, input_html: { class: 'form-control' }
    = f.input :image, input_html: { class: 'form-control' }

    = f.button :submit, class: "btn btn-primary"


问:
How can I simplify this code? (Chess game obstruction testing)
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

```<code>    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }
</code>```

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

答:
My soultion would be: introduce a direction class, and then do the check in this style:
isBlocked(startPossition, direction, numberOfFields)

I have done a little example, using 3 Classes.

Direction - an enum to represent the 8 directions (2 horizontal, 2 vertical, 4 diagonal)

Position - the x and y value of an position

LinarMove - represent one linear Move(startPossition, direction, numberOfFields) and contains the isBlockedMethod

The Enum:

```<code>public enum Direction {

    UP(0, 1),
    DOWN(0, -1),
    LEFT(1, 0),
    RIGHT(-1, 0),

    UP_LEFT(UP, LEFT),
    UP_RIGTH(UP, RIGHT),
    DOWN_LEFT(DOWN, LEFT),
    DOWN_RIGHT(
            DOWN, RIGHT);

    private final int incrementX;
    private final int incrementY;

    private Direction(int incrementX, int incrementY) {
        this.incrementX = incrementX;
        this.incrementY = incrementY;
    }

    private Direction(Direction sub1, Direction sub2) {
        this.incrementX = sub1.incrementX + sub2.incrementX;
        this.incrementY = sub1.incrementY + sub2.incrementY;
    }

    public Position oneField(Position start) {
        return new Position(start.getX() + this.incrementX, start.getY()
                + this.incrementY);
    }
}
</code>```

The purpuse of second constructor is only that it alowes to write the diagonal moves in a more readable way.

```<code>public class Position {
    private final int x;
    private final int y;

    public Position(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public String toString() {
        return "x:" + x + ", y:" + y;
    }
}
</code>```

The Move contains the isBlocked Method -- you can see how small it get, and how readable it become. At least there is no single direction related if statement left.

The name LinareMove sugget that there is possible an other kind of move for the knight.

```<code>public class LinearMove {

    private final Position start;
    private final Direction direction;

    /** Length of the move. */
    private final int numberOfFields;

    public LinearMove(Position start, Direction direction, int numberOfFields) {
        super();
        this.start = start;
        this.direction = direction;
        this.numberOfFields = numberOfFields;
    }

    boolean isBlocked() {
        Position pos = this.start;
        for (int i = 0; i < (this.numberOfFields - 1); i++) {
            pos = this.direction.oneField(pos);
            if (isPiece(pos)) {
                return true;
            }
        }
        return false;
    }

    boolean isPiece(Position pos) {
        //Dummy;
        System.out.println(pos);
        return false;
    }
}
</code>```

And this is how it works:

```<code>    public static void main(String[] args) {
    new LinearMove(new Position(1, 1), Direction.RIGHT, 3).isBlocked();
    }
</code>```

You maybe noticed, that the knights move is some kind of probem. With this soultion you could model it in two ways:

```<code>- 4 special Directions
- an other kind of move class (this is the more cleaner way, because you could always return true, in the isBockedMethod)
</code>```

Body:
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

Body:
My soultion would be: introduce a direction class, and then do the check in this style:
isBlocked(startPossition, direction, numberOfFields)

I have done a little example, using 3 Classes.

Direction - an enum to represent the 8 directions (2 horizontal, 2 vertical, 4 diagonal)

Position - the x and y value of an position

LinarMove - represent one linear Move(startPossition, direction, numberOfFields) and contains the isBlockedMethod

The Enum:

public enum Direction {

    UP(0, 1),
    DOWN(0, -1),
    LEFT(1, 0),
    RIGHT(-1, 0),

    UP_LEFT(UP, LEFT),
    UP_RIGTH(UP, RIGHT),
    DOWN_LEFT(DOWN, LEFT),
    DOWN_RIGHT(
            DOWN, RIGHT);

    private final int incrementX;
    private final int incrementY;

    private Direction(int incrementX, int incrementY) {
        this.incrementX = incrementX;
        this.incrementY = incrementY;
    }

    private Direction(Direction sub1, Direction sub2) {
        this.incrementX = sub1.incrementX + sub2.incrementX;
        this.incrementY = sub1.incrementY + sub2.incrementY;
    }

    public Position oneField(Position start) {
        return new Position(start.getX() + this.incrementX, start.getY()
                + this.incrementY);
    }
}

The purpuse of second constructor is only that it alowes to write the diagonal moves in a more readable way.

public class Position {
    private final int x;
    private final int y;

    public Position(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public String toString() {
        return "x:" + x + ", y:" + y;
    }
}

The Move contains the isBlocked Method -- you can see how small it get, and how readable it become. At least there is no single direction related if statement left.

The name LinareMove sugget that there is possible an other kind of move for the knight.

public class LinearMove {

    private final Position start;
    private final Direction direction;

    /** Length of the move. */
    private final int numberOfFields;

    public LinearMove(Position start, Direction direction, int numberOfFields) {
        super();
        this.start = start;
        this.direction = direction;
        this.numberOfFields = numberOfFields;
    }

    boolean isBlocked() {
        Position pos = this.start;
        for (int i = 0; i < (this.numberOfFields - 1); i++) {
            pos = this.direction.oneField(pos);
            if (isPiece(pos)) {
                return true;
            }
        }
        return false;
    }

    boolean isPiece(Position pos) {
        //Dummy;
        System.out.println(pos);
        return false;
    }
}

And this is how it works:

    public static void main(String[] args) {
    new LinearMove(new Position(1, 1), Direction.RIGHT, 3).isBlocked();
    }

You maybe noticed, that the knights move is some kind of probem. With this soultion you could model it in two ways:

- 4 special Directions
- an other kind of move class (this is the more cleaner way, because you could always return true, in the isBockedMethod)


问:
asp.net webservice jquery textbox autocomplete
I'm trying to implement jquery - textbox autocomplete. for this setup a web service.

```<code>    [WebMethod]

    public List<Condition> GetCondition(string term)
    {

        List<Condition> listCondition = new List<Condition>();

        string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spSelCondition", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@term",
                Value = term
            });
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
            }
            return listCondition;
        }
    }

    public class Condition
    {
        public string ConditionName { get; set; }
        public string ConditionID { get; set; }
    }
</code>```

WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.

```<code><script type="text/javascript">
            $(document).ready(function () {

                $('#txtCondition').autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: 'ibs_ws.asmx/GetCondition',
                            method: 'post',
                            contentType: 'application/json;charset=utf-8',
                            data: JSON.stringify({ term: request.term }),
                            dataType: 'json',
                            success: function (data) {
                                response(data.d);

                            },
                            error: function (err) {
                                alert(err);
                            }
                        });
                    }

            });
        })</script>
</code>```

When I access the webservice it takes the @term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].

What could be the problem.

--
Thanks & Regards

答:
May be it will help you. try this

I think you need to use $.map(data.d, function (value, key) {}).  here is the example need to update your success code like below then you can get value inside object.

```<code>success: function (data) {
                        response($.map(data.d, function (value, key) {
                            return {
                                ConID: value.ConditionID,
                                ConNAme: value.ConditionName,
                            }
                        }))
                    },
</code>```

AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.

Body:
I'm trying to implement jquery - textbox autocomplete. for this setup a web service.

    [WebMethod]

    public List<Condition> GetCondition(string term)
    {

        List<Condition> listCondition = new List<Condition>();

        string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spSelCondition", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@term",
                Value = term
            });
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
            }
            return listCondition;
        }
    }

    public class Condition
    {
        public string ConditionName { get; set; }
        public string ConditionID { get; set; }
    }

WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.

When I access the webservice it takes the @term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].

What could be the problem.

--
Thanks & Regards

Body:
May be it will help you. try this

I think you need to use $.map(data.d, function (value, key) {}).  here is the example need to update your success code like below then you can get value inside object.

success: function (data) {
                        response($.map(data.d, function (value, key) {
                            return {
                                ConID: value.ConditionID,
                                ConNAme: value.ConditionName,
                            }
                        }))
                    },

AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.


问:
How to install python modules?
I am new at python programing language, I want to install .whl file with pip but it doesn`t happen... I am trying to download pyHook for 64-bit windows 7 for python 3.6 or 2.7.

Please help me!

答:
Method 1

As already answered here, you simply have to use pip command to install whl file as well,
pip install some-package.whl assuming .whl file is in the same directory you are running command from, if not just provide the complete path like
pip install C:\somedir\mypackage.whl

Method 2

Alternatively you can unzip the .whl file using 7-zip. Then in the unzipped directory you will find the module which you can copy and paste in the directory C:/Python34/Lib/site-packages/ (or wherever else you have installed Python). as already anwered here

This method only works if there is not extension module to be compiled, therefore in this case it won't work as pointed out by @roland-smith

Title: How to install python modules?