问:
Try Catch Errors many script components - JavaScript
I have a page that contains many script components (50+) and I am getting an error when using IE at some random instance (doesn't happen in Chrome or Firefox).

"Out of Memory at line: 1"

I've done some google search too and that reveals issues with IE handling things differently to Chrome and FF. I would like to catch this error and know exactly what the cause of that script error is.

What would be the best way to use a global try-catch block on that many script components? All these script components are on the same page. Looking forward to your suggestions.

答:
One important thing that is missing in your question is if the error happens during the page loading or initialization or if it happens after some time while you browse the page.

If it's during loading or initialization, it's probably caused by the fact that your page contains too many components and uses much more memory than the browser is willing to accept (and IE is simply the first one to give up).

In such case there is no helping but reduce the page size. One possible way is to create only objects (components) that are currently visible (in viewport) and as soon as they get out of the viewport remove them from JS and DOM again (replacing the with empty DIVs sized to the size of the components).

In case the error happens while browsing the page, it may be caused by a memory leak. You may use Process Explorer to watch the memory used by your browser and check if the memory constantly increase - which would indicate the memory leak.

Memory leak in Internet Explorer may happen because it contains 2 separate garbage collectors (aka GC): one for DOM objects and other for JS properties. Other browsers (FF, Webkit, Chromium, etc.; not sure about the Edge) contains only one GC for both DOM and JS.

So when you create circular reference between DOM object and JS object, IE's GC cannot correctly release the memory and creates a memory leak.

```<code>var myGlobalObject;

function SetupLeak()
{
  myGlobalObject = document.getElementById("LeakDiv");
  document.getElementById("LeakDiv").expandoProperty = myGlobalObject;

  //When reference is not required anymore, make sure to release it
  myGlobalObject = null;
}
</code>```

After this code it seems the LeakDiv reference was freed but LeakDiv still reference the myGlobalObject in its expandoProperty which in turn reference the LeakDiv. In other browsers their GC can recognize such situation and release both myGlobalObject and LeakDiv but IE's GCs cannot because they don't know if the referenced object is still in use or not (because it's the other GC's responsibility).

Even less visible is a circular reference created by a closure:

```<code>function SetupLeak()
{
    // The leak happens all at once
    AttachEvents( document.getElementById("LeakedDiv"));
}

function AttachEvents(element)
{
    //attach event to the element
    element.attachEvent("onclick", function {
            element.style.display = 'none';
    });
}
</code>```

In this case the LeakedDiv's onclick property references the handler function whose closure element property reference the LeakedDiv.

To fix these situations you need to properly remove all references between DOM objects and JS variables:

```<code>function FreeLeak()
{
    myGlobalObject = null;
    document.getElementById("LeakDiv").expandoProperty = null;
}
</code>```

And you may want to reduce (or remove completely) closures created on DOM elements:

```<code>function SetupLeak()
{
    // There is no leak anymore
    AttachEvents( "LeakedDiv" );
}

function AttachEvents(element)
{
    //attach event to the element
    document.getElementById(element).attachEvent("onclick", function {
            document.getElementById(element).style.display = 'none';
    });
}
</code>```

In both cases using try-catch is not the option because the Out of memory may happen on random places in code and even if you find one line of code where it's happened the next time it may be elsewhere. The Process Explorer is the best chance to find the situations when the memory increase and and trying to guess what may be causing it.

For example: if the memory increase every time you open and close the menu (if you have one) then you should look how it's being opened and closed and look for the situations described above.

Body:
One important thing that is missing in your question is if the error happens during the page loading or initialization or if it happens after some time while you browse the page.

If it's during loading or initialization, it's probably caused by the fact that your page contains too many components and uses much more memory than the browser is willing to accept (and IE is simply the first one to give up).

In such case there is no helping but reduce the page size. One possible way is to create only objects (components) that are currently visible (in viewport) and as soon as they get out of the viewport remove them from JS and DOM again (replacing the with empty DIVs sized to the size of the components).

In case the error happens while browsing the page, it may be caused by a memory leak. You may use Process Explorer to watch the memory used by your browser and check if the memory constantly increase - which would indicate the memory leak.

Memory leak in Internet Explorer may happen because it contains 2 separate garbage collectors (aka GC): one for DOM objects and other for JS properties. Other browsers (FF, Webkit, Chromium, etc.; not sure about the Edge) contains only one GC for both DOM and JS.

So when you create circular reference between DOM object and JS object, IE's GC cannot correctly release the memory and creates a memory leak.

var myGlobalObject;

function SetupLeak()
{
  myGlobalObject = document.getElementById("LeakDiv");
  document.getElementById("LeakDiv").expandoProperty = myGlobalObject;

  //When reference is not required anymore, make sure to release it
  myGlobalObject = null;
}

After this code it seems the LeakDiv reference was freed but LeakDiv still reference the myGlobalObject in its expandoProperty which in turn reference the LeakDiv. In other browsers their GC can recognize such situation and release both myGlobalObject and LeakDiv but IE's GCs cannot because they don't know if the referenced object is still in use or not (because it's the other GC's responsibility).

Even less visible is a circular reference created by a closure:

function SetupLeak()
{
    // The leak happens all at once
    AttachEvents( document.getElementById("LeakedDiv"));
}

function AttachEvents(element)
{
    //attach event to the element
    element.attachEvent("onclick", function {
            element.style.display = 'none';
    });
}

In this case the LeakedDiv's onclick property references the handler function whose closure element property reference the LeakedDiv.

To fix these situations you need to properly remove all references between DOM objects and JS variables:

function FreeLeak()
{
    myGlobalObject = null;
    document.getElementById("LeakDiv").expandoProperty = null;
}

And you may want to reduce (or remove completely) closures created on DOM elements:

function SetupLeak()
{
    // There is no leak anymore
    AttachEvents( "LeakedDiv" );
}

function AttachEvents(element)
{
    //attach event to the element
    document.getElementById(element).attachEvent("onclick", function {
            document.getElementById(element).style.display = 'none';
    });
}

In both cases using try-catch is not the option because the Out of memory may happen on random places in code and even if you find one line of code where it's happened the next time it may be elsewhere. The Process Explorer is the best chance to find the situations when the memory increase and and trying to guess what may be causing it.

For example: if the memory increase every time you open and close the menu (if you have one) then you should look how it's being opened and closed and look for the situations described above.


来源: stackexchange

问:
How to connect to a localhost Rails site via mobile device locally?
I have a Rails site that I'm developing on localhost Ubuntu and I have a mobile.
My site is running on http://localhost:3000.

I want to access this directly via my mobile browser not going through the internet.

Is there any way to access it via WiFi or some other way?

答:
First find your Ip and note it down by typing ifconfig terminal(you should be connected to wifi or network)

ifconfig

than run the rails server by typing

rails server -b 0.0.0.0 (YOUR IP )

and press Enter
SERVER WILL BE RUNNING ON YOUR_IP:3000
2. Now connect your mobile with the same network and open url

https://YOUR_IP:3000
  CONGRATS YOU ARE RUNNING LOCALHOST ON MOBILE

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How to use Adobe AIR to make an app using native java code in Android?
Let me set the context - I have been tasked with refactoring an app which plays .swf files. Currently, the app is split into two apks - one which lists the files and another which plays the .swf files. The second - player APK is an Adobe AIR app developed using Flash builder, Flex and ActionScript. I've got to find a way to combine the two apps into one for convenience of end user. However, I can't find any way to do that - combining an app developed in ActionScript into java code. The Flash builder simply spits out an .apk file, but no native code.

I came across Native extensions for Adobe AIR, which I thought was the way to make Adobe AIR apps using java code, but turned out to just a way to add functionality to existing Adobe AIR apps using native code.

I found an app which is in some way using Adobe AIR's runtime to play .swf files natively in their app.

So, I'm guessing there is a way to access Adobe AIR runtime via java. However, I can't find any examples or documentation.

Any help would be really appreciated.

Thanks.

答: Not sure, but probably scaleform is waht you are looking for http://help.autodesk.com/view/SCLFRM/ENU/?guid=__scaleform_help_getting_started_installation_usage_sdk_mobiles_sdk_android_html</p>


问:
MYSQL where x in all
I am running a query like this

```<code>SELECT .......  WHERE column_name IN (1,2,3)
</code>```

How can I use the same query and say

```<code>SELECT ........WHERE column_name IN (*)
</code>```

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.

答:
If you are trying to filter your return table base on values in another table:

select column_1, column_2
from table_1
where column_1 IN (select column_with_value from tabl_2)

ContentLicense: CC BY-SA 2.5

Title: MYSQL where x in all

Body:
I am running a query like this

SELECT .......  WHERE column_name IN (1,2,3)

How can I use the same query and say

SELECT ........WHERE column_name IN (*)

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.


问:
Barcode with Text Under using ItextSharp
I am using iTextSharp in my application to generate a barcode. Though everything is working as I wanted, I need to display the value of the barcode under the barcode like the one showin in the attached image.

Below is the C# code I use:

```<code>Barcode39 barcodeImg = new Barcode39();
barcodeImg.Code = barcodeValue.ToString();
barcodeImg.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White).Save(stream, ImageFormat.Png);
</code>```

答:
```<code>iTextSharp.text.pdf.Barcode128 bc = new Barcode128();
bc.TextAlignment = Element.ALIGN_CENTER;
bc.Code = "anything";
bc.StartStopText = false;
bc.CodeType = iTextSharp.text.pdf.Barcode128.CODE128;
bc.Extended = true;
//bc.Font = null;

iTextSharp.text.Image PatImage1 = bc.CreateImageWithBarcode(cb, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.BaseColor.BLACK);
PatImage1.ScaleToFit(160, 20);

PdfPTable p_detail1 = new PdfPTable(1);
p_detail1.WidthPercentage = 100;

PdfPCell barcideimage = new PdfPCell(PatImage1);
//barcideimage.Colspan = 2;
barcideimage.HorizontalAlignment = 2;
barcideimage.Border = 0;
p_detail1.AddCell(barcideimage);

l1.Add(p_detail1);
</code>```

Body:
I am using iTextSharp in my application to generate a barcode. Though everything is working as I wanted, I need to display the value of the barcode under the barcode like the one showin in the attached image.

Below is the C# code I use:

Barcode39 barcodeImg = new Barcode39();
barcodeImg.Code = barcodeValue.ToString();
barcodeImg.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White).Save(stream, ImageFormat.Png);


