问:
"Unfortunately, camera has stopped" on camera intent
So im trying to allow the user to take a picture which I would then send to a server. I am a bit of a noob in android so i followed this tutorial on how to do so. I've seen a few questions similar to mine but not quite the same. The app does launch the camera app and allows me to take a picture, it's when I hit the "check" to accept the image so to say that I get the message "Unfortunately, camera has stopped" and the app returns to the activity where I don't get the thumbnail nor the image aparently. Logcat shows nothing from the moment the camera launches to when it stops working. Here is my code:

Activity

```<code>package com.example.ignacio.androidchat;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class TaskCompletionForm extends AppCompatActivity{

    private static final String TAG = "TaskCompletionForm";
    private static int REQUEST_IMAGE_CAPTURE = 1;
    ImageView formImageView;
    private String currImagePath;

    private final boolean submitTime = false;
    private final boolean submitGPS = false;
    private final boolean requestImage = true;
    private final boolean requestQRRead = false;
    private final boolean requestRFID = false;

    private LinearLayout formContainer;

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

        formContainer = (LinearLayout) findViewById(R.id.ll_formContainer);

        final Button b_submit = (Button) findViewById(R.id.b_submit);
        b_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });

        final Button b_takePicture = (Button) findViewById(R.id.b_takePicture);
        b_takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchPhotographIntent();
            }
        });

        formImageView = (ImageView) findViewById(R.id.formImageView);

    }

    private void submitForm() {
        final int childCount = formContainer.getChildCount() - 1;
        JSONObject jsonObject = new JSONObject();
        try {
            // add text fields
            int textFieldCount = 0;
            ArrayList<String> entries = new ArrayList<>();
            for (int i = 0; i < childCount; i++) {
                View v = formContainer.getChildAt(i);
                if (v instanceof EditText) {
                    entries.add(((EditText) v).getText().toString());
                    textFieldCount++;
                }
            }
            jsonObject.put("fieldCount", textFieldCount);
            jsonObject.put("fields", new JSONArray(entries));

            // add image
            if (requestImage && !currImagePath.equals(""))
            {
                Bitmap bitmap = BitmapFactory.decodeFile(currImagePath);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
                jsonObject.put("image", encodedImage);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        WebSocket.getInstance().submitCompletionForm(jsonObject);
    }

    private void dispatchPhotographIntent()
    {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            File photoFile = null;
            try{
                photoFile = createImageFile();
            } catch (IOException e)
            {
                e.printStackTrace();
                // handle exeption
            }

            // continue only if the file was successfully created
            if (photoFile != null)
            {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.ignacio.androidchat.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private File createImageFile() throws IOException
    {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        if (!image.exists())
        {
            image.getParentFile().mkdirs();
            image.createNewFile();
        }
        currImagePath = image.getAbsolutePath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            formImageView.setImageBitmap(imageBitmap);
        }
    }
}
</code>```

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ignacio.androidchat">

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

    <!-- To auto-complete the email text field in the login form with the user's emails
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />-->

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA"
        android:required = "true"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomeScreen"
            android:launchMode="singleTask"/>
        <activity android:name=".TaskDescription" />
        <activity android:name=".TaskCompletionForm"
            android:configChanges="keyboardHidden|orientation"/>

        <service android:name=".WebSocketIntentService" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.ignacio.androidchat.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>
</code>```

file_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.example.ignacio.androidchat/files/Pictures/" />
</paths>
</code>```

答:
I hypothesize that the camera application on older Samsung Android devices (api 17 in my case) requires a uri in the format "file:///.....".   The problem is the file uri format causes Android Nougat (api 24 and greater) to throw the FileUriExposedException.

I got this to work:

```<code>Uri imageUri;
// N is for Nougat Api 24 Android 7
if (Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
    // FileProvider required for Android 7.  Sending a file URI throws exception.
    imageUri = FileProvider.getUriForFile(getContext(),"com.<your name here>.fileprovider",imageFile);
} else {
    // For older devices:
    // Samsung Galaxy Tab 7" 2 (Samsung GT-P3113 Android 4.2.2, API 17)
    // Samsung S3
    imageUri = Uri.fromFile(imageFile);
}
</code>```

The ideal is to only use FileProvider in Nougat or higher.

You may want to lower the api version of Build.VERSION_CODES.  YMMV, depending on your tolerance for on the file uri exposure.

See: Android Documentation for note on FileUriExposedException in Android Nougat.

Body:
So im trying to allow the user to take a picture which I would then send to a server. I am a bit of a noob in android so i followed this tutorial on how to do so. I've seen a few questions similar to mine but not quite the same. The app does launch the camera app and allows me to take a picture, it's when I hit the "check" to accept the image so to say that I get the message "Unfortunately, camera has stopped" and the app returns to the activity where I don't get the thumbnail nor the image aparently. Logcat shows nothing from the moment the camera launches to when it stops working. Here is my code:

Activity

package com.example.ignacio.androidchat;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class TaskCompletionForm extends AppCompatActivity{

    private static final String TAG = "TaskCompletionForm";
    private static int REQUEST_IMAGE_CAPTURE = 1;
    ImageView formImageView;
    private String currImagePath;

    private final boolean submitTime = false;
    private final boolean submitGPS = false;
    private final boolean requestImage = true;
    private final boolean requestQRRead = false;
    private final boolean requestRFID = false;

    private LinearLayout formContainer;

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

        formContainer = (LinearLayout) findViewById(R.id.ll_formContainer);

        final Button b_submit = (Button) findViewById(R.id.b_submit);
        b_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });

        final Button b_takePicture = (Button) findViewById(R.id.b_takePicture);
        b_takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchPhotographIntent();
            }
        });

        formImageView = (ImageView) findViewById(R.id.formImageView);

    }

    private void submitForm() {
        final int childCount = formContainer.getChildCount() - 1;
        JSONObject jsonObject = new JSONObject();
        try {
            // add text fields
            int textFieldCount = 0;
            ArrayList<String> entries = new ArrayList<>();
            for (int i = 0; i < childCount; i++) {
                View v = formContainer.getChildAt(i);
                if (v instanceof EditText) {
                    entries.add(((EditText) v).getText().toString());
                    textFieldCount++;
                }
            }
            jsonObject.put("fieldCount", textFieldCount);
            jsonObject.put("fields", new JSONArray(entries));

            // add image
            if (requestImage && !currImagePath.equals(""))
            {
                Bitmap bitmap = BitmapFactory.decodeFile(currImagePath);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
                jsonObject.put("image", encodedImage);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        WebSocket.getInstance().submitCompletionForm(jsonObject);
    }

    private void dispatchPhotographIntent()
    {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            File photoFile = null;
            try{
                photoFile = createImageFile();
            } catch (IOException e)
            {
                e.printStackTrace();
                // handle exeption
            }

            // continue only if the file was successfully created
            if (photoFile != null)
            {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.ignacio.androidchat.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private File createImageFile() throws IOException
    {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        if (!image.exists())
        {
            image.getParentFile().mkdirs();
            image.createNewFile();
        }
        currImagePath = image.getAbsolutePath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            formImageView.setImageBitmap(imageBitmap);
        }
    }
}

Manifest

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

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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA"
        android:required = "true"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomeScreen"
            android:launchMode="singleTask"/>
        <activity android:name=".TaskDescription" />
        <activity android:name=".TaskCompletionForm"
            android:configChanges="keyboardHidden|orientation"/>

        <service android:name=".WebSocketIntentService" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.ignacio.androidchat.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.example.ignacio.androidchat/files/Pictures/" />
</paths>

Body:
I hypothesize that the camera application on older Samsung Android devices (api 17 in my case) requires a uri in the format "file:///.....".   The problem is the file uri format causes Android Nougat (api 24 and greater) to throw the FileUriExposedException.

I got this to work:

Uri imageUri;
// N is for Nougat Api 24 Android 7
if (Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
    // FileProvider required for Android 7.  Sending a file URI throws exception.
    imageUri = FileProvider.getUriForFile(getContext(),"com.<your name here>.fileprovider",imageFile);
} else {
    // For older devices:
    // Samsung Galaxy Tab 7" 2 (Samsung GT-P3113 Android 4.2.2, API 17)
    // Samsung S3
    imageUri = Uri.fromFile(imageFile);
}

The ideal is to only use FileProvider in Nougat or higher.

You may want to lower the api version of Build.VERSION_CODES.  YMMV, depending on your tolerance for on the file uri exposure.

See: Android Documentation for note on FileUriExposedException in Android Nougat.


来源: stackexchange

问:
C# ListBox Selection Unchanged Event?
I want to be able to de-select an item in the ListBox if the user clicks the same item again. There is the SelectionChanged event that everyone uses with ListBoxes, but this obviously will not fire when the selection is unchanged.

There is also no Click event, something people recommend. Visual Studio C# 2015 does not contain such event.

I have tried using MouseLeftButtonDown event, but once the ListBox has been populated with ListBoxItems, this event does not fire anymore. In addition, I thought about attaching Mouse events to the ListBoxItems, but this does not seem practicable, as I would have to attach n number of new events every time I populate the ListBox.

Does anyone have a XAML solution to this inquiry?

答:
I originally selected mm8's answer, but I later learned that SelectedIndex is not updated during the PreviewMouseLeftButtonDown event, a feature I indirectly was asking for in the question. You actually get the previous, out-of-date SelectedIndex value when using this event.

I found out if you use the MouseLeftButtonUp event, it actually fires, unlike the MouseLeftButtonDown event, and I get the most recent value for the SelectedIndex variable.

For anyone that cares, this is the System.Windows.Controls's ListBox version. I tried using the Systems.Windows.Forms's ListBox implementation, but it does not support multi-lines out of the box, unlike Controls, so I threw away that idea.

tldr

Use MouseLeftButtonUp event.

ContentLicense: CC BY-SA 3.0

Title: C# ListBox Selection Unchanged Event?


问:
Hide css dropdown menu
I've created a dropdown menu in css. My problem is that the dropdown is fixed on mobile phone if i touch somewhere outside the menu. How can i hide my dropdown menu on mobile phone? On desktop with mouse it works fine.

here is my css:

#nav {
 margin: 0;
 text-align:center;
 position:fixed;
 width:1162px;
 top: 0%;
 left: 50%;
 margin-left: -587px; /* Die Hälfte der Breite (width) + 6px */
 padding: 7px 6px 0;
 background: #7d7d7d url(img/gradient.png) repeat-x 0 -110px;
 line-height: 100%;

 border-radius: 1em;
 -webkit-border-radius: 1em;
 -moz-border-radius: 1em;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);
}
#nav li {
 margin: 0 5px;
 padding: 0 0 8px;
 float: left;
 position: relative;
 list-style: none;
}

