text:
Q: MySql IN clause using variable I have a table called product with id and name columns.
I want to search for product using multiple names. This list is coming from another select and I put it in a variable.
What I want to do is: SELECT the id of product that has the same name with the list elements.
-- works but I have my values in a variable.
select distinct id from product where name IN ('Chair','Mattresses','Table');

-- doesn't work -  THIS IS WHAT I WANT
set @products = 'Chair,Mattresses,Table';
select distinct id from product where name IN (SELECT CONCAT("'", REPLACE(@products, ",", "','"), "'"));

-- doesn't work -- THIS IS ANOTHER ALTERNANATIVE FOR ME BUT IT DOESN'T WORK
set @products = 'Chair,Mattresses,Table';
set @commaSeparated = (SELECT CONCAT("'", REPLACE(@products, ",", "','"), "'"));
select distinct id from product where name IN (@commaSeparated);

EDIT:
More detail information is presented below.
-- Temporary table to store the data from the FIRST query
CREATE TEMPORARY TABLE DataToProcess (
    productNames TEXT NOT NULL,
    locations TEXT NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci;

-- Read data and store in Temporary table
INSERT INTO DataToProcess
    SELECT
      REPLACE(REPLACE(names, '\r\n', ','), "'", "\'") AS productNames,
      REPLACE(REPLACE(locations, '\r\n', ','), "'", "\'") AS locations
    FROM table1
      LEFT JOIN table2 USING (id)
    WHERE table1.startDate <= NOW()
          AND table2.endDate > DATE_ADD(NOW(), INTERVAL 15 MINUTE);

Here, I will iterate through the records of DataToProcess temporary table
-- Define curser_finished
DECLARE product_cursor_finished INTEGER DEFAULT 0;

-- declare cursor for DataToProcess
DECLARE product_cursor CURSOR FOR SELECT * FROM DataToProcess;

-- declare NOT FOUND handler for product_cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET product_cursor_finished = 1;

OPEN product_cursor;

get_productsAndLocations: LOOP

    FETCH product_cursor INTO products, locations;

    **** THIS IS WHERE I WANT TO USE `SELECT WHERE IN`

END LOOP get_ProductsAndLocations;

CLOSE product_cursor;

A: You can use FIND_IN_SET() for that:
SET @products = 'Chair,Mattresses,Table';

SELECT DISTINCT
    `id`
FROM
    `product`
WHERE
    FIND_IN_SET(`name`, @products);

Other option is to use REGEXP():
SET @products = 'Chair,Mattresses,Table';
SET @products = REPLACE(@products,",","|");

SELECT DISTINCT
    `id`
FROM
    `product`
WHERE
    `name` REGEXP @products

A: You can just put it in one SELECT, if that is of course an option..
SELECT DISTINCT
   id
FROM
   product p
WHERE
   p.name IN (SELECT include_names FROM include_this)

Or use the FIND_IN_SET function


text:
Q: how to disable facebook auto login in my application using new Facebook Javascript SDK? I am now using Facebook Javascript SDK for connecting my application through Facebook login. If new user coming to connect with my application, the user details will be saved in the database. If the user already exists, then the appropriate page will be shown to the user through Facebook login. Sometimes if I login in Facebook in new tab of browser, during that time I come to Facebook connecting page in my application, the Facebook login is automatically login into my application page. I want to login into my application only after click of the facebook login button.How to do?
        <div id="fb-root">
            </div>

            <script>
            //FB initialization
               window.fbAsyncInit = function () {
                    FB.init({
                        appId: 'XXXXXXXXXX',
                        channelUrl : '//connect.facebook.net/en_US/all.js',
                        status     : true,
                        cookie     : true
                    });
        //Event to check status of the login status
                    FB.Event.subscribe('auth.authResponseChange', function (response) {
                        if (response.status === 'connected') {
                            base_url = base_url + "&access_token=" + response.authResponse.accessToken + "&userId=" + response.authResponse.userID;
                            window.location.href = base_url;
                        }
                        else if (response.status === 'not_authorized') {
              FB.login();
            } else {
              FB.login();
            }
                    });

                };
// Load the SDK asynchronously
            (function (d) {
                var js, id = 'facebook-jssdk',
               ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) { return; }
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            } (document));

        <fb:login-button scope="email,read_stream,publish_stream,offline_access,user_location"></fb:login-button>

A: I am not entirely sure what your problem is, but it sounds like your login function is firing on pageload as opposed to after a particular event, such as click.
If you wanted to bind the login function to clicks on an element with an id of 'login', then the following function (in jQuery) would work.
$(function() {
  $('#login').click(function() {
    FB.login(function(response) {
      // rest of function definition
    }, {scope: 'email'});
  });
});

And similarly, you might call FB.logout() after some other event.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is a Timer ID? I feel like this is a dumb question. But I've been struggling to understand some concepts and examples because they implement a timer ID in them and I don't really get what it is. Is it just a variable you assign a timer to?

A: Assuming JavaScript because of the "settimeout" tag you added, setTimeout and setInterval return an ID if they succeeded in being setup. This ID can be used to refer to that timeout or interval. Generally, this is used to cancel a timeout before it finishes, or stop an interval from running again. You can do this with the clearTimeout and clearInterval functions.
More information: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
In the future, you can find information like this very easily with a search engine.


text:
Q: Changing the focus of the edittexts in a list view Using the next Key in SoftKeyBoard How to configure the next button to change focus to the edit texts in the consecutive rows of the ListView..
I cannot use the android:nextFocusDown="@+id/...." since the edit texts have same id.

A: try this and let me know If this is what u wanted?
 <EditText android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:imeOptions="actionDone"
    android:singleLine="true" />

actionDone imeOption doesn't work on EditText in Android 2.3

A: To change focus of EditText in rows of ListView you can use following XML example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout         xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edit_1"
        android:nextFocusRight="@+id/edit_2"
        android:imeOptions="actionNext"
        />

    <EditText
        android:id="@+id/edit_2"
        android:nextFocusRight="@+id/edit_3"
        android:imeOptions="actionNext"
        />

   <EditText
        android:id="@+id/edit_3"
        android:nextFocusRight="@+id/edit_4"
        android:imeOptions="actionNext"
        />

   <EditText
        android:id="@+id/edit_4"
        android:nextFocusDown="@+id/edit_1"
        android:imeOptions="actionNext"
        />

</LinearLayout>


text:
Q: "'Timestamp' object does not support indexing", 'occurred at index 0') I am trying to work on a dataframe where I have to make a new column which will fill the result given by the xnpv function
def xnpv(rate, values, dates):

    if rate <= -1.0:
        return float('inf')
    d0 = dates[0]    # or min(dates)
    return sum([ vi / (1.0 + rate)**((di - d0).days / 365.0) for vi, di in zip(values, dates)])

F['newcolumn'] = F.apply(lambda x: xnpv(0.1, x['Cash'], x['Date']), axis=1)

when I execute the above code it gves me the following error: TypeError: ("'Timestamp' object does not support indexing", 'occurred at index 0')
Please help me solve this issue
When i use the following expression
F['newcolumn'] = F.groupby('Name').apply(lambda x: xnpv(0.1, x['Cash'], x['Date']))

it gives me another error : KeyError: 0

A: I think the problem is happening at step
d0 = dates[0]

dates will be a timeseries. I think you were assuming it would be the full "dates" column. When you itterate over a pandas series, with apply(lambda x: f(x) axis=1) x is a row, not a column. therefore x["date"] will be a timestamp, not a series as you were expecting.
Edit: maybe a vecotrised rather than one relying on .apply() would be better?
def xnpv(rate, values, dates):
    return  values / (1.0 + rate) ** ((dates - dates.min()).dt.days / 365.0)
F['newcolumn'] = xnpv(0.1, F['Cash'], F['Date'])

Edit 2: This seems to work for me. Is it consistent with what you were expecting?
F = pd.DataFrame({"name":['a','a','a','a','b','b','b','b'],
              "cash":[1,1,3,4,1,2,4,5],
              "date":['2017-01-01','2017-02-01','2017-03-01','2017-04-01',
                     '2017-01-01','2017-02-01','2017-03-01','2017-04-01']
             })
F["date"] = pd.to_datetime(F["date"])

def xnpv(rate, values, dates):
    return  sum(values / (1.0 + rate) ** ((dates - dates.min()).dt.days / 365.0))
F.groupby('name').apply(lambda x: xnpv(0.1, x['cash'], x['date']))


text:
Q: ComboBox.SelectionChanged doesn't catch the first selection I need to fill textboxes depending on the item selected in a combobox. I fill combo async and in Completed event I have the following code
combo.ItemsSource = e.Result;
combo.DisplayMemberPath = "Name";
combo.SelectedIndex = -1;

Then in the SelectionChanged event of the combo, I catch the selected object
MyClass mc= ((ComboBox)sender).SelectedItem as MyClass;
tbxName.Text = mc.Name;
...

However, when I load the project and select any event for the 1st time, NOTHING happens. Every other time (2nd, 3rd, nth) the data is correctly caught and displayed.
So I need to know why the combo doesn't catch the first selection? That's the reason I have the code combo.SelectedIndex = -1 (when the app loads, combo is empty - selection -1 works).

A: Solved by putting the code inside Completed event. Now I have delay in executing everything, but it works.


text:
Q: Algorithm to answer questions on dominated input Consider a setting where we see inputs one-by-one, with each input being an $n$-tuple $(a_1,a_2,...,a_n)$, where each $a_i\in\{0,1\}$. For each new input we see, we have to answer two questions:
1) Have we seen this input before?
2) Is the input dominated by some input we've seen before? (An input $A=(a_1,\ldots,a_n)$ is said to be dominated by an input $B=(b_1,\ldots,b_n)$ if $a_i\leq b_i$ for all $i$.)
How fast can we answer these two questions for each input?
For question 1), we can use a hash table. We check whether the input has been seen before in $O(1)$ time, and if not, insert the input into the hash table in $O(1)$ time.
To accommodate question 2), the trivial way is to compare the new input with each one of the previous inputs, which would take $O(k)$ time, where $k$ is the number of elements in the hash table. This could be up to $O(2^n)$ time. Is there a way to reduce this to something polynomial in $n$?

