问:
Place hyperlinks in CodeMirror textarea
I am new to codemirror.

I have a string in CodeMirror textarea. I want my text to be hyperlinked and it goes to a jsp page and fetch answers and append it back in the codemirror textarea.

I have tried using

hyperlink .

It prints everything along with the tags.

How to place hyperlinks in codemirror text area. A code snippet is really helpful.

Thanks in advance

答:
Sorry, for a very very delay update. Had got a work around at that time. Thought of sharing it.

Since I was looking at some code functions in this edtitor, on double click a function name I am able to append that code definition at the end of the editor.

Below is the example on how I have achieved:

```<code>// setup and fetched the editor earlier.
var editor = CodeMirror.fromTextArea(document.getElementById(key)); // Got my editor

// Later on placed a double click logic:
editor.on("dblclick", function(){
    if(editor.somethingSelected()){
        var from = editor.getCursor("from"), to = editor.getCursor("to");
        if( from.line!=to.line){
            alert("No word");
        }
        else{
            var word = editor.getRange(from, to);
            $.ajax({
                url : "hyperlink.jsp",
                data:{
                    keyword1 : word,
                },
                success: function(response){
                    if(response.length>6){
                        editor.setValue(editor.getValue()+"\n\n\n#"+word+":\n"+response);
                        var line = maxLineNumber;
                        formatMyEditor(); // Formatting my new code
                        editor.indentLine(maxLineNumber-5, -3);
                        editor.setCursor(line+2);
                    }
                    else{
                        alert(word+" -- Not in DB");
                    }
                }
           }
     });
}
</code>```

Title: Place hyperlinks in CodeMirror textarea

Body:
Sorry, for a very very delay update. Had got a work around at that time. Thought of sharing it.

Since I was looking at some code functions in this edtitor, on double click a function name I am able to append that code definition at the end of the editor.

Below is the example on how I have achieved:

// setup and fetched the editor earlier.
var editor = CodeMirror.fromTextArea(document.getElementById(key)); // Got my editor