/* main level link */
#nav a {
 font-weight: bold;
 color: #e7e5e5;
 text-decoration: none;
 display: block;
 padding:  8px 20px;
 margin: 0;

 -webkit-border-radius: 1.6em;
 -moz-border-radius: 1.6em;

 text-shadow: 0 1px 1px rgba(0,0,0, .3);
}
#nav a:hover {
 background: #000;
 color: #fff;
}

/* main level link hover */
#nav .current a, #nav li:hover > a {
 background: #666 url(img/gradient.png) repeat-x 0 -40px;
 color: #444;
 border-top: solid 1px #f8f8f8;

 -webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 -moz-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 box-shadow: 0 1px 1px rgba(0,0,0, .2);

 text-shadow: 0 1px 0 rgba(255,255,255, 1);
}

/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
 background: none;
 border: none;
 color: #666;

 -webkit-box-shadow: none;
 -moz-box-shadow: none;
}
#nav ul a:hover {
 background: #0078ff url(img/gradient.png) repeat-x 0 -100px !important;
 color: #fff !important;

 -webkit-border-radius: 0;
 -moz-border-radius: 0;

 text-shadow: 0 1px 1px rgba(0,0,0, .1);
}

/* dropdown */
#nav li:hover > ul {
 display: block;
}

/* level 2 list */
#nav ul {
 display: none;

 margin: 0;
 padding: 0;
 width: 185px;
 position: absolute;
 top: 35px;
 left: 0;
 background: #ddd url(img/gradient.png) repeat-x 0 0;
 border: solid 1px #b4b4b4;

 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 border-radius: 10px;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 box-shadow: 0 1px 3px rgba(0,0,0, .3);
}
#nav ul li {
 float: none;
 margin: 0;
 padding: 0;
}

#nav ul a {
 font-weight: normal;
 text-shadow: 0 1px 0 #fff;
}

/* level 3+ list */
#nav ul ul {
 left: 185px;
 top: -1px;
}

/* rounded corners of first and last link */
#nav ul li:first-child > a {
 -webkit-border-top-left-radius: 9px;
 -moz-border-radius-topleft: 9px;

 -webkit-border-top-right-radius: 9px;
 -moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a {
 -webkit-border-bottom-left-radius: 9px;
 -moz-border-radius-bottomleft: 9px;

 -webkit-border-bottom-right-radius: 9px;
 -moz-border-radius-bottomright: 9px;
}

/* clearfix */
#nav:after {
 content: ".";
 display: block;
 clear: both;
 visibility: hidden;
 line-height: 0;
 height: 0;
}
#nav {
 display: inline-block;
}
html[xmlns] #nav {
 display: block;
}

* html #nav {
 height: 1%;
}```
</div>
</div>
</p>

<p>and here the navigation menu set with ul and li</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="nav">
 <li class="current">Test</li>
 <li>Musik
  <ul>
   <li>Test</li>
   <li>Test
    <ul>
     <li>Test</li>
    </ul>
   </li>
  </ul>
 </li>
</ul></code>```