A: If we treat each $n$-tuple as a subset of $1,2,\ldots, n$ in the natural way, then we see that $A$ dominates $B$ if $B$ is a subset of $A$. The paper "New Algorithms for Subset Query, Partial Match, Orthogonal Range Searching and Related Problems" (pdf) by Charikar, Indyk, and Panigrahy presents some time/space tradeoff results for this problem.

A: I 'll take it you mean $a_i\in (0,1)$ not $\{0,1\}$ because this is a binary string. Non the less, what I am thinking apllies to both cases.
Since you get your tuples one by one we will sort them with an insertion sort algorithm a little modified to sort the tuples lexicographically . This is like a dictionary, e.g. $(1, 0.5, 0.4) \geq (1, 0.6, 1)\geq(0.9, 1,0.6)$ because: $0.5<0.6$.
Leaving the details,
1) when a tuple is sorted in its place it can only be identical with the ones adjacent to it, which is easy to check.
2) Starting from the last tuple and going up, check if each tuple is dominated by its previous. If $A$ and $B$ are two tuples and $A$ dominates $B$ then for sure $a_1\geq b_1$ and $A\geq B$, $A$ must be greater than $B$ to dominate $B$.
The overall time of insertion sort is $O(n^2)$ and the checks can be performes in linear time after the inputs are sorted.


text:
Q: Windows - change logged in user from command line I'm working on a project where I want to switch from a normal account to a non-logged in admin account from the command line, and the best I've managed is a psexec chain to get an NT AUTHORITY\SYSTEM shell, using tscon to switch to a logged-in admin account:
PsExec64.exe -u administrator -p xxxxxxx
PsExec64.exe -s tscon 3 /dest:console

*

*Using one psexec doesn't work for some reason, as I get access denied when using -s right away
Is there a simple way to create a new session with a logged-in administrator account (for which I know the password) or at least open a new explorer.exe instance; if not possible, could someone explain why?

*

*The best I got was 2s of an admin explorer.exe, then it restarts in the normal user

To clarify, what I want to do is a simple .exe / command line that locks me out of the current user and logs me in to the admin one without any other interaction. (This would then be used in conjunction with some other software to allow admin access under certain conditions)
@Cpt.Whale suggested an RDP to 127.0.0.2 which I've seen while doing some research, but he is right in that you can't have more than one active user (Just tested)
I can't really add much as to why I want this, but the end goal would be giving someone a token that allows to then switch to admin without the admin password, the token would be then invalidated giving access only once. I need to have the full desktop because the user given permission would have to start other programs and browse the filesystem as admin


text:
Q: Node-RED: where do I find docs for RED.nodes.createNode/getNode/eachNode/ I may be blind, but I cannot find documentation for functions I've seen in many node implementations as there are:

*

*RED.nodes.createNode()

*RED.nodes.getNode()

*RED.nodes.eachNode()

*RED.nodes.originaFlow()

including important details concerning nodes shown in the editor and those actually used by the runtime.
Everything I found seems to be horribly outdated.
For that reason: where do I find up-to-date docs for the mentioned functions?

A: Just to not leave this question unanswered:
answers for this question and similar ones (dealing with the internals of Node-RED) may be found in some postings written by Nick O'Leary for the Node-RED forum
The following is just a copy from there:
Everything that follows only applies in the editor. This is no equivalent in the runtime.
Finding by name
There's no direct way to find anything by its 'name' - names are optional fields and can be left blank. They are also not unique. Under the covers you should be using the id field to reference other nodes.
let node = RED.nodes.node(id);

To get any nodes whose name property is set to a particular value:
let results = [];
RED.nodes.eachNode(function(node) {
   if (node.name === "HELLO") {
      results.push(node);
   }
});

(If you dig around the code, you'll see RED.nodes.filterNodes exists - that currently only filters on z and type rather than any other property... but it would be simply enough to update to handle any property... we have never needed it)
The above works for regular flow nodes. To do the same for Config nodes or Flows, you'd do the same but with eachConfig() and eachWorkspace() respectively.
Find connected nodes of a given node
let node = RED.nodes.node(nodeId);
let allConnectedNodes = RED.nodes.getAllFlowNodes(node)

If you just want the nodes that come 'before' or 'after' this one, you can do:
let allUpstreamNodes = RED.nodes.getAllUpstreamNodes(node);
let getAllDownstreamNodes = RED.nodes.getAllDownstreamNodes(node)

Additional information can be found in another posting, which is also copied below (the first code line illustrates how to access a node by its internal id):

how to find the name of the tab a given node is placed on

let node = RED.nodes.node(id)

let tab = RED.nodes.workspace(node.z) || RED.nodes.subflow(node.z);


text:
Q: Dynamic list of checkboxes with onclick functions I have a page that returns a list of items backs from a database. I want to add each item to my android fragment as a checkbox dynamically with an onClick, that can tell if an item is being checked or un-checked.
How can I add checkboxes dynamically with on-clicks and different titles for each?
Below is the xml I am inserting the checkboxes into:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#e5e5e5"

    android:layout_height="match_parent" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:orientation="vertical"
                android:background="@drawable/bg_card">

                <!-- Card Contents go here -->

                <TextView
                    android:id="@+id/styleDescription"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:textSize="15sp"
                    android:padding="5dip"

                    ></TextView>

                <CheckBox
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="New CheckBox"
                    android:id="@+id/checkBox" />

            </LinearLayout >

        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:orientation="horizontal"
                android:background="@drawable/bg_card">

                <!-- Card Contents go here -->

                <Button
                    android:id="@+id/buttonAddList"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Create List"

                    style="?android:attr/borderlessButtonStyle"
                    android:textColor="@color/orange"
                    android:textStyle="bold"
                    />

            </LinearLayout >

        </FrameLayout>

    </LinearLayout>

</ScrollView>

I currently have one checkbox in the above code. I plan on removing this. That checkbox is just to show where I want my check boxes to show up.

A: What you need to do first is add an id to your LinearLayout (in that XML file), the one which is going to hold the CheckBoxes. Then, in the code you need to get that LinearLayout by its id and use addView() to add CheckBoxes that you create dynamically. I imagine in pseudocode it'd look like this:
for (int i = 0; i < numberOfCheckBoxes; i++) {

    CheckBox checkBox = new CheckBox();
    checkBox.setTitle("Your title");
    checkBox.setOnClickListener(new OnClickListener() {

        // Your code to be executed on click
    });

    linearLayout.addView(checkBox);
}

Does this help?
PS: It'd be nice if you kept your code clean - ADT (and I believe Eclipse too) gives you the Shift+Ctrl+F shortcut to indent your code automatically - use it as often as possible ;)

A: Since you are processing database items, I suggest using a CursorAdapter to do the heavy work for you. A CursorAdapter, like any of the Adapter classes can process the database items and custom-fit them into a layout of your choice, to use in a ListView.
You have to make adjustments to your code:

*

*Create a layout file that contains whatever you want to put in the dynamic list. This is an example, say it's named list_contents.xml:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:orientation="vertical"
        android:background="@drawable/bg_card">

        <!-- Card Contents go here -->

        <TextView
            android:id="@+id/styleDescription"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:textSize="15sp"
            android:padding="5dip"

            ></TextView>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New CheckBox"
            android:id="@+id/checkBox" />

    </LinearLayout >

</FrameLayout>

*Then, instead of returning a List from your AsyncTask, return the Cursor itself
from your database. This Cursor will be processed by CursorAdapter. I recommend this guide:
http://www.gustekdev.com/2013/05/custom-cursoradapter-and-why-not-use.html

*Implement the CursorAdapter methods:
In your implementation of newView(), inflate list_contents.xml (Note that if you use ResourceCursorAdapter you wouldn't need to do this)
In your implementation of CursorAdapter.bindView() do this:
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);
checkbox.setText(cursor.getString(cursor.getColumnIndex(YOUR_DATABASE_COLUMN_NAME_FOR_CHECKBOX_VALUES)));
checkbox.setOnCheckedChangedListener(listenerInitializedSomewhereFromFragmentCode);

*

*Change your ScrollView to a ListView (it can be inside any Layout), and give it an id, say R.id.listview.

*Finally, in the part where you process the List from the database, where we now have a Cursor instead, just do this:
CustomCursorAdapter cca = new CustomCursorAdapter(getActivity(), resultFromDatabase, 0);
listView.setAdapter(cca);
Note: getActivity() is for when you are working inside a Fragment. It should be a context, so inside an Activity it can just be "this".
Note2: listView should have been initialized at this point via findViewById.
Note3: If listView already has an Adapter and Cursor set, you should consider calling listView.getAdapter().changeCursor() instead.

A: Simple Code In Kotlin
    fun createCheckbox() {
    var arr_cb = arrayOfNulls<CheckBox>(checkbox_size)
    val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
    val ll = LinearLayout(this)
    ll.orientation = LinearLayout.VERTICAL

    for (i in 0 until arr_cb.size) {
        arr_cb[i] = CheckBox(this)
        arr_cb[i]?.text = health_status.get(i).toString()
        arr_cb[i]?.setPadding(25, 0, 0, 0)
        arr_cb[i]?.id = i
        arr_cb[i]?.tag = health_status[i]
        arr_cb[i]?.setTextColor(resources.getColor(R.color.title_color))
        arr_cb[i]?.setOnCheckedChangeListener(
            arr_cb[i]?.let {
                handleCheck(it)
            })

        arr_cb[i]?.buttonTintList =
            ColorStateList.valueOf(resources.getColor(R.color.theme_color))
        ll.addView(arr_cb[i])
    }
    layout.addView(ll)
}

handleCheck method
    private fun handleCheck(chk: CheckBox): CompoundButton.OnCheckedChangeListener? {
    return object : CompoundButton.OnCheckedChangeListener {
        override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
            if (!isChecked) {
                //uncheck
            } else {
                //check
            }
        }
    }
}

and you want to do something use direct checkboxList object like as
val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
    val ll = LinearLayout(this@MedicalHistoryActivity)
    ll.orientation = LinearLayout.VERTICAL
    for (i in 0 until health_status.size) {
        arr_cb[i]?.isEnabled = true
        // do something like change color or more
    }
    layout.addView(ll)