// Later on placed a double click logic:
editor.on("dblclick", function(){
    if(editor.somethingSelected()){
        var from = editor.getCursor("from"), to = editor.getCursor("to");
        if( from.line!=to.line){
            alert("No word");
        }
        else{
            var word = editor.getRange(from, to);
            $.ajax({
                url : "hyperlink.jsp",
                data:{
                    keyword1 : word,
                },
                success: function(response){
                    if(response.length>6){
                        editor.setValue(editor.getValue()+"\n\n\n#"+word+":\n"+response);
                        var line = maxLineNumber;
                        formatMyEditor(); // Formatting my new code
                        editor.indentLine(maxLineNumber-5, -3);
                        editor.setCursor(line+2);
                    }
                    else{
                        alert(word+" -- Not in DB");
                    }
                }
           }
     });
}


来源: stackexchange

问:
Error Sending Email in Codeigniter 2
I am new in codeigniter framework. I'm trying to send email but I have the problem:

Call to undefined method CI_Loader::libary()

here is my script on controller :

```<code>class Email extends CI_Controller{
function __construct()
{
    parent::__construct();
}

function index()
{
    $config = array(
        'protocol' => 'smtp',
        'smtp_host'=>'ss://smtp.googlemail.com',
        'smtp_port'=>465,
        'smtp_user'=>'thaitea.lumajang@gmail.com',
        'smtp_pass'=>'thaitealumajang1'
    );

    $this->load->libary('email', $config);
    $this->email->set_newline("\r\n");

    $this->email->from('thaitea.lumajang@gmail.com','Tri Wicaksono');
    $this->email->to('cha8agust@gmail.com');
    $this->email->subject('This is an email test');
    $this->email->message('It is working bro');

    if($this->email->send())
    {
        echo 'Your email send';
    } else {
        show_error($this->email->print_debbuger());
    }
}
}
</code>```

答:
I already find out the answer.

There is wrong typing in $this->load->libary.

It should be $this->load->library - there is a missing r in library word.

ContentLicense: CC BY-SA 3.0

Title: Error Sending Email in Codeigniter 2

Body:
I am new in codeigniter framework. I'm trying to send email but I have the problem:

Call to undefined method CI_Loader::libary()

here is my script on controller :

class Email extends CI_Controller{
function __construct()
{
    parent::__construct();
}

function index()
{
    $config = array(
        'protocol' => 'smtp',
        'smtp_host'=>'ss://smtp.googlemail.com',
        'smtp_port'=>465,
        'smtp_user'=>'thaitea.lumajang@gmail.com',
        'smtp_pass'=>'thaitealumajang1'
    );

    $this->load->libary('email', $config);
    $this->email->set_newline("\r\n");

    $this->email->from('thaitea.lumajang@gmail.com','Tri Wicaksono');
    $this->email->to('cha8agust@gmail.com');
    $this->email->subject('This is an email test');
    $this->email->message('It is working bro');

    if($this->email->send())
    {
        echo 'Your email send';
    } else {
        show_error($this->email->print_debbuger());
    }
}
}


问:
Does Spring Data support querying data from multiple schemas simultaneously?
Suppose I have two schemas in one database. Each schema has a table named 'products' which has almost same columns, such as 'title', 'sku'.

I have an entity class as follows, which is mapped to the products table:

```<code>@Entity
public class Products {
  private String title;
  private String sku;
}
</code>```

Now I would like to select 'title' and 'sku' from the two 'products' tables in these two different schemas, how can I do it in Spring Data or does Spring Data support this kind of feature?

答:
No it is not. In order to be able to query data from different datasources with spring-data-jpa you have to define two separate entity manager factories, two separate transaction managers and two different configurations with

```<code>@EnableJpaRepositories(entityManagerFactoryRef = "emf1", transactionManagerRef = "tx1")
</code>```

and

```<code>@EnableJpaRepositories(entityManagerFactoryRef = "emf2", transactionManagerRef = "tx2")
</code>```

respectively.
Then you will be able to create two different repositories and query your data.

To tackle your problem you can introduce an additional level of abstraction like ProductService where you'll inject your repositories and in load methods iterate through them, fetch and combine data from each repository.

Body:
Suppose I have two schemas in one database. Each schema has a table named 'products' which has almost same columns, such as 'title', 'sku'.

I have an entity class as follows, which is mapped to the products table:

@Entity
public class Products {
  private String title;
  private String sku;
}

Now I would like to select 'title' and 'sku' from the two 'products' tables in these two different schemas, how can I do it in Spring Data or does Spring Data support this kind of feature?

Body:
No it is not. In order to be able to query data from different datasources with spring-data-jpa you have to define two separate entity manager factories, two separate transaction managers and two different configurations with

@EnableJpaRepositories(entityManagerFactoryRef = "emf1", transactionManagerRef = "tx1")

and

@EnableJpaRepositories(entityManagerFactoryRef = "emf2", transactionManagerRef = "tx2")

respectively.
Then you will be able to create two different repositories and query your data.

To tackle your problem you can introduce an additional level of abstraction like ProductService where you'll inject your repositories and in load methods iterate through them, fetch and combine data from each repository.


问:
what is the tag specification i'm missing here?
this is  an assignment  given in an website.i tried my best to complete all the specifications that are mentioned in the website but i could not figure out.where my code is going wrong ?
specifications mentioned:

-

In addition to looking like the form shown in FigureBookform image, your form must include the constructs listed in the following instructions. When creating the code for your form, you must use the HTML5 tags that are appropriate to replicate the form and fulfill all the specifications listed.

Code the form with autocomplete active.

Given the image shown in Figure 1, it is easy to see that two field sets are used to create the main structure of the form. Your task is to create the field sets, including the names Customer Info and Books.Don't worry about the content fields for the moment.

The Name field you create should have autofocus, placeholder text, and be required. Don't forget to select the appropriate type for this field as well as all the fields that follow.

The Telephone field should have placeholder text, a pattern to restrict entry, and be required. Pattern should be of the type [Pattern: 1-234-567-8910]

The Email address field should have placeholder text and allow multiple entries. This field should also be required.

The Books field should have a data list. You can select the content you would like to list.

The Quantity (Maximum 5) field should have a minimum value of 1 and a maximum value of 5.

    <title>bookform</title>

<form autocomplete="on">

 A Simple Form

 Form Fundamentals

 <fieldset>
  <legend>Customer Info:</legend>
 Name:  <input type="text" name="Name" id="Name" placeholder="Enter Your Name" autofocus required/>

  Telephone: <input type="text"  id="Telephone" name="Telephone" placeholder="Pattern: 1-234-567-8910" pattern="[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}" required/>

Email address: <input type="text" name="Emailaddress" id="Emailaddress" placeholder="Enter Your Email address" multiple required/>

 </fieldset>

 <fieldset>
  <legend> Books</legend>
  <input type="text" name="Books" list="countries"> <datalist id="countries">

     </datalist>
  Quantity  (Maximum 5): <input type="number" name="Quantity"  id="Quantity" max="5" min="1">

 </fieldset>

<input type="submit" name="submit" value="Submit">

</form>

```

ERROR:testWeb(htmlpackage.WebTestBookform):
Please check specifications for each tag
false

image

update: when i use email type as email it is showing error hence i avoided using it.

答: You should write autocomplete="on" instead of just autocomplete in form tag..</p>

Body:
this is  an assignment  given in an website.i tried my best to complete all the specifications that are mentioned in the website but i could not figure out.where my code is going wrong ?
specifications mentioned:

-

In addition to looking like the form shown in FigureBookform image, your form must include the constructs listed in the following instructions. When creating the code for your form, you must use the HTML5 tags that are appropriate to replicate the form and fulfill all the specifications listed.

Code the form with autocomplete active.

Given the image shown in Figure 1, it is easy to see that two field sets are used to create the main structure of the form. Your task is to create the field sets, including the names Customer Info and Books.Don't worry about the content fields for the moment.

The Name field you create should have autofocus, placeholder text, and be required. Don't forget to select the appropriate type for this field as well as all the fields that follow.

The Telephone field should have placeholder text, a pattern to restrict entry, and be required. Pattern should be of the type [Pattern: 1-234-567-8910]

The Email address field should have placeholder text and allow multiple entries. This field should also be required.

The Books field should have a data list. You can select the content you would like to list.

The Quantity (Maximum 5) field should have a minimum value of 1 and a maximum value of 5.

    <title>bookform</title>

<form autocomplete="on">

 A Simple Form

 Form Fundamentals

 <fieldset>
  <legend>Customer Info:</legend>
 Name:  <input type="text" name="Name" id="Name" placeholder="Enter Your Name" autofocus required/>

  Telephone: <input type="text"  id="Telephone" name="Telephone" placeholder="Pattern: 1-234-567-8910" pattern="[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}" required/>

Email address: <input type="text" name="Emailaddress" id="Emailaddress" placeholder="Enter Your Email address" multiple required/>

 </fieldset>

 <fieldset>
  <legend> Books</legend>
  <input type="text" name="Books" list="countries"> <datalist id="countries">

     </datalist>
  Quantity  (Maximum 5): <input type="number" name="Quantity"  id="Quantity" max="5" min="1">

 </fieldset>

<input type="submit" name="submit" value="Submit">

</form>

ERROR:testWeb(htmlpackage.WebTestBookform):
Please check specifications for each tag
false

image

update: when i use email type as email it is showing error hence i avoided using it.


问:
Cannot initialize UART service on Android
I am developing mobile app which working with sensor, that use UART. Example from official github page works perfect, but code extracted from doesnt work. Only thing that i have changed, is a device search, but this code works perfect with Polar H7 device(only discovering device name and device adress and sending to next activity). On this activity i am trying to connect to UART device, here is code :

```<code>public class UartRecordingActivity extends AppCompatActivity {

    private final static String TAG = UartRecordingActivity.class.getSimpleName();

    // BLE stuff
    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    //private BleService bleService;

    private String deviceName;
    private String deviceAddress;

    //private BleServicesAdapter gattServiceAdapter;

    private boolean isConnected = false;

    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int UART_PROFILE_READY = 10;
    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private static final int STATE_OFF = 10;
    private int mState = UART_PROFILE_DISCONNECTED;

    private UartService mService = null;
    private BluetoothDevice mDevice = null;
    private BluetoothAdapter mBtAdapter = null;

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

        Log.i(TAG, "onCreate");

        final Intent intent = getIntent();
        deviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        deviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

        final Intent gattServiceIntent = new Intent(this, UartService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onStart() {
        super.onStart();

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        service_init();

        mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
        mService.connect(deviceAddress);
    }

    private void service_init() {
        Intent bindIntent = new Intent(this, UartService.class);
        bindService(bindIntent, mServiceConnection, BIND_AUTO_CREATE);

        LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver,
                makeGattUpdateIntentFilter());
    }

    //UART service connected/disconnected
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UartService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(menuItem);}

private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        final Intent mIntent = intent;
        //*********************//
        if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
            runOnUiThread(new Runnable() {
                public void run() {
                    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                    Log.d(TAG, "UART_CONNECT_MSG");

                    mState = UART_PROFILE_CONNECTED;
                }
            });
        }

        //*********************//
        if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {

            runOnUiThread(new Runnable() {
                public void run() {
                    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                    Log.d(TAG, "UART_DISCONNECT_MSG");
                    mState = UART_PROFILE_DISCONNECTED;
                    mService.close();
                }
            });
        }

        //*********************//
        if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
            mService.enableTXNotification();
        }
        //*********************//
        if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
            Log.i("data","received");
            final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
            //handle data
        }
        //*********************//
        if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
        }

    }
};

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }
}
</code>```

Error is caused by this line(mService causing NullPointerException):

```<code>mService.connect(deviceAddress);
</code>```

答:
Method OnServiceConnected is guarantees that you have been connected to service by binding. In OnStart callback you have NullPointer because when you call bindService, it needs a little time to make a connection. Just make your code something like that:</p>

```<code>public void onServiceConnected(ComponentName className, IBinder rawBinder) {
    mService = ((UartService.LocalBinder) rawBinder).getService();
    Log.d(TAG, "onServiceConnected mService= " + mService);
    if (!mService.initialize()) {
        Log.e(TAG, "Unable to initialize Bluetooth");
        finish();
    }
    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
    mService.connect(deviceAddress);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing mobile app which working with sensor, that use UART. Example from official github page works perfect, but code extracted from doesnt work. Only thing that i have changed, is a device search, but this code works perfect with Polar H7 device(only discovering device name and device adress and sending to next activity). On this activity i am trying to connect to UART device, here is code :

public class UartRecordingActivity extends AppCompatActivity {

    private final static String TAG = UartRecordingActivity.class.getSimpleName();

    // BLE stuff
    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    //private BleService bleService;

    private String deviceName;
    private String deviceAddress;

    //private BleServicesAdapter gattServiceAdapter;

    private boolean isConnected = false;

    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int UART_PROFILE_READY = 10;
    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private static final int STATE_OFF = 10;
    private int mState = UART_PROFILE_DISCONNECTED;

    private UartService mService = null;
    private BluetoothDevice mDevice = null;
    private BluetoothAdapter mBtAdapter = null;

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

        Log.i(TAG, "onCreate");

        final Intent intent = getIntent();
        deviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        deviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

        final Intent gattServiceIntent = new Intent(this, UartService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onStart() {
        super.onStart();

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        service_init();

        mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
        mService.connect(deviceAddress);
    }

    private void service_init() {
        Intent bindIntent = new Intent(this, UartService.class);
        bindService(bindIntent, mServiceConnection, BIND_AUTO_CREATE);

        LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver,
                makeGattUpdateIntentFilter());
    }

    //UART service connected/disconnected
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UartService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(menuItem);}

private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        final Intent mIntent = intent;
        //*********************//
        if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
            runOnUiThread(new Runnable() {
                public void run() {
                    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                    Log.d(TAG, "UART_CONNECT_MSG");

                    mState = UART_PROFILE_CONNECTED;
                }
            });
        }

        //*********************//
        if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {

            runOnUiThread(new Runnable() {
                public void run() {
                    String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                    Log.d(TAG, "UART_DISCONNECT_MSG");
                    mState = UART_PROFILE_DISCONNECTED;
                    mService.close();
                }
            });
        }

        //*********************//
        if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
            mService.enableTXNotification();
        }
        //*********************//
        if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
            Log.i("data","received");
            final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
            //handle data
        }
        //*********************//
        if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
        }

    }
};

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }
}

Error is caused by this line(mService causing NullPointerException):

mService.connect(deviceAddress);

Body:
Method OnServiceConnected is guarantees that you have been connected to service by binding. In OnStart callback you have NullPointer because when you call bindService, it needs a little time to make a connection. Just make your code something like that:

public void onServiceConnected(ComponentName className, IBinder rawBinder) {
    mService = ((UartService.LocalBinder) rawBinder).getService();
    Log.d(TAG, "onServiceConnected mService= " + mService);
    if (!mService.initialize()) {
        Log.e(TAG, "Unable to initialize Bluetooth");
        finish();
    }
    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
    mService.connect(deviceAddress);
}


问:
.net Regex for more than 5 consecutive alphabet letters
I am attempting to write a .Net Regex for more than 5 consecutive alphabet letters.

dfhjvudyfyreaaaaa - not allowed

dfhjvudyfyreAAAAA - not allowed

dfhjvAAAAAfyreAAA - not allowed

dfhjvAAAfyresdAAA - allowed

dfhjvAAAf3434yresdA - allowed

So far, i have tried some reg exp but, not working as per my requirement.

My requirement are below

String length should be less than 25 character

String is Combination of alphabet/number only, not allow special character.

Solution tried

^(?=.{1,25}$)(([a-zA-Z0-9])\5?(?!\5))+$

(?i)(.)\1\1

I will used string to represent vehicle engine number or chassis number.

I am okey, if there possible solution in JavaScript.

Can we build this type of regex in .net?

答:
With the case insensitive flag, you can write it using a negative lookahead to test if there isn't five consecutive characters:</p>