问:
initialized imageview in onCreate but still null
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

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

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}
</code>```

The follwoing is the_other_layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>
</code>```

EDIT:

Please check the answer below if you have the similar problem

答:
The reason is myimage is not part of activity_main.xml
so you need to move it after setContentView(....)

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

private Button mybtn;
private ImageView myimage;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}

public void init(){

    mybtn = (Button) findViewById(R.id.btn);
    mybtn.setOnClickListener(new MyListener());
}

public class MyListener implements View.OnClickListener {

    @Override
    public void onClick(View v){
        switch (v.getId()){

            case R.id.btn:
                setContentView(R.layout.the_other_layout);
                myimage = (ImageView) findViewById(R.id.imgview);
                initMap();
        }
    }
}

public void initMap(){

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap bmp = null;
    ......
}
</code>```

}

Body:
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

public class MainActivity extends AppCompatActivity {

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}

The follwoing is the_other_layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>

EDIT:

Please check the answer below if you have the similar problem

Body:
The reason is myimage is not part of activity_main.xml
so you need to move it after setContentView(....)

public class MainActivity extends AppCompatActivity {

private Button mybtn;
private ImageView myimage;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}

public void init(){

    mybtn = (Button) findViewById(R.id.btn);
    mybtn.setOnClickListener(new MyListener());
}

public class MyListener implements View.OnClickListener {

    @Override
    public void onClick(View v){
        switch (v.getId()){

            case R.id.btn:
                setContentView(R.layout.the_other_layout);
                myimage = (ImageView) findViewById(R.id.imgview);
                initMap();
        }
    }
}

public void initMap(){

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap bmp = null;
    ......
}

}


问:
Error 500 on wordpress update and plugin pages
I can't understand how to save an issue on a hosted worpdress installation.
My current wordpress version is 4.7 installed on linux hosting with mysql db.
Every time I access either wordpress update page or plugin update page I get a 500 error.

With some debugging I've narrowed down the issue to the file admin.php and precisely line 329:

```<code>do_action( "load-{$pagenow}" );
</code>```

I really can't figure out what the problem is!

答:
In your wp-config.php if you enable debugging (just find WP_DEBUG and set it to true)

```<code>define('WP_DEBUG', true);
</code>```

Then you should be able to see the error. If not, there would be error logs on your cpanel where you can see the errors. Also look for files named 'error_log' inside your WordPress installation.

Body:
I can't understand how to save an issue on a hosted worpdress installation.
My current wordpress version is 4.7 installed on linux hosting with mysql db.
Every time I access either wordpress update page or plugin update page I get a 500 error.

With some debugging I've narrowed down the issue to the file admin.php and precisely line 329:

do_action( "load-{$pagenow}" );

I really can't figure out what the problem is!

Body:
In your wp-config.php if you enable debugging (just find WP_DEBUG and set it to true)

define('WP_DEBUG', true);

Then you should be able to see the error. If not, there would be error logs on your cpanel where you can see the errors. Also look for files named 'error_log' inside your WordPress installation.


问:
Django background image disappear
I want to add the background image to my website.

settings.py:

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
STATIC_ROOT = ''
</code>```

path about the file:

```<code>project/app
       /static/css/base.css
              /images/img.jpg
</code>```

I tried the two ways,respectively int the html and css.

add in html:

html:

```<code>{% load static %}
<section style:"background-image: url({% static "images/img.jpg" %})"></section>
</code>```

add in css:

html:

```<code><link href="{{ STATIC_URL }}css/base.css" rel="stylesheet" type="text/css" />

<section id="intro-header"></section>
</code>```

css:

```<code>section#intro-header{
background-image: url({% static "images/img.jpg" %});
background-size: cover;
}
</code>```

Both of them don't work.

Which part I missed?

update

here is the system message:

```<code>"GET /images/img.jpg HTTP/1.1" 404 2387
</code>```

update

When I　put

```<code>    <style>
    section#intro-header{
           background-image: url("/static/images/winter.jpg");
           background-size: cover;
    }
    </style>
</code>```

in the html file and it works

But the css problem still exisits.

update

Thanks everyone

In add in css

turn into  <link href="/static/css/base.css" rel="stylesheet" type="text/css" />

Then it works,although {{ STATIC_URL }} equals with '/static/'

or the thing I missed?

答:
Have you setup your URL's to include static files in development? </p>

```<code>urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

Title: Django background image disappear

Body:
I want to add the background image to my website.

settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
STATIC_ROOT = ''

path about the file:

project/app
       /static/css/base.css
              /images/img.jpg

I tried the two ways,respectively int the html and css.

add in html:

html:

{% load static %}

add in css:

html:

<link href="{{ STATIC_URL }}css/base.css" rel="stylesheet" type="text/css" />

css:

section#intro-header{
background-image: url({% static "images/img.jpg" %});
background-size: cover;
}

Both of them don't work.

Which part I missed?

update

here is the system message:

"GET /images/img.jpg HTTP/1.1" 404 2387

update

When I　put

in the html file and it works

But the css problem still exisits.

update

Thanks everyone

In add in css

turn into  <link href="/static/css/base.css" rel="stylesheet" type="text/css" />

Then it works,although {{ STATIC_URL }} equals with '/static/'

or the thing I missed?

Body:
Have you setup your URL's to include static files in development?

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


问:
Array AND() ? Logical ANDing of all elements
I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

答:
Why dont you just use

in_array — Checks if a value exists in an array

Example:

```<code>// creates an array with 10 booleans having the value true.
$array = array_fill(0, 10, TRUE);

// checking if it contains a boolean false
var_dump(in_array(FALSE, $array, TRUE)); // FALSE

// adding a boolean with the value false to the array
$array[] = FALSE;