答:
 ul { display:block; padding:0px;}
 ul li{ display: inline-block; position:relative;}
 ul li ul { display:none; position:absolute; top:100%; left:0;}
 ul li ul li { display:block;}
 ul li ul li ul { left:100%; top:0;}
 ul li:hover > ul { display:block; width:120px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
     <li>
         Menu option
        </li>
        <li>
         Menu option2
            <ul>
             <li>
                 Submenu 1
                    <ul>
                        <li>
                            Submenu 2
                        </li>
                    </ul>
                </li>
                <li>
                    Submenu
                </li>
                <li>
                    Submenu
                </li>
            </ul>
        </li>
    </ul></code>```

If you are using hover property to show drop-down menu on desktop then it's automatically hidden on mobile when you touch outside the menu

Title: Hide css dropdown menu

Body:
I've created a dropdown menu in css. My problem is that the dropdown is fixed on mobile phone if i touch somewhere outside the menu. How can i hide my dropdown menu on mobile phone? On desktop with mouse it works fine.

here is my css:

#nav {
 margin: 0;
 text-align:center;
 position:fixed;
 width:1162px;
 top: 0%;
 left: 50%;
 margin-left: -587px; /* Die Hälfte der Breite (width) + 6px */
 padding: 7px 6px 0;
 background: #7d7d7d url(img/gradient.png) repeat-x 0 -110px;
 line-height: 100%;

 border-radius: 1em;
 -webkit-border-radius: 1em;
 -moz-border-radius: 1em;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);
}
#nav li {
 margin: 0 5px;
 padding: 0 0 8px;
 float: left;
 position: relative;
 list-style: none;
}

/* main level link */
#nav a {
 font-weight: bold;
 color: #e7e5e5;
 text-decoration: none;
 display: block;
 padding:  8px 20px;
 margin: 0;

 -webkit-border-radius: 1.6em;
 -moz-border-radius: 1.6em;

 text-shadow: 0 1px 1px rgba(0,0,0, .3);
}
#nav a:hover {
 background: #000;
 color: #fff;
}

/* main level link hover */
#nav .current a, #nav li:hover > a {
 background: #666 url(img/gradient.png) repeat-x 0 -40px;
 color: #444;
 border-top: solid 1px #f8f8f8;

 -webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 -moz-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 box-shadow: 0 1px 1px rgba(0,0,0, .2);

 text-shadow: 0 1px 0 rgba(255,255,255, 1);
}

/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
 background: none;
 border: none;
 color: #666;

 -webkit-box-shadow: none;
 -moz-box-shadow: none;
}
#nav ul a:hover {
 background: #0078ff url(img/gradient.png) repeat-x 0 -100px !important;
 color: #fff !important;

 -webkit-border-radius: 0;
 -moz-border-radius: 0;

 text-shadow: 0 1px 1px rgba(0,0,0, .1);
}

/* dropdown */
#nav li:hover > ul {
 display: block;
}

/* level 2 list */
#nav ul {
 display: none;

 margin: 0;
 padding: 0;
 width: 185px;
 position: absolute;
 top: 35px;
 left: 0;
 background: #ddd url(img/gradient.png) repeat-x 0 0;
 border: solid 1px #b4b4b4;

 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 border-radius: 10px;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 box-shadow: 0 1px 3px rgba(0,0,0, .3);
}
#nav ul li {
 float: none;
 margin: 0;
 padding: 0;
}

#nav ul a {
 font-weight: normal;
 text-shadow: 0 1px 0 #fff;
}

/* level 3+ list */
#nav ul ul {
 left: 185px;
 top: -1px;
}

/* rounded corners of first and last link */
#nav ul li:first-child > a {
 -webkit-border-top-left-radius: 9px;
 -moz-border-radius-topleft: 9px;

 -webkit-border-top-right-radius: 9px;
 -moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a {
 -webkit-border-bottom-left-radius: 9px;
 -moz-border-radius-bottomleft: 9px;

 -webkit-border-bottom-right-radius: 9px;
 -moz-border-radius-bottomright: 9px;
}

/* clearfix */
#nav:after {
 content: ".";
 display: block;
 clear: both;
 visibility: hidden;
 line-height: 0;
 height: 0;
}
#nav {
 display: inline-block;
}
html[xmlns] #nav {
 display: block;
}

* html #nav {
 height: 1%;
}

and here the navigation menu set with ul and li

Test

Musik

Test

Test

Test

Body:
 ul { display:block; padding:0px;}
 ul li{ display: inline-block; position:relative;}
 ul li ul { display:none; position:absolute; top:100%; left:0;}
 ul li ul li { display:block;}
 ul li ul li ul { left:100%; top:0;}
 ul li:hover > ul { display:block; width:120px;}

<ul>
     <li>
         <a href="#">Menu option</a>
        </li>
        <li>
         <a href="#">Menu option2</a>
            <ul>
             <li>
                 <a href="#">Submenu 1</a>
                    <ul>
                        <li>
                            <a href="#">Submenu 2</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#">Submenu</a>
                </li>
                <li>
                    <a href="#">Submenu</a>
                </li>
            </ul>
        </li>
    </ul>

If you are using hover property to show drop-down menu on desktop then it's automatically hidden on mobile when you touch outside the menu


问:
ViewPager Is Stuck Between Views after Disabling User Interaction for Activity
I recently implemented code in my app to allow the app to disable all user interaction while a boolean field is set to true. The purpose of doing this is to keep a user from interacting with the app while a vehicle is in motion. As suggested by other questions/answers I implemented this by overriding dispatchTouchEvent in my activity.

```<code>public boolean dispatchTouchEvent(MotionEvent event) {
    if (mLockedOut) {
        showLockedOutDialog();
        return true;
    }
    return super.dispatchTouchEvent(event);
}
</code>```

The problem with this code is that my app consists of multiple fragments displayed in a ViewPager. If user interaction is disabled while a user is swiping between pages, the ViewPager will become stuck between pages.

How can one prevent this from happening? I've posted my solution, but wonder if I didn't overlook some edge or corner case.

答:
I fixed this by only consuming MotionEvents which are of type ACTION_DOWN or ACTION_POINTER_DOWN.

```<code>@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (!mLockedOut) {
        return super.dispatchTouchEvent(event);
    }
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_POINTER_DOWN:
            showLockedOutDialog();
            return true;
        default:
            return super.dispatchTouchEvent(event);
    }
}
</code>```

Body:
I recently implemented code in my app to allow the app to disable all user interaction while a boolean field is set to true. The purpose of doing this is to keep a user from interacting with the app while a vehicle is in motion. As suggested by other questions/answers I implemented this by overriding dispatchTouchEvent in my activity.

public boolean dispatchTouchEvent(MotionEvent event) {
    if (mLockedOut) {
        showLockedOutDialog();
        return true;
    }
    return super.dispatchTouchEvent(event);
}

The problem with this code is that my app consists of multiple fragments displayed in a ViewPager. If user interaction is disabled while a user is swiping between pages, the ViewPager will become stuck between pages.

How can one prevent this from happening? I've posted my solution, but wonder if I didn't overlook some edge or corner case.

Body:
I fixed this by only consuming MotionEvents which are of type ACTION_DOWN or ACTION_POINTER_DOWN.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (!mLockedOut) {
        return super.dispatchTouchEvent(event);
    }
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_POINTER_DOWN:
            showLockedOutDialog();
            return true;
        default:
            return super.dispatchTouchEvent(event);
    }
}


问:
MySQL Date comparison advice
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks</p>

```<code>        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }
</code>```

答:
datediff(now(),dob) will give you the difference in days between two dates.

If you want to see whether somebody is at least 18, try if (date_sub(now(),18 years) > dob)

Everybody born in February? if (month(dob) = 2)

See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

Edit: and since you're stuck with (for unfathomable reasons) a database showing a date that's not in date format, replace dob with your STR_TO_DATE(dob... section.

ContentLicense: CC BY-SA 2.5

Title: MySQL Date comparison advice

Body:
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks

        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }


问:
how do get number separately
I have number from 1 to 100 in column A1 to A100.

I am trying to achieve two results from data.

I want separately 1,2,3,4,5,6,7,8,9 and another one 10,20,30,40,50,60,70,80,90,100

Please help me

答:
Let's say we want in column B "0, 1,2,3,4,5,6,7,8,9" and in column C "0, 10,20,30,40,50,60,70,80,90,100", put:

 -  =MOD(A1,10) as formula for the cell B1

 - =INT(A1/10)*10 as formula for the cell C1

and then copy them to rest of the rows.

Title: how do get number separately


问:
counting records in a query
I'm querying data from SQL SERVER, and using a lot of CASE statement to get the appropriate results. After the data is queries, I dump it to excel. Here's what I'm trying to achieve...

Query looks something like...

```<code>Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
From tblClientInformation
</code>```

So this is a much shortened version of the query, I actually have about 17 Case statements. Once I dump this data to Excel spreadsheet, I do a COUNTIF function to take a count of all Y values for each clientName/ClientNO, so the data looks something like...

```<code>ClientName    ClientNo     AAA        BBB       CCC       TotalY
Bob Smith     1775         Y          N         Y         2
</code>```

So in TotalY I basically use CountIF function in excel to count all the Y values starting in AAA - ZZZ (example). However, since my query yields around 12000 records, it seems to be quite time consuming.

Is there any way that I can count the Y's in the query so that by the time my data is queried in SQL SERVER, all I have to do is simply dump it in excel, rather than adding on the Column TotalY with CountIF function?

答:
What are the data types for fields AAA, BBB, and CCC? If they're integers, what are the possible values? If it is of some numeric data type, and the only values are 0 and 1, you can do it without a CTE

```<code>Select
    ClientName,
    ClientNo,
    Case when AAA=0 then 'N' Else 'Y' End As AAA,
    Case when BBB=0 then 'N' Else 'Y' End as BBB,
    Case when CCC=0 then 'N' Else 'Y' End as CCC,
    AAA+BBB+CCC as TotalY
From tblClientInformation
</code>```

If those three fields can have different values, we would be able to adjust to that as well.

Update: As per a comment from the OP, there can be values other than 0 or 1 for fields AAA, BBB, and CCC; that being the case, I have modified the query to have a nested query to achieve the same results without resorting to a CTE. Since we aren't doing anything recursive, the CTE will have no performance benefit here (I tested with 2.5M rows) and many people find a CTE to be harder to read... Here's the updated query:

```<code>SELECT
    ClientName
    ,ClientNo
    ,AAA
    ,BBB
    ,CCC
    ,LEN(REPLACE(AAA+BBB+CCC, 'N',''))
FROM (
    SELECT
        ClientName,
        ClientNo,
        CASE WHEN AAA=0 THEN 'N' ELSE 'Y' END AS AAA,
        CASE WHEN BBB=0 THEN 'N' ELSE 'Y' END AS BBB,
        CASE WHEN CCC=0 THEN 'N' ELSE 'Y' END AS CCC
    FROM tblClientInformation
)a
</code>```

Title: counting records in a query

Body:
I'm querying data from SQL SERVER, and using a lot of CASE statement to get the appropriate results. After the data is queries, I dump it to excel. Here's what I'm trying to achieve...

Query looks something like...

Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
From tblClientInformation

So this is a much shortened version of the query, I actually have about 17 Case statements. Once I dump this data to Excel spreadsheet, I do a COUNTIF function to take a count of all Y values for each clientName/ClientNO, so the data looks something like...

ClientName    ClientNo     AAA        BBB       CCC       TotalY
Bob Smith     1775         Y          N         Y         2

So in TotalY I basically use CountIF function in excel to count all the Y values starting in AAA - ZZZ (example). However, since my query yields around 12000 records, it seems to be quite time consuming.

Is there any way that I can count the Y's in the query so that by the time my data is queried in SQL SERVER, all I have to do is simply dump it in excel, rather than adding on the Column TotalY with CountIF function?

Body:
What are the data types for fields AAA, BBB, and CCC? If they're integers, what are the possible values? If it is of some numeric data type, and the only values are 0 and 1, you can do it without a CTE

Select
    ClientName,
    ClientNo,
    Case when AAA=0 then 'N' Else 'Y' End As AAA,
    Case when BBB=0 then 'N' Else 'Y' End as BBB,
    Case when CCC=0 then 'N' Else 'Y' End as CCC,
    AAA+BBB+CCC as TotalY
From tblClientInformation

If those three fields can have different values, we would be able to adjust to that as well.

Update: As per a comment from the OP, there can be values other than 0 or 1 for fields AAA, BBB, and CCC; that being the case, I have modified the query to have a nested query to achieve the same results without resorting to a CTE. Since we aren't doing anything recursive, the CTE will have no performance benefit here (I tested with 2.5M rows) and many people find a CTE to be harder to read... Here's the updated query:

SELECT
    ClientName
    ,ClientNo
    ,AAA
    ,BBB
    ,CCC
    ,LEN(REPLACE(AAA+BBB+CCC, 'N',''))
FROM (
    SELECT
        ClientName,
        ClientNo,
        CASE WHEN AAA=0 THEN 'N' ELSE 'Y' END AS AAA,
        CASE WHEN BBB=0 THEN 'N' ELSE 'Y' END AS BBB,
        CASE WHEN CCC=0 THEN 'N' ELSE 'Y' END AS CCC
    FROM tblClientInformation
)a


问:
Using jQuery is there a way to capitalize the first letter of each word in a datalist option value
I have an input form with a datalist of options. I would like to capitalize the first letter of each word in the value attribute.

What I have:

```<code><div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New hampshire"></option>
    <option value="New jersey"></option>
    <option value="New mexico"></option>
    <option value="New york"></option>
    <option value="North carolina"></option>
    <option value="North dakota"></option>
    <option value="Rhode island"></option>
    <option value="South carolina"></option>
    <option value="South dakota"></option>
    <option value="West virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>
</code>```

What I need:

```<code><div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New Hampshire"></option>
    <option value="New Jersey"></option>
    <option value="New Mexico"></option>
    <option value="New York"></option>
    <option value="North Carolina"></option>
    <option value="North Dakota"></option>
    <option value="Rhode Island"></option>
    <option value="South Carolina"></option>
    <option value="South Dakota"></option>
    <option value="West Virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>