```<code>^(?!.*(.)\1{4})[A-Z0-9]{1,25}$
</code>```

Body:
With the case insensitive flag, you can write it using a negative lookahead to test if there isn't five consecutive characters:

^(?!.*(.)\1{4})[A-Z0-9]{1,25}$


问:
shape Detection - TensorFlow
I'm trying to train a model to detect the basic shapes like Circle, Square, Rectangle, etc. using Tensorflow. What would be the best input data set? To load the shapes directly or to find the edge of the image using OpenCV and load only the edge image.

We can detect shapes using OpenCV too. What would be the added advantage to use Machine Learning.

Sample images given for training the model.

答:
I would recommend starting with this guide for doing classification, not object detection:
https://kiosk-dot-codelabs-site.appspot.com/codelabs/tensorflow-for-poets/#0

Classification is for one unique tag for one picture (99% square, 1%circle). Object Detection is for classification of several objects within the picture (x_min=3,y_min=8,x_max=20,y_max30, 99% square). Your case looks more like a classification problem.

You don't need the full Docker installation as in the guide.
If you have Python 3.6 on your system, you can just do:

```<code>pip install tensorflow
</code>```

And then jump to "4. Retrieving the images"

I had to try it out myself, so I downloaded the first 100 pictures of squares and circles from Google with the add-on "fatkun batch download image" from Chrome Web Store.

On my first 10 tests I get accuracy between 92,0% (0.992..) and 99,58%. If your examples are more uniform than a lot of different pictures from Google, you will probably get better results.

Title: shape Detection - TensorFlow

Body:
I would recommend starting with this guide for doing classification, not object detection:
https://kiosk-dot-codelabs-site.appspot.com/codelabs/tensorflow-for-poets/#0

Classification is for one unique tag for one picture (99% square, 1%circle). Object Detection is for classification of several objects within the picture (x_min=3,y_min=8,x_max=20,y_max30, 99% square). Your case looks more like a classification problem.

You don't need the full Docker installation as in the guide.
If you have Python 3.6 on your system, you can just do:

pip install tensorflow

And then jump to "4. Retrieving the images"

I had to try it out myself, so I downloaded the first 100 pictures of squares and circles from Google with the add-on "fatkun batch download image" from Chrome Web Store.

On my first 10 tests I get accuracy between 92,0% (0.992..) and 99,58%. If your examples are more uniform than a lot of different pictures from Google, you will probably get better results.


问:
send html template in php
My Php mail code is like this i want to send html content in mail but i can not send html template with this code

```<code>                    $to = $email;;
                    $subject = 'New Order Detail';
                    $message = 'Hi Jane';
                    $from = 'info@abc.co.in';

                    // Sending email
                    if(mail($to, $subject, $message))
                    {
                        echo 'Your mail has been sent successfully.';
                    }
                    else
                    {
                        echo 'Unable to send email. Please try again.';
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

                        // Create email headers
                        $headers .= 'From: '.$from."\r\n".
                            'Reply-To: '.$from."\r\n" .
                            'X-Mailer: PHP/' . phpversion();

                        // Compose a simple HTML email message
                        $message = '<html><body>';
                        $message = '<table border="1" align="center" width="50%">';
                        $message .= '<tr><td>Test Mail';
                        $message .= '</td></tr>';
                        //$message .= '<p style="color:#080;font-size:18px;">Will you marry me?</p>';
                        $message .= '</table>';
                        $message .= '</body></html>';

                        // Sending email
                        if(mail($to, $subject, $message, $headers))
                        {
                            echo 'Your mail has been sent successfully.';
                        } else
                        {
                            echo 'Unable to send email. Please try again.';
                        }
                    }
</code>```

This kind of output i get in mail i do not know where is my mistake in this code..
Output

```<code><html><body>
<table border="1" align="center" width="50%">
<tr><td>Test Mail</td></tr>
</table>
</body></html>
</code>```

答:
Set your character set to UTF-8:

```<code> $headers .= "Content-type:text/  html;charset=UTF-8" . "\r\n";
</code>```

That should fix it.

Title: send html template in php

Body:
My Php mail code is like this i want to send html content in mail but i can not send html template with this code

                    $to = $email;;
                    $subject = 'New Order Detail';
                    $message = 'Hi Jane';
                    $from = 'info@abc.co.in';

                    // Sending email
                    if(mail($to, $subject, $message))
                    {
                        echo 'Your mail has been sent successfully.';
                    }
                    else
                    {
                        echo 'Unable to send email. Please try again.';
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

                        // Create email headers
                        $headers .= 'From: '.$from."\r\n".
                            'Reply-To: '.$from."\r\n" .
                            'X-Mailer: PHP/' . phpversion();

                        // Compose a simple HTML email message
                        $message = '';
                        $message = '
';
                        $message .= '
Test Mail';
                        $message .= '
';
                        //$message .= '
Will you marry me?
';
                        $message .= '
';
                        $message .= '';

                        // Sending email
                        if(mail($to, $subject, $message, $headers))
                        {
                            echo 'Your mail has been sent successfully.';
                        } else
                        {
                            echo 'Unable to send email. Please try again.';
                        }
                    }

This kind of output i get in mail i do not know where is my mistake in this code..
Output

Test Mail

Body:
Set your character set to UTF-8:

 $headers .= "Content-type:text/  html;charset=UTF-8" . "\r\n";

That should fix it.


答:
This is a possible solution:

```<code>^(?![a-zA-Z0-9]*([a-zA-Z0-9])\1{4})[a-zA-Z0-9]{1,24}$
</code>```

See the regex demo.

Details

^ - start of string

(?![a-zA-Z0-9]*([a-zA-Z0-9])\1{4}) - no 5 consecutive alphanumeric chars anywhere inside the string

[a-zA-Z0-9]{1,24}  - 1 to 24 alphanumeric chars

$ -  end of string.

If you set a case insensitive flag, you will make the backreference also case insensitive (aaAAA will also fail the match). In .NET, you may pass the flag as RegexOptions.IgnoreCase option, and in JS, add i modifier.

C# implementation:

```<code>bool valid = Regex.IsMatch(input, @"^(?![a-z0-9]*([a-z0-9])\1{4})[a-z0-9]{1,24}\z", RegexOptions.IgnoreCase);
</code>```

I suggest \z in .NET because it always matches at the very end of the string while $ can match before a final newline char (not the case in JS).

In JS, you may use

```<code>var valid = /^(?![a-z0-9]*([a-z0-9])\1{4})[a-z0-9]{1,24}$/i.test(s)
</code>```

Title: .net Regex for more than 5 consecutive alphabet letters

Body:
I am attempting to write a .Net Regex for more than 5 consecutive alphabet letters.

dfhjvudyfyreaaaaa - not allowed

dfhjvudyfyreAAAAA - not allowed

dfhjvAAAAAfyreAAA - not allowed

dfhjvAAAfyresdAAA - allowed

dfhjvAAAf3434yresdA - allowed

So far, i have tried some reg exp but, not working as per my requirement.

My requirement are below

String length should be less than 25 character

String is Combination of alphabet/number only, not allow special character.

Solution tried

^(?=.{1,25}$)(([a-zA-Z0-9])\5?(?!\5))+$

(?i)(.)\1\1

I will used string to represent vehicle engine number or chassis number.

I am okey, if there possible solution in JavaScript.

Can we build this type of regex in .net?

Body:
This is a possible solution:

^(?![a-zA-Z0-9]*([a-zA-Z0-9])\1{4})[a-zA-Z0-9]{1,24}$

See the regex demo.

Details

^ - start of string

(?![a-zA-Z0-9]*([a-zA-Z0-9])\1{4}) - no 5 consecutive alphanumeric chars anywhere inside the string

[a-zA-Z0-9]{1,24}  - 1 to 24 alphanumeric chars

$ -  end of string.

If you set a case insensitive flag, you will make the backreference also case insensitive (aaAAA will also fail the match). In .NET, you may pass the flag as RegexOptions.IgnoreCase option, and in JS, add i modifier.

C# implementation:

bool valid = Regex.IsMatch(input, @"^(?![a-z0-9]*([a-z0-9])\1{4})[a-z0-9]{1,24}\z", RegexOptions.IgnoreCase);

I suggest \z in .NET because it always matches at the very end of the string while $ can match before a final newline char (not the case in JS).

In JS, you may use

var valid = /^(?![a-z0-9]*([a-z0-9])\1{4})[a-z0-9]{1,24}$/i.test(s)


问:
how to use order by multiple times on the results set along with rownum (oracle)
I have the below tables:

```<code>person table
personid |   firstname | lastname
------------------------------
P1       |  Jim        |  John
P2       |  Kori       |  Test
P3       |    Adam     |    Blair
P4       |    Kim      |    sand
P5       |    julia    |   Dan

order table
orderno |ordername | price | personid
---------------------------------
1       |shoes     |  100  | P1
2       |books     |  50   |P2
3       | pen      |   10  |P3
4       |laptop    |  80   |P4
5       |notebook  |   40  |P5

Email address table
clientid    emailid
---------------------
P1      |   jom.John@test.com
P3      |     adam.blair@test.com
P4      |    kim.sand@test.com
</code>```