for enable checkbox or more.
Thank you


text:
Q: How to decode audio via FFmpeg in Android I am writing a player for Android with FFmpeg compiled for Android NDK.
I could open the file through FFmpeg and wrote this:
av_register_all();

char* str = (*env) -> GetStringUTFChars(env, argv, 0);
__android_log_print(ANDROID_LOG_INFO, "HelloNDK!", str, str);

if (av_open_input_file (&pFormatCtx, str, NULL, 0, NULL) != 0)
    return -2; // Couldn't open file

// Retrieve stream information
if (av_find_stream_info(pFormatCtx) < 0)
    return -3; // Couldn't find stream information

// Dump information about file onto standard error
dump_format(pFormatCtx, 0, argv, 0);

// Find the first video stream
videoStream =- 1;
audioStream =- 1;
for (i = 0; i < pFormatCtx->nb_streams; i++) {
    if (pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO && audioStream <0) {
        audioStream = i;
    }
}

if (audioStream == -1)
    return -5;

aCodecCtx = pFormatCtx->streams[audioStream]->codec;
// Set audio settings from codec info

aCodec = avcodec_find_decoder(aCodecCtx->codec_id);

if (!aCodec) {
    fprintf (stderr, "Unsupported codec! \n");
    return -1;
}

avcodec_open (aCodecCtx, aCodec);

How can I now decode the audio and return it to the Java program? Maybe somebody could give me an example
EDIT:
When using avcodec_decode_audio3
Get the following:

03-22 07:54:00.988: INFO / DEBUG (31): *  ** *  ** *  ** * * * ** *  ** *
03-22 07:54:00.988: INFO / DEBUG (31): Build fingerprint: 'generic / sdk / generic /: 2.2/FRF91/43546: eng / test-keys'
03-22 07:54:00.988: INFO / DEBUG (31): pid: 435, tid: 435>>> org.libsdl.app <<<
03-22 07:54:00.998: INFO / DEBUG (1931): signal 11 (SIGSEGV), fault addr 00000000
03-22 07:54:00.998: INFO / DEBUG (1931): r0 00000000 r1 00000000 r2 81893210 r3 00000000
03-22 07:54:01.008: INFO / DEBUG (1931): r4 8189324c r5 818931d0 r6 00000000 r7 00000000
03-22 07:54:01.008: INFO / DEBUG (1931): r8 00000200 r9 00000600 10 00000300 00000500 fp
03-22 07:54:01.019: INFO / DEBUG (1931): ip 81350868 sp bef4c438 lr 8112cb3b pc 8112cb6c cpsr 80000030
03-22 07:54:01.369: INFO / DEBUG (31): # 00 pc 0012cb6c / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.369: INFO / DEBUG (31): # 01 pc 0012db46 / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.379: INFO / DEBUG (31): # 02 pc 0013052e / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.379: INFO / DEBUG (31): # 03 pc 00132142 / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.389: INFO / DEBUG (31): # 04 pc 001a2836 / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.399: INFO / DEBUG (31): # 05 pc 00024ee6 / data / data / org.libsdl.app / lib / libtest.so
03-22 07:54:01.399: INFO / DEBUG (31): # 06 pc 00013974 / system / lib / libdvm.so
03-22 07:54:01.409: INFO / DEBUG (31): # 07 pc 0003de3c / system / lib / libdvm.so
03-22 07:54:01.409: INFO / DEBUG (31): # 08 pc 00037216 / system / lib / libdvm.so
03-22 07:54:01.419: INFO / DEBUG (31): # 09 pc 000432ec / system / lib / libdvm.so
03-22 07:54:01.419: INFO / DEBUG (31): # 10 pc 00018714 / system / lib / libdvm.so
03-22 07:54:01.439: INFO / DEBUG (31): # 11 pc 0001e8c4 / system / lib / libdvm.so
03-22 07:54:01.439: INFO / DEBUG (31): # 12 pc 0001d790 / system / lib / libdvm.so
03-22 07:54:01.439: INFO / DEBUG (31): # 13 pc 0005408e / system / lib / libdvm.so
03-22 07:54:01.449: INFO / DEBUG (31): # 14 pc 0005bde2 / system / lib / libdvm.so
03-22 07:54:01.449: INFO / DEBUG (31): # 15 pc 00018714 / system / lib / libdvm.so
03-22 07:54:01.459: INFO / DEBUG (31): # 16 pc 0001e8c4 / system / lib / libdvm.so
03-22 07:54:01.469: INFO / DEBUG (31): # 17 pc 0001d790 / system / lib / libdvm.so
03-22 07:54:01.469: INFO / DEBUG (31): # 18 pc 00053eec / system / lib / libdvm.so
03-22 07:54:01.479: INFO / DEBUG (31): # 19 pc 0004072c / system / lib / libdvm.so
03-22 07:54:01.479: INFO / DEBUG (31): # 20 pc 00034454 / system / lib / libdvm.so
03-22 07:54:01.489: INFO / DEBUG (31): # 21 pc 0002c930 / system / lib / libandroid_runtime.so
03-22 07:54:01.489: INFO / DEBUG (31): # 22 pc 0002d85c / system / lib / libandroid_runtime.so
03-22 07:54:01.499: INFO / DEBUG (31): # 23 pc 00008c86 / system / bin / app_process
03-22 07:54:01.519: INFO / DEBUG (31): # 24 pc 0000d362 / system / lib / libc.so

Can I use avcodec_decode_audio2?
I have in recent days has reached the following code:
AVFormatContext * pFormatCtx;
int i, videoStream, audioStream;
AVCodecContext * pCodecCtx;
AVCodec * pCodec;
AVFrame * pFrame;
AVPacket packet;
int frameFinished;
float aspect_ratio;

AVCodecContext * aCodecCtx;
AVCodec * aCodec;

AVCodecContext * c = NULL;
int out_size, len;
int16_t * audio_buf;
uint8_t * outbuf;
uint8_t inbuf [AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];

av_register_all ();

char * str = (* env) -> GetStringUTFChars (env, argv, 0);

if (av_open_input_file (& pFormatCtx, str, NULL, 0, NULL)! = 0)
return -150;