</code>```

答:
in your css, put:</p>

```<code>#s option {
text-transform: capitalize;
}
</code>```

Body:
I have an input form with a datalist of options. I would like to capitalize the first letter of each word in the value attribute.

What I have:

<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New hampshire"></option>
    <option value="New jersey"></option>
    <option value="New mexico"></option>
    <option value="New york"></option>
    <option value="North carolina"></option>
    <option value="North dakota"></option>
    <option value="Rhode island"></option>
    <option value="South carolina"></option>
    <option value="South dakota"></option>
    <option value="West virginia"></option>
</datalist><button class="btn btn-default" type="submit"></button>

What I need:

<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New Hampshire"></option>
    <option value="New Jersey"></option>
    <option value="New Mexico"></option>
    <option value="New York"></option>
    <option value="North Carolina"></option>
    <option value="North Dakota"></option>
    <option value="Rhode Island"></option>
    <option value="South Carolina"></option>
    <option value="South Dakota"></option>
    <option value="West Virginia"></option>
</datalist><button class="btn btn-default" type="submit"></button>

Body:
in your css, put:

#s option {
text-transform: capitalize;
}


问:
C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"
```<code>// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }
</code>```

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you

答:
throw new BadConversion(”xxx“) is creating a new object on the heap and throwing a pointer to it.  That object will have to be deleted by the catch block.  I can't think of a good reason why you would want to do that.

The other version is taken care of by RAII, use that.

Body:
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you


问:
Encrypt Redis message on Azure using ServiceStack
I have a problem where we are using ServiceStack's Redis implementation for multi server caching and messaging via server sent events. As part of our security protocol, we are required to encrypt the data going into Redis. I was wondering if anyone has done this in past and what was their experience? Is there an easy way to do it or do we have to write our custom Redis Implementation? If it helps we are using Redis on Azure.</p>

答:
You shouldn't have to write a Custom Redis client but you would need to use ServiceStack.Redis raw IRedisNativeClient API in order to be able to store encrypted byte[] values. The RedisClient inherits from RedisNativeClient which you can cast to in order to access the low-level byte[] API, e.g:

```<code>using (var redis = clientsManager.GetClient())
{
    var redisNative = (RedisNativeClient)redis;
}
</code>```

ServiceStack also has a high-level CryptUtils available in its ServiceStack.Client library which provides an easy API to encrypt values using AES or RSA encryption.

Body:
You shouldn't have to write a Custom Redis client but you would need to use ServiceStack.Redis raw IRedisNativeClient API in order to be able to store encrypted byte[] values. The RedisClient inherits from RedisNativeClient which you can cast to in order to access the low-level byte[] API, e.g:

using (var redis = clientsManager.GetClient())
{
    var redisNative = (RedisNativeClient)redis;
}

ServiceStack also has a high-level CryptUtils available in its ServiceStack.Client library which provides an easy API to encrypt values using AES or RSA encryption.


问:
Association table in sqlalchemy core
I have 3 tables. Cable, PhysicalPoint and Interconnect.

Cable contain two PhysicalPoint (uphill, downhill) and Interconnect contain a PhysicalPoint. I'd like to request all Cable that have a PhysicalPoint in common with Interconnect. I figured it ou with SQL but not sqlalchemy.

```<code>#cable, physicalpoint and interconnect are sqlalchemy.Table
c = cable.alias('c')
pdh = physicalpoint.alias('pdh')
puh = physicalpoint.alias('puh')
idh = interconnect.alias('idh')
iuh = interconnect.alias('iuh')

j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
    .outerjoin(puh, puh.c.id==c.c.cab_uphill)

# this is where I don't know what to do...
j2 = outerjoin(idh, pdh, pdh.c.id==idh.c.id)
j3 = outerjoin(iuh, puh, puh.c.id==iuh.c.id)

# this works but how to integrate the two other join ?
db.execute(select(c.c).select_from(j))
</code>```

I hope this is comprehensive enough... In advance thanks.

Edit:
the sql query I wrote is like this :

```<code>SELECT c.*
FROM cable c
  LEFT JOIN physicalpoint pdh ON (pdh.id = c.cab_downhill)
  LEFT JOIN physicalpoint puh ON (puh.id = c.cab_uphill)
  LEFT JOIN interconnect idh ON (idh.id = pdh.id)
  LEFT JOIN interconnect iuh ON (iuh.id = puh.id)
WHERE idh.id='XXXX' OR iuh.id='XXXX'
</code>```

答:
You write it in the exact same way you wrote your SQL query:</p>

```<code>j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
    .outerjoin(puh, puh.c.id==c.c.cab_uphill)\
    .outerjoin(idh, idh.c.id==pdh.c.id)\
    .outerjoin(iuh, iuh.c.id==puh.c.id)
session.execute(select([c]).select_from(j).where(or_(idh.c.id == "foo", iuh.c.id == "foo"))))
</code>```

Title: Association table in sqlalchemy core

Body:
I have 3 tables. Cable, PhysicalPoint and Interconnect.

Cable contain two PhysicalPoint (uphill, downhill) and Interconnect contain a PhysicalPoint. I'd like to request all Cable that have a PhysicalPoint in common with Interconnect. I figured it ou with SQL but not sqlalchemy.

#cable, physicalpoint and interconnect are sqlalchemy.Table
c = cable.alias('c')
pdh = physicalpoint.alias('pdh')
puh = physicalpoint.alias('puh')
idh = interconnect.alias('idh')
iuh = interconnect.alias('iuh')

j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
    .outerjoin(puh, puh.c.id==c.c.cab_uphill)

# this is where I don't know what to do...
j2 = outerjoin(idh, pdh, pdh.c.id==idh.c.id)
j3 = outerjoin(iuh, puh, puh.c.id==iuh.c.id)

# this works but how to integrate the two other join ?
db.execute(select(c.c).select_from(j))

I hope this is comprehensive enough... In advance thanks.

Edit:
the sql query I wrote is like this :

SELECT c.*
FROM cable c
  LEFT JOIN physicalpoint pdh ON (pdh.id = c.cab_downhill)
  LEFT JOIN physicalpoint puh ON (puh.id = c.cab_uphill)
  LEFT JOIN interconnect idh ON (idh.id = pdh.id)
  LEFT JOIN interconnect iuh ON (iuh.id = puh.id)
WHERE idh.id='XXXX' OR iuh.id='XXXX'

Body:
You write it in the exact same way you wrote your SQL query:

j = c.outerjoin(pdh, pdh.c.id==c.c.cab_downhill)\
    .outerjoin(puh, puh.c.id==c.c.cab_uphill)\
    .outerjoin(idh, idh.c.id==pdh.c.id)\
    .outerjoin(iuh, iuh.c.id==puh.c.id)
session.execute(select([c]).select_from(j).where(or_(idh.c.id == "foo", iuh.c.id == "foo"))))


问:
Having problems outputting proper CGI, Python script?
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

```<code>import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<html><title>Hi</title><body><p>This is a test</p></body></html>")
</code>```

and

```<code>print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")
</code>```

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.

答:
I think the first line of the script needs to specify the interpreter path. Some examples are:

```<code>#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
#!c:\Python24\python.exe
#!c:\Python25\python.exe
</code>```

See if it helps.

Body:
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<title>Hi</title>
This is a test
")

and

print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title>
hello world
")

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.

Body:
I think the first line of the script needs to specify the interpreter path. Some examples are:

#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
#!c:\Python24\python.exe
#!c:\Python25\python.exe

See if it helps.


问:
UserControl with templates, change server-control rendered ID
TL;DR...

When creating a [UserControl] with single use templates, is it possible to get make server-side controls placed within those templates to render their id without the UserControl or container IDs?

In my ASP.NET web application I've create a UserControl with multiple single-use template (I've only given the code here for one of those templates)...

```<code>Public Class MyUserCtrl
    Inherits System.Web.UI.UserControl

    Private Class MyUserCtrlLiteralContainer
        Inherits Control
        Implements INamingContainer
    End Class

    <TemplateContainer(GetType(MyUserCtrlLiteralContainer)),
     TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
        If FirstTemplate IsNot Nothing Then
            Dim container As New MyUserCtrlLiteralContainer()
            FirstTemplate.InstantiateIn(container)
            plhFirst.Controls.Add(container)
        End If
    End Sub
End Class
</code>```

(Note, plhFirst is a <asp:PlaceHolder> in the mark-up)

This is an example of the control being used in a page (controlled by a Master page)...

```<code><asp:Content runat="server" ID="content" ContentPlaceHolderID="mainContent">
  <uc1:MyUserCtrl runat="server" id="muc1">
    <FirstTemplate>
      <asp:Button runat="server" id="btnMyButton" />
    </FirstTemplate>
  </uc1:MyUserCtrl>