I have to get the top 3 person names ordered by 'price' and then get rid of the persons who dont have an email address and this final list  should be ordered by firstname (desc)
My results should look like:

```<code>Firstname   lastname  price
------------------------------
Kim       |   sand   |  80
Jim       |  john    | 100

I tried minus but not able to figure out how to use order by (first by price) and then for the final results by firstname. oracle is not liking the combination of multiple order by and rownum together.
Any pointers would be helpful.
</code>```

答:
Try this:-

```<code>SELECT P.FIRSTNAME,P.LASTNAME,O.PRICE FROM PERSON_TABLE P
INNER JOIN ORDER_TABLE O
ON P.PERSONID = O.PERSONID
AND P.PERSONID NOT IN
       (SELECT E.CLIENTID FROM EMAIL_ADDRESS_TABLE E)
ORDER BY P.FIRSTNAME desc;
</code>```

output:

```<code>Firstname lastname price
------------------------
kim       | sand   | 80
julia     | dan    | 40
</code>```

My result is not look like as your but it may be help you. I wrote above script as per your above mentioned requirement.

Body:
I have the below tables:

person table
personid |   firstname | lastname
------------------------------
P1       |  Jim        |  John
P2       |  Kori       |  Test
P3       |    Adam     |    Blair
P4       |    Kim      |    sand
P5       |    julia    |   Dan

order table
orderno |ordername | price | personid
---------------------------------
1       |shoes     |  100  | P1
2       |books     |  50   |P2
3       | pen      |   10  |P3
4       |laptop    |  80   |P4
5       |notebook  |   40  |P5

Email address table
clientid    emailid
---------------------
P1      |   jom.John@test.com
P3      |     adam.blair@test.com
P4      |    kim.sand@test.com

I have to get the top 3 person names ordered by 'price' and then get rid of the persons who dont have an email address and this final list  should be ordered by firstname (desc)
My results should look like:

Firstname   lastname  price
------------------------------
Kim       |   sand   |  80
Jim       |  john    | 100

I tried minus but not able to figure out how to use order by (first by price) and then for the final results by firstname. oracle is not liking the combination of multiple order by and rownum together.
Any pointers would be helpful.

Body:
Try this:-

SELECT P.FIRSTNAME,P.LASTNAME,O.PRICE FROM PERSON_TABLE P
INNER JOIN ORDER_TABLE O
ON P.PERSONID = O.PERSONID
AND P.PERSONID NOT IN
       (SELECT E.CLIENTID FROM EMAIL_ADDRESS_TABLE E)
ORDER BY P.FIRSTNAME desc;

output:

Firstname lastname price
------------------------
kim       | sand   | 80
julia     | dan    | 40

My result is not look like as your but it may be help you. I wrote above script as per your above mentioned requirement.


问:
Height not resizing LayerSlider 5
Im having trouble with the latest version of LayerSlider. I have used everything from the full-width responsive demo and read through all the options but when I resize my browser, the height does not update. To make this clearer the image itself scales but the container's height stays the same. In the documentation it says that you must give the container a height.

My code below:

HTML:

```<code><div id="LayerSlider" class="Slider">
    <div class="ls-slide" data-ls="transition2d:1;timeshift:-1000;">
        <img src="/Assets/Images/Layerslider/Banner1.jpg" class="ls-bg" alt="Slide background"/>
    </div>
    <div class="ls-slide" data-ls="transition2d:1;timeshift:-1000;">
        <img src="/Assets/Images/Layerslider/Banner2.jpg" class="ls-bg" alt="Slide background"/>
    </div>
</div>
</code>```

jQuery

```<code>$(document).ready(function () {
    $('#LayerSlider').layerSlider({
        responsive: false,
        layersContainer : 1178,
        responsiveUnder : 1500
    });
});
</code>```

In the documentation is says you must use responsive: false if you want to use responsiveUnder which makes it responsive under a specified width.

Link to LayerSlider http://kreaturamedia.com/layerslider-responsive-jquery-slider-plugin/

答:
I used css break point to fix this height issue of the layer Slider. Use the layer slider's css editor. </p>

```<code>@media only screen and (min-width:800px) and (max-width:960px) {
.ls-wp-fullwidth-container {
    height: 65vh!important;
}
@media only screen and (min-width:768px) and (max-width:800px) {
    .ls-wp-fullwidth-container {
        height: 50vh!important;
    }
}
@media only screen and (min-width:600px) and (max-width:768px) {
    .ls-wp-fullwidth-container {
        height: 42vh!important;
    }
}
@media only screen and (min-width:480px)and (max-width:600px) {
    .ls-wp-fullwidth-container {
        height: 33vh!important;
    }
   }
</code>```

<p>-icodefy</p>

Title: Height not resizing LayerSlider 5

Body:
Im having trouble with the latest version of LayerSlider. I have used everything from the full-width responsive demo and read through all the options but when I resize my browser, the height does not update. To make this clearer the image itself scales but the container's height stays the same. In the documentation it says that you must give the container a height.

My code below:

HTML:

jQuery

$(document).ready(function () {
    $('#LayerSlider').layerSlider({
        responsive: false,
        layersContainer : 1178,
        responsiveUnder : 1500
    });
});

In the documentation is says you must use responsive: false if you want to use responsiveUnder which makes it responsive under a specified width.

Link to LayerSlider http://kreaturamedia.com/layerslider-responsive-jquery-slider-plugin/

Body:
I used css break point to fix this height issue of the layer Slider. Use the layer slider's css editor.