if (av_find_stream_info (pFormatCtx)  nb_streams; i + +) {

if (pFormatCtx-> streams [i] -> codec-> codec_type == CODEC_TYPE_VIDEO & & videoStream  streams [i] -> codec-> codec_type == CODEC_TYPE_AUDIO & & audioStream  streams [audioStream] -> codec;

aCodec = avcodec_find_decoder (aCodecCtx-> codec_id);
if (! aCodec) {
fprintf (stderr, "Unsupported codec! \ n");
return -45;
}

avcodec_open (aCodecCtx, aCodec);
c = avcodec_alloc_context ();
packet_queue_init (& audioq);
while (av_read_frame (pFormatCtx, & packet)> = 0) {

if (packet.stream_index == videoStream) {

} Else if (packet.stream_index == audioStream) {

packet_queue_put (& audioq, & packet);
int len1, data_size;
data_size = 417;

len1 = avcodec_decode_audio2 (aCodecCtx, (int16_t *) audio_buf, & data_size,
packet.data, packet.size);
return packet.size;
} Else {
av_free_packet (& packet);
}

}

return 0;

In this case, when the avcodec_decode_audio2 I got -1. What I did wrong?
Note:
When I drove int data_size = 417; then DEBUG does not appear and the function returns -1, but when I drive a: int data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE * 2; then vyskakievaet DEBUG in your function so in my own! How can this be solved?
EDIT2:
My new code:

JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_main( JNIEnv* env, jobject obj, int argc, jstring argv, jbyteArray array) {
      AVFormatContext *pFormatCtx;
      int             i, videoStream, audioStream;
      AVCodecContext  *pCodecCtx;
      AVCodec         *pCodec;
      AVFrame         *pFrame;
      AVPacket        packet;
      int             frameFinished;
      float           aspect_ratio;

      AVCodecContext  *aCodecCtx;
      AVCodec         *aCodec;

      SDL_Overlay     *bmp;
      SDL_Surface     *screen;
      SDL_Rect        rect;
      SDL_Event       event;
      SDL_AudioSpec   wanted_spec, spec;
      AVCodecContext *c= NULL;
         int out_size, len;
         int16_t *audio_buf;
         uint8_t *outbuf;
         uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
         char *pAudioBuffer = (char *) av_malloc (AVCODEC_MAX_AUDIO_FRAME_SIZE * 2);

      av_register_all();

      char *str = (*env)->GetStringUTFChars(env, argv, 0);

      if(av_open_input_file(&pFormatCtx, str, NULL, 0, NULL)!=0)
        return -150; // Couldn't open file

      if(av_find_stream_info(pFormatCtx)nb_streams; i++) {
        if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO &&
           videoStream streams[i]->codec->codec_type==CODEC_TYPE_AUDIO &&
           audioStream streams[audioStream]->codec;

      aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
      if(!aCodec) {
        fprintf(stderr, "Unsupported codec!\n");
        return -45;
      }

      avcodec_open(aCodecCtx, aCodec);
      c=avcodec_alloc_context();
      packet_queue_init(&audioq);
        while (av_read_frame(pFormatCtx, &packet)>= 0) {
            if (aCodecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
                        int data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE * 2;
                        int size=packet.size;
                        while(size > 0) {
                                int len = avcodec_decode_audio3(aCodecCtx, (int16_t *) pAudioBuffer, &data_size, &packet);

                                jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);
                                memcpy(bytes, (int16_t *) pAudioBuffer, size);
                                (*env)->ReleaseByteArrayElements(env, array, bytes, 0);

                                size = packet.size-len;
                                }
            }

     }

 return 5;
}

A: Use audiotrack class to do the work for you. You can do something like this.
JAVA side.
            AudioTrack track;

            int bufSize = AudioTrack.getMinBufferSize(44100,                                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                            AudioFormat.ENCODING_PCM_16BIT);

            track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                        AudioFormat.ENCODING_PCM_16BIT, bufSize, AudioTrack.MODE_STREAM);

            track.play();

            while(true){
            readBufferFromNative(); //update buffer from native code

                    ....................
                    ....................
                    }

On native Side : You need to read the frames and convert them into raw pcm format first and then start filling the audio buffer continuously. When the buffer is full, it will automatically play.
JNIEXPORT int JNICALL Java_com_ffmpeg_Main_jniMainEntry(JNIEnv* env, jobject obj, jstring input) {

    const char * pszFileName = (*env)->GetStringUTFChars(env, input, 0);
    AVFormatContext * m_fc;
    int err;
    AVPacket pkt;
    char * pAudioBuffer = (char *) av_malloc (AVCODEC_MAX_AUDIO_FRAME_SIZE * 2);
    int i;

    avcodec_register_all ();
    avdevice_register_all ();
    av_register_all ();

    err = av_open_input_file(&m_fc, pszFileName, 0, 0, 0);
    err = av_find_stream_info(m_fc);
    for(i = 0; i<m_fc->nb_streams; i++) {
    if((m_fc->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) || (m_fc->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
    AVCodec *codec = avcodec_find_decoder(m_fc->streams[i]->codec->codec_id);

    if (codec == 0)
            continue;
    err = avcodec_open(m_fc->streams[i]->codec, codec);
    if (err <0)
            continue;
    }
 }
    while (av_read_frame(m_fc, &pkt)>= 0) {
            if (m_fc-> streams[pkt.stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
                    int data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE * 2;
                    int size=pkt->size;
                    while(size > 0) {
                            int len = avcodec_decode_audio3(m_fc->streams[pkt.stream_index]->codec, (int16_t *) pAudioBuffer, &data_size, &pkt);
                            LOGD("data_size %d len %d", data_size, len);
                            size = pkt->size-len;
                            }
            }
 }

}

A: I could not post a comment, so am posting this as an answer.
I'm also trying to do play aac audio using ffmpeg but have a lot of questions on how to get it working.
I tried using http://code.google.com/p/aacplayer-android/ as a reference, but the author of the code is not using avcodec_decode_audio3 for decoding. The playback through AudioTrack stutters a lot and I assume that the buffer is not getting filled by the decoder fast enough for the audiotrack to play.
Is there any other way I can do this?
Once again, sorry for posting this as a answer.


text:
Q: error on create new config database for sharepoint wih New-SPConfigurationDatabase I want setup SharePoint 2010 and SQL Server 2008. When I want to create new configuration database with this command:
    New-SPConfigurationDatabase -DatabaseName "SPConfigDB" -AdministrationContentDatabaseName "SPAdminContentDB" -DatabaseServer "DESKTOP-54TIM0H\dadkh" -Passphrase (ConvertTo-SecureString "mypass" -AsPlainText -force) -FarmCredentials (Get-Credential)

run it in SharePoint 2010 Management Shell I have error:

New-SPConfigurationDatabase : Cannot connect to database master at SQL server at DESKTOP-54TIM0H\dadkh. The database migh
t not exist, or the current user does not have permission to connect to it.
At line:1 char:28
+ New-SPConfigurationDatabase <<<<  -DatabaseName "SPConfigDB" -AdministrationContentDatabaseName "SPAdminContentDB" -Dat
abaseServer "DESKTOP-54TIM0H\dadkh" -Passphrase (ConvertTo-SecureString "mypass" -AsPlainText -force) -FarmCredent
ials (Get-Credential)
    + CategoryInfo          : InvalidData: (Microsoft.Share...urationDatabase:SPCmdletNewSPConfigurationDatabase) [New-S
   PConfigurationDatabase], SPException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPConfigurationDatabase

I follow this guide but the problem not solved.

I create a database with name "SPConfigDB" but no result.

A: problem was IIS!
I check status of IIS and it was not active! so I enable it and problem solved!


text:
Q: How do I let my task-handler function accept a default POST request from GAE pushqueue I am using python and flask rest_plus. I wrote a push task and pushed to a queue with GAE. By default the queue pushes the message of the task to the handler by a POST request. Is there a way I can make my task-handler function accept a POST request , so that it can enter my task handler body and execute my task. Currently I am getting a 405 method not allowed error in the logs . Any help is appreciated!

A: You can add a post() method as your task-handler function, instead of a get()method, see Full Example from the official rest_plus doc.
Alternatively, you can change the HTTP method of the push task to GET when creating it, default is POST.


text:
Q: How can I apply TDD and BDD in a web application that just collects data from many web services and shows them on screen Is it overkill to try TDD and BDD in applications in which we consume web services, collect data based on some conditionals, and then show that data on a web page? I am trying to convince my team to use TDD and BDD, but they don't seem to understand the necessity for this.

A: Especially for communication across system borders I find automated tests extremely helpful.
Setting up the other system in a way so that it shows the behavior which is required for the test is often rather tedious. With automated tests you'd mock those webservices. With this approach development becomes much faster and easier (after overcomming the learning curve for TDD).
Throw in some tests that test the actual webservices to behave as expected and you get early notification if a change in the webservices is going to break your system.


text:
Q: Enlaces automáticos a partir de palabras clave tengo una duda y estoy buscando la manera más fácil de darme a entender... voy a lo siguiente:
Estoy creando un sitio fan de un juego de rol con wordpress y debo agregar muchas publicaciones que describan cada elemento del juego, cada criatura, cada ítem, cada cosa... como es de esperarse en prácticamente todas las páginas existen referencias a otros elementos, ítems o criaturas que han sido publicados con anterioridad o serán publicados en un futuro... estoy hablando de miles de elementos.
Lo que yo haré será crear publicaciones personalizadas con campos personalizados para cada tipo de post, en varios de esos campos tengo que añadir una serie de palabras (ítems del juego) que deben ser enlaces que apunten a esas publicaciones.
¿Existe alguna manera de crear una lista de palabras clave y que éstas palabras se conviertan automáticamente en enlaces internos en cada aparición de esa palabra en todas las publicaciones de mi sitio?
Supongamos que tengo una serie de campos personalizados (custom fields) para una publicación personalizada (custom post) en el cual tengo que agregar una serie de palabras separadas por coma (,) y necesito que esas palabras se conviertan en enlaces internos que apuntan a otras publicaciones.
Un ejemplo real de esas palabras seria esto:
0-5 Small Amethysts, 0-5 Small Emeralds, 0-5 Small Rubies, 0-5 Small Topazes.

¿Existe "algo" que - exceptuando los números y las comas (,) - convierta a cada una de esas palabras en enlaces en cada aparición en todas mis publicaciones?
¿No hay alguna extensión donde pueda agregar una lista extensa de palabras y que al guardar simplemente todas las apariciones de esas palabras se conviertan en enlaces en cada publicación donde aparezcan?
En cualquier caso ¿cual sería el modo más eficiente para realizar dicha tarea?
Espero haberme dado a entender, de cualquier modo todo aporte es bienvenido.

A: Parece que lo que explicas es la funcionalidad de las tags, en tu custom post type al registrarlo en el área de taxonomía agrega 'post_tag' como soporte, de esta forma
taxonomies' => array( 'post_tag' )

Si estas usando un plugin posiblemente tenga la opción de habilitarlo desde ahí, esto le permitirá usar tags para su publicación personalizada, por lo que podrá crear una lista de palabras clave las cuales al presionarlas redirigirá a la publicación o publicaciones que contengan esas tags, te recomiendo investigar del tema para tener una idea mas amplia.
Las tags usan como vista el archivo archive.php, anexo a eso, en su single debe agregar, en caso de que no este el codigo <?php get_the_tags(); ?> para mostrar los tags de su publicación.


text:
Q: Pivot data type error I have a table which needs to do pivot as column to row, but getting data type error,
I have below table data

Need to pivot and output should be like

I tried with query:
select prod As product_id , para As parameter_id
from
(
  select product_family_id,product_id,parameter_id
  from product_family_exclusion
) d
pivot
(
  max(product_id)
  for parameter_id in (prod,para)
) piv;

But getting error:

Msg 8114, Level 16, State 1, Line 15 Error converting data type
  nvarchar to int. Msg 473, Level 16, State 1, Line 15 The incorrect
  value "prod" is supplied in the PIVOT operator.

What I am missing about PIVOT table?

A: I don't think your sample output is correct for product_id 10211.  You seem to be missing parameter_id 416.
Here is an example of using dynamic SQL (in SQL Server) to solve the problem.  You could probably adapt it to other RDBMS's.  I took the liberty of generating unique column names for parameter_id because using the same column name might be problematic for the PIVOT.
--Demo setup
set nocount on
DECLARE @cols AS NVARCHAR(MAX),@colsCoalesce AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);
drop table if exists Table1
create table Table1 (product_family_id int, product_id int, parameter_id int)

insert into table1(product_family_id,product_id,parameter_id) values
(111,3227,334),
(111,3227,335),
(1112,10211,414),
(1112,10211,415),
(1112,10211,416),
(1112,10211,417),
(1112,11784,514),
(1112,11784,515),
(1112,11784,516),
(1112,11784,519)

--The solution
drop table if exists PivotTemp
select * into PivotTemp from
(
select product_family_id, product_id, parameter_id, 'parameter_id' + convert(varchar(5),ROW_NUMBER() over(partition by product_family_id, product_id order by parameter_id)) as GeneratedParameterHeading from table1
)a
--select * from PivotTemp
SElect @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.GeneratedParameterHeading)
            FROM PivotTemp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')
SElect @colsCoalesce = STUFF((SELECT distinct ',' + 'coalesce(convert(varchar(100),' + QUOTENAME(c.GeneratedParameterHeading) + '),'' '') as ' + QUOTENAME(c.GeneratedParameterHeading)
            FROM PivotTemp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

print @cols
print @colsCoalesce
set @query = 'SELECT product_family_id, product_id, ' + @colsCoalesce + ' from
            (
                select product_family_id
                    , product_id
                    , parameter_id
                    , GeneratedParameterHeading
                from PivotTemp
           ) x
            pivot
            (
                 max(parameter_id)
                for GeneratedParameterHeading in (' + @cols + ')
            ) p '

print @query
execute(@query)

| product_family_id | product_id | parameter_id1 | parameter_id2 | parameter_id3 | parameter_id4 |
|-------------------|------------|---------------|---------------|---------------|---------------|
| 111               | 3227       | 334           | 335           |               |               |
| 1112              | 10211      | 414           | 415           | 416           | 417           |
| 1112              | 11784      | 514           | 515           | 516           | 519           |


text:
Q: How to get point coordinates from a plot in Mathematica v11? I have been using the points of Mathematica plots for more than 25 years and it suddenly does not work any longer in version 11:
gr = Plot[Sin[2 \[Pi] x], {x, 0, 1}]

gr[[0]]

returns Graphics
gr[[1, 1, 1, 3]]

returns
{Directive[Opacity[1.], RGBColor[0.368417, 0.506779, 0.709798], AbsoluteThickness[1.6]],
Line[{{2.04082*10^-8, 1.28228*10^-7}, {0.000306718,
0.00192716}, {0.000613415, 0.00385419}, {0.00122681,
0.0077082}, {0.0024536, 0.0154158}, {0.00490718,
0.0308278}, {0.00981434, 0.0616262}, {0.0196287, 0.123018},....

The points seem to be there and reachable, but
gr[[1, 1, 1, 3, 2]

returns "ChartingPrivateTag$109972#1" instead of the Line[] with the points!
How to get the points in version 11 (and above)?
Thank you for your help.
Denis

A: Cases[gr, Line[x_] :> x, -1]


text:
Q: Google Map API Street View controls? I couldn't figure out how to change/hide Street View controls in scenario where there's a map by default and you drag "little guy" to road.
This is the piece of code about my options:
    function initMap() {

        var mapOptions = {
            center: new google.maps.LatLng( <?php echo $latitude . ',' . $longitude; ?>),
            zoom: 12,
            disableDefaultUI: true,
            backgroundColor: 'white',
            streetViewControl: true
            };
// I have markers & other stuff in here, it's properly closed function!

I found reference for Street View controls only when it's Street View by default, here's a code example from Google Developers:
function initPano() {
  // Note: constructed panorama objects have visible: true
  // set by default.
  var panorama = new google.maps.StreetViewPanorama(
      document.getElementById('map'), {
        position: {lat: 42.345573, lng: -71.098326},
        addressControlOptions: {
          position: google.maps.ControlPosition.BOTTOM_CENTER
        },
        linksControl: false,
        panControl: false,
        zoomControlOptions: {
          style: google.maps.ZoomControlStyle.SMALL
        },
        enableCloseButton: false
  });
}

How to add Street View UI options if default view is map and you can drag Street View "guy" to map?

A: Have a look at this answer to see if it helps. I think you need to listen for the streetview becoming visible and then hide the controls using streetViewControl = false etc.
Detecting Google Maps streetview mode


text:
Q: Why JBoss Wildfly server can't use 9999 as its manage port? If I changed manage port to 9999 for Wildfly 10, then I can't use jboss-cli.bat/sh to stop this server. Is there some restrict of using 9999

A: In Wildfly 10 management console and CLI uses same port for communication i.e 9990. This is done to reduce the number of ports opened by server instance. If you want to use 9999 port for CLI then you need to define this port in socket-binding and use 'remote' protocol to connect like "jboss-cli.sh -c --controller=remote://localhost:9999"

A: Per default 9999 is associated with the remote protocol so the CLI will use remote instead of http-remoting which is the default protocol. Use "jboss-cli.sh -c --controller=http-remoting://localhost:9999"


text:
Q: How to turn Python program into executable file I apologize for such a basic question.  I've done some research online and still cannot figure out for the life of me how to turn a python folder into something like an actual app I can open in OS X.  I am using Mac OS X, Terminal and Coderunner for my Python project.

A: Here are a few options:

*

*Platypus is not Python-specific. It lets you wrap a simple GUI around a command line tool.

*py2app is Python-specific and a good choice if you have a GUI, or need to run in the background.

*PyInstaller is similar to py2app but cross-platform; I've never used it, so I don't know how well it works.

The right choice depends on what your program does; who is the expected audience — do you need to redistribute it, if so how, and so forth.  If you want to make the application entirely self-contained — not dependent on anything else beyond the OS — then things get more complicated (though certainly not insoluble; there are several commercial Mac desktop apps written in Python.)

A: Typically you would make the script executable by putting
#!/usr/bin/env python

as the first line, and then in a terminal window typing
chmod u+x myscript.py

You might also want to put it in a special scripts folder and then add that to your PATH by editing .bash_profile. (I am putting a lot of buzz-words here to help you find the tutorials explaining how these things work.)
You can wrap your script into an Automator object if you want to try running it that way, but in the long run you will be better off getting comfortable working in a terminal window.
It would also help to know what your app does: Process files, generate a GUI, do a calculation, etc...


text:
Q: Aws ElasticBeanstalk & CodePipeline Url 404 Not Found So i have a Laravel WebApp on a Github repo, and I have an AWS cicd pipeline using ElasticBeanstalk (EBS) & CodePipeline connected to it.
Now EBS gives me a url to view the webapp but it only shows the homepage of the webapp and nothing else.

Any idea as to why this is happening and how can i fix it?


text:
Q: perl script to print xml file data How to print multiple number of trouble code and descripions using perl script.I have the xml file like this..
 <data>........
        .......
      </data>

lik this i have more number of trouble codes.still now i am printing only trouble code,how should i print descrption below the trouble code.

A: Try this:
#!/C:/Languages/Perl64/bin/perl.exe

use warnings;
use strict;
use XML::LibXML::Reader;

my $file;
open( $file, 'test.xml' );
my $reader = XML::LibXML::Reader->new( IO => $file ) or die( "unable to open file" );
while ( $reader->nextElement( 'DTC' ) ) {
    my $description = $reader->readOuterXml();
    $reader->nextElement( 'TroubleCode' );
    my $troubleCode = $reader->readInnerXml();
    print( "trouble code: $troubleCode\n" );
    print( " description: $description\n" );
}
close( $file );

Okay, corrected and tested.  This works per your question.

A: I answered the same question over on perlmonks so hopefully he finds an answer he likes.
use XML::Simple;
my $xml = new XML::Simple;

my $data = $xml->XMLin("data.xml");

my %by_code;
foreach my $dtc ( @{ $data->{DTC} } ) {
    push @{ $by_code{ $dtc->{TroubleCode} } }, $dtc;
}

foreach my $code ( sort { $a <=> $b } keys %by_code ) {
    print "trouble code: $code\n";
    print "description:\n";
    print map { $xml->XMLout( $_, RootName => 'DTC', NoAttr => 1, ) }
        @{ $by_code{$code} };
}

A: Would you try this:
 print " DTCnumber: \n" . join("\n", @dtcnumber);

and:
print " DTCdes: \n" .  join("\n", @dtcdes);


text:
Q: How to plot random intercept and slope in a mixed model with multiple predictors? Is it possible to plot the random intercept or slope of a mixed model when it has more than one predictor?
With one predictor I would do like this:
#generate one response, two predictors and one factor (random effect)
resp<-runif(100,1, 100)
pred1<-c(resp[1:50]+rnorm(50, -10, 10),resp[1:50]+rnorm(50, 20, 5))
pred2<-resp+rnorm(100, -10, 10)
RF1<-gl(2, 50)

#gamm
library(mgcv)
mod<-gamm(resp ~ pred1, random=list(RF1=~1))
plot(pred1, resp, type="n")
for (i in ranef(mod$lme)[[1]]) {
abline(fixef(mod$lme)[1]+i, fixef(mod$lme)[2])
}

#lmer
library(lme4)
mod<-lmer(resp ~ pred1 + (1|RF1))
plot(pred1, resp, type="n")
for (i in ranef(mod)[[1]][,1]) {
abline(fixef(mod)[1]+i, fixef(mod)[2])
}

But what if I have a model like this instead?:
mod<-gamm(resp ~ pred1 + pred2, random=list(RF1=~1))

Or with lmer
mod<-lmer(resp ~ pred1 + pred2 + (1|RF1))

Should I consider all the coefficients or only the ones of the variable that I'm plotting?
Thanks

A: ## generate one response, two predictors and one factor (random effect)
set.seed(101)
resp <- runif(100,1,100)
pred1<- rnorm(100,
           mean=rep(resp[1:50],2)+rep(c(-10,20),each=50),
           sd=rep(c(10,5),each=50))
pred2<- rnorm(100, resp-10, 10)

NOTE that you should probably not be trying to fit a random
effect for an grouping variable with only two levels -- this will
almost invariably result in an estimated random-effect variance of zero,
which will in turn put your predicted lines right on top of each
other -- I'm switching from gl(2,50) to gl(10,10) ...
RF1<-gl(10,10)
d <- data.frame(resp,pred1,pred2,RF1)

#lmer
library(lme4)
mod <- lmer(resp ~ pred1 + pred2 + (1|RF1),data=d)

The development version of lme4 has a predict() function
that makes this a little easier ...

*

*Predict for a range of pred1 with pred2 equal to its mean,
and vice versa.  This is all a little bit cleverer than it needs
to be, since it generates all the values for both focal predictors
and plots them with ggplot in one go ...

()
nd <- with(d,
           rbind(data.frame(expand.grid(RF1=levels(RF1),
                      pred1=seq(min(pred1),max(pred1),length=51)),
                      pred2=mean(pred2),focus="pred1"),
                 data.frame(expand.grid(RF1=levels(RF1),
                      pred2=seq(min(pred2),max(pred2),length=51)),
                      pred1=mean(pred1),focus="pred2")))
nd$val <- with(nd,pred1[focus=="pred1"],pred2[focus=="pred2"])
pframe <- data.frame(nd,resp=predict(mod,newdata=nd))
library(ggplot2)
ggplot(pframe,aes(x=val,y=resp,colour=RF1))+geom_line()+
         facet_wrap(~focus,scale="free")

*

*Alternatively, focusing just on pred1 and generating predictions for a (small/discrete) range of pred2 values ...

()
nd <- with(d,
           data.frame(expand.grid(RF1=levels(RF1),
                      pred1=seq(min(pred1),max(pred1),length=51),
                      pred2=seq(-20,100,by=40))))
pframe <- data.frame(nd,resp=predict(mod,newdata=nd))
ggplot(pframe,aes(x=pred1,y=resp,colour=RF1))+geom_line()+
         facet_wrap(~pred2,nrow=1)

You might want to set scale="free" in the last facet_wrap() ... or
use facet_grid(~pred2,labeller=label_both)
For presentation you might want to replace the colour aesthetic,
with group, if all you want to do is distinguish among groups
(i.e. plot separate lines) rather than identify them ...


text:
Q: Limit content inside the div by its size I'm dynamically filling a table of content fetch from the database.
This table is inside a

So I'm setting a variable $col to limit how much columns I want each row (by default I saw 5 fit perfectly) in the div. Otherwise the table content just goes outside the div.
The problem is I had to set that manually. I looked around a lot how to make any content inside div and  once it colides with the border but couldn't find anything. If I could have the same result without using tables which are the problem I think . I'll be glad to update that.
$col = 1; //initialisation

foreach ($result as $product){ //a loop to fetch data into product object
if($product->visible == 1){
    if($Col < 6){
   echo "";
   echo "id_product."&p=0'>
";
   echo "id_product."/c".$product->id_product.".jpg' alt = 'cover' width='220' height='300'>
".$product->name_product."
";
   echo "
";
   echo "	";
   $col= $col+ 1; //here I'm incrementing
   }
  else{ //I close the line
 then another line begin
echo "

";
echo "id_hentai."&p=0'>
";
 echo "id_product."/c".$product->id_product.".jpg' alt = 'cover' width='220' height='300'>
".$product->name_product."
";
   echo "
";
   echo "	";
   $col= 1;
}//end the code

result

A: Please use
display: inline-block

It will accommodate the content. And where you have open the
 in "if" condition.

A: Not fully sure I understood your question but this sounds like a job for JS
1 You should read all possible columns from db and create table from them but set visibility to hidden.
2 Then add JS and define column priorities.
3 Get maximum allowed width for table.
4 Using JS read width of all you cells
5 By priority sum your cell width until it's > max width
6 hide cells with lesser priority that can't fit


text:
Q: how to make the same orientation for every navigation of tab bar controller how to make the same effect of eletticitàTable in the other navigation controllers? i'd try to change the "if" in func application into appdelegate but nothing to do.
i would that only first page of navigation controller for all tabBar item can change from portrait to landscape mode. now only tabBar item elettricità table it's ok.
can we help me please?
sorry for my bad english
this is my appdelegate code:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let tabBarController = window?.rootViewController as? UITabBarController {
        if let tabBarViewControllers = tabBarController.viewControllers {
            if let projectsNavigationController = tabBarViewControllers[1] as? UINavigationController {
                if projectsNavigationController.visibleViewController is ElettricitàTable  //use here your own ViewController class name

                {
                    return .all
                }

            }
        }
    }
    return .portrait
}


text:
Q: Submitting form in iframe in IE11 throws java.lang.StringIndexOutOfBoundsException while restoring JSF state After the user get's redirected from a session bean, the following exception is thrown:
StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1911
 at com.sun.faces.renderkit.ServerSideStateHelper.getState(ServerSideStateHelper.java:266
 at com.sun.faces.renderkit.ResponseStateManagerImpl.getState(ResponseStateManagerImpl.java:100
 at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:227
 at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:188
 at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:123
 at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:453
 at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:148
 at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:303
 at org.omnifaces.viewhandler.RestorableViewHandler.restoreView(RestorableViewHandler.java:66
 at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:303
 at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:192
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101
 at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:116
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593
 at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161
 at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231
 at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317
 at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195
 at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860
 at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757
 at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056
 at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229
 at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90
 at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79
 at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54
 at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59
 at com.sun.grizzly.ContextTask.run(ContextTask.java:71
 at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532
 at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513
 at java.lang.Thread.run(Thread.java:745)

The button code uses the actionListener attribute:
actionListener="#{aController.aMethod}"

The controller performs the redirect like this:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
String encodedURL = response.encodeURL(context.getRequestContextPath() + "/page.xhtml?faces-redirect=true");
context.redirect(encodedURL);

My session config:
<session-config>
    <session-timeout>60</session-timeout>
    <tracking-mode>URL</tracking-mode>
</session-config>

The page only contains one single form (as well as the generated HTML output), defined:
<form id="wrapper" name="wrapper" method="post" action="/ACETOwebkalender/a/b.xhtml" enctype="application/x-www-form-urlencoded">

The outer pages uses the Slider Revolution Responsive WordPress Plugin, which uses jQuery.ajax. May this produce the issue?
This issue only appears in IE11 and Safari, when the page is embedded in another page using iFrame.

A: Fixed the bug for Safari with the following code snippet on every single page:
    <script>
    window.onload = function() {
        if (top != self) { // If true, then page is been requested inside an iframe.
            var jsessionid = '#{session.id}';
            var forms = document.forms;

            for (i = 0; i < forms.length; i++) {
                forms[i].action += ';JSESSIONID=' + jsessionid;
          }
        }
    };
</script>

And for IE, I updated the web.xml to following:
....
<filter>
    <filter-name>P3P Response Filter</filter-name>
    <filter-class>util.ResponseFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>P3P Response Filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
    <session-timeout>60</session-timeout>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
    </cookie-config>
    <tracking-mode>COOKIE</tracking-mode>
    <tracking-mode>URL</tracking-mode>
</session-config>
...

Where ResponseFilter.class is:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ResponseFilter implements Filter {

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {}

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletResponse resp = (HttpServletResponse) response;
  resp.addHeader("P3P", "CP=\"DC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
  chain.doFilter(request, resp);
 }

 @Override
 public void destroy() {}
}


text:
Q: Layout messed up in bootstrap I wrote a simple web page for experiment:
Here is the code:
<!doctype html>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="./css/bootstrap-theme.min.css">

                    Menu Bar!

                    Previous

                    Next

                Footer!!

And the web page is like this:

Footer isn't coming up properly. Carousel isn't working properly. But the page is responsive and loads properly in various screens. How can I fix it?

A: Ensure that your images are something that can be found. By appearance alone it seems that your code was able to find index.jpeg but not any of the others. Try using index.jpeg all 4 times and see if that helps.


text:
Q: How to show an image with imagemagick? The following code works like a charm:
<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat( "jpg" );
header( "Content-Type: image/jpeg" );
echo $im;
?>

But what if I need to include that image in an existing html page? If I remove the header image/jpeg it shows the image as text. I'm looking for an ImageMagick method that can do the trick. Any advice?

A: You would have the code above on a seperate page called something like image.php ( note you will need to remove the header part ).
Then where you want it on the main page use:

A: Write the image in the filesystem, and then output a HTML page with a  tag:
<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
$im->writeImage('/var/www/domain/image/something.png');

echo "";

Note that the file must be in a publicly accessible directory

A: You will have to call this php page in a img tag


text:
Q: subtitle syncing with timings copy-paste? I've got 2 subs in 2 different languages for a video.
One is synced, the other has all the right lines but wrong timing [NOT fixed nor progressive delay]: the easiest thing would be changing the timings of the latter with the ones from the former, kind of copy paste time codes.
Which subtitles editor for Ubuntu has the capabilities to accomplish/would be more suited for this task?
EDIT: Unfortunately there's no fixed delay, such that moving the subs by a certain amount of time could do it. They are simply wrongly synced (and that doesn't have to do with framerate either).
I need an editor which can kind of copy and paste the "timing" column beside the "text" column
EDIT 2: please people be civilised and read before marking as a duplicate. I'm not looking for a general sub editor, I'm looking for one with a particular feature NOT even mentioned in the question you would like to redirect me to. If it was, would you be able to point that out?
Sorry for any misunderstanding I might have created, I'm only looking for an answer, which unfortuntely is something I haven't got so far
FOR ANYONE WITH THE SAME ISSUE stumbling upon this question, the answer to what I was looking for is in the thread posted by smurfendrek123, containing nice programs that will help you (under Wine) to achieve copy-paste of timings: http://forum.videohelp.com/threads/346020-Program-to-replace-timecode-in-srt-with-timecode-from-another-srt

A: In vlc you can delay or speed up the subtitles by a set time.
For more software recommendations: check this thread: What apps to sync movie subtitles easily are available for Ubuntu?
Also have a look at this thread: http://forum.videohelp.com/threads/346020-Program-to-replace-timecode-in-srt-with-timecode-from-another-srt


text:
Q: Firebase - Retention Rates(Cohort) I have a question on the way Firebase calculates retention rates.
At my company, we release a new version almost every 2-3 weeks, and a lot of people uninstall the app to get the latest version.
If an active user uninstalls and reinstalls the app to access new features, would that user be counted as an inactive user, and the user would be included in the new cohort?

A: Yes, when users reinstall your app they are regarded as a brand new user, they get new instance id/user_pseudo_id assigned. Which in your case means you will have worse retention rate that you actually have. But if you have any way of identifying users (which you can probably do using Advertising ID) you could override this instance id with your own userID.


text:
Q: Android Asynk Task run in thread i want to run asynk task in every 5 seconds till 5 minuts, how can i do this ?
i am able to run asynk task in every 5 seconds but can no limit 5 minuts
public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        new CheckTxnStatusSTResult().execute(final_verification_card);
                        Log.d("dinesh","execute in every five seconds"+ final_verification_card);
                    } catch (Exception e) {

                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 15000);

}

A: Just you can do like this
public void FunctionName() {
    new CountDownTimer(Total_time, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            MyUtils.Log("execute in every one seconds");
            // Display Data by Every Ten Second
        }

        @Override
        public void onFinish() {
           // Call Other function on Function
        }

    }.start();
}


text:
Q: Im trying to make this code recursive but for some reason it doesnt work I'm trying to make this code recursive but for some reason it doesn't work.
void compress_spaces(char *str)
{
    char *dst = str;

    for (; *str; ++str) {
            *dst++ = *str;
            if (isspace(*str)) {
                    do ++str; while (isspace(*str));
                    --str;
            }
    }
    *dst = 0;
}

EDIT:
I tried this:
void text_r(char *str)
{
    char *dst = str;

            if(*str=='\0')return ;
            *dst++ = *str;
            if (isspace(*str)) {
                    do ++str; while (isspace(*str));
                    --str;
            }//Missing brace from orig is this ok?
          return text_r(str++);
}

Didn't work. Any ideas?

A: Your dst pointer is not the same pointer in the recursively called function, pass it as an argument instead.
void text_r(char *dst, char *str) {
  if (*str=='\0')
    return;
  *dst++ = *str;
  if (isspace(*str)
    while (isspace(*str++));
  else
    ++str;
  return text_r(dst, str);
}

Why you want to do this with recursion is completely beyond me by the way, it only wastes time and space.

A: Perhaps this SO question may helps you. It resolves your problem with a regular expression


text:
Q: having trouble updating a column name in sqlite, with a variable in Python 3 having trouble updating a column name in sqlite, with a variable in Python 3
it selects the corect column but won't do the update

colToEdit = input('Which COL do you want to edit?: ')
if colToEdit == '1':
  newvalue = input('What is the new name?: ')
  c.execute("UPDATE cards SET ccname = ?", newvalue "WHERE ROWID=?",cardToEdit);

Error
c.execute("UPDATE cards SET ccname = ?", newvalue "WHERE ROWID=?",cardToEdit);


text:
Q: Why do I need to use the "this" keyword when accessing a parameter for an anonymous self-executing function? I'm just getting started learning Javascript and I've been playing around with anonymous self-executing functions. I made some code that doesn't work the way I would expect. Why is the "this" keyword needed to get the value of variable "shoutIt" in this instance?
The first alert displays "Did it work? (1) undefined" while the second displays "Did it work? (2) [YES!]".
Thanks!
var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function (shoutIt) {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt); //doesn't work, undefined
        alert("Did it work? (2) " + this.shoutIt) //works
})();

A: There are two variables called shoutIt here: one is the global variable defined by var shoutIt, and the other is a variable defined by the formal argument in function (shoutIt) { ...
When you run a non-method function (i.e., of the form foo() rather than bar.foo()) in non-strict mode, this is equal to the global object (in the browser, window). Inside the function, this.shoutIt refers to the shoutIt variable in the global scope.
By contrast, shoutIt refers here to the function argument with that name, instead of the global variable, which is one scope level up. (The global variable is "shadowed" by the more immediate variable of the same name.) The function isn't called with any arguments, so the value of shoutIt within the function is undefined.
If you want to pass in a value to use as the argument named shoutIt, supply one in the invoking parentheses:
(function (shoutIt) {
    ...
})(someValue);

A: because your anonymous function is expecting shoutIt as an argument but you are passing nothing to it.
Basically your function expects a parameter shoutIt. This parameter will be in the local scope of the function. If nothing is passed, and when the compiler will fetch the value of shoutIt it will access it from the local scope now and wont go to the global level. At the local level since you are not passing anything to the function, it gives you undefined
There are two solutions to it
1) Pass the value of shoutIt
var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function (shoutIt) { //expecting that value
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt);
        alert("Did it work? (2) " + this.shoutIt)
})(shoutIt);**strong text** //passing argument to the function

OR
2) Do not pass any parameter
var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function () {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt);
        alert("Did it work? (2) " + this.shoutIt)
})();

How 'this' works
Basically 'this' refers to the context in javascript.
By default it points to the window object. Try doing
console.log(this) //outputs the window object

Whatever is defined at the global level automatically gets linked to the window object.

A: You're parameter is named the same as the variable outside of the function and you're not passing a variable into the function.
With your example you could do a couple different things to get it to work as you expect it.
A. Pass shoutIt into the function
var shoutIt = "[YES!]";
//creating an anonymous, self-executing function
(
    function (shoutIt) {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt); //doesn't work, undefined
        alert("Did it work? (2) " + this.shoutIt) //works
})(shoutIt);

B. Change the name of the parameter in your function definition.
var shoutIt = "[YES!]";

//creating an anonymous, self-executing function
(
    function (shoutItAgain) {
        shoutItDebug = shoutIt;
        shoutItDebug = this.shoutIt;
        alert("Did it work? (1) " + shoutIt); //doesn't work, undefined
        alert("Did it work? (2) " + this.shoutIt) //works
})();


text:
Q: How to render template and layout from different directories with Sinatra I want to put template files in defferent directories. (foo/, bar/)
How do you write using Sinatra?

This way get wrong.

A: From the documentation:
set :views, Proc.new { File.join(root, "templates") }

If you want to use multiple directories (also from the docs):
set :views, ['views', 'templates']

helpers do
  def find_template(views, name, engine, &block)
    Array(views).each { |v| super(v, name, engine, &block) }
  end
end

By the way, you need to reference templates with symbols, not strings. So the complete code would be:
require 'rubygems'
require 'sinatra'
require 'haml'

set :views, ['foo', 'bar']

helpers do
  def find_template(views, name, engine, &block)
    Array(views).each { |v| super(v, name, engine, &block) }
  end
end

get '/' do
  haml :index, :layout => :bar
end

and you have these files:
foo/index.haml
bar/bar.haml


text:
Q: VirtualBox guest machine as a nginx host I have VirtualBox 4.3.12 with Fedora 20 and nginx 1.4.7 installed. Machine has Bridged Network interface and pings can be done both ways:
from host machine (Windows 7) using
ping 192.168.0.15 (virtual machine's ip address)
and from guest machine
ping 192.168.0.10 (host machine ip address)
but what i can't do is access guest machine's nginx from host machine. I have read this and this and have done as those articles / previously asked question told me to, but i still can't manage to view nginx site from host machine.
netstat -tnlp returns:
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN        930/nginx: master p

A: When I did:
iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT

I got an error of:
iptables: Index of insertion too big.

The reason is that I do not have any policies in place and so the "INPUT 4" part is trying to insert at index 4 when it should be index = 1. To view your rules do:
sudo iptables --list-rules

Then insert at the appropriate index. (In most cases):
sudo iptables -I INPUT 1 -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT

This finally got it to work!

*

*My virtualbox settings are:

*

*host port 8080,

*guest IP 10.0.2.15

*guest port 80

nginx conf file is:
server {
  listen 0.0.0.0:80;

  location / {
      proxy_pass http://localhost:9000;
      }
}

A: I did:
iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT

in VM's console and it worked.


text:
Q: How can get the json in the url? I can get the json data in the url with browser.
https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5

Opened in chrome.

Opened in firefox.

Try to crawl the web with requests library:
import requests
url="https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5"
headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0"}
r = requests.get(url, headers=headers)
<Response [400]>

Try to crawl the web with selenium library:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
browser = webdriver.Chrome(options=options)
url="https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5"
browser.get(url)
browser.page_source
'

{"error_description":"遇到错误,请刷新页面或者重新登录帐号后再试","error_uri":"/v5/stock
/finance/us/income.json","error_code":"400016"}
'

How can get the json in the url?
I have never login the website,clear all caches in browser, and open the json's url ,it encountered error message,open the https://xueqiu.com/snowman/S/ASX/detail#/GSLRB in browser ,wait for a moment and  open the https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5 again,all data shown in browser.

A: Page https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5 requires the cookies of page https://xueqiu.com/snowman/S/ASX/detail#/GSLRB, so a possible solution is to use requests.Session:
import requests
import pprint

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0"
}
url1 = "https://xueqiu.com/snowman/S/ASX/detail#/GSLRB"
url2 = "https://stock.xueqiu.com/v5/stock/finance/us/income.json?symbol=ASX&type=all&is_detail=true&count=5"

with requests.Session() as s:
    s.headers.update(headers)
    s.get(url1)
    r = s.get(url2)
    pprint.pprint(r.json())

Output:
{'data': {'annual_settle_date': '12-31',
          'currency': 'TWD',
          'currency_name': '新台币',
          'last_report_name': '2020年FY',
          'list': [{'ctime': 1617756162000,
                    'ed': '2020-12-31',
                    'gross_profit': [77984268000.0, 0.21261555583679398],
                    'income_from_co': [28651900000.0, 0.5683716810816832],
                    'income_from_co_before_it': [35768798000.0,
                                                 0.536472869131111],
                    'income_from_co_before_tax_si': [3302123000.0,
                                                     -0.18326588478789202],
                    'income_tax': [7116898000.0, 0.4201853191801001],
                    'interest_expense': [3459511000.0, -0.1769721855785621],
                    'interest_income': [None, None],
                    'marketing_selling_etc': [23805768000.0,
                                              0.06327703424731415],
                    'net_income': [28651900000.0, 0.5683716810816832],
                    'net_income_atcss': [26970580000.0, 0.5808702054928813],
                    'net_income_atms_interest': [1681320000.0,
                                                 0.39185114911413654],
                    'net_interest_expense': [3459511000.0, -0.1769721855785621],
                    'operating_income': [31919063000.0, 0.6751497051555505],
                    'othr_revenues': [None, None],
                    'preferred_dividend': [0.0, None],
                    'rad_expenses': [19302418000.0, 0.04931054799005009],
                    'report_annual': 2020,
                    'report_date': 1609344000005,
                    'report_name': '2020年FY',
                    'report_type_code': 596001,
                    'revenue': [476978710000.0, 0.15440289651985575],
                    'sales_cost': [398994442000.0, 0.1436720014683004],
                    'sd': '2020-01-01',
                    'share_of_earnings_of_affiliate': [547612000.0,
                                                       2.004317651899602],
                    'total_basic_earning_common_ps': [6.32, 0.576059850374065],
                    'total_compre_income': [29147213000.0, 1.097230498820186],
                    'total_compre_income_atcss': [27440726000.0,
                                                  1.0911704872321188],
                    'total_compre_income_atms': [1706487000.0,
                                                 1.1997360038877551],
                    'total_dlt_earnings_common_ps': [6.17, 0.578005115089514],
                    'total_net_income_atcss': [26970580000.0,
                                               0.5808702054928813],
                    'total_operate_expenses': [46065205000.0,
                                               0.017872987914466523],
                    'total_operate_expenses_si': [-502492000.0,
                                                  -2.871095306361825],
                    'total_revenue': [476978710000.0, 0.15440289651985575]},
                   {'ctime': 1617756162000,
                    'ed': '2019-12-31',
                    'gross_profit': [64310793000.0, 0.05146478143258062],
                    'income_from_co': [18268565000.0, -0.33385504808890537],
                    'income_from_co_before_it': [23279811000.0,
                                                 -0.27108630126460664],
                    'income_from_co_before_tax_si': [4043082000.0,
                                                     -0.5491069252894362],
                    'income_tax': [5011246000.0, 0.11031160979747058],
                    'interest_expense': [4203395000.0, 0.17800199033641506],
                    'interest_income': [None, None],
                    'marketing_selling_etc': [22389055000.0,
                                              0.14507365860389632],
                    'net_income': [18268565000.0, -0.33385504808890537],
                    'net_income_atcss': [17060591000.0, -0.34934699164069516],
                    'net_income_atms_interest': [1207974000.0,
                                                 0.0036441041286553208],
                    'net_interest_expense': [4203395000.0, 0.17800199033641506],
                    'operating_income': [19054454000.0, -0.18748112827671856],
                    'othr_revenues': [None, None],
                    'preferred_dividend': [0.0, None],
                    'rad_expenses': [18395334000.0, 0.22940460538165353],
                    'report_annual': 2019,
                    'report_date': 1577721600004,
                    'report_name': '2019年FY',
                    'report_type_code': 596001,
                    'revenue': [413182184000.0, 0.11342124122766711],
                    'sales_cost': [348871391000.0, 0.1256480464382964],
                    'sd': '2019-01-01',
                    'share_of_earnings_of_affiliate': [182275000.0,
                                                       1.379546647121047],
                    'total_basic_earning_common_ps': [4.01,
                                                      -0.3511326860841424],
                    'total_compre_income': [13897954000.0, -0.4769636105391466],
                    'total_compre_income_atcss': [13122185000.0,
                                                  -0.48782400909960205],
                    'total_compre_income_atms': [775769000.0,
                                                 -0.18444496307883804],
                    'total_dlt_earnings_common_ps': [3.91,
                                                     -0.35584843492586493],
                    'total_net_income_atcss': [17060591000.0,
                                               -0.34934699164069516],
                    'total_operate_expenses': [45256339000.0,
                                               0.20005272067674873],
                    'total_operate_expenses_si': [268555000.0,
                                                  1.7227322024958085],
                    'total_revenue': [413182184000.0, 0.11342124122766711]},
                   {'ctime': 1560942703000,
                    'ed': '2019-03-31',
                    'gross_profit': [11385000000.0, 0.09597612629957643],
                    'income_from_co': [2230000000.0, -0.053480475382003394],
                    'income_from_co_before_it': [2635000000.0,
                                                 -0.3021716101694915],
                    'income_from_co_before_tax_si': [1462000000.0,
                                                     4.601532567049809],
                    'income_tax': [405000000.0, -0.7147887323943662],
                    'interest_expense': [None, None],
                    'interest_income': [None, None],
                    'marketing_selling_etc': [5137000000.0, 0.5580831058538065],
                    'net_income': [2230000000.0, -0.053480475382003394],
                    'net_income_atcss': [2043000000.0, -0.025286259541984733],
                    'net_income_atms_interest': [187000000.0,
                                                 -0.28076923076923077],
                    'net_interest_expense': [966000000.0, 1.7058823529411764],
                    'operating_income': [1327000000.0, -0.6648143470573377],
                    'othr_revenues': [None, None],
                    'preferred_dividend': [0.0, None],
                    'rad_expenses': [3955000000.0, 0.4252252252252252],
                    'report_annual': 2019,
                    'report_date': 1553961600000,
                    'report_name': '2019年Q1',
                    'report_type_code': 596003,
                    'revenue': [88861000000.0, 0.3678077763753348],
                    'sales_cost': [77476000000.0, 0.4195463373520466],
                    'sd': '2019-01-01',
                    'share_of_earnings_of_affiliate': [-154000000.0,
                                                       0.6531531531531531],
                    'total_basic_earning_common_ps': [0.48,
                                                      -0.02040816326530614],
                    'total_compre_income': [None, None],
                    'total_compre_income_atcss': [None, None],
                    'total_compre_income_atms': [None, None],
                    'total_dlt_earnings_common_ps': [0.46,
                                                     -0.04166666666666659],
                    'total_net_income_atcss': [2043000000.0,
                                               -0.025286259541984733],
                    'total_operate_expenses': [10058000000.0,
                                               0.5644734795458081],
                    'total_operate_expenses_si': [None, None],
                    'total_revenue': [88861000000.0, 0.3678077763753348]},
                   {'ctime': 1617756162000,
                    'ed': '2018-12-31',
                    'gross_profit': [61163050000.0, 0.15987892878726956],
                    'income_from_co': [27424309000.0, 0.11949389028724264],
                    'income_from_co_before_it': [31937678000.0,
                                                 0.02956142491216258],
                    'income_from_co_before_tax_si': [8966831000.0,
                                                     0.28700510835977744],
                    'income_tax': [4513369000.0, -0.3081478134092464],
                    'interest_expense': [3568241000.0, 0.9829135301368052],
                    'interest_income': [None, None],
                    'marketing_selling_etc': [19552502000.0,
                                              0.24008657043304116],
                    'net_income': [27424309000.0, 0.11949389028724264],
                    'net_income_atcss': [26220721000.0, 0.14906806875410045],
                    'net_income_atms_interest': [1203588000.0,
                                                 -0.2826994512917915],
                    'net_interest_expense': [3568241000.0, 0.9829135301368052],
                    'operating_income': [23451091000.0, -0.003255017899346956],
                    'othr_revenues': [None, None],
                    'preferred_dividend': [0.0, None],
                    'rad_expenses': [14962799000.0, 0.2737968808540811],
                    'report_annual': 2018,
                    'report_date': 1546185600004,
                    'report_name': '2018年FY',
                    'report_type_code': 596001,
                    'revenue': [371092421000.0, 0.2776851589186339],
                    'sales_cost': [309929371000.0, 0.3038187579796379],
                    'sd': '2018-01-01',
                    'share_of_earnings_of_affiliate': [-480244000.0,
                                                       -1.9133899600975308],
                    'total_basic_earning_common_ps': [6.18,
                                                      0.10554561717352413],
                    'total_compre_income': [26571677000.0, 0.33800831224856964],
                    'total_compre_income_atcss': [25620461000.0,
                                                  0.38309049519201155],
                    'total_compre_income_atms': [951216000.0,
                                                 -0.28751067367758754],
                    'total_dlt_earnings_common_ps': [6.07, 0.16955684007707125],
                    'total_net_income_atcss': [26220721000.0,
                                               0.14906806875410045],
                    'total_operate_expenses': [37711959000.0,
                                               0.29130215356164646],
                    'total_operate_expenses_si': [-371583000.0,
                                                  -2.4229614208334866],
                    'total_revenue': [371092421000.0, 0.2776851589186339]},
                   {'ctime': 1541759982000,
                    'ed': '2018-09-30',
                    'gross_profit': [42479000000.0, 0.11966577927726087],
                    'income_from_co': [20571000000.0, 0.15088956025511915],
                    'income_from_co_before_it': [24813000000.0,
                                                 0.07648590021691974],
                    'income_from_co_before_tax_si': [8885000000.0,
                                                     0.3284988038277512],
                    'income_tax': [4242000000.0, -0.1804482225656878],
                    'interest_expense': [None, None],
                    'interest_income': [None, None],
                    'marketing_selling_etc': [13734000000.0,
                                              0.17124339075558587],
                    'net_income': [20571000000.0, 0.15088956025511915],
                    'net_income_atcss': [19816000000.0, 0.18361008242742802],
                    'net_income_atms_interest': [755000000.0,
                                                 -0.3330388692579505],
                    'net_interest_expense': [2147000000.0, 0.8669565217391304],
                    'operating_income': [15928000000.0, -0.02652487470969319],
                    'othr_revenues': [None, None],
                    'preferred_dividend': [0.0, None],
                    'rad_expenses': [10670000000.0, 0.22629582806573956],
                    'report_annual': 2018,
                    'report_date': 1538236800000,
                    'report_name': '2018年Q9',
                    'report_type_code': 596007,
                    'revenue': [257064000000.0, 0.24513332203143542],
                    'sales_cost': [214585000000.0, 0.2733805692041112],
                    'sd': '2018-01-01',
                    'share_of_earnings_of_affiliate': [None, None],
                    'total_basic_earning_common_ps': [4.67,
                                                      0.12259615384615379],
                    'total_compre_income': [None, None],
                    'total_compre_income_atcss': [None, None],
                    'total_compre_income_atms': [None, None],
                    'total_dlt_earnings_common_ps': [4.6, 0.2137203166226912],
                    'total_net_income_atcss': [19816000000.0,
                                               0.18361008242742802],
                    'total_operate_expenses': [26551000000.0,
                                               0.23052324234138202],
                    'total_operate_expenses_si': [None, None],
                    'total_revenue': [257064000000.0, 0.24513332203143542]}],
          'org_type': 1,
          'quote_name': '日月光半导体',
          'sas': '国际会计准则',
          'statuses': None,
          'tip': '日月光半导体财年为每年的1月1日至12月31日,最新披露财报所属2020财年。'},
 'error_code': 0,
 'error_description': ''}


text:
Q: EF Custom Result Set Mapping I am wondering if there is a way, using Entity Framework, of mapping results from arbitrary sql, like ResultSetMapping in Doctrine. I know i can create a configuration class doing the mapping but that requires me registering the class as an entity type.
What i am trying to do is utilize the materialization element (Object Services) of EF without the rest of EF. Sometimes i have results from a proc with cryptic or less meaningful column names, but need to map to classes with more meaningful property names but have no permission to alter the proc definition, e.g:
exec dbo.getRecDetail @var

returning columns :
sd, ed, nm, ....

which should be mapped to a class such as:
  class Obj{
       public DateTime StartDate; //sd
       public DateTime EndDate; //ed
       public String Name; //nm
       ....
    }

A: If you are using .EDMX file (designer) with database first approach you can import your stored procedures into the model (simply select stored procedures in wizard) and map their results to complex types.
It actually works with arbitrary SQL queries as well but those queries cannot be imported into the model automatically (because they don't exist in your database). It requires manual modification of storage model in EDMX file (it is XML - check documentation for Function and CommandText elements). Once you do that you cannot use update from database feature of the designer any more because it would delete your custom queries.
If you are using code first there is currently no option to map results of stored procedures or custom queries. You can only use automatic mapping which requires your class to have properties with exactly same name as columns in result sets.