// checking if it contains a boolean false now
var_dump(in_array(FALSE, $array, TRUE)); // TRUE
</code>```

Body:
Why dont you just use

in_array — Checks if a value exists in an array

Example:

// creates an array with 10 booleans having the value true.
$array = array_fill(0, 10, TRUE);

// checking if it contains a boolean false
var_dump(in_array(FALSE, $array, TRUE)); // FALSE

// adding a boolean with the value false to the array
$array[] = FALSE;

// checking if it contains a boolean false now
var_dump(in_array(FALSE, $array, TRUE)); // TRUE


问:
LIBSVM SVM in octave - how to use myself (without "svmpredict" ) with the parameter that return from "svmtrain"
Hi i have a previous background in ANN (Artificial Neural Network), and i did it with octave. i succeeded to  converted the network from octave to c++.

the way i did it is to look on the parameter that return from network (wight matrix, and bias matrix) and copy it to c++ parameter and doing the correct calculation.

Now i start to work with svm in octave, with LIBSVM i succeeded to train

here the code to train:

```<code>model = svmtrain(vOutput, vInput,'-g 1 -c 100 ' );
</code>```

and as well to predict the result for validation  group (new group)
here the code for  predict:

```<code>[predicted_label, accuracy, dec_values] = svmpredict(targetHit', inputHit, model);
</code>```

it's work well.. but i need to do it with c++ so i want to understand how to predict the result myself without using  svmpredict build function.

The parameters i got after train is:

```<code>fieldnames(model)
ans =
{
  [1,1] = Parameters
  [2,1] = nr_class
  [3,1] = totalSV
  [4,1] = rho
  [5,1] = Label
  [6,1] = sv_indices
  [7,1] = ProbA
  [8,1] = ProbB
  [9,1] = nSV
  [10,1] = sv_coef
  [11,1] = SVs
}
</code>```

but i don't know how to use with this parameters.
If anyone can help me and explain me how to use with the parameters by hand without using svmpredict function.

O.k i find this code :

```<code>w = (model.sv_coef' * full(model.SVs));
bias = -model.rho;
predictions = sign(inputMiss * w' + bias);
</code>```

But it doesn't compatible to result from svmpredict..

答:
This code should help you:

```<code>w = (model.sv_coef' * full(model.SVs));
bias = -model.rho;
predictions = sign(inputMiss * w' + bias);
</code>```

But it doesn't compatible to result from svmpredict -> It should Fit(Check Again.

Body:
Hi i have a previous background in ANN (Artificial Neural Network), and i did it with octave. i succeeded to  converted the network from octave to c++.

the way i did it is to look on the parameter that return from network (wight matrix, and bias matrix) and copy it to c++ parameter and doing the correct calculation.

Now i start to work with svm in octave, with LIBSVM i succeeded to train

here the code to train:

model = svmtrain(vOutput, vInput,'-g 1 -c 100 ' );

and as well to predict the result for validation  group (new group)
here the code for  predict:

[predicted_label, accuracy, dec_values] = svmpredict(targetHit', inputHit, model);

it's work well.. but i need to do it with c++ so i want to understand how to predict the result myself without using  svmpredict build function.

The parameters i got after train is:

fieldnames(model)
ans =
{
  [1,1] = Parameters
  [2,1] = nr_class
  [3,1] = totalSV
  [4,1] = rho
  [5,1] = Label
  [6,1] = sv_indices
  [7,1] = ProbA
  [8,1] = ProbB
  [9,1] = nSV
  [10,1] = sv_coef
  [11,1] = SVs
}

but i don't know how to use with this parameters.
If anyone can help me and explain me how to use with the parameters by hand without using svmpredict function.

O.k i find this code :

w = (model.sv_coef' * full(model.SVs));
bias = -model.rho;
predictions = sign(inputMiss * w' + bias);

But it doesn't compatible to result from svmpredict..

Body:
This code should help you:

w = (model.sv_coef' * full(model.SVs));
bias = -model.rho;
predictions = sign(inputMiss * w' + bias);

But it doesn't compatible to result from svmpredict -> It should Fit(Check Again.


问:
Does Azure Active Directory B2C work with Oauth or Open ID?
I successfully implemented Azure Active Directory for user management/authentication/login in a web app, following this example:
Azure Sample AAD with Flask

I decided to try Azure Active Directory B2C because of its integration for the various social apps. However, I could not get the flask app to work using OAuth 2.0, since Azure AD B2C does not seem to be compatible with OAuth 2.0. I found some documentation that states Azure AD B2C requires Open ID Connect.

Could you please confirm whether Azure Active Directory B2C requires Open ID Connect, or whether it works with OAuth 2.0 as well?

Thanks

答:
It is worth to not that Azure Active Directory B2C (AAD B2C) supports both OpenID Connect and OAuth 2.0 in that it uses these two protocols to exchange information and secure tokens. However, AAD B2C "extends" these protocols by introducing Policies to handle the user experience for Sign-up, Sign-in and general account management.

What does this mean? First of, it means that you cannot create your own sign-up/sign-in experience, you are restricted to redirecting the user to the right policy (which you to some extent can customize). You cannot create your own sign-up/-in UI for this and you are restricted to styling/branding the provided web-based UI for this.

So in order to Authenticate using AAD B2C you could follow this guide, it should be easy enough to adapt to Python. You simply redirect the user to the /authorize endpoint of the AAD B2C and then validate the JWT you receive


问:
Codeigniter ion auth trying to get the user name of a logged in user in to a string
Hi team i am new to CI and ion auth and i want to find the best way to get the user name on the logged user and make it a string. I have try this and im getting an error.

Object of class CI_Email could not be converted to string

This is my Controller

```<code> class Dashboard extends CI_Controller {

    function index() {
        $user = $this->ion_auth->user();
        $email = $user->email;

        $data['email']= $email;
        $data['mainContent'] = 'dashboard_view';
        $this->load->view('template', $data);
    }
</code>```

and view

```<code><div id='dashboarWap'>
    <?php echo form_open('dashboard/dashInput'); ?>

    <?php echo $email; ?>
</code>```

Any idea on why i am getting this error would be a big help thanks.

答:
Ion auth already passes any data on logged in user through

```<code>$this->data['users'] = $this->ion_auth->users()->result();
</code>```

You can access user name by doing this

```<code>foreach ($users as $value) {
    echo $value->first_name. " " . $value->last_name;
}
</code>```

Body:
Hi team i am new to CI and ion auth and i want to find the best way to get the user name on the logged user and make it a string. I have try this and im getting an error.

Object of class CI_Email could not be converted to string

This is my Controller

 class Dashboard extends CI_Controller {

    function index() {
        $user = $this->ion_auth->user();
        $email = $user->email;

        $data['email']= $email;
        $data['mainContent'] = 'dashboard_view';
        $this->load->view('template', $data);
    }

and view

    <?php echo form_open('dashboard/dashInput'); ?>

    <?php echo $email; ?>

Any idea on why i am getting this error would be a big help thanks.

Body:
Ion auth already passes any data on logged in user through

$this->data['users'] = $this->ion_auth->users()->result();

You can access user name by doing this

foreach ($users as $value) {
    echo $value->first_name. " " . $value->last_name;
}


问:
Hibernate : MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'
I am new to Hibernate.

I want to fetch all records from Transaction table,

I got following error

```<code> Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column transactio2_.deleted' in 'field list'
</code>```

Though deleted column in present in Table

Entity Class :

```<code>@Entity
@Table(name = "transaction")
public class Transaction implements Comparable<Transaction>
{
@Id
@GeneratedValue
@Column(name = "transactionId")
private int transactionId;

@Column(name = "date")
private Date date;

@Column(name = "amount")
private BigDecimal amount;

@ManyToOne
@JoinColumn(name = "transactionTypeId")
private TransactionType transactionType;

@ManyToOne
@JoinColumn(name = "userId")
private User user;

@Column(name = "operation")
private String operation;

@Column(name = "lastUpdate")
private Date lastUpdate;

@Column(name = "deleted")
private int deleted;

@Column(name = "remark")
private String remark;

public Transaction()
{
    super();
}

@Override
public int compareTo(Transaction c)
{
    if (getTransactionId() < c.getTransactionId())
    {
        return -1;
    }
    if (getTransactionId() > c.getTransactionId())
    {
        return 1;
    }
    return 0;
}

public Date getLastUpdate()
{
    return lastUpdate;
}

public void setLastUpdate(Date lastUpdate)
{
    this.lastUpdate = lastUpdate;
}

public User getUser()
{
    return user;
}

public void setUser(User user)
{
    this.user = user;
}

public int getDeleted()
{
    return deleted;
}

public void setDeleted(int deleted)
{
    this.deleted = deleted;
}

public int getTransactionId()
{
    return transactionId;
}

public void setTransactionId(int transactionId)
{
    this.transactionId = transactionId;
}

public Date getDate()
{
    return date;
}

public void setDate(Date date)
{
    this.date = date;
}

public BigDecimal getAmount()
{
    return amount;
}

public void setAmount(BigDecimal amount)
{
    this.amount = amount;
}

public TransactionType getTransactionType()
{
    return transactionType;
}

public void setTransactionType(TransactionType transactionType)
{
    this.transactionType = transactionType;
}

public String getOperation()
{
    return operation;
}

public String getRemark()
{
    return remark;
}

public void setRemark(String remark)
{
    this.remark = remark;
}

public void setOperation(String operation)
{
    this.operation = operation;
}
 }
</code>```

Hibernate transactionBean :

```<code>@ManagedBean
@ViewScoped
public class TransactionBean implements Serializable
{

    ArrayList<Transaction> transactionList = new ArrayList<>();

    /**
   * Public Constructor
    */
public TransactionBean()
{
     Session session = HibernateUtil.getSessionFactory().openSession();
    @SuppressWarnings("unchecked")
    transactionList = (ArrayList<Transaction>) session.createCriteria(Transaction.class).list();
}
</code>```

What goes wrong in my code ?

Edit : Here is create statement of DB Table

```<code> delimiter $$

   CREATE TABLE `transaction` (
      `transactionId` int(11) NOT NULL AUTO_INCREMENT,
      `date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
      `amount` decimal(10,2) DEFAULT NULL,
      `transactionTypeId` int(11) NOT NULL,
      `operation` varchar(45) DEFAULT NULL,
      `lastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      `userId` int(11) NOT NULL,
      `deleted` tinyint(4) NOT NULL DEFAULT '0',
      `remark` varchar(450) DEFAULT NULL,
        PRIMARY KEY (`transactionId`),
        KEY `fk_transaction_1` (`userId`),
        KEY `fk_transaction_2` (`transactionTypeId`),
        CONSTRAINT `fk_transaction_1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`) ON     DELETE NO ACTION ON UPDATE NO ACTION,
       CONSTRAINT `fk_transaction_2` FOREIGN KEY (`transactionTypeId`) REFERENCES   `transaction_type` (`transactionTypeId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1$$
</code>```

答: I experienced similar issue recently. In my case it was missing database column</p>

Body:
I am new to Hibernate.

I want to fetch all records from Transaction table,

I got following error

 Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column transactio2_.deleted' in 'field list'

Though deleted column in present in Table

Entity Class :

@Entity
@Table(name = "transaction")
public class Transaction implements Comparable<Transaction>
{
@Id
@GeneratedValue
@Column(name = "transactionId")
private int transactionId;

@Column(name = "date")
private Date date;

@Column(name = "amount")
private BigDecimal amount;

@ManyToOne
@JoinColumn(name = "transactionTypeId")
private TransactionType transactionType;

@ManyToOne
@JoinColumn(name = "userId")
private User user;

@Column(name = "operation")
private String operation;

@Column(name = "lastUpdate")
private Date lastUpdate;

@Column(name = "deleted")
private int deleted;

@Column(name = "remark")
private String remark;

public Transaction()
{
    super();
}

@Override
public int compareTo(Transaction c)
{
    if (getTransactionId() < c.getTransactionId())
    {
        return -1;
    }
    if (getTransactionId() > c.getTransactionId())
    {
        return 1;
    }
    return 0;
}

public Date getLastUpdate()
{
    return lastUpdate;
}

public void setLastUpdate(Date lastUpdate)
{
    this.lastUpdate = lastUpdate;
}

public User getUser()
{
    return user;
}

public void setUser(User user)
{
    this.user = user;
}

public int getDeleted()
{
    return deleted;
}

public void setDeleted(int deleted)
{
    this.deleted = deleted;
}

public int getTransactionId()
{
    return transactionId;
}

public void setTransactionId(int transactionId)
{
    this.transactionId = transactionId;
}

public Date getDate()
{
    return date;
}

public void setDate(Date date)
{
    this.date = date;
}

public BigDecimal getAmount()
{
    return amount;
}

public void setAmount(BigDecimal amount)
{
    this.amount = amount;
}

public TransactionType getTransactionType()
{
    return transactionType;
}

public void setTransactionType(TransactionType transactionType)
{
    this.transactionType = transactionType;
}

public String getOperation()
{
    return operation;
}

public String getRemark()
{
    return remark;
}

public void setRemark(String remark)
{
    this.remark = remark;
}

public void setOperation(String operation)
{
    this.operation = operation;
}
 }

Hibernate transactionBean :

@ManagedBean
@ViewScoped
public class TransactionBean implements Serializable
{

    ArrayList<Transaction> transactionList = new ArrayList<>();

    /**
   * Public Constructor
    */
public TransactionBean()
{
     Session session = HibernateUtil.getSessionFactory().openSession();
    @SuppressWarnings("unchecked")
    transactionList = (ArrayList<Transaction>) session.createCriteria(Transaction.class).list();
}

What goes wrong in my code ?

Edit : Here is create statement of DB Table

 delimiter $$

   CREATE TABLE `transaction` (
      `transactionId` int(11) NOT NULL AUTO_INCREMENT,
      `date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
      `amount` decimal(10,2) DEFAULT NULL,
      `transactionTypeId` int(11) NOT NULL,
      `operation` varchar(45) DEFAULT NULL,
      `lastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      `userId` int(11) NOT NULL,
      `deleted` tinyint(4) NOT NULL DEFAULT '0',
      `remark` varchar(450) DEFAULT NULL,
        PRIMARY KEY (`transactionId`),
        KEY `fk_transaction_1` (`userId`),
        KEY `fk_transaction_2` (`transactionTypeId`),
        CONSTRAINT `fk_transaction_1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`) ON     DELETE NO ACTION ON UPDATE NO ACTION,
       CONSTRAINT `fk_transaction_2` FOREIGN KEY (`transactionTypeId`) REFERENCES   `transaction_type` (`transactionTypeId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1$$


问:
Create a String based sequence in Python SQL Alchemy
I'm trying to create a String based sequence in SQLAlchemy ORM. I know that the best practice is to use a Integer based column to manage ID of a table but in my case, due to some requirements of the project I need to store the data as a String based PK for ID's.

I know that in some databases it is possible to store data using a string based sequence like:

"AAA1"

"AAA2"

"AAAN"

But in SQL alchemy I can't achieve this by using Sequence method. It only generates Integer based sequences and I can't find an options to "append" a prefix in the sequence generation.

There is a easy solution to achieve this?

答:
You can do this in PostgreSQL similar to this:

```<code>CREATE TABLE test(
   id text PRIMARY KEY,
   val text
);

CREATE SEQUENCE test_id_seq OWNED BY test.id;

ALTER TABLE test
   ALTER id SET DEFAULT to_hex(nextval('test_id_seq'));
</code>```

In that example I used the to_hex function to get the hexadecimal representation, but you can use any expression you like.

Body:
You can do this in PostgreSQL similar to this:

CREATE TABLE test(
   id text PRIMARY KEY,
   val text
);

CREATE SEQUENCE test_id_seq OWNED BY test.id;

ALTER TABLE test
   ALTER id SET DEFAULT to_hex(nextval('test_id_seq'));

In that example I used the to_hex function to get the hexadecimal representation, but you can use any expression you like.


问:
Codeigniter - multiple checkbox values returns NULL
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

```<code>public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}
</code>```

Controller (view_leave)

```<code>$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');
</code>```

PHP/HTML (view_leave.php)

```<code><form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."<br/>";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>
</code>```

Controller (update_leave)

```<code>$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value
</code>```

Why and how can I check for the checkbox values?

Please help.

Thanks!

答:
Change the view like this</p>

```<code><?php $attributes = array('name'=>'leave_form','id'=>'leave_form');
        echo form_open('home/update_leave',$attributes);?>

<?php
if(isset($leave_list)){
foreach($leave_list as $row): ?>

<input type='checkbox' name='leave_types[]' value='<?php echo $row->Leave_Code; ?>' /> <?php echo $row->Leave_Description; ?>
<?php endforeach; } ?>
 ?>
</code>```

Body:
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}

Controller (view_leave)

$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');

PHP/HTML (view_leave.php)

<form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."
";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>

Controller (update_leave)

$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value

Why and how can I check for the checkbox values?

Please help.

Thanks!

Body:
Change the view like this

<?php $attributes = array('name'=>'leave_form','id'=>'leave_form');
        echo form_open('home/update_leave',$attributes);?>

<?php
if(isset($leave_list)){
foreach($leave_list as $row): ?>

<input type='checkbox' name='leave_types[]' value='<?php echo $row->Leave_Code; ?>' /> <?php echo $row->Leave_Description; ?>
<?php endforeach; } ?>
 ?>


问:
Recording Audio and Video using MediaMuxer on Android
I'm trying to record audio and video using AudioRecord, MediaCodec and MediaMuxer provided in Android 4.3
However, sometimes the audio encoder thread stops and is not encoding anymore. The result is, a broken mp4 file, because the muxer does not receive any encoded audio frames. On my Samsung Galaxy Note 3 it is working 99% but on my Sony Xperia Z1 the encoding thread is always stuck. I really don't know what is the reason, maybe someone could help me optimizing my code:

AudioRecorder.java

```<code>package com.cmdd.horicam;

import java.nio.ByteBuffer;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.os.Looper;
import android.util.Log;

public class AudioRecorder implements Runnable {
    public static final String TAG = "AudioRecorder";
    public static final boolean VERBOSE = false;

    public MovieMuxerAudioHandler mAudioHandler;

     // audio format settings
    public static final String MIME_TYPE_AUDIO = "audio/mp4a-latm";
    public static final int SAMPLE_RATE = 44100;
    public static final int CHANNEL_COUNT = 1;
    public static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    public static final int BIT_RATE_AUDIO = 128000;
    public static final int SAMPLES_PER_FRAME = 1024; // AAC
    public static final int FRAMES_PER_BUFFER = 24;
    public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;

    public static final int MSG_START_RECORDING = 0;
    public static final int MSG_STOP_RECORDING = 1;
    public static final int MSG_QUIT = 2;

    private MediaCodec mAudioEncoder;
    private int iBufferSize;
    int iReadResult = 0;
    private boolean bIsRecording = false;

    private static final int TIMEOUT_USEC = 10000;

    private MovieMuxer mMovieMuxer;

    private MediaFormat mAudioFormat;

    private volatile AudioRecorderHandler mHandler;

    private Object mReadyFence = new Object();      // guards ready/running
    private boolean mReady;
    private boolean mRunning;

    public AudioRecorder(MovieMuxer mMovieMuxer){
        this.mMovieMuxer = mMovieMuxer;
    }

    /**
     * Recorder thread entry point.  Establishes Looper/Handler and waits for messages.
     * <p>
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // Establish a Looper for this thread, and define a Handler for it.
        Looper.prepare();
        synchronized (mReadyFence) {
            mHandler = new AudioRecorderHandler(this);
            mReady = true;
            mReadyFence.notify();
        }
        Looper.loop();

        if(VERBOSE)Log.d(TAG, "audio recorder exiting thread");
        synchronized (mReadyFence) {
            mReady = mRunning = false;
            mHandler = null;
        }
    }

    public void prepareEncoder(){
        // prepare audio format
        mAudioFormat = MediaFormat.createAudioFormat(MIME_TYPE_AUDIO, SAMPLE_RATE, CHANNEL_COUNT);
        mAudioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
        mAudioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16384);
        mAudioFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE_AUDIO);

        mAudioEncoder = MediaCodec.createEncoderByType(MIME_TYPE_AUDIO);
        mAudioEncoder.configure(mAudioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
        mAudioEncoder.start();

        new Thread(new AudioEncoderTask(), "AudioEncoderTask").start();
    }

    public void prepareRecorder() {
        int iMinBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

        bIsRecording = false;

        iBufferSize = SAMPLES_PER_FRAME * FRAMES_PER_BUFFER;

        // Ensure buffer is adequately sized for the AudioRecord
        // object to initialize
        if (iBufferSize < iMinBufferSize)
            iBufferSize = ((iMinBufferSize / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;

        AudioRecord mAudioRecorder;
        mAudioRecorder = new AudioRecord(
                AUDIO_SOURCE, // source
                SAMPLE_RATE, // sample rate, hz
                CHANNEL_CONFIG, // channels
                AUDIO_FORMAT, // audio format
                iBufferSize); // buffer size (bytes)

        mAudioRecorder.startRecording();

        new Thread(new AudioRecorderTask(mAudioRecorder), "AudioRecorderTask").start();
    }

    /**
     * Tells the audio recorder to start recording.  (Call from non-encoder thread.)
     * <p>
     * Creates a new thread, which will create an encoder using the provided configuration.
     * <p>
     * Returns after the recorder thread has started and is ready to accept Messages.  The
     * encoder may not yet be fully configured.
     */
    public void startRecording() {
        if(VERBOSE)Log.d(TAG, "audio recorder: startRecording()");
        synchronized (mReadyFence) {
            if (mRunning) {
                Log.w(TAG, "audio recorder thread already running");
                return;
            }
            mRunning = true;

            new Thread(this, "AudioRecorder").start();
            while (!mReady) {
                try {
                    mReadyFence.wait();
                } catch (InterruptedException ie) {
                    // ignore
                }
            }
        }

        mHandler.sendMessage(mHandler.obtainMessage(MSG_START_RECORDING));
    }

    public void handleStartRecording(){
        if(VERBOSE)Log.d(TAG, "handleStartRecording");
        prepareEncoder();
        prepareRecorder();
        bIsRecording = true;
    }

    /**
     * Tells the video recorder to stop recording.  (Call from non-encoder thread.)
     * <p>
     * Returns immediately; the encoder/muxer may not yet be finished creating the movie.
     * <p>
     */
    public void stopRecording() {
        if(mHandler != null){
            mHandler.sendMessage(mHandler.obtainMessage(MSG_STOP_RECORDING));
            mHandler.sendMessage(mHandler.obtainMessage(MSG_QUIT));
        }
    }

    /**
     * Handles a request to stop encoding.
     */
    public void handleStopRecording() {
        if(VERBOSE)Log.d(TAG, "handleStopRecording");
        bIsRecording = false;
    }

    public String getCurrentAudioFormat(){
        if(this.mAudioFormat == null)
            return "null";
        else
            return this.mAudioFormat.toString();
    }

    private class AudioRecorderTask implements Runnable {

        AudioRecord mAudioRecorder;
        ByteBuffer[] inputBuffers;
        ByteBuffer inputBuffer;

        public AudioRecorderTask(AudioRecord recorder){
            this.mAudioRecorder = recorder;
        }

        @Override
        public void run() {
            if(VERBOSE)Log.i(TAG, "AudioRecorder started recording");
            long audioPresentationTimeNs;

            byte[] mTempBuffer = new byte[SAMPLES_PER_FRAME];

            while (bIsRecording) {
                audioPresentationTimeNs = System.nanoTime();

                iReadResult = mAudioRecorder.read(mTempBuffer, 0, SAMPLES_PER_FRAME);
                if(iReadResult == AudioRecord.ERROR_BAD_VALUE || iReadResult == AudioRecord.ERROR_INVALID_OPERATION)
                    Log.e(TAG, "audio buffer read error");

                // send current frame data to encoder
                try {
                    if(inputBuffers == null)
                        inputBuffers = mAudioEncoder.getInputBuffers();

                    int inputBufferIndex = mAudioEncoder.dequeueInputBuffer(-1);
                    if (inputBufferIndex >= 0) {
                        inputBuffer = inputBuffers[inputBufferIndex];
                        inputBuffer.clear();
                        inputBuffer.put(mTempBuffer);
                        //recycleInputBuffer(mTempBuffer);

                        if(VERBOSE)Log.d(TAG, "sending frame to audio encoder");
                        mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, mTempBuffer.length, audioPresentationTimeNs / 1000, 0);
                    }
                } catch (Throwable t) {
                    Log.e(TAG, "sendFrameToAudioEncoder exception");
                    t.printStackTrace();
                }
            }

            // finished recording -> send it to the encoder
            audioPresentationTimeNs = System.nanoTime();

            iReadResult = mAudioRecorder.read(mTempBuffer, 0, SAMPLES_PER_FRAME);
            if (iReadResult == AudioRecord.ERROR_BAD_VALUE
                    || iReadResult == AudioRecord.ERROR_INVALID_OPERATION)
                Log.e(TAG, "audio buffer read error");

            // send current frame data to encoder
            try {
                int inputBufferIndex = mAudioEncoder.dequeueInputBuffer(-1);
                if (inputBufferIndex >= 0) {
                    inputBuffer = inputBuffers[inputBufferIndex];
                    inputBuffer.clear();
                    inputBuffer.put(mTempBuffer);

                    if(VERBOSE)Log.d(TAG, "sending EOS to audio encoder");
                    mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, mTempBuffer.length, audioPresentationTimeNs / 1000, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                }
            } catch (Throwable t) {
                Log.e(TAG, "sendFrameToAudioEncoder exception");
                t.printStackTrace();
            }

            //if (mAudioRecorder != null) {
            //  mAudioRecorder.release();
            //  mAudioRecorder = null;
            //  if(VERBOSE)Log.i(TAG, "stopped");
            //}
        }
    }

    private class AudioEncoderTask implements Runnable {
        private boolean bAudioEncoderFinished;
        private int iAudioTrackIndex;
        private MediaCodec.BufferInfo mAudioBufferInfo;

        @Override
        public void run(){
            if(VERBOSE)Log.i(TAG, "AudioEncoder started encoding");
            bAudioEncoderFinished = false;

            ByteBuffer[] encoderOutputBuffers = mAudioEncoder.getOutputBuffers();
            ByteBuffer encodedData;

            mAudioBufferInfo = new MediaCodec.BufferInfo();

            while(!bAudioEncoderFinished){
                int encoderStatus = mAudioEncoder.dequeueOutputBuffer(mAudioBufferInfo, TIMEOUT_USEC);
                if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
                    // no output available yet
                    if (VERBOSE) Log.d(TAG + "_encoder", "no output available, spinning to await EOS");
                } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                    // not expected for an encoder
                    encoderOutputBuffers = mAudioEncoder.getOutputBuffers();
                } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                    MediaFormat newFormat = mAudioEncoder.getOutputFormat();
                    if(VERBOSE)Log.d(TAG, "received output format: " + newFormat);
                    // should happen before receiving buffers, and should only happen once
                    iAudioTrackIndex = mMovieMuxer.addTrack(newFormat);

                } else if (encoderStatus < 0) {
                    Log.w(TAG + "_encoder", "unexpected result from encoder.dequeueOutputBuffer: " + encoderStatus);
                    // let's ignore it
                } else {
                    if(mMovieMuxer.muxerStarted()){
                        encodedData = encoderOutputBuffers[encoderStatus];
                        if (encodedData == null) {
                            throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
                        }

                        if ((mAudioBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                            // The codec config data was pulled out and fed to the muxer when we got
                            // the INFO_OUTPUT_FORMAT_CHANGED status. Ignore it.
                            if (VERBOSE) Log.d(TAG + "_encoder", "ignoring BUFFER_FLAG_CODEC_CONFIG");
                            mAudioBufferInfo.size = 0;
                        }

                        if (mAudioBufferInfo.size != 0) {

                            // adjust the ByteBuffer values to match BufferInfo (not needed?)
                            encodedData.position(mAudioBufferInfo.offset);
                            encodedData.limit(mAudioBufferInfo.offset + mAudioBufferInfo.size);

                            mMovieMuxer.writeSampleData(iAudioTrackIndex, encodedData, mAudioBufferInfo);

                            if (VERBOSE) {
                                Log.d(TAG + "_encoder", "sent " + mAudioBufferInfo.size + " bytes (audio) to muxer, ts=" + mAudioBufferInfo.presentationTimeUs);
                            }
                        }

                        mAudioEncoder.releaseOutputBuffer(encoderStatus, false);

                        if ((mAudioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                            // reached EOS
                            if(VERBOSE)Log.i(TAG + "_encoder", "audio encoder finished");
                            bAudioEncoderFinished = true;

                            // tell the muxer that we are finished
                            mAudioHandler.onAudioEncodingFinished();
                            break;
                        }
                    }
                }
            }
        }

    }
}
</code>```

Thanks for your help.

答:
The document indicates that the AudioFormat should be ENCODING_PCM_8BIT when reading into a byte[]. If you want to use ENCODING_PCM_16BIT, try reading into a ByteBuffer instead, but remember to user iReadResult as the size when queue in the data.

```<code>//Creating ByteBuffer
ByteBuffer mTempBuffer = ByteBuffer.allocateDirect(SAMPLES_PER_FRAME);

//In reading loop
mTempBuffer.clear();
iReadResult = mAudioRecorder.read(mTempBuffer, SAMPLES_PER_FRAME);

//Send to encoder
mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, iReadResult, audioPresentationTimeNs / 1000L, 0);
</code>```

Body:
I'm trying to record audio and video using AudioRecord, MediaCodec and MediaMuxer provided in Android 4.3
However, sometimes the audio encoder thread stops and is not encoding anymore. The result is, a broken mp4 file, because the muxer does not receive any encoded audio frames. On my Samsung Galaxy Note 3 it is working 99% but on my Sony Xperia Z1 the encoding thread is always stuck. I really don't know what is the reason, maybe someone could help me optimizing my code:

AudioRecorder.java

package com.cmdd.horicam;

import java.nio.ByteBuffer;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.os.Looper;
import android.util.Log;

public class AudioRecorder implements Runnable {
    public static final String TAG = "AudioRecorder";
    public static final boolean VERBOSE = false;

    public MovieMuxerAudioHandler mAudioHandler;

     // audio format settings
    public static final String MIME_TYPE_AUDIO = "audio/mp4a-latm";
    public static final int SAMPLE_RATE = 44100;
    public static final int CHANNEL_COUNT = 1;
    public static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    public static final int BIT_RATE_AUDIO = 128000;
    public static final int SAMPLES_PER_FRAME = 1024; // AAC
    public static final int FRAMES_PER_BUFFER = 24;
    public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;

    public static final int MSG_START_RECORDING = 0;
    public static final int MSG_STOP_RECORDING = 1;
    public static final int MSG_QUIT = 2;

    private MediaCodec mAudioEncoder;
    private int iBufferSize;
    int iReadResult = 0;
    private boolean bIsRecording = false;

    private static final int TIMEOUT_USEC = 10000;

    private MovieMuxer mMovieMuxer;

    private MediaFormat mAudioFormat;

    private volatile AudioRecorderHandler mHandler;

    private Object mReadyFence = new Object();      // guards ready/running
    private boolean mReady;
    private boolean mRunning;

    public AudioRecorder(MovieMuxer mMovieMuxer){
        this.mMovieMuxer = mMovieMuxer;
    }

    /**
     * Recorder thread entry point.  Establishes Looper/Handler and waits for messages.
     *

     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // Establish a Looper for this thread, and define a Handler for it.
        Looper.prepare();
        synchronized (mReadyFence) {
            mHandler = new AudioRecorderHandler(this);
            mReady = true;
            mReadyFence.notify();
        }
        Looper.loop();

        if(VERBOSE)Log.d(TAG, "audio recorder exiting thread");
        synchronized (mReadyFence) {
            mReady = mRunning = false;
            mHandler = null;
        }
    }

    public void prepareEncoder(){
        // prepare audio format
        mAudioFormat = MediaFormat.createAudioFormat(MIME_TYPE_AUDIO, SAMPLE_RATE, CHANNEL_COUNT);
        mAudioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
        mAudioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16384);
        mAudioFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE_AUDIO);

        mAudioEncoder = MediaCodec.createEncoderByType(MIME_TYPE_AUDIO);
        mAudioEncoder.configure(mAudioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
        mAudioEncoder.start();

        new Thread(new AudioEncoderTask(), "AudioEncoderTask").start();
    }

    public void prepareRecorder() {
        int iMinBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

        bIsRecording = false;

        iBufferSize = SAMPLES_PER_FRAME * FRAMES_PER_BUFFER;

        // Ensure buffer is adequately sized for the AudioRecord
        // object to initialize
        if (iBufferSize < iMinBufferSize)
            iBufferSize = ((iMinBufferSize / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;

        AudioRecord mAudioRecorder;
        mAudioRecorder = new AudioRecord(
                AUDIO_SOURCE, // source
                SAMPLE_RATE, // sample rate, hz
                CHANNEL_CONFIG, // channels
                AUDIO_FORMAT, // audio format
                iBufferSize); // buffer size (bytes)

        mAudioRecorder.startRecording();

        new Thread(new AudioRecorderTask(mAudioRecorder), "AudioRecorderTask").start();
    }

    /**
     * Tells the audio recorder to start recording.  (Call from non-encoder thread.)
     *

     * Creates a new thread, which will create an encoder using the provided configuration.
     *

     * Returns after the recorder thread has started and is ready to accept Messages.  The
     * encoder may not yet be fully configured.
     */
    public void startRecording() {
        if(VERBOSE)Log.d(TAG, "audio recorder: startRecording()");
        synchronized (mReadyFence) {
            if (mRunning) {
                Log.w(TAG, "audio recorder thread already running");
                return;
            }
            mRunning = true;

            new Thread(this, "AudioRecorder").start();
            while (!mReady) {
                try {
                    mReadyFence.wait();
                } catch (InterruptedException ie) {
                    // ignore
                }
            }
        }

        mHandler.sendMessage(mHandler.obtainMessage(MSG_START_RECORDING));
    }

    public void handleStartRecording(){
        if(VERBOSE)Log.d(TAG, "handleStartRecording");
        prepareEncoder();
        prepareRecorder();
        bIsRecording = true;
    }

    /**
     * Tells the video recorder to stop recording.  (Call from non-encoder thread.)
     *

     * Returns immediately; the encoder/muxer may not yet be finished creating the movie.
     *

     */
    public void stopRecording() {
        if(mHandler != null){
            mHandler.sendMessage(mHandler.obtainMessage(MSG_STOP_RECORDING));
            mHandler.sendMessage(mHandler.obtainMessage(MSG_QUIT));
        }
    }

    /**
     * Handles a request to stop encoding.
     */
    public void handleStopRecording() {
        if(VERBOSE)Log.d(TAG, "handleStopRecording");
        bIsRecording = false;
    }

    public String getCurrentAudioFormat(){
        if(this.mAudioFormat == null)
            return "null";
        else
            return this.mAudioFormat.toString();
    }

    private class AudioRecorderTask implements Runnable {

        AudioRecord mAudioRecorder;
        ByteBuffer[] inputBuffers;
        ByteBuffer inputBuffer;

        public AudioRecorderTask(AudioRecord recorder){
            this.mAudioRecorder = recorder;
        }

        @Override
        public void run() {
            if(VERBOSE)Log.i(TAG, "AudioRecorder started recording");
            long audioPresentationTimeNs;

            byte[] mTempBuffer = new byte[SAMPLES_PER_FRAME];

            while (bIsRecording) {
                audioPresentationTimeNs = System.nanoTime();

                iReadResult = mAudioRecorder.read(mTempBuffer, 0, SAMPLES_PER_FRAME);
                if(iReadResult == AudioRecord.ERROR_BAD_VALUE || iReadResult == AudioRecord.ERROR_INVALID_OPERATION)
                    Log.e(TAG, "audio buffer read error");

                // send current frame data to encoder
                try {
                    if(inputBuffers == null)
                        inputBuffers = mAudioEncoder.getInputBuffers();

                    int inputBufferIndex = mAudioEncoder.dequeueInputBuffer(-1);
                    if (inputBufferIndex >= 0) {
                        inputBuffer = inputBuffers[inputBufferIndex];
                        inputBuffer.clear();
                        inputBuffer.put(mTempBuffer);
                        //recycleInputBuffer(mTempBuffer);

                        if(VERBOSE)Log.d(TAG, "sending frame to audio encoder");
                        mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, mTempBuffer.length, audioPresentationTimeNs / 1000, 0);
                    }
                } catch (Throwable t) {
                    Log.e(TAG, "sendFrameToAudioEncoder exception");
                    t.printStackTrace();
                }
            }

            // finished recording -> send it to the encoder
            audioPresentationTimeNs = System.nanoTime();

            iReadResult = mAudioRecorder.read(mTempBuffer, 0, SAMPLES_PER_FRAME);
            if (iReadResult == AudioRecord.ERROR_BAD_VALUE
                    || iReadResult == AudioRecord.ERROR_INVALID_OPERATION)
                Log.e(TAG, "audio buffer read error");

            // send current frame data to encoder
            try {
                int inputBufferIndex = mAudioEncoder.dequeueInputBuffer(-1);
                if (inputBufferIndex >= 0) {
                    inputBuffer = inputBuffers[inputBufferIndex];
                    inputBuffer.clear();
                    inputBuffer.put(mTempBuffer);

                    if(VERBOSE)Log.d(TAG, "sending EOS to audio encoder");
                    mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, mTempBuffer.length, audioPresentationTimeNs / 1000, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                }
            } catch (Throwable t) {
                Log.e(TAG, "sendFrameToAudioEncoder exception");
                t.printStackTrace();
            }

            //if (mAudioRecorder != null) {
            //  mAudioRecorder.release();
            //  mAudioRecorder = null;
            //  if(VERBOSE)Log.i(TAG, "stopped");
            //}
        }
    }

    private class AudioEncoderTask implements Runnable {
        private boolean bAudioEncoderFinished;
        private int iAudioTrackIndex;
        private MediaCodec.BufferInfo mAudioBufferInfo;

        @Override
        public void run(){
            if(VERBOSE)Log.i(TAG, "AudioEncoder started encoding");
            bAudioEncoderFinished = false;

            ByteBuffer[] encoderOutputBuffers = mAudioEncoder.getOutputBuffers();
            ByteBuffer encodedData;

            mAudioBufferInfo = new MediaCodec.BufferInfo();

            while(!bAudioEncoderFinished){
                int encoderStatus = mAudioEncoder.dequeueOutputBuffer(mAudioBufferInfo, TIMEOUT_USEC);
                if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
                    // no output available yet
                    if (VERBOSE) Log.d(TAG + "_encoder", "no output available, spinning to await EOS");
                } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                    // not expected for an encoder
                    encoderOutputBuffers = mAudioEncoder.getOutputBuffers();
                } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                    MediaFormat newFormat = mAudioEncoder.getOutputFormat();
                    if(VERBOSE)Log.d(TAG, "received output format: " + newFormat);
                    // should happen before receiving buffers, and should only happen once
                    iAudioTrackIndex = mMovieMuxer.addTrack(newFormat);

                } else if (encoderStatus < 0) {
                    Log.w(TAG + "_encoder", "unexpected result from encoder.dequeueOutputBuffer: " + encoderStatus);
                    // let's ignore it
                } else {
                    if(mMovieMuxer.muxerStarted()){
                        encodedData = encoderOutputBuffers[encoderStatus];
                        if (encodedData == null) {
                            throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
                        }

                        if ((mAudioBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                            // The codec config data was pulled out and fed to the muxer when we got
                            // the INFO_OUTPUT_FORMAT_CHANGED status. Ignore it.
                            if (VERBOSE) Log.d(TAG + "_encoder", "ignoring BUFFER_FLAG_CODEC_CONFIG");
                            mAudioBufferInfo.size = 0;
                        }

                        if (mAudioBufferInfo.size != 0) {

                            // adjust the ByteBuffer values to match BufferInfo (not needed?)
                            encodedData.position(mAudioBufferInfo.offset);
                            encodedData.limit(mAudioBufferInfo.offset + mAudioBufferInfo.size);

                            mMovieMuxer.writeSampleData(iAudioTrackIndex, encodedData, mAudioBufferInfo);

                            if (VERBOSE) {
                                Log.d(TAG + "_encoder", "sent " + mAudioBufferInfo.size + " bytes (audio) to muxer, ts=" + mAudioBufferInfo.presentationTimeUs);
                            }
                        }

                        mAudioEncoder.releaseOutputBuffer(encoderStatus, false);

                        if ((mAudioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                            // reached EOS
                            if(VERBOSE)Log.i(TAG + "_encoder", "audio encoder finished");
                            bAudioEncoderFinished = true;

                            // tell the muxer that we are finished
                            mAudioHandler.onAudioEncodingFinished();
                            break;
                        }
                    }
                }
            }
        }

    }
}

Thanks for your help.

Body:
The document indicates that the AudioFormat should be ENCODING_PCM_8BIT when reading into a byte[]. If you want to use ENCODING_PCM_16BIT, try reading into a ByteBuffer instead, but remember to user iReadResult as the size when queue in the data.

//Creating ByteBuffer
ByteBuffer mTempBuffer = ByteBuffer.allocateDirect(SAMPLES_PER_FRAME);

//In reading loop
mTempBuffer.clear();
iReadResult = mAudioRecorder.read(mTempBuffer, SAMPLES_PER_FRAME);

//Send to encoder
mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, iReadResult, audioPresentationTimeNs / 1000L, 0);


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答:
From W3C: http://www.w3.org/TR/html4/intro/sgmltut.html

```<code>All attribute values [should] be delimited using either double quotation
marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39).

Single quote marks can be included within the attribute value when the
value is delimited by double quote marks, and vice versa.
</code>```

Strings in PHP follow the same principle - interchangeable single/double quotes.

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>

Body:
From W3C: http://www.w3.org/TR/html4/intro/sgmltut.html

All attribute values [should] be delimited using either double quotation
marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39).

Single quote marks can be included within the attribute value when the
value is delimited by double quote marks, and vice versa.

Strings in PHP follow the same principle - interchangeable single/double quotes.


问:
How to load 2 controllers one by one or at a time in angularjs?
Is it possible to load multiple controllers one by one or at a time. If yes  then Can anyone tell me how to load two different controllers at the time of loading page in AngularJs. I'm using routing.

Thank you.

答:
Apart from just referring them on index.html as @Sajeetharan suggested how about:</p>

```<code><ANY ng-controller="controller1 as ctrl1">
    <ANY ng-controller="controller2 as ctrl2">
        ....
    </ANY>
</ANY>
</code>```

Body:
Apart from just referring them on index.html as @Sajeetharan suggested how about:

<ANY ng-controller="controller1 as ctrl1">
    <ANY ng-controller="controller2 as ctrl2">
        ....
    </ANY>
</ANY>


问:
To write the value from resultset to text file (.txt file)
Please help me on the below code as i want to write the values from the resultset to a txt file

Code

```<code>while (rs.next()){
    FileWriter fstream = new FileWriter(file);
    BufferedWriter out = new BufferedWriter(fstream);

    out.write(Integer.toString(rs.getInt("SBL_PRODUCT_ID")) + ", ");
    out.write(Integer.toString(rs.getInt("SBL_TARIFF_ID")) + ", ");
    out.write(rs.getString("PRODUCT_DESCRIPTION") + ", ");
    out.write(rs.getString("SERVICE_TYPE") + ", ");
    out.write(Integer.toString(rs.getInt("MARKET_CLASS")) + ", ");
    out.write(rs.getString("ENTITY_TYPE") + ", ");
    out.newLine();
    /*out.write(System.getProperty("line.separator"));*/

    System.out.println("Completed writing into text file");
    out.close();
}
</code>```

Required Output in the txt file

```<code>4087, 98, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 99, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 100, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 101, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL
</code>```

Current output which i am getting is only one line that too the last value from the resultset ie below

Current output

```<code>4087, 101, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL
</code>```

Kindly help me on this :(

答:
From GitHub: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/resultset/ResultSetConverters.java

```<code>public static void writeResultSetToWriter(ResultSet resultSet, PrintWriter writer) throws SQLException
{
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();
int numRows = 0;

while(resultSet.next())             //iterate rows
{
    ++numRows;
    JSONObject obj = new JSONObject();      //extends HashMap
    for (int i = 1; i <= numColumns; ++i)           //iterate columns
    {
        String column_name = metadata.getColumnName(i);
        obj.put(column_name, resultSet.getObject(column_name));
    }
    writer.println(obj.toJSONString());

    if(numRows % 1000 == 0)
        writer.flush();
}
</code>```

}

Body:
Please help me on the below code as i want to write the values from the resultset to a txt file

Code

while (rs.next()){
    FileWriter fstream = new FileWriter(file);
    BufferedWriter out = new BufferedWriter(fstream);

    out.write(Integer.toString(rs.getInt("SBL_PRODUCT_ID")) + ", ");
    out.write(Integer.toString(rs.getInt("SBL_TARIFF_ID")) + ", ");
    out.write(rs.getString("PRODUCT_DESCRIPTION") + ", ");
    out.write(rs.getString("SERVICE_TYPE") + ", ");
    out.write(Integer.toString(rs.getInt("MARKET_CLASS")) + ", ");
    out.write(rs.getString("ENTITY_TYPE") + ", ");
    out.newLine();
    /*out.write(System.getProperty("line.separator"));*/

    System.out.println("Completed writing into text file");
    out.close();
}

Required Output in the txt file

4087, 98, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 99, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 100, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

4087, 101, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

Current output which i am getting is only one line that too the last value from the resultset ie below

Current output

4087, 101, POSTE SIM, Deal [SoHo Flat Tariff Recurring Charge, Prepaid], /service/telco/SIM, 101, DEAL

Kindly help me on this :(

Body:
From GitHub: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/resultset/ResultSetConverters.java

public static void writeResultSetToWriter(ResultSet resultSet, PrintWriter writer) throws SQLException
{
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();
int numRows = 0;

while(resultSet.next())             //iterate rows
{
    ++numRows;
    JSONObject obj = new JSONObject();      //extends HashMap
    for (int i = 1; i <= numColumns; ++i)           //iterate columns
    {
        String column_name = metadata.getColumnName(i);
        obj.put(column_name, resultSet.getObject(column_name));
    }
    writer.println(obj.toJSONString());

    if(numRows % 1000 == 0)
        writer.flush();
}

}


问:
Is a mongodb query with 1 indexed field faster than multiple indexed fields?
In the following model a product is owned by a customer. and cannot be ordered by other customers. So I know that in an order by customer 1 there can only be products owned by customer one.

To give you an idea here is a simple version of the data model:

Orders:

```<code>{
  'customer' : 1
  'products' : [
  {'productId' : 'a'},
  {'productId' : 'b'}
  ]
}
</code>```

Products:

```<code>{
  'id' : 'a'
  'name' : 'somename'
  'customer' : 1
}
</code>```

I need to find orders that contain certain products. I know the product id and customer id. I'm free to add/change indexes on my database.

Now my question is. Is it faster to just add a single field index on the product id's and query only using that ID. Or should I go for a compound index with customer and product id?

I'm not sure if this matters, but in my real model the list of products is actually a list of objects which have an amount and a dbref to the product. And the customer is also a dbref.

Here is a full order object:

```<code>{
    "_id" : 0,
    "_class" : "nl.pfa.myprintforce.models.Order",
    "orderNumber" : "e35f1fa8-b4c4-4d53-89c9-66abe94a3553",
    "status" : "ERROR",
    "created" : ISODate("2017-03-30T11:50:50.292Z"),
    "finished" : false,
    "orderTime" : ISODate("2017-01-12T12:50:50.292Z"),
    "expectedDelivery" : ISODate("2017-03-30T11:50:50.292Z"),
    "totalItems" : 19,
    "orderItems" : [
        {
            "amount" : 4,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(16)
            }
        },
        {
            "amount" : 7,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(26)
            }
        },
        {
            "amount" : 8,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(7)
            }
        }
    ],
    "stateList" : [
        {
            "timestamp" : ISODate("2017-03-28T11:50:50.074Z"),
            "status" : "NEW",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-29T11:50:50.075Z"),
            "status" : "IN_PRODUCTION",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-30T11:50:50.075Z"),
            "status" : "ERROR",
            "message" : "Something went wrong"
        }
    ],
    "customer" : {
        "$ref" : "customer",
        "$id" : ObjectId("58dcf11a71571a24c475c044")
    }
}
</code>```

答:
When I have the following indexes:

```<code>1: {"customer" : 1, "orderItems.product" : 1}
2: {"orderItems.product" : 1}
</code>```

both count queries (I use count to forcefully find all documents without the network transfer):

```<code>a: db.getCollection('order').find({
'orderItems.product' : DBRef('product',113)
}).count()

b: db.getCollection('order').find({
'customer' : DBRef('customer',ObjectId("58de009671571a07540a51d5")),
'orderItems.product' : DBRef('product',113)
}).count()
</code>```

Run with the same time of ~0.007 seconds on a set of 200k.
When I add 1000k record for a different customer (and different products) it does not effect the time at all.

an extended explain shows that:

query 1 just uses index 2.
query 2 uses index 2 but also considered index 1. Perhaps index intersection is used here?

Because if I drop index 1 the results are:

Query a: 0.007 seconds
Query b: 0.035 seconds (5x as long!)

So my conclusion is that with the right indexing both methods work about as fast. However, if you do not need the compound index for anything else it's just a waste of space & write speed.

So: single field index is better in my case.

Body:
In the following model a product is owned by a customer. and cannot be ordered by other customers. So I know that in an order by customer 1 there can only be products owned by customer one.

To give you an idea here is a simple version of the data model:

Orders:

{
  'customer' : 1
  'products' : [
  {'productId' : 'a'},
  {'productId' : 'b'}
  ]
}

Products:

{
  'id' : 'a'
  'name' : 'somename'
  'customer' : 1
}

I need to find orders that contain certain products. I know the product id and customer id. I'm free to add/change indexes on my database.

Now my question is. Is it faster to just add a single field index on the product id's and query only using that ID. Or should I go for a compound index with customer and product id?

I'm not sure if this matters, but in my real model the list of products is actually a list of objects which have an amount and a dbref to the product. And the customer is also a dbref.

Here is a full order object:

{
    "_id" : 0,
    "_class" : "nl.pfa.myprintforce.models.Order",
    "orderNumber" : "e35f1fa8-b4c4-4d53-89c9-66abe94a3553",
    "status" : "ERROR",
    "created" : ISODate("2017-03-30T11:50:50.292Z"),
    "finished" : false,
    "orderTime" : ISODate("2017-01-12T12:50:50.292Z"),
    "expectedDelivery" : ISODate("2017-03-30T11:50:50.292Z"),
    "totalItems" : 19,
    "orderItems" : [
        {
            "amount" : 4,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(16)
            }
        },
        {
            "amount" : 7,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(26)
            }
        },
        {
            "amount" : 8,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(7)
            }
        }
    ],
    "stateList" : [
        {
            "timestamp" : ISODate("2017-03-28T11:50:50.074Z"),
            "status" : "NEW",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-29T11:50:50.075Z"),
            "status" : "IN_PRODUCTION",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-30T11:50:50.075Z"),
            "status" : "ERROR",
            "message" : "Something went wrong"
        }
    ],
    "customer" : {
        "$ref" : "customer",
        "$id" : ObjectId("58dcf11a71571a24c475c044")
    }
}

Body:
When I have the following indexes:

1: {"customer" : 1, "orderItems.product" : 1}
2: {"orderItems.product" : 1}

both count queries (I use count to forcefully find all documents without the network transfer):

a: db.getCollection('order').find({
'orderItems.product' : DBRef('product',113)
}).count()

b: db.getCollection('order').find({
'customer' : DBRef('customer',ObjectId("58de009671571a07540a51d5")),
'orderItems.product' : DBRef('product',113)
}).count()

Run with the same time of ~0.007 seconds on a set of 200k.
When I add 1000k record for a different customer (and different products) it does not effect the time at all.

an extended explain shows that:

query 1 just uses index 2.
query 2 uses index 2 but also considered index 1. Perhaps index intersection is used here?

Because if I drop index 1 the results are:

Query a: 0.007 seconds
Query b: 0.035 seconds (5x as long!)

So my conclusion is that with the right indexing both methods work about as fast. However, if you do not need the compound index for anything else it's just a waste of space & write speed.

So: single field index is better in my case.


问:
How to add profile specific properties files when I have custom name to my property file
I have properties file with name : transactionexpiry.properties in my project's src/main/resources folder.

I am able to read the properties in the code with @PropertySource("classpath:/transactionexpiry.properties")

Now I wan't to add application scope and add environment specific config files as transactionexpiry-dev.properties, transactionexpiry-local.properties, etc

But the same works with application.properties, application-dev.properties, application-local.properties

Is there a way to make it work with my previous set-up?

答:
If you are using spring profiles:

```<code>-Dspring.profiles.active=dev
</code>```

Then you can call the properties file like:

```<code>@PropertySource("classpath:/transactionexpiry${spring.profiles.active}.properties")
</code>```

Body:
If you are using spring profiles:

-Dspring.profiles.active=dev

Then you can call the properties file like:

@PropertySource("classpath:/transactionexpiry${spring.profiles.active}.properties")


问:
Find value in range sql
Lets say i had a bunch of records and they had a column max_val and min_val. lets assume min_val is 1 and max_val is 55 how would i use sql or eloquent orm to find records that fit the description of a value of 14? i.e 14 falls between min_val and max_val?
Thanks</p>

答:
If I understand you correctly, you can use the BETWEEN operator. For example:

```<code>SELECT * FROM yourtable WHERE 14 BETWEEN min_value AND max_value;
</code>```

which is roughly equal to

```<code>SELECT * FROM yourtable WHERE min_value <= 14 AND max_value >= 14;
</code>```

Title: Find value in range sql

Body:
If I understand you correctly, you can use the BETWEEN operator. For example:

SELECT * FROM yourtable WHERE 14 BETWEEN min_value AND max_value;

which is roughly equal to

SELECT * FROM yourtable WHERE min_value <= 14 AND max_value >= 14;


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答:
Yes, F# will perform better.

Here are some performance results for a single-thread algorithm implemented in different languages (benchmarking activation function approaches for the neural networks):

C#:

```<code>10^7 iterations using Sigmoid1() took 3899,1979 ms
10^7 iterations using Sigmoid2() took 411,4441 ms
</code>```

Pure C:

```<code>10^7 iterations using sigmoid1: 628 ms
10^7 iterations using sigmoid2: 157 ms
</code>```

F#:

```<code>10^7 iterations using sigmoid1: 588.843700 ms
10^7 iterations using sigmoid2: 156.626700 ms
</code>```

More details

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

Body:
Yes, F# will perform better.

Here are some performance results for a single-thread algorithm implemented in different languages (benchmarking activation function approaches for the neural networks):

C#:

10^7 iterations using Sigmoid1() took 3899,1979 ms
10^7 iterations using Sigmoid2() took 411,4441 ms

Pure C:

10^7 iterations using sigmoid1: 628 ms
10^7 iterations using sigmoid2: 157 ms

F#:

10^7 iterations using sigmoid1: 588.843700 ms
10^7 iterations using sigmoid2: 156.626700 ms

More details

OwnerDisplayName: Rinat Abdullin


答:
There's nothing wrong with this in principle, as long as you don't AND all of the values indiscriminately; that is, you should terminate as soon as the first false is found:

```<code>function array_and(array $array)
{
    foreach ($array as $value)
    {
        if (!$value)
        {
            return false;
        }
    }

    return true;
}
</code>```

Title: Array AND() ? Logical ANDing of all elements

Body: I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

Body:
There's nothing wrong with this in principle, as long as you don't AND all of the values indiscriminately; that is, you should terminate as soon as the first false is found:

function array_and(array $array)
{
    foreach ($array as $value)
    {
        if (!$value)
        {
            return false;
        }
    }

    return true;
}


问:
How to do energy havesting with nucleo NFC02A1
I'm starting with nucleo L476RG , MEMS and NFC02A1.
I try to write MEMS data to nfc tag and its work.
My problems is when i try to use energy harvesting mode, it  doesn't work and i don't know why. I use the exemple within the nfc cube but it doesn't work.

Below is the function for harvesting that doesn't work

```<code>void Enable_EnergyHarvesting( void )
{
    NFCTAG_ExtDrvTypeDef toto;
    /* Initialise M24LR Board */
    if( BSP_NFCTAG_GetExtended_Drv() != NULL )
    {
        /* Enable Energy Harvesting */
        BSP_NFCTAG_GetExtended_Drv()->Enable_EH_mode();
        BSP_NFCTAG_GetExtended_Drv()->SetEH( );

        /* Store configuration in non Volatile Memory */
        BSP_NFCTAG_GetExtended_Drv()->WriteEH_Cfg( M24LR_EH_Cfg_6MA);
   }
}

int main( void )
{
   HAL_Init();
   /* Configure the system clock */
   SystemClock_Config();

   /* Init of the Nucleo Board led */
   BSP_LED_Init(LED2);
   //M24lr_IO_Init();
   /* Init of the Leds on X-NUCLEO-NFC02A1 board */
   NFC02A1_LED_Init( );
   NFC02A1_LED_ON( GREEN_LED );
   wait_ms( 500 );
   NFC02A1_LED_ON( BLUE_LED );
   wait_ms( 500 );
   NFC02A1_LED_ON( ORANGE_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( GREEN_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( BLUE_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( ORANGE_LED );

   /* Init M24LR driver */
   while( BSP_NFCTAG_Init( ) != NFCTAG_OK );

   Enable_EnergyHarvesting( );

   /* Check if no NDEF detected, init mem in Tag Type 5 */
   if( NfcType5_NDEFDetection( ) != NDEF_OK )
   {
       CCFileStruct.MagicNumber = NFCT5_MAGICNUMBER_E1_CCFILE;
       CCFileStruct.Version = NFCT5_VERSION_V1_0;
       CCFileStruct.MemorySize = ( M24LR_MAX_SIZE / 8 ) & 0xFF;
       CCFileStruct.TT5Tag = 0x05;

       /* Init of the Type Tag 5 component (M24LR) */
       while( NfcType5_TT5Init( ) != NFCTAG_OK );
   }

   /* Set the LED2 on to indicate Init done */
   NFC02A1_LED_ON( BLUE_LED );

   /* Prepare URI NDEF message content */
   strcpy( URI.protocol,URI_ID_0x01_STRING );
   strcpy( URI.URI_Message,/"google.com");
   strcpy( URI.Information,"\0" );

   /* Write NDEF to EEPROM */
   while( NDEF_WriteURI( &URI ) != NDEF_OK );

   /* Set the LED3 on to indicate Programing done */
   NFC02A1_LED_ON( ORANGE_LED );

   while( 1 )
   {

   }
}
</code>```

答:
Try with this configuration:

/* Store configuration in non Volatile Memory */

BSP_NFCTAG_GetExtended_Drv()->WriteEH_Cfg(M24LR_EH_Cfg_300UA);

May be your reader does not deliver sufficient power.

Body:
I'm starting with nucleo L476RG , MEMS and NFC02A1.
I try to write MEMS data to nfc tag and its work.
My problems is when i try to use energy harvesting mode, it  doesn't work and i don't know why. I use the exemple within the nfc cube but it doesn't work.

Below is the function for harvesting that doesn't work

void Enable_EnergyHarvesting( void )
{
    NFCTAG_ExtDrvTypeDef toto;
    /* Initialise M24LR Board */
    if( BSP_NFCTAG_GetExtended_Drv() != NULL )
    {
        /* Enable Energy Harvesting */
        BSP_NFCTAG_GetExtended_Drv()->Enable_EH_mode();
        BSP_NFCTAG_GetExtended_Drv()->SetEH( );

        /* Store configuration in non Volatile Memory */
        BSP_NFCTAG_GetExtended_Drv()->WriteEH_Cfg( M24LR_EH_Cfg_6MA);
   }
}

int main( void )
{
   HAL_Init();
   /* Configure the system clock */
   SystemClock_Config();

   /* Init of the Nucleo Board led */
   BSP_LED_Init(LED2);
   //M24lr_IO_Init();
   /* Init of the Leds on X-NUCLEO-NFC02A1 board */
   NFC02A1_LED_Init( );
   NFC02A1_LED_ON( GREEN_LED );
   wait_ms( 500 );
   NFC02A1_LED_ON( BLUE_LED );
   wait_ms( 500 );
   NFC02A1_LED_ON( ORANGE_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( GREEN_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( BLUE_LED );
   wait_ms( 500 );
   NFC02A1_LED_OFF( ORANGE_LED );

   /* Init M24LR driver */
   while( BSP_NFCTAG_Init( ) != NFCTAG_OK );

   Enable_EnergyHarvesting( );

   /* Check if no NDEF detected, init mem in Tag Type 5 */
   if( NfcType5_NDEFDetection( ) != NDEF_OK )
   {
       CCFileStruct.MagicNumber = NFCT5_MAGICNUMBER_E1_CCFILE;
       CCFileStruct.Version = NFCT5_VERSION_V1_0;
       CCFileStruct.MemorySize = ( M24LR_MAX_SIZE / 8 ) & 0xFF;
       CCFileStruct.TT5Tag = 0x05;

       /* Init of the Type Tag 5 component (M24LR) */
       while( NfcType5_TT5Init( ) != NFCTAG_OK );
   }

   /* Set the LED2 on to indicate Init done */
   NFC02A1_LED_ON( BLUE_LED );

   /* Prepare URI NDEF message content */
   strcpy( URI.protocol,URI_ID_0x01_STRING );
   strcpy( URI.URI_Message,/"google.com");
   strcpy( URI.Information,"\0" );

   /* Write NDEF to EEPROM */
   while( NDEF_WriteURI( &URI ) != NDEF_OK );

   /* Set the LED3 on to indicate Programing done */
   NFC02A1_LED_ON( ORANGE_LED );

   while( 1 )
   {

   }
}