@media only screen and (min-width:800px) and (max-width:960px) {
.ls-wp-fullwidth-container {
    height: 65vh!important;
}
@media only screen and (min-width:768px) and (max-width:800px) {
    .ls-wp-fullwidth-container {
        height: 50vh!important;
    }
}
@media only screen and (min-width:600px) and (max-width:768px) {
    .ls-wp-fullwidth-container {
        height: 42vh!important;
    }
}
@media only screen and (min-width:480px)and (max-width:600px) {
    .ls-wp-fullwidth-container {
        height: 33vh!important;
    }
   }

-icodefy


问:
Static sources not supported for video yet
I was trying to play a song using Pyglet, but encountered this error

NotImplementedError: Static sources not supported for video yet.

But the file is mp3 format. I have AVbin11-win64.exe installed (avbin64.dll) which is copied in 'C:\Windows\SysWOW64' Folder, downloaded from https://github.com/AVbin/AVbin/downloads.

Here is the script I am using :

```<code>import pyglet
player = pyglet.media.Player()
source = pyglet.media.load(r'C:\Users\MANDAV\Desktop\New folder (2)\Diamond-
Platnumz-All-The-Way-Up-v2.mp3', streaming=False)
player.play()
player.app.run()
</code>```

答:
Your code contains a few issues.

The first being player.app.run(), player doesn't have .app - you're probably looking for pyglet.app.run().

The second thing is that you try to call player.play(), but you never did player.queue(source). So either do source.play() or player.queue(source) (both does exactly the same thing, playing the source directly will create a player in the background.)

The third thing being streaming=False. avbin (10 at least) have issues decoding mp3 as a static source. Not quite sure why, but the project has been dead for soon to be a century (yes, in just a few short years, this code has been dead for 10 years).

Here's a minimal working example:

```<code>import pyglet
source = pyglet.media.load('epic.mp3')
source.play()
pyglet.app.run()
</code>```

Altho, you probably want some more functionality while playing your stuff. So here's a bigger example of how you could put together a start for a music playing application:

```<code>import pyglet
from pyglet.gl import *
from collections import OrderedDict

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = OrderedDict() # This just keeps track of which keys we're holding down. In case we want to do repeated input.
        self.alive = 1 # And as long as this is True, we'll keep on rendering.

        ## Add more songs to the list, either here, via input() from the console or on_key_ress() function below.
        self.songs = ['A.wav', 'B.wav', 'C.wav']
        self.song_pool = None

        self.player = pyglet.media.Player()
        for song in self.songs:
            media = pyglet.media.load(song)
            if self.song_pool is None:
                ## == if the Song Pool hasn't been setup,
                ##    we'll set one up. Because we need to know the audio_format()
                ##    we can't really set it up in advance (consists more information than just 'mp3' or 'wav')
                self.song_pool = pyglet.media.SourceGroup(media.audio_format, None)
            ## == Queue the media into the song pool.
            self.song_pool.queue(pyglet.media.load(song))

        ## == And then, queue the song_pool into the player.
        ##    We do this because SourceGroup (song_pool) as a function called
        ##    .has_next() which we'll require later on.
        self.player.queue(self.song_pool)
        ## == Normally, you would do self.player.eos_action = self.function()
        ##    But for whatever fucky windows reasons, this doesn't work for me in testing.
        ##    So below is a manual workaround that works about as good.

        self.current_track = pyglet.text.Label('', x=width/2, y=height/2+50, anchor_x='center', anchor_y='center')
        self.current_time = pyglet.text.Label('', x=width/2, y=height/2-50, anchor_x='center', anchor_y='center')

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        elif symbol == key.SPACE:
            if self.player.playing:
                self.player.pause()
            else:
                self.player.play()

        elif symbol == key.RIGHT:
            self.player.seek(self.player.time + 15)

        ## == You could check the user input here,
        ##    and add more songs via the keyboard here.
        ##    For as long as self.song_pool has tracks,
        ##    this player will continue to play.

        self.keys[symbol] = True

    def end_of_tracks(self, *args, **kwargs):
        self.alive=0

    def render(self):
        ## Clear the screen
        self.clear()

        ## == You could show some video, image or text here while the music plays.
        ##    I'll drop in a example where the current Track Name and time are playing.

        ## == Grab the media_info (if any, otherwise this returns None)
        media_info = self.player.source.info
        if not media_info:
            ## == if there were no meta-data, we'll show the file-name instead:
            media_info = self.player.source._file.name
        else:
            ## == But if we got meta data, we'll show "Artist - Track Title"
            media_info = media_info.author + ' - ' + media_info.title

        self.current_track.text = media_info
        self.current_track.draw()

        ## == This part exists of two things,
        ## 1. Grab the Current Time Stamp and the Song Duration.
        ##    Check if the song_pool() is at it's end, and if the track Cur>=Max -> We'll quit.
        ## *  (This is the manual workaround)
        cur_t, end_t = int(self.player.time), int(self.player.source._get_duration())
        if self.song_pool.has_next() is False and cur_t >= end_t:
            self.alive=False

        ## 2. Show the current time and maximum time in seconds to the user.
        self.current_time.text = str(cur_t)+'/'+str(end_t) + 'seconds'
        self.current_time.draw()

        ## This "renders" the graphics:
        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

x = main()
x.run()
</code>```

If you're just interested in playing sounds.

I wholeheartedly recommend Pydub.

Not only does it use libav which is more of a defacto standard when encoding and decoding, but it's also rich in features. Such as converting .mp3 to .wav and you can control audio gain, play two sources at the same time etc.

Body:
I was trying to play a song using Pyglet, but encountered this error

NotImplementedError: Static sources not supported for video yet.

But the file is mp3 format. I have AVbin11-win64.exe installed (avbin64.dll) which is copied in 'C:\Windows\SysWOW64' Folder, downloaded from https://github.com/AVbin/AVbin/downloads.

Here is the script I am using :

import pyglet
player = pyglet.media.Player()
source = pyglet.media.load(r'C:\Users\MANDAV\Desktop\New folder (2)\Diamond-
Platnumz-All-The-Way-Up-v2.mp3', streaming=False)
player.play()
player.app.run()

Body:
Your code contains a few issues.

The first being player.app.run(), player doesn't have .app - you're probably looking for pyglet.app.run().

The second thing is that you try to call player.play(), but you never did player.queue(source). So either do source.play() or player.queue(source) (both does exactly the same thing, playing the source directly will create a player in the background.)

The third thing being streaming=False. avbin (10 at least) have issues decoding mp3 as a static source. Not quite sure why, but the project has been dead for soon to be a century (yes, in just a few short years, this code has been dead for 10 years).

Here's a minimal working example:

import pyglet
source = pyglet.media.load('epic.mp3')
source.play()
pyglet.app.run()

Altho, you probably want some more functionality while playing your stuff. So here's a bigger example of how you could put together a start for a music playing application:

import pyglet
from pyglet.gl import *
from collections import OrderedDict

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = OrderedDict() # This just keeps track of which keys we're holding down. In case we want to do repeated input.
        self.alive = 1 # And as long as this is True, we'll keep on rendering.

        ## Add more songs to the list, either here, via input() from the console or on_key_ress() function below.
        self.songs = ['A.wav', 'B.wav', 'C.wav']
        self.song_pool = None

        self.player = pyglet.media.Player()
        for song in self.songs:
            media = pyglet.media.load(song)
            if self.song_pool is None:
                ## == if the Song Pool hasn't been setup,
                ##    we'll set one up. Because we need to know the audio_format()
                ##    we can't really set it up in advance (consists more information than just 'mp3' or 'wav')
                self.song_pool = pyglet.media.SourceGroup(media.audio_format, None)
            ## == Queue the media into the song pool.
            self.song_pool.queue(pyglet.media.load(song))

        ## == And then, queue the song_pool into the player.
        ##    We do this because SourceGroup (song_pool) as a function called
        ##    .has_next() which we'll require later on.
        self.player.queue(self.song_pool)
        ## == Normally, you would do self.player.eos_action = self.function()
        ##    But for whatever fucky windows reasons, this doesn't work for me in testing.
        ##    So below is a manual workaround that works about as good.

        self.current_track = pyglet.text.Label('', x=width/2, y=height/2+50, anchor_x='center', anchor_y='center')
        self.current_time = pyglet.text.Label('', x=width/2, y=height/2-50, anchor_x='center', anchor_y='center')

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        elif symbol == key.SPACE:
            if self.player.playing:
                self.player.pause()
            else:
                self.player.play()

        elif symbol == key.RIGHT:
            self.player.seek(self.player.time + 15)

        ## == You could check the user input here,
        ##    and add more songs via the keyboard here.
        ##    For as long as self.song_pool has tracks,
        ##    this player will continue to play.

        self.keys[symbol] = True

    def end_of_tracks(self, *args, **kwargs):
        self.alive=0

    def render(self):
        ## Clear the screen
        self.clear()

        ## == You could show some video, image or text here while the music plays.
        ##    I'll drop in a example where the current Track Name and time are playing.

        ## == Grab the media_info (if any, otherwise this returns None)
        media_info = self.player.source.info
        if not media_info:
            ## == if there were no meta-data, we'll show the file-name instead:
            media_info = self.player.source._file.name
        else:
            ## == But if we got meta data, we'll show "Artist - Track Title"
            media_info = media_info.author + ' - ' + media_info.title

        self.current_track.text = media_info
        self.current_track.draw()

        ## == This part exists of two things,
        ## 1. Grab the Current Time Stamp and the Song Duration.
        ##    Check if the song_pool() is at it's end, and if the track Cur>=Max -> We'll quit.
        ## *  (This is the manual workaround)
        cur_t, end_t = int(self.player.time), int(self.player.source._get_duration())
        if self.song_pool.has_next() is False and cur_t >= end_t:
            self.alive=False

        ## 2. Show the current time and maximum time in seconds to the user.
        self.current_time.text = str(cur_t)+'/'+str(end_t) + 'seconds'
        self.current_time.draw()

        ## This "renders" the graphics:
        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

x = main()
x.run()

If you're just interested in playing sounds.

I wholeheartedly recommend Pydub.

Not only does it use libav which is more of a defacto standard when encoding and decoding, but it's also rich in features. Such as converting .mp3 to .wav and you can control audio gain, play two sources at the same time etc.


问:
Coldfusion - Structure and dynamic variables names
I have problem for getting and working on a structure containing dynamic variable names. I have a structure cfStruct which contains another structure EMAILS. In the last structure the maximum of items is 4

Here my structure for EMAILS

```<code>EMAILS":{"1":"mail1@test.com","2":"mail2@test.net","3":"mail3@test.fr"}
</code>```

I try to create one variable for each item of this structure if it exists by doing that. Nevertheless it doesn't work:

```<code>    <cfif IsDefined("cfStruct.EMAILS")>
        <cfloop from="1" to="5" index="i">
            <cfif StructKeyExists( cfStruct.EMAILS, '#i#' ) >
                <cfset setVariable( "EMAIL_#i#", "#cfStruct.EMAILS.i#" >
            <cfelse>
                <cfset setVariable( "EMAIL_#i#", '') >
            </cfif>
        </cfloop>
    <cfelse>
</code>```

Could you please help me to solve the problem?

Regards,

答:
Strictly speaking, you should use cfStruct.EMAILS["#i#"] instead of "#cfStruct.EMAILS[i]#". That is, </p>

```<code><cfloop from="1" to="5" index="i">
    <cfif StructKeyExists( cfStruct.EMAILS, "#i#" ) >
        <cfset setVariable( "EMAIL_#i#", cfStruct.EMAILS["#i#"]) >
    <cfelse>
        <cfset setVariable( "EMAIL_#i#", '') >
    </cfif>
</cfloop>
</code>```

Body:
I have problem for getting and working on a structure containing dynamic variable names. I have a structure cfStruct which contains another structure EMAILS. In the last structure the maximum of items is 4

Here my structure for EMAILS

EMAILS":{"1":"mail1@test.com","2":"mail2@test.net","3":"mail3@test.fr"}

I try to create one variable for each item of this structure if it exists by doing that. Nevertheless it doesn't work:

    <cfif IsDefined("cfStruct.EMAILS")>
        <cfloop from="1" to="5" index="i">
            <cfif StructKeyExists( cfStruct.EMAILS, '#i#' ) >
                <cfset setVariable( "EMAIL_#i#", "#cfStruct.EMAILS.i#" >
            <cfelse>
                <cfset setVariable( "EMAIL_#i#", '') >
            </cfif>
        </cfloop>
    <cfelse>

Could you please help me to solve the problem?

Regards,

Body:
Strictly speaking, you should use cfStruct.EMAILS["#i#"] instead of "#cfStruct.EMAILS[i]#". That is,

<cfloop from="1" to="5" index="i">
    <cfif StructKeyExists( cfStruct.EMAILS, "#i#" ) >
        <cfset setVariable( "EMAIL_#i#", cfStruct.EMAILS["#i#"]) >
    <cfelse>
        <cfset setVariable( "EMAIL_#i#", '') >
    </cfif>
</cfloop>


问:
Is it fine to provide message exchange in WAN by rabbitmq?
I want to build a cluster in Internet. It likely deploy openstack neutron with its agents not in same idc, but can be in anywhere and connect by WAN. Those agents also need to connect server, and server also need to push some data to agent. I'm doubt rabbitmq can be used in WAN. Since we should consider the cluster security and network failure issues. I also investigate the grpc. But seems grpc do not support amqp, so it is not convenient to make a remote procedure call to some same role agents.

Did someone use rabbitmq in WAN? Or should I chose another middle to provide message exchange service? Thanks.

答:
```<code>public function sendOrder()
{

    foreach ($$_REQUEST->div['producte'] as $producte) {
    $avg+= $producte['qty'] ;
        if($producte['qty']>0)
        {
    $ord_item=new order_items(
    ['id'=>$producte->id,
     'qty'=>$producte['qty']
    ]
    );
    $ord_item->save();
        }
    }
    $order=new orders(['qty'=>$avg]);
    $order->save();
    return $this->render('catalog',['data'=>$order]);

}
</code>```


问:
Why can't I access vars loaded via file in Ansible?
Why can't I access these Ansible file variables from within the Ansible task?

I've tried vars_files as well wit combinations of calling global.varname and global[varname]

```<code>- hosts: localhost
  gather_facts: True
  remote_user: root
  - include_vars: site_vars.yml
  tasks:
    - digital_ocean:
        state: present
        command: droplet
        unique_name: yes
        name: do_16_04_common
        api_token: "{{HOST_PROVIDER}}"
</code>```

global_vars.yml:

```<code>global:
  WORKER_TAG_PREFIX:"dev"
  HOST_PROVIDER:"heroku-prod"
</code>```

Error:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'WORKER_TAG_PREFIX'"}

答:
Firstly, your vars file is broken - it requires spaces between : and the values (and you don't need quotes for strings in this example):

```<code>global:
  WORKER_TAG_PREFIX: dev
  HOST_PROVIDER: heroku-prod
</code>```

The above is the reason for the included error, but then the code has also syntax error which should be thrown first:

The correct syntax to include vars files at the play level is to define a vars_files key containing a list of files:

```<code>- hosts: localhost
  gather_facts: True
  remote_user: root
  vars_files:
    - site_vars.yml
  tasks:
    # ...
</code>```

On the other hand, include_vars is a module (action) name for a task.

If you wanted to use it, you should add it to the tasks list:

```<code>- hosts: localhost
  gather_facts: True
  remote_user: root
  tasks:
    - include_vars: site_vars.yml
</code>```

Body:
Why can't I access these Ansible file variables from within the Ansible task?

I've tried vars_files as well wit combinations of calling global.varname and global[varname]

- hosts: localhost
  gather_facts: True
  remote_user: root
  - include_vars: site_vars.yml
  tasks:
    - digital_ocean:
        state: present
        command: droplet
        unique_name: yes
        name: do_16_04_common
        api_token: "{{HOST_PROVIDER}}"

global_vars.yml:

global:
  WORKER_TAG_PREFIX:"dev"
  HOST_PROVIDER:"heroku-prod"

Error:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'WORKER_TAG_PREFIX'"}

Body:
Firstly, your vars file is broken - it requires spaces between : and the values (and you don't need quotes for strings in this example):

global:
  WORKER_TAG_PREFIX: dev
  HOST_PROVIDER: heroku-prod

The above is the reason for the included error, but then the code has also syntax error which should be thrown first:

The correct syntax to include vars files at the play level is to define a vars_files key containing a list of files:

- hosts: localhost
  gather_facts: True
  remote_user: root
  vars_files:
    - site_vars.yml
  tasks:
    # ...

On the other hand, include_vars is a module (action) name for a task.

If you wanted to use it, you should add it to the tasks list:

- hosts: localhost
  gather_facts: True
  remote_user: root
  tasks:
    - include_vars: site_vars.yml


问:
I can't get the order list from square up platform server
```<code>var request = require("request");

var options = { method: 'GET',
  url: 'https://connect.squareup.com/v2/locations/{location_id}/transactions',
  headers:
   { 'postman-token': 'token',
     'cache-control': 'no-cache',
     authorization: 'Bearer square_token' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
</code>```

The following results are obtains;

```<code>"transactions": [<br>
        {
            "id": "wDWQ6dH7q4IneSDTpEx3zI2eV",<br>
            "location_id": "3XT6YVHAYDPFS",<br>
            "created_at": "2017-07-06T13:40:15Z<br>",
            "tenders": [<br>
                {<br>
                    "id": "IZPusLhhGnacnOHFysNpKQB",<br>
                    "location_id": "3XT6YVHAYDPFS",<br>
                    "transaction_id": "wDWQ6dH7q4IneSDTpEx3zI2eV",<br>
                    "created_at": "2017-07-06T13:40:13Z",<br>
                    "amount_money": {<br>
                        "amount": 730,<br>
                        "currency": "USD"<br>
                    },<br>
                    "processing_fee_money": {<br>
                        "amount": 0,<br>
                        "currency": "USD"<br>
                    },<br>
                    "type": "CASH",<br>
                    "cash_details": {<br>
                        "buyer_tendered_money": {<br>
                            "amount": 730,<br>
                            "currency": "USD"<br>
                        },<br>
                        "change_back_money": {<br>
                            "amount": 0,<br>
                            "currency": "USD"<br>
                        }<br>
                    }<br>
                }<br>
            ],<br>
            "product": "REGISTER",<br>
            "client_id": "60FA84DB-865C-4DC2-B824-56A4F87B7264"<br>
        },<br>
</code>```

I can't get order food & coffee items and modifiers, only amount money.

答: To get the itemization information use the v1 endpoints. https://docs.connect.squareup.com/api/connect/v1/#navsection-transactions</p>

Body:
var request = require("request");

var options = { method: 'GET',
  url: 'https://connect.squareup.com/v2/locations/{location_id}/transactions',
  headers:
   { 'postman-token': 'token',
     'cache-control': 'no-cache',
     authorization: 'Bearer square_token' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

The following results are obtains;

"transactions": [

        {
            "id": "wDWQ6dH7q4IneSDTpEx3zI2eV",

            "location_id": "3XT6YVHAYDPFS",

            "created_at": "2017-07-06T13:40:15Z
",
            "tenders": [

                {

                    "id": "IZPusLhhGnacnOHFysNpKQB",

                    "location_id": "3XT6YVHAYDPFS",

                    "transaction_id": "wDWQ6dH7q4IneSDTpEx3zI2eV",

                    "created_at": "2017-07-06T13:40:13Z",

                    "amount_money": {

                        "amount": 730,

                        "currency": "USD"

                    },

                    "processing_fee_money": {

                        "amount": 0,

                        "currency": "USD"

                    },

                    "type": "CASH",

                    "cash_details": {

                        "buyer_tendered_money": {

                            "amount": 730,

                            "currency": "USD"

                        },

                        "change_back_money": {

                            "amount": 0,

                            "currency": "USD"

                        }

                    }

                }

            ],

            "product": "REGISTER",

            "client_id": "60FA84DB-865C-4DC2-B824-56A4F87B7264"

        },

I can't get order food & coffee items and modifiers, only amount money.


问:
HQL query for entity with max value
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

```<code>@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}
</code>```

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

```<code>Select f.name, max(f.version) from FeatureList f group by f.name
</code>```

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

答:
The straightforward version of this query looks like this (assuming that (name, version) pairs are unique):

```<code>select f from FeatureList f
where f.version =
     (select max(ff.version) from FeatureList ff where ff.name = f.name)
</code>```

ContentLicense: CC BY-SA 2.5

Title: HQL query for entity with max value

Body:
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

Select f.name, max(f.version) from FeatureList f group by f.name

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

Body:
The straightforward version of this query looks like this (assuming that (name, version) pairs are unique):

select f from FeatureList f
where f.version =
     (select max(ff.version) from FeatureList ff where ff.name = f.name)


问:
The relationship between code behind class and aspx generated class
I was reading a book says that "a Web Form’s code-behind class was the base class for the class generated by the runtime from the .aspx file itself, as the picture below shows:

I don't know how the generated class looks like, as I only deal with aspx.cs which is the code-behind class.

So let say I have a .aspx file that have some controls like textboxes, do the generated class generated by .aspx file contains Textbox class?  and how this generated class inherit the code-behind class, I'm really confused, can anybody post an example code of generated class generated by .aspx file?

答:
The generated classes are stored here:

```<code>%windir%\Microsoft.NET\Framework\version\Temporary ASP.NET Files\root
</code>```

Replace the version in the above path with the version of your framework. There will be many files in there but you can delete them all to start afresh. Then restart the web application in question and you will see a brand new folder (with a numeric name) will be created in the root folder. Inside the folder you will see many files but if you sort them by type, one of the CS Files will be the one generated for the .aspx page. The name will not be a friendly name so you will have to keep opening them and search for nameofpage_aspx. For example, if the aspx page is named About, search for about_aspx. If you do not find it, search for it in another file and one of them will be for about_aspx.

You may also look for the first line in the file which starts with #pragma checksum and it will have the name of the .aspx page. Not all files will have this line.

In those CS File types are the generated code which will be used by asp.net and you can examine its contents in more details if you want. Please do not ask me to explain the details of what is in those files but I am sure if you search online, you will find info on that.

Body:
The generated classes are stored here:

%windir%\Microsoft.NET\Framework\version\Temporary ASP.NET Files\root

Replace the version in the above path with the version of your framework. There will be many files in there but you can delete them all to start afresh. Then restart the web application in question and you will see a brand new folder (with a numeric name) will be created in the root folder. Inside the folder you will see many files but if you sort them by type, one of the CS Files will be the one generated for the .aspx page. The name will not be a friendly name so you will have to keep opening them and search for nameofpage_aspx. For example, if the aspx page is named About, search for about_aspx. If you do not find it, search for it in another file and one of them will be for about_aspx.

You may also look for the first line in the file which starts with #pragma checksum and it will have the name of the .aspx page. Not all files will have this line.

In those CS File types are the generated code which will be used by asp.net and you can examine its contents in more details if you want. Please do not ask me to explain the details of what is in those files but I am sure if you search online, you will find info on that.


问:
Concept of R.java class
I just have few questions to solidify my understanding to R.java class.

(1): Does it generated at run-time or compile-time?
To test it, I created a new 'Button' with a text, the 'id' of the 'Button' is 'actMain_btnTest' and the name attribute of its text in 'strings.xml' is
'btn_test'. Then in the java file I referred to the 'Button' using 'findViewById' and it was accessible. Therefore, I would say that the 'R.java'
can be generated at compile time. But, then I navigated to 'R.java' to make sure that the 'actMain_btnTest' and 'btn_test' was added to 'R.java', but surprisingly, they were not existing!!
Now, anew question popped-up, how the 'id' was accessile while it was not yet added to 'R.java'?!

(2): What is the relation between 'R class' and 'Android Resource Manager'? how they work together?is it only for localization?!

(3): Since 'R class' contains sub-classes which contain 'ids' of the App's resources, and each 'id' is assigned to a value. For example,

```<code>public static final int request_identifiers=0x7f060019;
</code>```

What does '0x7f060019' refer to? is it an address in the memory??!!

答:
It is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.

Title: Concept of R.java class

Body:
I just have few questions to solidify my understanding to R.java class.

(1): Does it generated at run-time or compile-time?
To test it, I created a new 'Button' with a text, the 'id' of the 'Button' is 'actMain_btnTest' and the name attribute of its text in 'strings.xml' is
'btn_test'. Then in the java file I referred to the 'Button' using 'findViewById' and it was accessible. Therefore, I would say that the 'R.java'
can be generated at compile time. But, then I navigated to 'R.java' to make sure that the 'actMain_btnTest' and 'btn_test' was added to 'R.java', but surprisingly, they were not existing!!
Now, anew question popped-up, how the 'id' was accessile while it was not yet added to 'R.java'?!

(2): What is the relation between 'R class' and 'Android Resource Manager'? how they work together?is it only for localization?!

(3): Since 'R class' contains sub-classes which contain 'ids' of the App's resources, and each 'id' is assigned to a value. For example,

public static final int request_identifiers=0x7f060019;

What does '0x7f060019' refer to? is it an address in the memory??!!


问:
How to load CSS and Bootstrap files into server using node.js?
I have a html file called myfile.html that displays 'Hello World'. My css file called myfile.css is used to insert background image. My bootstrap files are used to insert a image in the form of a circle.

The HTML file is as follows:

```<code> <!DOCTYPE html>
 <html>
     <head>
         <title>MY FILE</title>
         <link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
         <link rel="stylesheet" type="text/css" href="public\myfile.css">
     </head>
     <body>
         <h1>Hello World!!</h1>

         <img src="public\pinky.jpg"  class="img-circle">
     </body>
 </html>
</code>```

My CSS file is as follows:

```<code>body {
    background-image: url('fishy.jpg');
}
</code>```

My node.js file called new.js is as follows:

```<code>  const express = require('express')
  const app = express()
  app.use(express.static('public'))

  app.get('/',function (req,res) {
          console.log(__dirname)
          res.sendFile(__dirname+"/myfile.html")
  })

  app.listen(3000, function() {
          console.log('Example app listening on port 3000!')
  })
</code>```

My main folder is called Bootsstrap and it has the following contents:

```<code>     Bootsstrap
          -myfile.html
          -public /*Folder*/

         /*inside public folder*/
          -myfile.css
          -css
          -js
          -fonts
          -fishy.jpg /*background image*/
          -pinky.jpg /*circular image*/
</code>```

I open Command Prompt from Bootsstrap folder and run

```<code>           node new.js
</code>```

I get the message as:

```<code>          'Example app listening on port 3000!'
</code>```

When I open Chrome Browser and type localhost:3000, I get only 'Hello World'.The images are not getting displayed. I get an Error 404.

What can I do in order to run my HTML file in server using node.js by including all my css and bootstrap files?

答:
You must not use the public path in your html. Also, in URLs use always forward slashes. Backslashes are just for Windows directories.

```<code><!DOCTYPE html> <html> <head> <title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</head> <body> <h1>Hello World!!</h1>
<img src="pinky.jpg" class="img-circle"> </body> </html>
</code>```

Body:
I have a html file called myfile.html that displays 'Hello World'. My css file called myfile.css is used to insert background image. My bootstrap files are used to insert a image in the form of a circle.

The HTML file is as follows:

 <!DOCTYPE html>

         <title>MY FILE</title>
         <link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
         <link rel="stylesheet" type="text/css" href="public\myfile.css">

Hello World!!

My CSS file is as follows:

body {
    background-image: url('fishy.jpg');
}

My node.js file called new.js is as follows:

  const express = require('express')
  const app = express()
  app.use(express.static('public'))

  app.get('/',function (req,res) {
          console.log(__dirname)
          res.sendFile(__dirname+"/myfile.html")
  })

  app.listen(3000, function() {
          console.log('Example app listening on port 3000!')
  })

My main folder is called Bootsstrap and it has the following contents:

     Bootsstrap
          -myfile.html
          -public /*Folder*/

         /*inside public folder*/
          -myfile.css
          -css
          -js
          -fonts
          -fishy.jpg /*background image*/
          -pinky.jpg /*circular image*/

I open Command Prompt from Bootsstrap folder and run

           node new.js

I get the message as:

          'Example app listening on port 3000!'

When I open Chrome Browser and type localhost:3000, I get only 'Hello World'.The images are not getting displayed. I get an Error 404.

What can I do in order to run my HTML file in server using node.js by including all my css and bootstrap files?

Body:
You must not use the public path in your html. Also, in URLs use always forward slashes. Backslashes are just for Windows directories.

<!DOCTYPE html> <html> <head> <title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</head> <body> <h1>Hello World!!</h1>
<img src="pinky.jpg" class="img-circle"> </body> </html>


问:
Can we define min-margin and max-margin, max-padding and min-padding in css?
Can we define min-margin and max-margin, max-padding and min-padding in CSS ?

答:
margin and padding don't have min or max prefixes. Sometimes you can try to specify margin and padding in terms of percentage to make it variable with respect to screen size.

Further you can also use min-width, max-width, min-height and max-height for doing the similar things.

Hope it helps.


问:
Android MediaPlayer reset freezes UI
I have a problem with the Android MediaPlayer when changing the dataSource of the player. According the specification of the MediaPlayer (http://developer.android.com/reference/android/media/MediaPlayer.html) I have to reset the player when changing the dataSource. This works fine, but as soon as the channelChanged method is called twice in quick succession the MediaPlayer.reset freezes the UI. I profile the code as seen here:

```<code>public void channelChanged(String streamingUrl)
{
    long m1 = System.currentTimeMillis();
    mMediaPlayer.reset();
    long m2 = System.currentTimeMillis();
    try
    {
        mMediaPlayer.setDataSource(streamingUrl);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    long m3 = System.currentTimeMillis();
    mMediaPlayer.prepareAsync();
    long m4 = System.currentTimeMillis();
    Log.d("MEDIAPLAYER", "reset: " + (m2 - m1));
    Log.d("MEDIAPLAYER", "setDataSource: " + (m3 - m2));
    Log.d("MEDIAPLAYER", "preparing: " + (m4 - m3));
}
</code>```

reset: 3

setDataSource: 1

preparing: 0

reset: 3119

setDataSource: 2

preparing: 1

So apparently the reset is blocked by the asynchronous preparing of the first call (when I wait until the first stream starts and then call channelChanged() again, everything is fine).

Any ideas how to solve the problems? Should I execute the whole method in a separate thread? Basically I want to avoid that, because it seems not to be a good coding style and can possibly cause some further issues, e.g. when the user tries to start the player again, but the player is still in the reset method, which on the other hand seems to wait for the asyncPrepare method. It is not clear how the player would behave...

Is there any other good solution?

答:
The newest phones and Android API works much butter, reset method takes only 5-20 ms when fast switching between songs (next or prev)

So there is no solution for older phones, it just how it works

Title: Android MediaPlayer reset freezes UI

Body:
I have a problem with the Android MediaPlayer when changing the dataSource of the player. According the specification of the MediaPlayer (http://developer.android.com/reference/android/media/MediaPlayer.html) I have to reset the player when changing the dataSource. This works fine, but as soon as the channelChanged method is called twice in quick succession the MediaPlayer.reset freezes the UI. I profile the code as seen here:

public void channelChanged(String streamingUrl)
{
    long m1 = System.currentTimeMillis();
    mMediaPlayer.reset();
    long m2 = System.currentTimeMillis();
    try
    {
        mMediaPlayer.setDataSource(streamingUrl);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    long m3 = System.currentTimeMillis();
    mMediaPlayer.prepareAsync();
    long m4 = System.currentTimeMillis();
    Log.d("MEDIAPLAYER", "reset: " + (m2 - m1));
    Log.d("MEDIAPLAYER", "setDataSource: " + (m3 - m2));
    Log.d("MEDIAPLAYER", "preparing: " + (m4 - m3));
}

reset: 3

setDataSource: 1

preparing: 0

reset: 3119

setDataSource: 2

preparing: 1

So apparently the reset is blocked by the asynchronous preparing of the first call (when I wait until the first stream starts and then call channelChanged() again, everything is fine).

Any ideas how to solve the problems? Should I execute the whole method in a separate thread? Basically I want to avoid that, because it seems not to be a good coding style and can possibly cause some further issues, e.g. when the user tries to start the player again, but the player is still in the reset method, which on the other hand seems to wait for the asyncPrepare method. It is not clear how the player would behave...

Is there any other good solution?


问:
How do I write a function that returns another function?
In Python, I'd like to write a function make_cylinder_volume(r) which returns another function. That returned function should be callable with a parameter h, and return the volume of a cylinder with height h and radius r.

I know how to return values from functions in Python, but how do I return another function?

答:
Using lambdas, also known as anonymous functions, you can abstract out the volume function inside the make_cylinder_volume_func to a single line. In no way different from Óscar López's answer, the solution using lambda is still in a sense 'more functional'.

This is how you can write the accepted answer using a lambda expression:

```<code>import math
def make_cylinder_volume_fun(r):
    return lambda h: math.pi * r * r * h
</code>```

And then call as you'd any other curried function:

```<code>volume_radius_1 = make_cylinder_volume_fun(1)
volume_radius_1(1)
=> 3.141592653589793
</code>```

Body:
Using lambdas, also known as anonymous functions, you can abstract out the volume function inside the make_cylinder_volume_func to a single line. In no way different from Óscar López's answer, the solution using lambda is still in a sense 'more functional'.

This is how you can write the accepted answer using a lambda expression:

import math
def make_cylinder_volume_fun(r):
    return lambda h: math.pi * r * r * h

And then call as you'd any other curried function:

volume_radius_1 = make_cylinder_volume_fun(1)
volume_radius_1(1)
=> 3.141592653589793


问:
Android setting text view color from java code
I have a list and i write a custom adapter for this. And I want to set some text color for this (e.g. Orange color code #F06D2F). I am presenting the code snippet for my getView() method.

```<code>TextView text = new TextView(this.context);
// text.setPadding(25, 5, 0, 0);

text.setBackgroundResource(R.drawable.back_horizontal);

// text.setClickable(false);
// text.setFocusable(false);
text.setEllipsize(TruncateAt.END);
text.setSingleLine(true);

// text.setTextColor(R.color.yellow);

text.setTextColor(R.color.Orange);
text.setGravity(Gravity.CENTER_VERTICAL);

helvetica_normal = Typeface.createFromAsset(context.getAssets(), "fonts/helvetica.ttf");

text.setTypeface(helvetica_normal);
// text.setTextColor(R.color.yellow);

text.setText(objects[position]);

LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
manager.addView(text, layoutParams);
</code>```

The problem is that i can't see the color set to orange. What went wrong?

Note: The context is passed in constructor as well as objects (the string array)

Thanks for your help

答:
try like this , the following worked fine for me</p>

```<code>textview.setTextColor(this.getResources().getColor(R.color.orange));
</code>```

Body:
I have a list and i write a custom adapter for this. And I want to set some text color for this (e.g. Orange color code #F06D2F). I am presenting the code snippet for my getView() method.

TextView text = new TextView(this.context);
// text.setPadding(25, 5, 0, 0);

text.setBackgroundResource(R.drawable.back_horizontal);

// text.setClickable(false);
// text.setFocusable(false);
text.setEllipsize(TruncateAt.END);
text.setSingleLine(true);

// text.setTextColor(R.color.yellow);

text.setTextColor(R.color.Orange);
text.setGravity(Gravity.CENTER_VERTICAL);

helvetica_normal = Typeface.createFromAsset(context.getAssets(), "fonts/helvetica.ttf");

text.setTypeface(helvetica_normal);
// text.setTextColor(R.color.yellow);

text.setText(objects[position]);

LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
manager.addView(text, layoutParams);

The problem is that i can't see the color set to orange. What went wrong?

Note: The context is passed in constructor as well as objects (the string array)

Thanks for your help

Body:
try like this , the following worked fine for me

textview.setTextColor(this.getResources().getColor(R.color.orange));


问:
Query on Tableau Dashboard
I am a new to Tableau and having some issues with it.I am  Using a parameter to filter  month data across Sheets connected to different Data Sources.

I want to Filter  Current Month Data Automatically  when the dashboard starts.

Can anyone guide me on how to do it.

Thanks in Advance.

T

答:
Hope this helps!

Create a calculated field Date_Filter as

lookup(min([Your_Date_Field]),0)

Drag this to 'Filter'; select 'relative date' option and choose last 1
month (because you wanted to show just the current month data by default).

Right click this filter and select "Apply to selected worksheet" and
choose sheets in which you want this filter to be applied on the
dashboard.Viola!

With this solution you can very well see current month's data by default and can go back to as many time periods you want.

Title: Query on Tableau Dashboard


问:
Read text file display to console then append text file
I have a text file of names. I want to read the text file into a stream, display it to the console. When it is done, it will prompt the user to enter their name. It should then add it to the file.

I can get it to do both of these things separately but not together.
Here is my code.

```<code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    {
      while( getline(myfile, line) )
      {
          cout << line << endl;
      }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}
</code>```

If I leave the while loop in there, it writes all the names to the console, but doesn't append the user entered name to the list. If I take out the while loop, I can add a name to the file but then of course I am not getting a list of the names that are already in that file.

My best guess is, I think it might have something to do with the fact that after I loop through the file using getline, The position is at the end of my stream, so when I try to add a name to it, there isn't any room left in the stream?

答:
Just bumped in to this issue and even though there is accepted answer here I think one can use full code that shows how to use canonical C++ file reading loop:</p>

```<code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    {
      while( getline(myfile, line) )
          cout << line << endl;
      if (file_list.eof())
          file_list.clear();  //otherwise we can't do any further I/O
      else if (file_list.bad()) {
          std::cout << "Error occured while reading file";
          return 1;
     }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}
</code>```

Body:
I have a text file of names. I want to read the text file into a stream, display it to the console. When it is done, it will prompt the user to enter their name. It should then add it to the file.

I can get it to do both of these things separately but not together.
Here is my code.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    {
      while( getline(myfile, line) )
      {
          cout << line << endl;
      }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}

If I leave the while loop in there, it writes all the names to the console, but doesn't append the user entered name to the list. If I take out the while loop, I can add a name to the file but then of course I am not getting a list of the names that are already in that file.

My best guess is, I think it might have something to do with the fact that after I loop through the file using getline, The position is at the end of my stream, so when I try to add a name to it, there isn't any room left in the stream?

Body:
Just bumped in to this issue and even though there is accepted answer here I think one can use full code that shows how to use canonical C++ file reading loop:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    {
      while( getline(myfile, line) )
          cout << line << endl;
      if (file_list.eof())
          file_list.clear();  //otherwise we can't do any further I/O
      else if (file_list.bad()) {
          std::cout << "Error occured while reading file";
          return 1;
     }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}


答:
replace

```<code><link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
</code>```

by

```<code><link rel="stylesheet" type="text/css" href="css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</code>```

Title: How to load CSS and Bootstrap files into server using node.js?

Body:
replace

<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">

by

<link rel="stylesheet" type="text/css" href="css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">