</asp:Content>
</code>```

When the <asp:Button> is rendered to the HTML, the id of the element results in...

```<code>id="ctl00_content_muc1_ctl00_btnMyButton"
</code>```

... where the second ctl00 is the ID of the MyUserCtrlLiteralContainer instance.

Is there any way to make the id of the control render as follows?  (So the ID of the container is not used)

```<code>ctl00_content_muc1_btnMyButton
</code>```

Or even better, is there any way to make the id of the control render as follows? (So neither the ID of the usercontrol or container is used)

```<code>ctl00_content_btnMyButton
</code>```

Alternatively, is there a different way to instantiate the controls in the UserControl that would result in either of the above?

答:
I don't believe you are going to be able to get the IDs to look as you wish because they were designed to show control hierarchy, ugly as they are.

You can, however use static IDs on a control, page, or entire project if you wish. Check out this handy ScottGu article from way back in 2010:

https://weblogs.asp.net/scottgu/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series

The section you'll be looking for is Today’s Cleaner Markup Topic: Client IDs

Body:
TL;DR...

When creating a [UserControl] with single use templates, is it possible to get make server-side controls placed within those templates to render their id without the UserControl or container IDs?

In my ASP.NET web application I've create a UserControl with multiple single-use template (I've only given the code here for one of those templates)...

Public Class MyUserCtrl
    Inherits System.Web.UI.UserControl

    Private Class MyUserCtrlLiteralContainer
        Inherits Control
        Implements INamingContainer
    End Class

    <TemplateContainer(GetType(MyUserCtrlLiteralContainer)),
     TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
        If FirstTemplate IsNot Nothing Then
            Dim container As New MyUserCtrlLiteralContainer()
            FirstTemplate.InstantiateIn(container)
            plhFirst.Controls.Add(container)
        End If
    End Sub
End Class

(Note, plhFirst is a <asp:PlaceHolder> in the mark-up)

This is an example of the control being used in a page (controlled by a Master page)...

<asp:Content runat="server" ID="content" ContentPlaceHolderID="mainContent">
  <uc1:MyUserCtrl runat="server" id="muc1">
    <FirstTemplate>
      <asp:Button runat="server" id="btnMyButton" />
    </FirstTemplate>
  </uc1:MyUserCtrl>
</asp:Content>

When the <asp:Button> is rendered to the HTML, the id of the element results in...

id="ctl00_content_muc1_ctl00_btnMyButton"

... where the second ctl00 is the ID of the MyUserCtrlLiteralContainer instance.

Is there any way to make the id of the control render as follows?  (So the ID of the container is not used)

ctl00_content_muc1_btnMyButton

Or even better, is there any way to make the id of the control render as follows? (So neither the ID of the usercontrol or container is used)

ctl00_content_btnMyButton

Alternatively, is there a different way to instantiate the controls in the UserControl that would result in either of the above?


问:
How can I ask cloudflare to return json instead of html
My code consumes an API from XYZ which is being served through CloudFlare. From time to time, the XYZ server is overloaded and the CloudFlare -> XYZ connection times out. When that happens, I get a human readable HTML page from CloudFlare.

Is there anything I can include in my HTTP request to tell CloudFlare that I am an App, not a person, and to report any errors in a JSON response?

答:
This might achieve what you're looking for: https://support.cloudflare.com/hc/en-us/articles/206777107-What-is-Enable-Origin-Error-Pages-

With that enabled you can send your own error pages -- which presumably you'll send in JSON instead of HTML.


问:
Most performant way to use a background image throughout an iphone application
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

```<code>view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];
</code>```

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?

答: Perhaps you can add a subview that contains the image as the bottom view of the window object in the app delegate. Then, for any views that you add on top, you can do: self.view.backgroundColor = [UIColor clearColor] (assuming it's a UIViewController or one of its children that you're using).

Body:
I have an image that I want to use as the background for every view in my application including several modal views.

Right now I'm just creating a new UIColor for each view:

view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"metal-bg.png"]];

This works for the most part but with the modal views there is a brief period during the sliding animation before the background image displays when I can see through the modal view to the view below it.

Is there a better way to do this?
Such as setting up some sort of global object that all the views can use?


问:
.htaccess to change directory name with querystring
I have a url like

domain.com/order/index.php?q=

the order folder no longer exists as its been changed to ecom, so it now looks like the below.

domain.com/ecom/index.php?q=

The problem is we have a ton of external links wanting the order url some scripts and images pull from this url, etc.

How can I simply set .htaccess to still allow the order directory.

I tried this

```<code>RewriteRule ^order/(.*)$ /ecom/$1 [L]
</code>```

It works only if it exactly matches order (e.g domain.com/order/ , but anything after order it then breaks (e.g domain.com/order/index.php?q=)

Any help would be appreciated. I just keep seeing examples similar to what I have above so not sure if I am doing something wrong here.

答:
Use QSA flag</p>

```<code>RewriteRule ^order/(.*)$ /ecom/$1 [QSA,L]
</code>```

Body:
I have a url like

domain.com/order/index.php?q=

the order folder no longer exists as its been changed to ecom, so it now looks like the below.

domain.com/ecom/index.php?q=

The problem is we have a ton of external links wanting the order url some scripts and images pull from this url, etc.

How can I simply set .htaccess to still allow the order directory.

I tried this

RewriteRule ^order/(.*)$ /ecom/$1 [L]

It works only if it exactly matches order (e.g domain.com/order/ , but anything after order it then breaks (e.g domain.com/order/index.php?q=)

Any help would be appreciated. I just keep seeing examples similar to what I have above so not sure if I am doing something wrong here.

Body:
Use QSA flag

RewriteRule ^order/(.*)$ /ecom/$1 [QSA,L]


问:
datetimepicker opening drop down causes application to exit
this is the craziest thing I have ever seen

I have a simple app with nothing in it except a datetimepicker.

If I run the app inside VS(2013-2017) and open the calendar popup everything works fine.

If I compile the app (debug or release) and run it the application closes as soon as I click on the calendar icon.

There are no exceptions reported, attaching to running process does not catch any exception putting in the unhandled exception catch all does not catch anything on the UI or the application thread.

The application targets .NET 4.5.1 with any cpu. Same result if I target x86 or 64.

I am thinking it's probably some security policy or something along those lines but don't know enough about this to pose a correct question to the security team.

Here is the log from Debug Diagnostic Tool:

Loading control script C:\Program Files\DebugDiag\scripts\CrashRule_Process_WindowsFormsApp1.exe.vbs DumpPath set to C:\Program Files\DebugDiag\Logs\Crash rule for all instances of WindowsFormsApp1.exe

[6/13/2017 11:40:42 AM]

Process created. BaseModule - C:\Users\developer1\Documents\Visual Studio 2017\Projects\WindowsFormsApp1\bin\Debug\WindowsFormsApp1.exe. BaseThread - System ID: 9468

C:\Windows\SysWOW64\ntdll.dll loaded at 0x774f0000

 Thread created. New thread - System ID: 8472

 Thread created. New thread - System ID: 14748

 Thread created. New thread - System ID: 12908

 Thread created. New thread - System ID: 14436

 Thread created. New thread - System ID: 5704

 Thread created. New thread - System ID: 5880

 Thread created. New thread - System ID: 7596

 C:\Windows\SYSTEM32\MSCOREE.DLL loaded at 0x74ad0000

 C:\Windows\syswow64\KERNEL32.dll loaded at 0x769f0000

 C:\Windows\syswow64\KERNELBASE.dll loaded at 0x76e60000

 C:\Windows\syswow64\ADVAPI32.dll loaded at 0x76fa0000

 C:\Windows\syswow64\msvcrt.dll loaded at 0x753b0000

 C:\Windows\SysWOW64\sechost.dll loaded at 0x75460000

 C:\Windows\syswow64\RPCRT4.dll loaded at 0x750d0000

 C:\Windows\syswow64\SspiCli.dll loaded at 0x74d90000

 C:\Windows\syswow64\CRYPTBASE.dll loaded at 0x74d80000

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscoreei.dll loaded at 0x74a50000

 C:\Windows\syswow64\SHLWAPI.dll loaded at 0x751e0000

 C:\Windows\syswow64\GDI32.dll loaded at 0x77060000

 C:\Windows\syswow64\USER32.dll loaded at 0x752a0000

 C:\Windows\syswow64\LPK.dll loaded at 0x769e0000

 C:\Windows\syswow64\USP10.dll loaded at 0x766e0000

 C:\Windows\system32\IMM32.DLL loaded at 0x75240000

 C:\Windows\syswow64\MSCTF.dll loaded at 0x76ec0000

 C:\Windows\system32\ctiuser.dll loaded at 0x749d0000

 C:\Windows\syswow64\WS2_32.dll loaded at 0x75050000

 C:\Windows\syswow64\NSI.dll loaded at 0x75480000

 C:\Windows\syswow64\PSAPI.DLL loaded at 0x774c0000

 C:\Windows\system32\FLTLIB.DLL loaded at 0x749c0000

 C:\Windows\system32\VERSION.dll loaded at 0x749b0000

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll loaded at 0x742f0000

 C:\Windows\system32\MSVCR120_CLR0400.dll loaded at 0x741f0000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\mscorlib\50bcbedc6ed7027bd709339d3ec4c388\mscorlib.ni.dll loaded at 0x730a0000

 C:\Windows\syswow64\ole32.dll loaded at 0x76560000

 C:\Windows\system32\uxtheme.dll loaded at 0x6cdd0000

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\clrjit.dll loaded at 0x73020000

 C:\Windows\syswow64\OLEAUT32.dll loaded at 0x76dc0000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System\48fb602d35146bc0c0002b21343a9f56\System.ni.dll loaded at 0x72690000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System.Drawing\d59cbbb217b18f4219761e344ccf1c10\System.Drawing.ni.dll loaded at 0x6a610000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System.Windows.Forms\a615de88390374e7e71749451bfa5eaf\System.Windows.Forms.ni.dll loaded at 0x653c0000

 C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.7601.18837_none_ec86b8d6858ec0bc\comctl32.dll loaded at 0x71c90000

 C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7601.18837_none_41e855142bd5705d\comctl32.dll loaded at 0x6cc30000

 C:\Windows\Microsoft.NET\Framework\v4.0.30319\nlssorting.dll loaded at 0x72270000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System.Core\a514635984ff3f4239dc0421b7e024b9\System.Core.ni.dll loaded at 0x68370000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System.Configuration\a11c194343da7333f7f7e38960758384\System.Configuration.ni.dll loaded at 0x6ab30000

 C:\Windows\assembly\NativeImages_v4.0.30319_32\System.Xml\43529c5402fb2a8ebc8c76877b802cdc\System.Xml.ni.dll loaded at 0x68f70000

 C:\Windows\syswow64\shell32.dll loaded at 0x75490000

C:\Windows\WinSxS\x86_microsoft.windows.gdiplus_6595b64144ccf1df_1.1.7601.23721_none_5c052bcda00f9399\gdiplus.dll loaded at 0x6b010000

 C:\Windows\system32\dwmapi.dll loaded at 0x6ecc0000

 Thread created. New thread - System ID: 6124

 Initializing control script

 Clearing any existing breakpoints

 Current Breakpoint List(BL)

 [6/13/2017 11:40:43 AM]

 Thread exited. Exiting thread - System ID: 6124. Exit code - 0x00000000

 [6/13/2017 11:41:11 AM]

 Thread created. New thread - System ID: 14984

 C:\Windows\SysWOW64\CRYPTSP.dll loaded at 0x74c20000

 C:\Windows\SysWOW64\rsaenh.dll loaded at 0x74be0000

 C:\Windows\SysWOW64\RpcRtRemote.dll loaded at 0x74bd0000

 Thread created. New thread - System ID: 13868

 Thread exited. Exiting thread - System ID: 12908. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 13868. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 14984. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 7596. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 5704. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 5880. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 14436. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 14748. Exit code - 0x00000001

 Thread exited. Exiting thread - System ID: 8472. Exit code - 0x00000001

 Process exited. Exit code - 0x00000001

 Debugging Overhead Cost:

 Total Elapsed Ticks = 28767 (100%)

 Total Ticks Spent in Debugger Engine = 920 (3%)

 Total Ticks Spent in Crash Rule Script = 63 (0%)

答:
Do you have a breakpoint for any of your DateTimePicker's events? If so, remove the breakpoint(s), and the problem should stop. This is a known issue per Microsoft Windows Forms Team on this page: https://connect.microsoft.com/VisualStudio/feedback/details/1290685/debugging-datetimepicker-event-hangs-vs:

"The DateTimePicker control installs a mouse hook as part of its functionality, but when the debugger has the WinForms application stopped on a breakpoint, it allows the possibility of a deadlock if VS happens to get a mouse message. For now, the deadlock is unfortunately a consequence of the DateTimePicker's design. The mouse hook is installed when the drop down is clicked to display the calendar. This means that breakpoints should not be sent in any event handlers which would be called while the calendar is active. We are currently investigating whether it is possible to address this issue and we will update this thread with further information if we are able to make a fix available."


问:
Trying to understand why my python script is skipping the second row in a csv file
I am putting together a python script to create an output of email addresses from a csv. For whatever reason, the script below is skipping the second row (row after the headers) and only recording the data I need after that row. For example, if the users in the csv file were:

```<code>Username:
test
admin
root
</code>```

The output would only be:

```<code>Emails:
admin@gmail.com
root@gmail.com
</code>```

Thus completely ignoring the first entry. Here is the code, any thoughts on the matter are greatly appreciated.

```<code>for filename in glob.glob(path):
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        initialExportOneList = []
        for row in reader:
            iE = [row['Computer Name'], row['Username']]
            finalExportInOneList = [column['Username'] for column in reader if column['Username']]
            initialExportOneList.append(iE)

        domain = '@gmail.com'
        for i in finalExportInOneList:
            fullEmailCreation = i + domain
            print(fullEmailCreation)
</code>```

答:
```<code>for column in reader
</code>```

I am sure you want

```<code>for column in row
</code>```

Body:
I am putting together a python script to create an output of email addresses from a csv. For whatever reason, the script below is skipping the second row (row after the headers) and only recording the data I need after that row. For example, if the users in the csv file were:

Username:
test
admin
root

The output would only be:

Emails:
admin@gmail.com
root@gmail.com

Thus completely ignoring the first entry. Here is the code, any thoughts on the matter are greatly appreciated.

for filename in glob.glob(path):
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        initialExportOneList = []
        for row in reader:
            iE = [row['Computer Name'], row['Username']]
            finalExportInOneList = [column['Username'] for column in reader if column['Username']]
            initialExportOneList.append(iE)

        domain = '@gmail.com'
        for i in finalExportInOneList:
            fullEmailCreation = i + domain
            print(fullEmailCreation)

Body:
for column in reader

I am sure you want

for column in row


答:
you can do a permanent redirect to a page</p>

```<code>RewriteRule ^url-string-to-redirect$ http://www.yourdomain.com/your-new-url-string [R=301,L]
</code>```

Title: .htaccess to change directory name with querystring

Body:
you can do a permanent redirect to a page

RewriteRule ^url-string-to-redirect$ http://www.yourdomain.com/your-new-url-string [R=301,L]


问:
Why is VS Code javascript intellisense dependent on the files I have open?
I have a project using .js and .es6 files (Rails, though I don't think that matters) on which I'm trying to use VS Code's javascript intellisense per these instructions. I have a jsconfig.json file:

```<code>{
    "include": [
        "app/assets/javascripts/**/*",
        "vendor/assets/javascripts/**/*"
    ],
    "compilerOptions": {
        "target": "ES6",
        "checkJs": true
    }
}
</code>```

at the root and all the javascript is in the folders mentioned in the include section. I've also created a globals.d.ts file at the root.

If I open globals.d.ts in VS Code and then run Typescript: Restart TS server, VS Code recognizes those global variables in javascript files. However if I then close  globals.d.ts and run Typescript: Restart TS server again, VS Code does not recognize the globals. This also happens with global variables created in other javascript files. For example, say Class.es6 defines a class. I only get intellisense for the class if I have Class.es6 open in VS Code.

I'm not sure first why my setup isn't working, and second why it would ever depend on which files I have open at the time in VS Code.

答: Since you explicitly specified include, only those included files will be part of your javascript project. You also need to put global.d.ts in your include if you want it to be picked up

Body:
I have a project using .js and .es6 files (Rails, though I don't think that matters) on which I'm trying to use VS Code's javascript intellisense per these instructions. I have a jsconfig.json file:

{
    "include": [
        "app/assets/javascripts/**/*",
        "vendor/assets/javascripts/**/*"
    ],
    "compilerOptions": {
        "target": "ES6",
        "checkJs": true
    }
}

at the root and all the javascript is in the folders mentioned in the include section. I've also created a globals.d.ts file at the root.

If I open globals.d.ts in VS Code and then run Typescript: Restart TS server, VS Code recognizes those global variables in javascript files. However if I then close  globals.d.ts and run Typescript: Restart TS server again, VS Code does not recognize the globals. This also happens with global variables created in other javascript files. For example, say Class.es6 defines a class. I only get intellisense for the class if I have Class.es6 open in VS Code.

I'm not sure first why my setup isn't working, and second why it would ever depend on which files I have open at the time in VS Code.


问:
Cross-platform (microcontroller-PC) algorithm development
I was asked to develop a algorithm for network application on C. This project will be developed on Linux for PC and then it will be transferred to a more portable platform, something that will include a microcontroller. There are many microcontroller/companies out there that provide very nice and large libraries for TCP/IP. This software will hold statistics on the network performance.

The whole idea of a cross platform (uC - PC) seems rubbish to me cause eventually the code should be written in a more platform specific way for the microcontroller, but I am not expert to judge anyway.

Is there any clever way of doing this or is there a anyone that did this before? My brainstorming has "Wrapper library" and "Matlab"... Any ideas?

Thx!

答:
Just assume you can use the standard BSD socket library (system calls are socket(), bind(), accept(), connect(), recv(), send(), with various options).  Any OS with a TCP/IP stack will support this standard API.

There may be some caveats that you will run into if your embedded system uses a run to completion type TCP/IP stack like *u*IP, but those will be easily solvable.

Also only use POSIX file I/O (fopen, fread, fwrite, printf, etc).  But keep in mind your target may not have a filesystem.


问:
add values with PHP
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

```<code>function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }
</code>```

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

答:
I haven't tested it, but something like this could potentially be a one-liner.

```<code>echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );
</code>```

That said, if you do not need all the results, this is a better option:

```<code>$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];
</code>```

Title: add values with PHP

Body:
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

Body:
I haven't tested it, but something like this could potentially be a one-liner.

echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );

That said, if you do not need all the results, this is a better option:

$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];


问:
How can I have multiple left axisItems with the same alignment/position using pyqtgraph?
I wonder if someone can help me out. I am trying to convert the MultiplePlotAxes.py example in pyqtgraph so that the all the axes are on the right side and aligned. Here is my code which I have added an extra plot:

```<code>"""
Demonstrates a way to put multiple axes around a single plot.
(This will eventually become a built-in feature of PlotItem)
"""
#import initExample  ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

pg.mkQApp()

pw = pg.PlotWidget()
pw.show()
pw.setWindowTitle('pyqtgraph example: MultiplePlotAxes')
p1 = pw.plotItem
p1.setLabels(left='axis 1')

## create a new ViewBox, link the right axis to its coordinate system
p2 = pg.ViewBox()
p1.showAxis('right')
p1.scene().addItem(p2)
p1.getAxis('right').linkToView(p2)
p2.setXLink(p1)
p1.getAxis('right').setLabel('axis2', color='#0000ff')

## create third ViewBox.
## this time we need to create a new axis as well.
p3 = pg.ViewBox()
ax3 = pg.AxisItem('right')
p1.layout.addItem(ax3, 2, 3)
p1.scene().addItem(p3)
ax3.linkToView(p3)
p3.setXLink(p1)
ax3.setZValue(-10000)
ax3.setLabel('axis 3', color='#ff0000')

## create forth ViewBox.
## this time we need to create a new axis as well.
p4 = pg.ViewBox()
ax4 = pg.AxisItem('right')
p1.layout.addItem(ax4, 2, 4)
p1.scene().addItem(p4)
ax4.linkToView(p4)
p4.setXLink(p1)
ax4.setZValue(-10000)
ax4.setLabel('axis 4', color='#2EFEF7')

## Handle view resizing
def updateViews():
    ## view has resized; update auxiliary views to match
    global p1, p2, p3, p4
    p2.setGeometry(p1.vb.sceneBoundingRect())
    p3.setGeometry(p1.vb.sceneBoundingRect())
    p4.setGeometry(p1.vb.sceneBoundingRect())

    ## need to re-update linked axes since this was called
    ## incorrectly while views had different shapes.
    ## (probably this should be handled in ViewBox.resizeEvent)
    p2.linkedViewChanged(p1.vb, p2.XAxis)
    p3.linkedViewChanged(p1.vb, p3.XAxis)
    p4.linkedViewChanged(p1.vb, p4.XAxis)

updateViews()
p1.vb.sigResized.connect(updateViews)

p1.plot([1, 2, 4, 8, 16, 32])
p2.addItem(pg.PlotCurveItem([1, 2, 4, 9, 16, 32], pen='b'))
p3.addItem(pg.PlotCurveItem([1, 2, 4, 7, 16, 32], pen='r'))
p4.addItem(pg.PlotCurveItem([1, 3, 5, 7, 17, 32], pen='c'))

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
</code>```

This produces the following picture which I have added a red arrow showing what I want to do.

Based on what I have been able to figure out I can do this using pg.GraphicsLayout(). However, the axisItem directly associated with plotItem and the created axisItems don't match because the one attached to the plotitem is smaller.

Here is a picture of what I believe is happening:

This is my problem as I want them to all align. In the attached code you can addItem(axes,2,1) to the right but it doesn't work on the left. Anyone know how I can do this?

Thanks in advance for any help you can provide.

答:
I have figured something out that is not perfect but is pretty close. Using the suggestion above and adding an extra axis item to the bottom in the appropriate space and blanking it out I have come up with this. All lines  line up but not perfectly with the y-axis but close enough to get away with it. Heres the difference

Original

New

Heres the code:

```<code>from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

pg.mkQApp()

# Axis
a2 = pg.AxisItem("left")
a3 = pg.AxisItem("left")
a4 = pg.AxisItem("left")
a5 = pg.AxisItem("left")
a6 = pg.AxisItem("left")

# ViewBoxes
v2 = pg.ViewBox()
v3 = pg.ViewBox()
v4 = pg.ViewBox()
v5 = pg.ViewBox()
v6 = pg.ViewBox()

# main view
pw = pg.GraphicsView()
pw.setWindowTitle('pyqtgraph example: multiple y-axis')
pw.show()

# layout
l = pg.GraphicsLayout()
pw.setCentralWidget(l)

# add axis to layout
## watch the col parameter here for the position
l.addItem(a2, row=1, col=5, rowspan=1, colspan=1)
l.addItem(a3, row=1, col=4, rowspan=1, colspan=1)
l.addItem(a4, row=1, col=3, rowspan=1, colspan=1)
l.addItem(a5, row=1, col=2, rowspan=1, colspan=1)
l.addItem(a6, row=1, col=1, rowspan=1, colspan=1)

# Blank axis used for aligning things
ax = pg.AxisItem(orientation='bottom')
ax.setPen('#000000')
pos = (2,2)
l.addItem(ax, *pos)

# plotitem and viewbox
## at least one plotitem is used whioch holds its own viewbox and left axis
pI = pg.PlotItem()
v1 = pI.vb  # reference to viewbox of the plotitem
l.addItem(pI, row=1, col=8, rowspan=2, colspan=1)  # add plotitem to layout

# split off 1st axis and put to side
pI.axis_left = pI.getAxis('left')
pos = (1,7)
l.addItem(pI.axis_left, *pos)

# add viewboxes to layout
l.scene().addItem(v2)
l.scene().addItem(v3)
l.scene().addItem(v4)
l.scene().addItem(v5)
l.scene().addItem(v6)

# link axis with viewboxes
a2.linkToView(v2)
a3.linkToView(v3)
a4.linkToView(v4)
a5.linkToView(v5)
a6.linkToView(v6)

# link viewboxes
v2.setXLink(v1)
v3.setXLink(v2)
v4.setXLink(v3)
v5.setXLink(v4)
v6.setXLink(v5)

# axes labels
pI.getAxis("left").setLabel('axis 1 in ViewBox of PlotItem', color='#FFFFFF')
a2.setLabel('axis 2 in Viewbox 2', color='#2E2EFE')
a3.setLabel('axis 3 in Viewbox 3', color='#2EFEF7')
a4.setLabel('axis 4 in Viewbox 4', color='#2EFE2E')
a5.setLabel('axis 5 in Viewbox 5', color='#FFFF00')
a6.setLabel('axis 6 in Viewbox 6', color='#FE2E64')

# slot: update view when resized
def updateViews():
    v2.setGeometry(v1.sceneBoundingRect())
    v3.setGeometry(v1.sceneBoundingRect())
    v4.setGeometry(v1.sceneBoundingRect())
    v5.setGeometry(v1.sceneBoundingRect())
    v6.setGeometry(v1.sceneBoundingRect())

# data
x = [1, 2, 3, 4, 5, 6]
y1 = [0, 4, 6, 8, 10, 4]
y2 = [0, 5, 7, 9, 11, 3]
y3 = [0, 1, 2, 3, 4, 12]
y4 = [0, 8, 0.3, 0.4, 2, 5]
y5 = [0, 1, 6, 4, 2, 1]
y6 = [0, 0.2, 0.3, 0.4, 0.5, 0.6]

# plot
v1.addItem(pg.PlotCurveItem(x, y1, pen='#FFFFFF'))
v2.addItem(pg.PlotCurveItem(x, y2, pen='#2E2EFE'))
v3.addItem(pg.PlotCurveItem(x, y3, pen='#2EFEF7'))
v4.addItem(pg.PlotCurveItem(x, y4, pen='#2EFE2E'))
v5.addItem(pg.PlotCurveItem(x, y5, pen='#FFFF00'))
v6.addItem(pg.PlotCurveItem(x, y6, pen='#FE2E64'))

# updates when resized
v1.sigResized.connect(updateViews)

# autorange once to fit views at start
v2.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v3.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v4.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v5.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v6.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)

updateViews()

if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
</code>```

Hope it helps anyone who has the same problem in the future

Body:
I wonder if someone can help me out. I am trying to convert the MultiplePlotAxes.py example in pyqtgraph so that the all the axes are on the right side and aligned. Here is my code which I have added an extra plot:

"""
Demonstrates a way to put multiple axes around a single plot.
(This will eventually become a built-in feature of PlotItem)
"""
#import initExample  ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

pg.mkQApp()

pw = pg.PlotWidget()
pw.show()
pw.setWindowTitle('pyqtgraph example: MultiplePlotAxes')
p1 = pw.plotItem
p1.setLabels(left='axis 1')

## create a new ViewBox, link the right axis to its coordinate system
p2 = pg.ViewBox()
p1.showAxis('right')
p1.scene().addItem(p2)
p1.getAxis('right').linkToView(p2)
p2.setXLink(p1)
p1.getAxis('right').setLabel('axis2', color='#0000ff')

## create third ViewBox.
## this time we need to create a new axis as well.
p3 = pg.ViewBox()
ax3 = pg.AxisItem('right')
p1.layout.addItem(ax3, 2, 3)
p1.scene().addItem(p3)
ax3.linkToView(p3)
p3.setXLink(p1)
ax3.setZValue(-10000)
ax3.setLabel('axis 3', color='#ff0000')

## create forth ViewBox.
## this time we need to create a new axis as well.
p4 = pg.ViewBox()
ax4 = pg.AxisItem('right')
p1.layout.addItem(ax4, 2, 4)
p1.scene().addItem(p4)
ax4.linkToView(p4)
p4.setXLink(p1)
ax4.setZValue(-10000)
ax4.setLabel('axis 4', color='#2EFEF7')

## Handle view resizing
def updateViews():
    ## view has resized; update auxiliary views to match
    global p1, p2, p3, p4
    p2.setGeometry(p1.vb.sceneBoundingRect())
    p3.setGeometry(p1.vb.sceneBoundingRect())
    p4.setGeometry(p1.vb.sceneBoundingRect())

    ## need to re-update linked axes since this was called
    ## incorrectly while views had different shapes.
    ## (probably this should be handled in ViewBox.resizeEvent)
    p2.linkedViewChanged(p1.vb, p2.XAxis)
    p3.linkedViewChanged(p1.vb, p3.XAxis)
    p4.linkedViewChanged(p1.vb, p4.XAxis)

updateViews()
p1.vb.sigResized.connect(updateViews)

p1.plot([1, 2, 4, 8, 16, 32])
p2.addItem(pg.PlotCurveItem([1, 2, 4, 9, 16, 32], pen='b'))
p3.addItem(pg.PlotCurveItem([1, 2, 4, 7, 16, 32], pen='r'))
p4.addItem(pg.PlotCurveItem([1, 3, 5, 7, 17, 32], pen='c'))

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

This produces the following picture which I have added a red arrow showing what I want to do.

Based on what I have been able to figure out I can do this using pg.GraphicsLayout(). However, the axisItem directly associated with plotItem and the created axisItems don't match because the one attached to the plotitem is smaller.

Here is a picture of what I believe is happening:

This is my problem as I want them to all align. In the attached code you can addItem(axes,2,1) to the right but it doesn't work on the left. Anyone know how I can do this?

Thanks in advance for any help you can provide.

Body:
I have figured something out that is not perfect but is pretty close. Using the suggestion above and adding an extra axis item to the bottom in the appropriate space and blanking it out I have come up with this. All lines  line up but not perfectly with the y-axis but close enough to get away with it. Heres the difference

Original

New

Heres the code:

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

pg.mkQApp()

# Axis
a2 = pg.AxisItem("left")
a3 = pg.AxisItem("left")
a4 = pg.AxisItem("left")
a5 = pg.AxisItem("left")
a6 = pg.AxisItem("left")

# ViewBoxes
v2 = pg.ViewBox()
v3 = pg.ViewBox()
v4 = pg.ViewBox()
v5 = pg.ViewBox()
v6 = pg.ViewBox()

# main view
pw = pg.GraphicsView()
pw.setWindowTitle('pyqtgraph example: multiple y-axis')
pw.show()

# layout
l = pg.GraphicsLayout()
pw.setCentralWidget(l)

# add axis to layout
## watch the col parameter here for the position
l.addItem(a2, row=1, col=5, rowspan=1, colspan=1)
l.addItem(a3, row=1, col=4, rowspan=1, colspan=1)
l.addItem(a4, row=1, col=3, rowspan=1, colspan=1)
l.addItem(a5, row=1, col=2, rowspan=1, colspan=1)
l.addItem(a6, row=1, col=1, rowspan=1, colspan=1)

# Blank axis used for aligning things
ax = pg.AxisItem(orientation='bottom')
ax.setPen('#000000')
pos = (2,2)
l.addItem(ax, *pos)

# plotitem and viewbox
## at least one plotitem is used whioch holds its own viewbox and left axis
pI = pg.PlotItem()
v1 = pI.vb  # reference to viewbox of the plotitem
l.addItem(pI, row=1, col=8, rowspan=2, colspan=1)  # add plotitem to layout

# split off 1st axis and put to side
pI.axis_left = pI.getAxis('left')
pos = (1,7)
l.addItem(pI.axis_left, *pos)

# add viewboxes to layout
l.scene().addItem(v2)
l.scene().addItem(v3)
l.scene().addItem(v4)
l.scene().addItem(v5)
l.scene().addItem(v6)

# link axis with viewboxes
a2.linkToView(v2)
a3.linkToView(v3)
a4.linkToView(v4)
a5.linkToView(v5)
a6.linkToView(v6)

# link viewboxes
v2.setXLink(v1)
v3.setXLink(v2)
v4.setXLink(v3)
v5.setXLink(v4)
v6.setXLink(v5)

# axes labels
pI.getAxis("left").setLabel('axis 1 in ViewBox of PlotItem', color='#FFFFFF')
a2.setLabel('axis 2 in Viewbox 2', color='#2E2EFE')
a3.setLabel('axis 3 in Viewbox 3', color='#2EFEF7')
a4.setLabel('axis 4 in Viewbox 4', color='#2EFE2E')
a5.setLabel('axis 5 in Viewbox 5', color='#FFFF00')
a6.setLabel('axis 6 in Viewbox 6', color='#FE2E64')

# slot: update view when resized
def updateViews():
    v2.setGeometry(v1.sceneBoundingRect())
    v3.setGeometry(v1.sceneBoundingRect())
    v4.setGeometry(v1.sceneBoundingRect())
    v5.setGeometry(v1.sceneBoundingRect())
    v6.setGeometry(v1.sceneBoundingRect())

# data
x = [1, 2, 3, 4, 5, 6]
y1 = [0, 4, 6, 8, 10, 4]
y2 = [0, 5, 7, 9, 11, 3]
y3 = [0, 1, 2, 3, 4, 12]
y4 = [0, 8, 0.3, 0.4, 2, 5]
y5 = [0, 1, 6, 4, 2, 1]
y6 = [0, 0.2, 0.3, 0.4, 0.5, 0.6]

# plot
v1.addItem(pg.PlotCurveItem(x, y1, pen='#FFFFFF'))
v2.addItem(pg.PlotCurveItem(x, y2, pen='#2E2EFE'))
v3.addItem(pg.PlotCurveItem(x, y3, pen='#2EFEF7'))
v4.addItem(pg.PlotCurveItem(x, y4, pen='#2EFE2E'))
v5.addItem(pg.PlotCurveItem(x, y5, pen='#FFFF00'))
v6.addItem(pg.PlotCurveItem(x, y6, pen='#FE2E64'))

# updates when resized
v1.sigResized.connect(updateViews)

# autorange once to fit views at start
v2.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v3.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v4.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v5.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
v6.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)

updateViews()

if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

Hope it helps anyone who has the same problem in the future


问:
how to check if data exist in mysql database before enter
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

```<code> TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID
</code>```

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

```<code>`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "<b>";
   echo "<h3>";
   echo "RECORD ADDED ";
   echo "<h3>";
   echo "</b>";
 }
   else
 {
 echo "<b>";
 echo "<h3>";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "</h3>";
 echo "</b>";
 echo "<br>";
 echo mysql_error();
  }
 ?>
</code>```

`

NOTE:ST2_ID is auto increment

I need your thought guys.

答: Once you have the $name variable, you can simply query table 1 with a select statement to find if information for a specific student exists in table 1 (SELECT * from table1 WHERE NAME=$name). If this query returns any results, perform the insertion into table 2 which you mention above. Otherwise, do nothing.

Body:
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

 TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "";
   echo "
";
   echo "RECORD ADDED ";
   echo "
";
   echo "";
 }
   else
 {
 echo "";
 echo "
";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "
";
 echo "";
 echo "
";
 echo mysql_error();
  }
 ?>

`

NOTE:ST2_ID is auto increment

I need your thought guys.


问:
Execute only when array's length reaches X elements
I was wondering if it's possible to execute function only when arrays length is long enough.

I have a setInterval function to repeatedly fetch info from interweb, if a new user appears it will send his id to an array, and I want to execute different function only when this array's length reaches a specific amount.

Thanks in advance!

答:
After each item is added you can check the length property of the array:</p>

```<code>addUser(...) {
  array.push(...)
  if (array.length > x) {
   execute();
 }
}
</code>```

Body:
After each item is added you can check the length property of the array:

addUser(...) {
  array.push(...)
  if (array.length > x) {
   execute();
 }
}


问:
Different Truncation Results When Casting
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

```<code>float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);
</code>```

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.

答:
aschepler explained the mechanics of what's going on well, but the fundamental problem with your code is using a value which does not exist as a float in code that depends upon the value of its approximation in an unstable way. If you want to multiply by 0.9 (the actual number 0.9=9/10, not the floating point value 0.9 or 0.9f) you should multiply by 9 then divide by 10, or forget about floating point types and use a decimal arithmetic library.

A cheap and dirty way around the problem, when the unstable points are isolated as in your example here, is to just add a value (typically 0.5) which you know will be larger than the error but smaller than the difference from the next integer before truncating.

Body:
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.


问:
calling .focus() on <input type="text"> in WKWebView causes keyboard lag
I'm building an app in HTML5 and Javascript using WKWebView.

I have a very plain text input that I want to call focus() on manually via javascript. It does work, the keyboard pops up and there is a cursor in the input however the iOS keyboard is very laggy when typing/deleting the first character. It takes over a second for the character to appear and for the keyboard to become interactive again.

Does anyone have any idea on how what the problem might be?

答: We had a similar problem in an AngularJS app with WKWebview and we solved it by using ng-click event instead of ng-focus (only on iOS).