text:
Q: Android app crashes on network request I have integrated a currency converter in my app but when I try to get the results from the internet the app crashes. I am getting an error about: android.os.NetworkOnMainThreadException, some people say you have to add asynctask in order to fix the problem as it runs on main thread. So how can I do that in my current code?
Below is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_Currency_Converter extends DashBoardActivity {
    public int to;
    public int from;
    public String [] val;
    public String s;
    public Handler handler;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_converter);
        Spinner s1 = (Spinner) findViewById(R.id.spinner1);
        Spinner s2 = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.name, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        val  = getResources().getStringArray(R.array.value);
        s1.setAdapter(adapter);
        s2.setAdapter(adapter);
        s1.setOnItemSelectedListener(new spinOne(1));
        s2.setOnItemSelectedListener(new spinOne(2));
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                TextView t = (TextView) findViewById(R.id.textView4);
                if(from == to)
                {
                    Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
                }
                else
                {
                      try {
                         s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                        JSONObject jObj;
                        jObj = new JSONObject(s);
                        String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
                        t.setText(exResult);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        });
    }
    public String getJson(String url)throws ClientProtocolException, IOException {

        StringBuilder build = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String con;
        while ((con = reader.readLine()) != null) {
                    build.append(con);
                }
        return build.toString();
    }
    private class spinOne implements OnItemSelectedListener
    {
        int ide;
        spinOne(int i)
        {
            ide =i;
        }
        public void onItemSelected(AdapterView<?> parent, View view,
                int index, long id) {
            if(ide == 1)
                from = index;
            else if(ide == 2)
                to = index;

        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    }
}

Logcat log:
11-27 13:58:17.120: E/AndroidRuntime(1470): android.os.NetworkOnMainThreadException
11-27 13:58:17.120: E/AndroidRuntime(1470):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-27 13:58:17.120: E/AndroidRuntime(1470):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

A: Use Asynchtask for performing Network related operations..
Chack this for more details NetworkOnMainThread and Asynchtask

A: Try this,
public class Activity_Currency_Converter extends DashBoardActivity {
    public int to;
    public int from;
    public String [] val;
    public String s;
    public Handler handler;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_converter);
        Spinner s1 = (Spinner) findViewById(R.id.spinner1);
        Spinner s2 = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.name, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        val  = getResources().getStringArray(R.array.value);
        s1.setAdapter(adapter);
        s2.setAdapter(adapter);
        s1.setOnItemSelectedListener(new spinOne(1));
        s2.setOnItemSelectedListener(new spinOne(2));
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                TextView t = (TextView) findViewById(R.id.textView4);
                if(from == to)
                {
                    Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
                }
                else
                {
                      new GetResponseData(t).execute();
                    }
                }
        });
    }
    public String getJson(String url)throws ClientProtocolException, IOException {

        StringBuilder build = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String con;
        while ((con = reader.readLine()) != null) {
                    build.append(con);
                }
        return build.toString();
    }
    private class spinOne implements OnItemSelectedListener
    {
        int ide;
        spinOne(int i)
        {
            ide =i;
        }
        public void onItemSelected(AdapterView<?> parent, View view,
                int index, long id) {
            if(ide == 1)
                from = index;
            else if(ide == 2)
                to = index;

        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    }
    class GetResponseData extends AsyncTask<String, String, String> {
         private ProgressDialog dialog;
         private ArrayList<String> titleList;
         private TextView textView;

         public GetResponseData(TextView textView) {
             this.textView=textView;
        }

         @Override
         protected void onPreExecute() {
         super.onPreExecute();
         dialog = ProgressDialog.show(Activity_Currency_Converter.this, "", "Loading",
         false);
         }

         @Override
         protected String doInBackground(String... params) {

             try {
                 String s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                JSONObject jObj;
                jObj = new JSONObject(s);
                String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
               return exResult;
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                }
                catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                }

         }

         @Override
         protected void onPostExecute(String result) {
         super.onPostExecute(result);
         if (dialog != null)
             dialog.dismiss();
         if(result!=null)
         {
          textView.setText(result);
         }
         }

         }
}

A: Make StringBuilder class level, create your ProgressDialog accordingly.
Inside your getJSON method create an async task like this
new AsyncTask<Void, Void, Void>() {

        protected void onPreExecute() {
          //Your code
        }

        @Override
        protected Void doInBackground(Void... params) {
        StringBuilder build = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String con;
        while ((con = reader.readLine()) != null) {
                    build.append(con);
                }
        return null;
        }

        protected void onPostExecute(Void result) {
          //Update UI from here
        }
      }.execute();

A: Use AsyncTask as
class myAsyncTask extends AsyncTask<String[] ,String,String>
{
    String s=null;
    String output=null;
    JSONObject main;

    @Override
    protected void onPreExecute()
    {

    }

    @Override
    protected String doInBackground(String[]... val) {

        s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                    JSONObject jObj;
                    jObj = new JSONObject(s);
                    String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");

        return exResult;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        t.setText(result);
             }
}

and then call the following method from the 'else' block
new myAsyncTask().execute(val);

A: The app crashes due to strict mode policy, insert below given lines before you send a request to service or connecting to network:
 ThreadPolicy tp = ThreadPolicy.LAX;
 StrictMode.setThreadPolicy(tp);

Hope it Helps you :)


text:
Q: How can I display pandas dataframe into django template? I have a pandas dataframe and i want to show this dataframe into my django template. But everytime the code compile successfully without showing any table in my django web app. What am i missing here? My data frame looks like this:
dataframe sample
and my html looks like:

Total match data and Profit Mergin

                            Total Contest
                            Total Entry Amount
                            Total Seat
                            Total Winning Amount
                            Total Team Capacity
                            Profit Mergin

                            {% for value in final_data.iterrows %}

                            {{ value.0 }}
                            {{ value.1 }}
                            {{ value.2 }}
                            {{ value.3 }}
                            {{ value.4 }}
                            {{ value.5 }}

                        {% endfor %}

i tried final_data.itertuplus but still got the same result. What should i do now?

A: This a basic html table that shows a pandas dataframe in a django template:

    {% for col in df.columns %}

        {{col}}

    {% endfor %}

    {% for index, row in df.iterrows %}

        {% for cell in row %}

            {{cell}}

        {% endfor %}

    {% endfor %}

This one is not showing the index, so if you want to render it, you could pass df.reset_index() to the template.

A: Looks like there are two options:

*

*Leave the DataFrame as-is and then use a statement in your template.
Currently, you're using the pandas.DataFrame.iterrows method but it is not called.
Call the method by adding () at the end of final_data.iterrows.
(Also, make sure to close your table header row with
.)

*Convert the DataFrame to HTML and then use an expression in your template.
As @david-sielski mentions, consider using the pandas.DataFrame.to_html method.
Take a look at this example of How to render Pandas DataFrame as HTML Table?
Uncomment the final_df = final_df.to_html()  line and replace the table with {{ final_data }}.
(Also, make sure to add your styling classes using the classes kwarg.)
Check out how to use developer tools to inspect your HTML if you haven't already.
Comment if you have any questions,
Clay

redpajama_set_name: RedPajamaStackExchange


text:
Q: Netsuite Invoice / GL entry I have a unique situation where we need to assign different GL Account when we create an invoice. For now, the first part is done. I created 2 custom fields:
COGS and Income. The user can pick it from the list, save it, etc. Users are fine with it.
However the GL transaction is still with the original Account. I want to write to the GL using the accounts entered on the invoice.
Anyone can help?

A: If you have a developer or you know SuiteScript, you can use Custom GL Plugin for this.


text:
Q: Using async to get API data does not render I'm pulling data from Firebase in getSubscriptions() which returns an array:
[
    {
        "price": 2000.01,
        "product_name": "Awesome product"
    },
    {
        "active": true,
        "product_name": "Other product",
        "Price": 599.99
    }
]

I'm iterating through the array and I'm able to get a result but I'm having trouble getting that result to render.
I know the issue has something to do with async and waiting for the result to return but I'm stuck on how to apply those concepts to my issue here.
When I uncomment the line useEffect(() => setActiveNotifications(active), [active]), introducing the useState, the calls are put in an infinite loop calling the Firebase API ad infinitum.
export default function UserAccount(props) {

  const [activeNotifications, setActiveNotifications] = useState()

  function buildSubscriptions(userId) {
    getSubscriptions(userId).then(active => {
      console.log(JSON.stringify(active, null, 4))  // This returns output above

      // useEffect(() => setActiveNotifications(active), [active])  // This will cause infinite loop

      return (
        active.map(product =>

{product.product_name}
)  // key defined some value to not throw warning
      )
    })
  }

  async function getSubscriptions(userId) {
    const subPtrCollection = await getUserSubs(userId)
    let a = []
    await Promise.all(subPtrCollection.map(async docId => {  // Promise.all used to execute commands in series
      const docData = await getDocData(docId.product)
      a.push(docData)
    }))
    return a

  }

  return (
    ...
    <Box>{buildSubscriptions(user.uid)}</Box>  // Not important where `user.uid` comes from
    ...
  )
}

A: Infinite loop is because the method invoked in render method setting the state and that causes render. Try some thing like below 1) On change of uid, request for build 2) in when you receive the results from api save to state, this cause render 3) in render method used the state data.
export default function UserAccount(props) {
  const [activeNotifications, setActiveNotifications] = useState();

  // when ever uid changes, do the build subscriptions
  useEffect(() => buildSubscriptions(user.uid), [user.uid]);

  // get subscriptions and save to state
  function buildSubscriptions(userId) {
    getSubscriptions(userId).then((active) => setActiveNotifications(active));
  }

  async function getSubscriptions(userId) {
    const subPtrCollection = await getUserSubs(userId);
    let a = [];
    await Promise.all(
      subPtrCollection.map(async (docId) => {
        // Promise.all used to execute commands in series
        const docData = await getDocData(docId.product);
        a.push(docData);
      })
    );
    return a;
  }

  return (
    <Box>
      {activeNotifications.map((product) => (

{product.product_name}

      ))}
    </Box>
  );
}


text:
Q: How to merge 2 Firestore queries streams in Flutter / Dart? I am trying to merge 2 Firestore queries to merge their snapshots/streams in Flutter/Dart. I have created a function for the same:
final _startAtTimestamp = Timestamp.fromMillisecondsSinceEpoch(DateTime.parse('2000-01-01 01:01:01.001').millisecondsSinceEpoch);

_messagesStream() {
  // message sent by logged in user
  var  streamData1 = FirebaseFirestore.instance
      .collection('messages')
      .where('encSenderUId', isEqualTo: _loggedInUserId)
      .where('encReceiverUId', isEqualTo: widget.encUId)
      .orderBy('sentOn', descending: false)
      .startAt([_startAtTimestamp]).snapshots();

  // message received by logged in user
  var  streamData2 = FirebaseFirestore.instance
      .collection('messages')
      .where('encSenderUId', isEqualTo: widget.encUId)
      .where('encReceiverUId', isEqualTo: _loggedInUserId)
      .orderBy('sentOn', descending: false)
      .startAt([_startAtTimestamp]).snapshots();

  return StreamZip([streamData1, streamData2]);
  // return StreamGroup.merge(streamData1, streamData2);
}

In the build widget calling as:
StreamBuilder<QuerySnapshot>(
    stream: _messagesStream(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {.......

I have used both methods StreamZip and StreamGroup.merge. None of them work.
Kindly suggest what is the issue and how can fix it? Thanks a lot.

A: You're not returning anything from ZipStream
ZipStream.zip2<QuerySnapshot, QuerySnapshot, List<Query DocumentSnapshot>>(streamData1, streamData2, (a, b) => [...a.docs, ...b.docs]);

Also wouldn't be easier to use only one snapshot? You only change the where, so maybe you could do 4 where or in to filter your data
FirebaseFirestore.instance
      .collection('messages')
      .where('encSenderUId', isEqualTo: widget.encUId)
      .where('encReceiverUId', isEqualTo: _loggedInUserId)
      .where('encSenderUId', isEqualTo: _loggedInUserId)
      .where('encReceiverUId', isEqualTo: widget.encUId)
      .orderBy('sentOn', descending: false)
      .startAt([_startAtTimestamp]).snapshots();

Or
FirebaseFirestore.instance
      .collection('messages')
      .where('encSenderUId', whereIn: [widget.encUId , _loggedInUserId])
      .where('encReceiverUId', isEqualTo: _loggedInUserId)
      .where('encReceiverUId', isEqualTo: widget.encUId)
      .orderBy('sentOn', descending: false)
      .startAt([_startAtTimestamp]).snapshots();


text:
Q: crm 2013 online custom workflow write to text file I am using CRM 2013 Online. I have a requirement to generate a batch file from crm records for our billing system. I was wondering if someone could confirm that a custom workflow on CRM online is able to write to a text file via streamwriter for example?

A: You can't write directly to text file via streamwriter with CRM Online, because workflows are sandboxed.
The alternative is to create the file in memory and add is at attachment to a record, or send it by email as attachment, or host a Web Service in Azure and store the file there, etc etc.


text:
Q: Automatically acquire IPV6 address in CentOS 6 The network has fixed IPv4 address, and automatic acquired IPv6 address. Does anyone have an idea how to setup? Thanks a lot!
I didn't use NetworkManager. The following is my setting, but it does not work :(
/etc/sysconfig/network:
NETWORKING=yes
HOSTNAME=desk.myname.ca
NETWORKING_IPV6=yes
IPV6FORWARDING=yes
IPV6_AUTOCONF=yes

/etc/sysconfig/network-scripts/ifcfg-eth0 :
DEVICE=eth0
TYPE="Ethernet"
UUID=29b0480a-83aa-4124-ab27-01dda940afv3
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPADDR=214.52.131.212
GATEWAY=214.52.137.1
NETMASK=255.255.255.0
DNS1=214.52.101.101
DNS2=214.52.101.100
NAME="System eth0"
HWADDR=49:73:E6:CC:6A:26
IPV6INIT=yes
IPV6_AUTOCONFIG=yes

I could not get the a global IPV6 address, as shown by the output of ifconfig:
eth0      Link encap:Ethernet  HWaddr 49:73:E6:CC:6A:26
          inet addr:214.52.131.212 Bcast:214.52.137.255  Mask:255.255.255.0
          inet6 addr: fe80::4637:e6ff:fecc:6a26/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2721783 errors:0 dropped:0 overruns:0 frame:0
          TX packets:526400 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:731944071 (698.0 MiB)  TX bytes:107641953 (102.6 MiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:3020 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3020 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:92956 (90.7 KiB)  TX bytes:92956 (90.7 KiB)

virbr0    Link encap:Ethernet  HWaddr 79:73:E1:1C:AA:61
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

A: In order to do SLAAC, you have to have a router that's sending Router Advertisements (RA), to provide the network prefix and prefix length.  That will also have the default gateway.
Something, somewhere on the local subnet needs to send the RAs.  Usually its the router, but there are some tools to have a Linux (or BSD) box send the RAs on behalf of the local router, if it' not able (like some home routers).
Also, make sure that you are accepting the RAs. See
net.ipv6.conf.default.accept_ra
net.ipv6.conf.all.accept_ra
and make sure they are set to 1


text:
Q: How to connect a Chat Client to a game server? I just want to create a "Chat Client" that can connect to a Game Server..
My problem is that I dont know how to start, I've already read several tutorials about socket programming / chat client / server client / etc. but I can't find a way to implement it on a game  server.
The server I want to connect is a Battle.net server "Warcraft III".
I've already know the IP Adress of the server but I dont know how will I able to access the game server.
The IP address of the server serves as a Webserver "acts a forum" and a GameServer "of course the game itself".
to summarize my problem:
I just want to create my own "Topaz Chat" using C# but I dont have any idea how to do it?
any idea? guys even a keyword is enough, I will try my best to find a tutorial for it. I know its hard to answer my question because I failed to provide any code T_T

A: First things first, you need to find out the protocol that the chat uses. Try to find answers to these questions:

*

*Do you really need raw sockets?

*Is the protocol a know protocol, such as IRC?

*What are the chat's commands and how are they processed?

When you find these answers, you'll be half way there.

A: If you are saying that you can access the Battle.net to get some informations, then I believe it uses a WEB SERVICE. Using it, you can request some informations or to create a room or something. You should not use socket programming. WCF is a highter level technology of .NET. Use it as web service.


text:
Q: sum based joining table on comma seperated values I have table cost like this

and table benang

can I sum (benang.biaya) when id_benang in table cost have same values on table benang
so the result like this
id_benang    biaya
8        = 4000000
6        = 4000000
       8000000

sory for my bad english

A: Presuming you want the total value from the benang table next to the cost information...
SELECT kain, id_cuci, cost_id_benang, SUM(biaya)
FROM
(
    SELECT b.id_benang, biaya, c.kain, c.id_cuci, c.id_benang as cost_id_benang
    FROM BENANG b
    INNER JOIN
    COST c
    ON LOCATE( RTRIM(CAST(b.id_benang AS CHAR(10))),c.id_benang) > 0
)AS seperatedData
GROUP BY kain, id_cuci, cost_id_benang

Using this sample schema and seed data:
CREATE TABLE COST (kain int, id_benang varchar(10), id_cuci int);
CREATE TABLE BENANG (id_benang int, biaya int);

INSERT INTO COST (kain, id_benang, id_cuci)
VALUES(8,'8,6', 3);

INSERT INTO BENANG(id_benang, biaya)
SELECT 5,3000000 UNION ALL
SELECT 6,4000000 UNION ALL
SELECT 7,3000000 UNION ALL
SELECT 8,4000000;


text:
Q: M2E - web project where are stored the options about target? I m trying to repair the Eclipse Maven Web project, where after some build the folder
disappeared.
I get: target/classes and target/generated sources folder, but no
/target/m2e-wtp/web-resources, what suppose to be there according to settings(see below)
I can not solve the problem from any menu in "properties", so i looked at the config files of the project.
The project name is TomkatFromArchetype.
I searched in this forum for solution and checked my settings files like:

* /.metadata/src/main/webapp/WEB-INF/faces-config.pageflow is :
<?xml version="1.0" encoding="UTF-8"?>
<pageflow:Pageflow xmlns:pageflow="http://www.sybase.com/suade/pageflow" id="pf15021503419240" configfile="/TomkatFromArchetype/src/main/webapp/WEB-INF/faces-config.xml"/>

in /.settings/org.eclipse.wst.common.component must be like :
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
    <wb-module deploy-name="TomkatFromArchetype">
        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
        <wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
        <wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java2"/>
        <property name="context-root" value="TomkatFromArchetype"/>
        <property name="java-output-path" value="/TomkatFromArchetype/target/classes"/>
    </wb-module>
</project-modules>

So you can see, the entry
 <wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>

is there, as mentioned in the topic
here
also /.settings/.jsdtscope (maybe it is important) is like :
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src/main/webapp" />
    <classpathentry excluding="**/bower_components/*|**/node_modules/*|**/*.min.js"
        kind="src" path="target/m2e-wtp/web-resources" />
    <classpathentry kind="con"
        path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER" />
    <classpathentry kind="con"
        path="org.eclipse.wst.jsdt.launching.WebProject">
        <attributes>
            <attribute name="hide" value="true" />
        </attributes>
    </classpathentry>
    <classpathentry kind="con"
        path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary" />
    <classpathentry kind="output" path="" />
</classpath>

Is there other config files, what are related to the question or how else must i set it properly?
Thie web file are strangely located now in :
workspaceEclipse.metadata.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\TomkatFromArchetype\


text:
Q: How to properly Queue animations/transitions using the jQuery Cycle Plugin I'm working on this project
I want to queue my animations in the fader/slider.
<script>
$(function() {
  // Hover Switch
   function fnFadeHover(){$('#feature_fadeSlideshow').cycle($('#feature_fadeBtns li').index($(this).parent()));}
   function fnFadeOut(){}
   $('#feature_fadeSlideshow').cycle({
     //fx:'fade',
     timeout:9000,
     delay:5000,
     pause:true,
     after:onAfter,
     before: function(currSlideElement, nextSlideElement, options, afterCallBack, forwardFlag){
       console.log('before');
       var slide_index = $('#feature_fadeSlideshow .panel').index(nextSlideElement);
       $('#feature_fadeBtns li').removeClass('activePager').eq(slide_index).addClass('activePager');

        $('#auto-automobile').animate({"top": "75px","left": "-2000px"}, "slow",  function(){
           $('#auto-sun').animate({"top": "-300px"}, "slow", function(){
             $('#auto-cloud').animate({"top": "20px", "right":"300px"}, "slow", function(){
               $('#auto-smallCloud').animate({"top": "10px"}, "slow")})

         $('#home-house').animate({"top": "-300px", "left": "310px"}, "slow", function(){
           $('#home-tree').animate({"bottom":"-400px"}, "slow", function(){
             $('#home-smallCloud').animate({"top": "20px"}, "slow")})
           });

          $('#business-highway').animate({"top": "-200px"}, "slow", function(){
           $('#business-buildings').animate({"bottom": "-400px"}, "slow", function(){
             $('#business-cloud').animate({"top": "20px"}, "slow")})
           });

          $('#life-object').animate({"top": "150px"}, "slow", function(){
           $('#life-flowers').animate({"top": "131px"}, "slow", function(){
             $('#life-scope').animate({"top": "284px"}, "slow")})
           });

          });
         });
     }});
   $('#feature_fadeBtns li a').hoverIntent(fnFadeHover,300,fnFadeOut);
});
      function onAfter() {
           $('#auto-automobile').animate({"top": "75px","left": "260px"}, "slow", function(){
               $('#auto-sun').animate({"top": "0px", "right":"400px"}, "slow", function(){
                 $('#auto-cloud').animate({"top": "20px"}, "slow", function(){
                   $('#auto-smallCloud').animate({"top": "20px", "left": "415px"}, "slow")})

         $('#home-house').animate({"top": "105px", "left": "310px"}, "slow", function(){
           $('#home-tree').animate({"top": "90px"}, "slow", function(){
             $('#home-smallCloud').animate({"top": "25px", "right":"5px"}, "slow")})
           });

          $('#business-highway').animate({"top": "200px"}, "slow", function(){
           $('#business-buildings').animate({"bottom": "60px"}, "slow", function(){
             $('#business-cloud').animate({"top": "30px"}, "slow")})
           });

          $('#life-object').animate({"top": "150px"}, "slow", function(){
           $('#life-flowers').animate({"top": "131px"}, "slow", function(){
             $('#life-scope').animate({"top": "284px"}, "slow")})
           });
        });
      });
}
</script>
[[Content]]

Goal
If you hover over the navigation under the fader/slider you will see that my animations are not working properly. They Jump around. I want the animation to animate when i hover over auto/home/business or life or when they transition.
As of right now it isn't working properly. Any suggestions?

A: I think you are trying to do something like this:
jsFiddle DEMO
What I was trying to convey in comments is that you want your positions to start as hidden (whatever top/bottom px amount it takes to do that). THEN, you animate then into the correct position.
Super basic example, but you get the idea here. They originally started off as hidden from view, then they both appear one at a time.
#one { position:absolute; top:-500px; }
#two { position:absolute; bottom:-500px; }

$('#one').animate({ left: '50px', top: '0px' }, 'slow', function () {
    $('#two').animate({ left: '200px', bottom: '200px' }, 'slow');
});


text:
Q: best Segmentation algorithm I'm trying to develop a system, which recognizes various objects present in an image based on their primitive features like texture, shape & color.
The first stage of this process is to extract out individual objects from an image and later on doing image processing on each one by one.
However, segmentation algorithm I've studied so far are not even near perfect or so called Ideal Image segmentation algorithm.
Segmentation accuracy will decide how much better the system responds to given query.
Segmentation should be fast as well as accurate.
Can any one suggest me any segmentation algorithm developed or implemented so far, which won't be too complicated to implement but will be fair enough to complete my project..
Any Help is appreicated..

A: A very late answer, but might help someone searching for this in google, since this question popped up as the first result for "best segmentation algorithm".
Fully convolutional networks seem to do exactly the task you're asking for. Check the paper in arXiv, and an implementation in MatConvNet.
The following image illustrates a segmentation example from these CNNs (the paper I linked actually proposes 3 different architectures, FCN-8s being the best).

A: Unfortunately, the best algorithm type for facial recognition uses wavelet reconstruction.  This is not easy, and almost all current algorithms in use are proprietary.
This is a late response, so maybe it's not useful to you but one suggestion would be to use the watershed algorithm.
beforehand, you can use a generic drawing(black and white) of a face, generate a FFT of the drawing---call it *FFT_Face*.
Now segment your image of a persons face using the watershed algorithm. Call the segmented image *Water_face*.
now find the center of mass for each contour/segment.
generate an FFT of *Water_Face*, and correlate it with the *FFT_Face image*.  The brightest pixel in resulting image should be the center of the face. Now you can compute the distances between this point and the centers of segments generated earlier.  The first few distances should be enough to distinguish one person from another.
I'm sure there are several improvements to the process, but the general idea should get you there.

A: Doing a Google search turned up this paper: http://www.cse.iitb.ac.in/~sharat/papers/prim.pdf
It seems that getting it any better is a hard problem, so I think you might have to settle for what's there.

A: you can try the watershed segmentation algorithm
also you can calculate the accuracy of the segmentation algorithm by the qualitative measures


text:
Q: Approximation on partitions in $L^2([0,1]\times \Omega)$ I'm working on Nualart's book "The Malliavin calculus and related topics" and in the proof of lemma 1.1.3 he mentions that the operators $P_n$ have their operator norm bounded by 1. I fail to see why, can you help me? Using Jensen's inequality I get a norm more akin to $2^n$, so I guess Jensen is too weak to prove that?
Quoting the proof:
Let $u$ be a process in $L^2_a([0,1]\times\Omega)$ ($L^2_a$ are the adapted processes w.r.t Brownian motion) and consider the sequence of processes defined by
$\tilde u^n(t)=\sum_{i=1}^{2^n-1}2^n\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)ds\right)1_{]i2^{-n},(i+1)2^{-n}]}(t)$.
We claim that the sequence converges to $u$ in $L^2([0,1]\times\Omega)$. In fact define $P_n(u)=\tilde u^n$. Then $P_n$ is a linear operator in $L^2([0,1]\times\Omega)$ with norm bounded by one.

A: I believe that there are some typos. It should be
\begin{align*}
\tilde u^n(t)=\sum_{i=1}^{\color{red}{2^n}}2^n\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)ds\right)1_{]\color{red}{(i-1)2^{-n}, i2^{-n}}]}(t)
\end{align*}
Then, note that
\begin{align*}
E\left(\int_0^1\left(\tilde{u}^n\right)^2dt \right)&=\sum_{i=1}^{2^n}2^{2n}E\left(\int_{(i-1)2^{-n}}^{i2^{-n}}\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)ds\right)^2 dt\right)\\
&=\sum_{i=1}^{2^n}2^{n}E\left(\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)ds\right)^2 \right)\\
&\le \sum_{i=1}^{2^n}2^{n}E\left(\int_{(i-1)2^{-n}}^{i2^{-n}}1^2ds\int_{(i-1)2^{-n}}^{i2^{-n}}u^2(s)ds \right) \ \ \text{(by Schwarz inequality)}\\
&= \sum_{i=1}^{2^n}E\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u^2(s)ds\right)\\
&= E\left(\sum_{i=1}^{2^n}\int_{(i-1)2^{-n}}^{i2^{-n}}u^2(s)ds\right)\\
&= E\left(\int_0^{1}u^2(s)ds \right)\\
&=||u||^2.
\end{align*}
Therefore, $P$ has norm 1.

A: Jensen inequality works fine. Indeed (correcting the mistake spotted by Gordon):
$$\int_0^1 (\tilde{u}^n)^2 (t) dt
= \int_0^1 \sum_{i=0}^{2^n-1}\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)2^nds\right)^2 1_{]i2^{-n},(i+1)2^{-n}]}(t) dt,$$
since all the caracteristic functions have disjoint support. Hence, using Jensen inequality (with the probability measures $2^n ds$ on each interval $]i2^{-n},(i+1)2^{-n}]$):
$$\begin{align}\|P_n u\|_{\mathbb{L}^2}^2
& \leq \int_0^1 \sum_{i=0}^{2^n-1}\left(\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)^2 2^nds\right) 1_{]i2^{-n},(i+1)2^{-n}]}(t) dt \\
& = \sum_{i=0}^{2^n-1} \left(2^n\int_{(i-1)2^{-n}}^{i2^{-n}}u(s)^2 ds\right) \int_0^1 1_{]i2^{-n},(i+1)2^{-n}]}(t) dt \\
& = \sum_{i=0}^{2^n-1} \int_{(i-1)2^{-n}}^{i2^{-n}}u(s)^2 ds \\
& = \|u\|_{\mathbb{L}^2}^2. \end{align}$$
So, in this case, Jensen's inequality is not weaker; you just need to be careful on where you apply it.
Note, by the way, that this can be proved much faster. Fix $n\geq 0$. Let $\pi_n := \{]i2^{-n},(i+1)2^{-n}]: \ 0 \leq i < 2^n\}$, and $\mathcal{C}_n := \sigma (\pi_n)$ be the $\sigma$-algebra generated by $\pi_n$. Then:
$$P_n (u) = \mathbb{E} (u | \mathcal{C}_n),$$
and the conditional expectation is always a weak $\mathbb{L}^2$ contraction, which can be proved for instance with the conditional version of Jensen inequality:
$$\mathbb{E} (P_n (u)^2) = \mathbb{E} (\mathbb{E} (u | \mathcal{C}_n)^2) \leq \mathbb{E} (\mathbb{E} (u^2 | \mathcal{C}_n)) = \mathbb{E} (u^2).$$
This point of view makes more sense from a probabilist's standpoint, I think.


text:
Q: UDF and fstab (no UUID) In my search for the ideal filesystem to share files between a lot of computer with a lot of different OS'es I accepted this answer and installed a UDF filesystem on my USB stick.
First I blanked the disk, to make sure there are no leftovers to confuse a system that's reading the drive:
dd if=/dev/zero of=/dev/sdb bs=1M

Then I formatted the drive, using udftools from arch linux's AUR:
sudo mkudffs --media-type=hd --blocksize=512 /dev/sdb

Obviously, the drive was in /dev/sdb.
Now my question is, since the drive doesn't have any traditional partitions or even a partition table as far as I know, it does not have a UUID. Therefore, I
can not add it to the fstab, which I find rather annoying.
What can I do to fix this (e.g. is there an alternative way to set default mount point and options, or an alternate partitioning option)?

A: Choose a blocksize of at least 2K (which is the default) and add --vid= to your mkudffs parameters.  (The blkid from util-linux doesn't seem to cope with smaller blocksizes.)

$ mkudffs --media-type=hd --vid=my-drive /dev/sdj
$ blkid /dev/sdj
/dev/sdj: LABEL="my-drive" TYPE="udf"

Now you can use LABEL=my-drive in /etc/fstab.

A: If you need blocksize=512 for Windows compatibility, there is a fix to util-linux that updates blkid to recognize vid as label on any block size.  It has not gotten into a released version yet; it was committed on March 1, 2013.  There is also a bug in the udf kernel module that prevents it from using a partition larger than 128G - the fix for that was committed to mainline in early February and has just been committed to the 3.0-stable, 3.4-stable, and 3.8-stable branches.

A: Make sure that you use --blocksize=512 (unless you have native 4k disk). UDF blocksize must matches logical (sector) size of the disk which is 512 bytes. Older mkudfffs versions are unable to detect logical sector size and fallback to value CD/DVD value 2048 (which cause problems for other OS as they do not expect CD/DVD blocksize on hard disks).
blkid from the util-linux v2.30 provides UUID also for UDF filesystems, so just upgrade util-linux to new version and then you can use UUID in /etc/fstab. UUID is calculated from the UDF Volume Set Identifier which has by UDF definition, first 16 characters unique, non-trivial, non-fixed and suitable to guarantee unique identifier.
Also mkudffs since version 1.1 has option --uuid= for specifying own UUID.

A: Alternatively, you can put on an FS label, and then mount using the LABEL= option. This definitely works, but it doesn't meet your UUID criteria.

A: Does your distribution have /dev/disk/by-* symlinks?
Among them, you could probably find a way to identify the USB-stick-with-UDF in a way that won't vary like /dev/sd* could.

A: Well, UUID is not a parition-only attribute, actually.
man mkudffs mentions:

*

*--lvid=logical-volume-ident — Specify the logical volume identifier.

*--vid=volume-ident — Specify the volume identifier.

*--vsid=volume-set-ident — Specify the volume set identifier.

Have you tried using any of it?


text:
Q: Order of growth for algorithms: $\log(n)^{4}$or $\log(n)^{4}$ vs $5\sqrt(n)$ I am not sure how to compare behaviour of $\log^4n$ or $\log^2n$ to $5\sqrt n $ for growth. Can someone help me compare it with an explanation?

A: Try taking the logarithm.
$$\log(\log^4 n) =4\log \log n$$
$$\log 5\sqrt n=\frac12\log n+\log 5$$
If you are comfortable with the fact that $\log x$ is asymptotically smaller than $ax$ for any $a>0$, it is clear which is larger.


text:
Q: Qt WebKit and HTML5 geolocation I'm learning HTML5 and testing the new features on a Qt hybrid application.
Now I'm working on a simple geolocation example but when I call navigator.geolocation.getCurrentPosition(displayLocation); it seems the QtWebKit does not support it, but acording to this http://trac.webkit.org/wiki/QtWebKitFeatures22 the version of QtWebKit that comes with Qt4.8.0 supports geolocation.
This is the code I'm using:
window.onload = function()
{
    getMyLocation();
}

function getMyLocation()
{
    if(navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(displayLocation);
    }
    else
    {
        alert("No geolocation support");
    }
}

function displayLocation(position)
{
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var div = document.getElementById("location");

    div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}

And on the Qt side:
QWebView* MyWindow::createWebView()
    {
        QWebSettings* default_settings = QWebSettings::globalSettings();
        default_settings->setAttribute(QWebSettings::JavascriptEnabled,true);
        default_settings->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled,true);
        default_settings->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,true);
        default_settings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,true);
        default_settings->setAttribute(QWebSettings::LocalStorageEnabled,true);
        default_settings->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);
        default_settings->setAttribute(QWebSettings::DeveloperExtrasEnabled,true);

        QWebView* web_view = new QWebView(this);

        connect(web_view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
                this, SLOT(addJavascriptObject()));

        inspector_->setPage(web_view->page());

        inspector_->setVisible(true);
        inspector_->show();

        web_view->load(QUrl("qrc:/html/geolocation_example.html"));

        return web_view;
    }

Anyone knows how to enable Html5 geolocation for a Qt desktop app?

A: You need to subclass QWebPage and make a signal handler for the QWebPage::featurePermissionRequested(QWebFrame*, QWebPage::Feature) signal.
Here is a reference implementation:
class WebPage : public QWebPage
{
    Q_OBJECT

    public:
        WebPage(QObject* parent = 0) :
            QWebPage(parent)
        {
            connect(this, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), SLOT(permissionRequested(QWebFrame*, QWebPage::Feature)));
        }

        virtual ~WebPage()
        {
        }

    private slots:
        void permissionRequested(QWebFrame* frame, QWebPage::Feature feature)
        {
            setFeaturePermission(frame, feature, PermissionGrantedByUser);
        }
};

Use QWebView::setPage() with an instance of your newly created subclass to make QtWebKit use your QWebPage implementation.
In case you need more help, have a look at the QtMiniBrowser which is part of the WebKit.org repository. The source code is available from here http://trac.webkit.org/browser/trunk/Tools/QtTestBrowser


text:
Q: how to hide the iphone top bar? I am new to ios development .......
When My App is run There is one BAR Appear on top of the screen .....Which Contains
network , digital clock and battery symbol
how i can hied this bar ?
  thanks in advance.........
[window addSubview:navigationController.view];
[window makeKeyAndVisible];

arryName = [[NSMutableArray alloc] initWithObjects:@"Savasana",@"Makarasana",@"Padahastasana",@"Natarajasana",@"Ustrasana",@"Hanumanasana",@"Garbhasana",@"Bhujapidasana",@"Astavakrasana(Eight-Angle Pose)",@"Mayurasana",@"Paschimottanasana",@"Janu Sirsasana",@"Urdhva Mukha Svanasana",@"Urdhva Dhanurasana",@"Bhujangasana",@"Bakasana",@"Surya Namaskar",@"Akarna Dhanur asana",@"Anjaneya asana",@"Ardha Chandra asana",@"Ardha Matsyendra asana",@"Baddha Kona Asana",@"Bala Asana",@"Chakra Asana",@"Dhanur asana",@"Ekapada asana",@"Garuda asana",@"Gomukha asana",@"Hala sana",@"Hasta Pada angusta",@"Matsya asana",@"Naga asana",@"Nataraja asana",@"Padma asana",@"Parivritta parshvakona",@"Pavana mukta asana",@"Sarvanga asana",@"Shalabha asana",@"Shava asana",@"Siddha asana",@"Simha asana",@"Sirsha asana",@"Tada asana",@"Trikona asana",@"Ugra asana",@"Ushtra asana",@"Vajra asana",@"Vira asana",@"Vriksha asana",@"Vrischika asana",@"Anjali Mudra",@"Ardha Matsyendrasana",nil];

arryImage = [[NSMutableArray alloc]initWithObjects:@"savasana_248.jpg",@"crocodile.jpg",@"Padahastasana.jpg",@"Natarajasana_248.jpg",@"Ustrasana_248.jpg",@"Hanumanasana_248.jpg",@"garbhasana.gif",@"bhujapidasana_1.jpg",@"Astavakrasana_248.jpg",@"Mayurasana.jpg",@"Paschimottanasa_248.jpg",@"JanuSirsasana.jpg",@"UrdhvaMukhaSvanasana.jpg",@"UrdhvaDhanurasana.jpg",@"Bhujangasana.jpg",@"Bakasana.jpg",@"1_Surya-namaskar.png",@"2-akarna_dhanurasana.png",@"3-Anjanya.png",@"4-ardha-chand.png",@"5-Adhamatsya.png",@"6-Baddha-kona.png",@"7-child-pose-balasana.png",@"8-Chakrasana-wheel-pose.png",@"9-Dhanura_asana-Bow_Pose.png",@"10-ekapada-asana-the-one-legged-pose.png",@"11-garudasana.png",@"12-gomukhasana.png",@"13-Halasan.png",@"14-Hasta.Padangusthasana.png",@"15-Matsyasana.png",@"16-naga-vj-g.png",@"17-natarajasana.png",@"18--padma.png",@"19--Parivrtta_Parsvakonasana-Revolved_Side_Angle_Pose.png",@"20-PAWANMUKTASANA.png",@"21-SHOULDER STAND.png",@"22--Salabhasana.png",@"23-Savasana.png",@"24-SIDDHASANA.png",@"25-Simha-asan-the lion.png",@"26-Sirsasana.png",@"27-Tada_Asana.png",@"28-Trikona_Asana.png",@"29-Ugra-asna-the Noblepose.png",@"30--ustrasana.png",@"31--Vijrasana.png",@"32-Vira-asna-the hero pose.png",@"33--Vriksha_Asana-Tree_Pose.png",@"34-VariskhikaiPad.png",@"AnjaliMudra.jpg",@"ArdhaMatsyendrasana.jpg",nil];

A: In your Project Info.plist file set Status bar is initially hidden YES, This will hide status bar for complete project.

And if you want to hide status bar in particular view the
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:<#(UIStatusBarAnimation)#>];

A: Try the below code
[[UIApplication sharedApplication] setStatusBarHidden:YES];

A: It's called "Status Bar".
You can hide it by adding below line in "AppDidFinishLauching" method in "AppDelegate":
[[UIApplication sharedApplication] setStatusBarHidden:YES];

You can also hide it from .plist file.
Cheers.

A: In your ProjectName-Info.plist file set Status bar is initially hidden YES
otherwise use [[UIApplication sharedApplication] setStatusBarHidden:YES];

A: Its Called Status bar:
if you want to hide status bar then write following code in didFinishLaunchingWithOptions method AppDelegate
 [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];

This code hide status bas with animation , if you want to remove animation then set withAnimation:NO
Another Way that automatically set size of your viewController when status bar hide :
 CGRect appFrame = [[UIScreen mainScreen] applicationFrame];

        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBar.frame = self.navigationController.navigationBar.bounds;
            self.view.window.frame = CGRectMake(0, 0, appFrame.size.width, appFrame.size.height);
        }];


text:
Q: What are these extra symbols in a comprehension's symtable? I'm using symtable to get the symbol tables of a piece of code. Curiously, when using a comprehension (listcomp, setcomp, etc.), there are some extra symbols I didn't define.
Reproduction (using CPython 3.6):
import symtable

root = symtable.symtable('[x for x in y]', '?', 'exec')
# Print symtable of the listcomp
print(root.get_children()[0].get_symbols())

Output:
[<symbol '.0'>, <symbol '_[1]'>, <symbol 'x'>]

Symbol x is expected. But what are .0 and _[1]?
Note that with any other non-comprehension construct I'm getting exactly the identifiers I used in the code. E.g., lambda x: y only results in the symbols [<symbol 'x'>, <symbol 'y'>].
Also, the docs say that symtable.Symbol is...

An entry in a SymbolTable corresponding to an identifier in the source.

...although these identifiers evidently don't appear in the source.

A: The two names are used to implement list comprehensions as a separate scope, and they have the following meaning:

*

*.0 is an implicit argument, used for the iterable (sourced from y in your case).

*_[1] is a temporary name in the symbol table, used for the target list. This list eventually ends up on the stack.*
A list comprehension (as well as dict and set comprehension and generator expressions) is executed in a new scope. To achieve this, Python effectively creates a new anonymous function.
Because it is a function, really, you need to pass in the iterable you are looping over as an argument. This is what .0 is for, it is the first implicit argument (so at index 0). The symbol table you produced explicitly lists .0 as an argument:
>>> root = symtable.symtable('[x for x in y]', '?', 'exec')
>>> type(root.get_children()[0])
<class 'symtable.Function'>
>>> root.get_children()[0].get_parameters()
('.0',)

The first child of your table is a function with one argument named .0.
A list comprehension also needs to build the output list, and that list could be seen as a local too. This is the _[1] temporary variable. It never actually becomes a named local variable in the code object that is produced; this temporary variable is kept on the stack instead.
You can see the code object produced when you use compile():
>>> code_object = compile('[x for x in y]', '?', 'exec')
>>> code_object
<code object <module> at 0x11a4f3ed0, file "?", line 1>
>>> code_object.co_consts[0]
<code object <listcomp> at 0x11a4ea8a0, file "?", line 1>

So there is an outer code object, and in the constants, is another, nested code object. That latter one is the actual code object for the loop. It uses .0 and x as local variables. It also takes 1 argument; the names for arguments are the first co_argcount values in the co_varnames tuple:
>>> code_object.co_consts[0].co_varnames
('.0', 'x')
>>> code_object.co_consts[0].co_argcount
1

So .0 is the argument name here.
The _[1] temporary variable is handled on the stack, see the disassembly:
>>> import dis
>>> dis.dis(code_object.co_consts[0])
  1           0 BUILD_LIST               0
              2 LOAD_FAST                0 (.0)
        >>    4 FOR_ITER                 8 (to 14)
              6 STORE_FAST               1 (x)
              8 LOAD_FAST                1 (x)
             10 LIST_APPEND              2
             12 JUMP_ABSOLUTE            4
        >>   14 RETURN_VALUE

Here we see .0 referenced again. _[1] is the BUILD_LIST opcode pushing a list object onto the stack, then .0 is put on the stack for the FOR_ITER opcode to iterate over (the opcode removes the iterable from .0 from the stack again).
Each iteration result is pushed onto the stack by FOR_ITER, popped again and stored in x with STORE_FAST, then loaded onto the stack again with LOAD_FAST. Finally LIST_APPEND takes the top element from the stack, and adds it to the list referenced by the next element on the stack, so to _[1].
JUMP_ABSOLUTE then brings us back to the top of the loop, where we continue to iterate until the iterable is done. Finally, RETURN_VALUE returns the top of the stack, again _[1], to the caller.
The outer code object does the work of loading the nested code object and calling it as a function:
>>> dis.dis(code_object)
  1           0 LOAD_CONST               0 (<code object <listcomp> at 0x11a4ea8a0, file "?", line 1>)
              2 LOAD_CONST               1 ('<listcomp>')
              4 MAKE_FUNCTION            0
              6 LOAD_NAME                0 (y)
              8 GET_ITER
             10 CALL_FUNCTION            1
             12 POP_TOP
             14 LOAD_CONST               2 (None)
             16 RETURN_VALUE

So this makes a function object, with the function named <listcomp> (helpful for tracebacks), loads y, produces an iterator for it (the moral equivalent of iter(y), and calls the function with that iterator as the argument.
If you wanted to translate that to Psuedo-code, it would look like:
def <listcomp>(.0):
    _[1] = []
    for x in .0:
        _[1].append(x)
    return _[1]

<listcomp>(iter(y))

The _[1] temporary variable is of course not needed for generator expressions:
>>> symtable.symtable('(x for x in y)', '?', 'exec').get_children()[0].get_symbols()
[<symbol '.0'>, <symbol 'x'>]

Instead of appending to a list, the generator expression function object yields the values:
>>> dis.dis(compile('(x for x in y)', '?', 'exec').co_consts[0])
  1           0 LOAD_FAST                0 (.0)
        >>    2 FOR_ITER                10 (to 14)
              4 STORE_FAST               1 (x)
              6 LOAD_FAST                1 (x)
              8 YIELD_VALUE
             10 POP_TOP
             12 JUMP_ABSOLUTE            2
        >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE

Together with the outer bytecode, the generator expression is equivalent to:
def <genexpr>(.0):
    for x in .0:
        yield x

<genexpr>(iter(y))

* The temporary variable is actually no longer needed; they were used in the initial implementation of comprehensions, but this commit from April 2007 moved the compiler to just using the stack, and this has been the norm for all of the 3.x releases, as well as Python 2.7. It still is easier to think of the generated name as a reference to the stack. Because the variable is no longer needed, I filed issue 32836 to have it removed, and Python 3.8 and onwards will no longer include it in the symbol table.
In Python 2.6, you can still see the actual temporary name in the disassembly:
>>> import dis
>>> dis.dis(compile('[x for x in y]', '?', 'exec'))
  1           0 BUILD_LIST               0
              3 DUP_TOP
              4 STORE_NAME               0 (_[1])
              7 LOAD_NAME                1 (y)
             10 GET_ITER
        >>   11 FOR_ITER                13 (to 27)
             14 STORE_NAME               2 (x)
             17 LOAD_NAME                0 (_[1])
             20 LOAD_NAME                2 (x)
             23 LIST_APPEND
             24 JUMP_ABSOLUTE           11
        >>   27 DELETE_NAME              0 (_[1])
             30 POP_TOP
             31 LOAD_CONST               0 (None)
             34 RETURN_VALUE

Note how the name actually has to be deleted again!

A: So, the way list-comprehensions are implemented is actually by creating a code-object, it is sort of like creating a one-time use anonymous function, for scoping purposes:
>>> import dis
>>> def f(y): [x for x in y]
...
>>> dis.dis(f)
  1           0 LOAD_CONST               1 (<code object <listcomp> at 0x101df9db0, file "<stdin>", line 1>)
              3 LOAD_CONST               2 ('f.<locals>.<listcomp>')
              6 MAKE_FUNCTION            0
              9 LOAD_FAST                0 (y)
             12 GET_ITER
             13 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             16 POP_TOP
             17 LOAD_CONST               0 (None)
             20 RETURN_VALUE
>>>

Inspecting the code-object, I can find the .0 symbol:
>>> dis.dis(f.__code__.co_consts[1])
  1           0 BUILD_LIST               0
              3 LOAD_FAST                0 (.0)
        >>    6 FOR_ITER                12 (to 21)
              9 STORE_FAST               1 (x)
             12 LOAD_FAST                1 (x)
             15 LIST_APPEND              2
             18 JUMP_ABSOLUTE            6
        >>   21 RETURN_VALUE

Note, the LOAD_FAST in the list-comp code-object seems to be loading the unnamed argument, which would correspond to the GET_ITER


text:
Q: jQuery: $.ajax success callback doesn't let me assign to outside private variable var doCheck = function() {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            data = resp;
        }
    });
console.log(data);
    return data == 1;
};

The above code, regardless of the data only ever returns a 0 or a 1. Within the scope of the success callback, this is true. The argument resp has a value of 0 or 1 depending on input.
However, whenever I try to access a private variable (should not be affected by scope), nothing happens; and when console.log(data); is called all that is written to the console is undefined.
This function has no parent, so don't worry about some other kind of scope interference.

A: Ajax is asynchronous. Which is why you have to organize your logic with callbacks:
var doCheck = function(callback) {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            callback(data == 1);
        }
    });
};

doCheck(function(result) {
    // result is true or false
});

A: Place the 'console.log(data)' sentence after 'data=resp'.
Probably it is executing before the success method and becuase this it has no value set.

A: It takes time till you get the response, so the console.log() comes when the data isn't set yet

A: This is because the ajax Request by default is asynchronous, however instead of making it synchronous, I'd suggest redesigning you're approach.

A: Ajax stands for Asynchronous JavaScript and XML. data is being set after the call to the server returns, and only if the call was sucessfull.
The console.log is happening immediatly after sending the async request off, before the sucess has a chance to run.


text:
Q: How to prove that the projection length $\frac{x^T y}{\|x\|}$ is normally distributed if $x,y\sim N(0,I_p)$? $x,y\in\mathbb{R}^p$ are independently drawn from the standard multivariate Gaussian distribution $N(0,I_p)$. How do you prove that the projection length $z=\frac{x^T y}{\|x\|}$ is normally distributed?
If $x$ is fixed, then $z$ is just a linear combination of the entries of $y$, so it is normally distributed. And we can easily calculate the mean and variance, so $z|x\sim N(0,1)$ for any $x$. Is this enough to conclude that $z\sim N(0,1)$ unconditionally?

A: In essence yes! It follows from the law of total probability as mentioned by @Mathew Pilling. If you calculate $$P(z \le t) = \int P(z \le t|x) f_X(x)dx= \Phi(t)$$
since $P(z \le t|x) = \Phi(t)$, and $f_X$, the density of $x$ integrates to 1.


text:
Q: 3D perspective mode using xy package Starting from this code where I have used xy package:
\documentclass[a4paper,12pt]{article}
\usepackage{amssymb}
\usepackage[all,cmtip]{xy}

\begin{document}
\xymatrix@!0{
& \alpha \ar@{-}[rr]\ar@{-}'[d][dd]
& & \beta D \ar@{-}[dd]
\\
\gamma \ar@{-}[ur]\ar@{-}[rr]\ar@{-}[dd]
& & \delta A \ar@{-}[ur]\ar@{-}[dd]
\\
& ax \ar@{-}'[r][rr]
& & bx\xi\mu
\\
\Gamma_r(f(x,y)) \ar@{-}[rr]\ar@{-}[ur]
& & \lambda P \ar@{-}[ur]
}
\end{document}

looking this image taken in this question,

the labels seem to be rotated, put in a frontal perspective. Is it possible to do this with the xy package instead of tikz-cd?

A: Second approach
With the extension Rotate and Scale extension by Ross Moore you can also achieve a similar output. Therefore, load the option \xyoption{rotate} and add the argument [@!<number>] . For further details, see p. 29 of Reference manual
\documentclass[a4paper,12pt]{article}
\usepackage{amssymb}
\usepackage[all,cmtip]{xy}
\xyoption{rotate}

\begin{document}
    \def\angle{50}
    \xymatrix@!0{
        & *+[@!\angle]{\alpha} \ar@{-}[rr]\ar@{-}'[d][dd]
        & & *+[@!\angle]{\beta D} \ar@{-}[dd]
        \\
        \gamma \ar@{-}[ur]\ar@{-}[rr]\ar@{-}[dd]
        & & \delta A \ar@{-}[ur]\ar@{-}[dd]
        \\
        & *+=[@!\angle]{ax} \ar@{-}'[r][rr]
        & & *+=[@!\angle]{bx\xi\mu}
        \\
        \Gamma_r(f(x,y)) \ar@{-}[rr]\ar@{-}[ur]
        & & \lambda P \ar@{-}[ur]
    }
\end{document}

First approach
The answer of David Carlisle to Rotating labels in xypic shows you a possible solution, that is, using for example the \rotatebox command of the graphicx package.
\documentclass[a4paper,12pt]{article}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage[all,cmtip]{xy}

\begin{document}
\def\angle{50}
\xymatrix@!0{
& \rotatebox[origin=c]{\angle}{$\alpha$} \ar@{-}[rr]\ar@{-}'[d][dd]
& & \rotatebox[origin=c]{\angle}{$\beta D$} \ar@{-}[dd]
\\
\gamma \ar@{-}[ur]\ar@{-}[rr]\ar@{-}[dd]
& & \delta A \ar@{-}[ur]\ar@{-}[dd]
\\
& \rotatebox[origin=c]{\angle}{ax} \ar@{-}'[r][rr]
& & \rotatebox[origin=c]{\angle}{$bx\xi\mu$}
\\
\Gamma_r(f(x,y)) \ar@{-}[rr]\ar@{-}[ur]
& & \lambda P \ar@{-}[ur]
}
\end{document}


text:
Q: Am I right in interpreting the part in bold?
Everard Gault had been missing in 1915; and waiting, not knowing, had
been the loneliest time of Heloise's life, her two-year-old baby her greatest
comfort. Then a telegram had come, and soon afterwards she had closed
her eyes in selfish relief when there was the news that her husband had
been invalided out of the army. As long as they lived, she vowed to herself,
she would never again be parted from him, her resolve an expression of
her gratitude for this kind misfortune.

Is "close your eye to something" the same as "close your eye in something"?
And does the part in bold mean: when there was the news that her husband had been invalided out of the army she was not proud and selfish of this relief and vowed to herself that as long as they lived she would never again be parted from him and in this kind of misfortune she decided to show her gratitude because of that time and not to be parted from her husband?
Source: The Story Of Lucy Gault by William trevor

A: In she had closed her eyes in selfish relief, in selfish relief is describing the manner (how?) she closed her eyes. "in selfish relief" could also be expressed by "with selfish relief" which may be more comprehensible for non-natives, but less idiomatic.
The author means that she was relieved by the fact that her husband was invalided from the army, and this was selfish because, although her husband must have gone through physical suffering and lost his career, she was only thinking of her own advantage of having him back home.
As for the rest of the passage in bold, you can see a ellipsis there:

As long as they lived, she vowed to herself, she would never again be parted from him, her resolve (being) an expression of her gratitude for this kind misfortune.

Her resolve not to depart from her husband for the rest of her life is the expression of her gratitude for the fact that he is coming back home due to unfortunate circumstances.
I like the use of the oxymoron kind misfortune. It is a misfortune for her husband and for her (if she shares in the suffering of her husband in any way), but it is a kind one for her, because they are reunited.


text:
Q: Um service do Android trava a aplicação mesmo rodando em background? Um service do Android trava a aplicação mesmo rodando em background? Ou há algo de errado na minha aplicação?
Tenho um banco de dados aonde a última tabela tem 3000 linhas. Com isso resolvi inserir em background usando uma service para dar mais rapidez para o usuário na hora da inserção. Porém este service está travando minha aplicação, e só libera a minha aplicação quando a Thread inserir todos os dados no banco.
Alguém sabe o que pode ser? Segue o código.
public class ServiceAndroid extends Service{

    Thread thread;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(getApplicationContext(), "iniciou o service", Toast.LENGTH_LONG).show();

        thread = new Thread(){
            public void run(){
                try {
                    //meu código
                } catch (ClassNotFoundException | IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        thread.start();

        return START_STICKY;
    }

}

método onde chamo o service:
// inicia o service
   public void startService(View view){

       Intent i = new Intent(getBaseContext(), ServiceAndroid.class);
       startService(i);
   }


text:
Q: Eclipse RCP build MacOSX: app folder empty I have built an Eclipse RCP from scratch (based on Eclipse Mars 4.5.1), and I tried to export it to multiple platforms (win32.x86, win32.x86_64, linux.x86, linux.x86_64 and macosx.x86_64).
All the platforms work fine except macosx. If I explore the generated RCP folder, I found that the app folder is empty.
Do you know what could be happen?

A: It is like the build process in Eclipse (windows) when generating a macosx version, doesn't generate the folder structure correctly. There are some folders outside the xxx.app folder. If I put it into this folder, it works correctly.


text:
Q: Which Sieve of Eratosthenes implementation is more efficient? I have two implementations of the Sieve of Eratosthenes. Here's the first:
public class SieveOfEratosthenes extends PrimeGenerator {

    private boolean[] sieve;
    private List<Integer> primes;

    public SieveOfEratosthenes(int depth) {
        super(depth);

        sieve = new boolean[depth + 1];
        primes = new ArrayList<>();

        generate();
    }

    private void setPrime(int n) {
        sieve[n] = true;
        primes.add(n);
    }

    private void generate() {
        setPrime(2);
        setPrime(3);

        for (int n = 4; n <= depth; n++) {
            boolean isPrime = true;

            for (int prime : primes)
                if (n % prime == 0)
                    isPrime = false;

            if (isPrime)
                setPrime(n);
        }
    }
}

And here's the second.
public boolean[] sieve(int n)
{
   boolean[] prime=new boolean[n+1];
   Arrays.fill(prime,true);
   prime[0]=false;
   prime[1]=false;
   int m=Math.sqrt(n);

   for (int i=2; i<=m; i++)
      if (prime[i])
         for (int k=i*i; k<=n; k+=i)
            prime[k]=false;

   return prime;
}

Obviously the second is less verbose. It's not meant to be part of a hierarchy of prime generators. But my question is, which is more efficient? The first one seems to be O(N*log(N)) but I am not sure of that. I'm not sure what the growth rate would be of the second.

A: The second is more efficient. It is also the Sieve of Eratosthenes. The first algorithm is trial division, and is not the Sieve of Eratosthenes.
The first algorithm has a time complexity of O(n sqrt(n)), or perhaps a bit less if you use only primes as trial divisors. The second algorithm has a time complexity of O(n log log n), which is near-enough linear since log log n is very small.
As an experiment, compute the first million primes, up to 15485863, and see which one is faster. It won't be even close. The second algorithm will finish in a few seconds. The first algorithm will take a few hours.


text:
Q: Count frequencies with logical condition Here is the R code.
illdate<-c("2009-05-26","2010-12-03","2011-06-05","2010-08-10","2009-05-14","2010-01-08","2012-08-07","2010-11-13","2013-06-06","2010-08-26")

Treated<-c("T","T","N","T","N","N","T","T","T","N")

Reason<-c("Finish","Finish","Dead","Dead","Cured","Cured","Finish","Finish","Dead","Cured")

Enddate<-c("2009-12-12","2011-05-08","2011-02-28","2010-10-30","2011-10-08","2011-03-03","2013-05-05","2011-05-06","2014-08-08","2012-07-07")

number<-c(1:10)

mydata<-data.frame(number,illdate,Treated,Reason,Enddate)

And I want to count the number of cases that fit  the logical conditions:
1:illdate between "2010-01-01" and "2010-12-31"

2:Treated= "T"

3:Reason= "Finish" & "Cured"

4:Enddate between "2011-01-01" and "2012-12-31"

Please tell me how to write the code in R. Thank you very much.

A: Here is another way, maybe less beautiful:
   nrow(subset(mydata,"2010-01-01" < as.Date(illdate) & as.Date(illdate) < "2010-12-31" &
   Treated == "T" & Reason %in% c("Finish", "Cured") &
   "2011-01-01" < as.Date(Enddate) & as.Date(Enddate) < "2012-12-31"))

A: We can do
res <- mydata %>%
         mutate_at(vars(matches("date")),  as.Date) %>%
         filter(between(illdate, as.Date("2010-01-01"), as.Date("2010-12-31")),
          Treated == "T",
          Reason %in% c("Finish", "Cured"),
          between(Enddate, as.Date("2011-01-01"), as.Date("2012-12-31")))

dim(res)
#[1] 2 5


text:
Q: Having trouble spying on an action within a component test I'm trying to test for a dispatched action using chai-spies. I've tried various trouble shooting techniques, but have been unable to get the test to pass.
I've attempted to spy on both the (component.prototype, 'method) and (wrapper.instance().props.store, 'dispatch'), but have been unsuccessful.
Here's the component code:
export class Appointments extends React.Component {
    componentDidMount() {
        this.props.dispatch(fetchAppointments(this.props.user.id));
    }

render() {
    if (this.props.appointments) {
        const list = this.props.appointments.map(l => {
            let appointmentDate = new Date(l.date);

                let day = appointmentDate.getDate();
                if (day < 10) {
                    day = `0${day}`
                }
                let month = appointmentDate.getMonth() + 1;
                if (month < 10) {
                    month = `0${month}`;
                }
                const year = appointmentDate.getFullYear();

                let formattedAppointmentDate = `${month}/${day}/${year}`;
            return {
                id: l._id,
                date: formattedAppointmentDate
            };
        });
        return (

                            Need to create an appointment?

                        <button
                            className={"create-appointment-button "  + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}
                            onClick={() => this.props.dispatch(chooseCreateAppointment())}
                        >
                            Click here
                        </button>

                            Need to create an appointment?

                        <button
                            className={"create-appointment-button "  + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}
                            onClick={() => this.props.dispatch(chooseCreateAppointment())}
                        >
                            Click here
                        </button>

                        <CreateAppointmentForm />

        );
    }
}
}

const mapStateToProps = state => ({
    appointments: state.app.appointments,
    user: state.auth.currentUser,
    isCreateAppointmentFormShowing: state.app.isCreateAppointmentFormShowing,
    isAppointmentInfoShowing: state.app.isAppointmentInfoShowing,
    deletedAppointment: state.app.deletedAppointment,
    isMessageShowing: state.app.isMessageShowing,
    isLoading: state.app.isLoading
});

export default requiresLogin()(connect(mapStateToProps)(Appointments));

Here's the test code:
import React from 'react';
import {shallow, mount} from 'enzyme';
import configureStore from 'redux-mock-store';
import {Provider} from 'react-redux';
import {MemoryRouter} from 'react-router';
import thunk from 'redux-thunk';
import chai, {expect} from 'chai';
import spies from 'chai-spies';

import Appointments from './appointments';
import NavigationBar from './navBar';
import Footer from './footer';
import AppointmentsList from './appointmentsList';
import AppointmentsShow from './appointmentsShow';
import CreateAppointmentForm from './createAppointmentForm';

const middlewares = [thunk];

const mockStore = configureStore(middlewares);

chai.use(spies);

const appointments = [
    {
      address: {
        street: '40 South Greenlake Ave',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 35421
      },
      _id: '5cb694034859fh37701f316e',
      description: 'Access evaluation',
      date: '2019-01-04T05:00:00.000Z',
      time: '2:15 p.m.',
      with: 'Jason Strickland',
      title: 'MD',
      where: 'Vascular Access Center',
      phoneNumber: '904-943-2942',
      patient: '5cb694034859f123701f3159'
    },
    {
      address: {
        street: '632 Oak St',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 34423
      },
      _id: '5cb694034859f123701f316d',
      description: 'Back pain',
      date: '2019-01-19T05:00:00.000Z',
      time: '12:30 p.m.',
      with: 'Jessica Brown',
      title: 'Primary care physician',
      where: 'Baptist Primary Care',
      phoneNumber: '904-233-1114',
      patient: '5cb694034859f123701f3159'
    },
    {
      address: {
        street: '402 South Lakeside Dr',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 35422
      },
      _id: '5cb694034859f123701f316f',
      description: 'Vein mapping',
      date: '2019-02-04T05:00:00.000Z',
      time: '2:10 p.m.',
      with: 'Jason Strickland',
      title: 'MD',
      where: 'Vascular Access Center',
      phoneNumber: '904-943-2942',
      patient: '5cb694034859f123701f3159'
    }
  ];

describe('<Appointments />', () => {
    let wrapper;
    let store;
    let initialState;
    beforeEach(() => {
        initialState = {
            app: {
                selectedAppointments: [],
                selectedLabResult: null,
                isSidebarShowing: false,
                labResults: [],
                isLabResultsInfoShowing: false,
                profile: [],
                loadedBasicProfileInfoFormData: {},
                isUserInfoShowing: false,
                section: 0,
                appointments: [],
                isAppointmentInfoShowing: false,
                areSublinksShowing: false,
                currentDoctor: 0,
                isCreateAppointmentFormShowing: false,
                isCreateDoctorFormShowing: false,
                isEditBasicProfileInfoFormShowing: false,
                selectedAppointmentToEdit: null,
                selectedDoctorToEdit: null,
                loadedAppointmentFormData: {},
                isDoctorMenuShowing: false,
                loadedDoctorFormData: {},
                doctors: [],
                areAppointmentsShowing: false,
                deletedAppointment: null,
                deletedDoctor: null,
                isLoading: true,
                animation: false,
                isEditAppointmentFormShowing: false,
                isEditDoctorFormShowing: false
            },
            auth: {
                loading: false,
                currentUser: {
                    _id: 1
                },
                error: null
            }
        };
        store = mockStore(initialState);
    });

    it('Should render without crashing', () => {
        shallow(<Appointments />);
    });

    it('Should simulate a click event when the button that renders the createAppointmentForm component is clicked', () => {
        initialState.app.appointments = appointments;
        initialState.app.isLoading = false;
        wrapper = mount(
            <Provider store={store}>
                <MemoryRouter initalEntries={['/appointments']}>
                    <Appointments />
                </MemoryRouter>
            </Provider>
        );
        console.log('props', wrapper.instance().props);
        const spy = chai.spy.on(wrapper.instance().props.store, 'dispatch');
        expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
        wrapper.find('button.create-appointment-button').at(0).simulate('click');
        expect(spy).to.have.been.called();
    });
});

I want the spy to be called but I keep receiving this error:
● <Appointments /> › Should simulate a click event when the button that renders the createAppointmentForm component is clicked

AssertionError: expected { Spy 'object.dispatch' }
function (action) {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }

        return next(action);
      } to have been called

  300 |         expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
  301 |         wrapper.find('button.create-appointment-button').at(0).simulate('click');
> 302 |         expect(spy).to.have.been.called();
      |                                  ^
  303 |     });
  304 | });
  305 |

  at Object.called (src/components/appointments.test.js:302:34)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 11 passed, 12 total
Snapshots:   0 total
Time:        6.625s
Ran all test suites matching /appointments.test.js/i.

Any help would be greatly appreciated.

A: Try this out
 // chooseCreateAppointmentFile - file from where chooseCreateAppointment is coming or
 just spy on chooseCreateAppointment
 const spy = chai.spy.on(chooseCreateAppointmentFile, 'chooseCreateAppointment');
 expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
 wrapper.update();
 wrapper.find('button.create-appointment-button').at(0).simulate('click');

In Unit testing you should isolate your component and then run assertions on provided inputs. You can just test if chooseCreateAppointment is called or not. No need to check for dispatch.


text:
Q: how to draw an arrow in SceneKit? I am trying to draw arrow using SCNGeometrySource, SCNGeometryElement. but not able to draw exact arrow like below image.
is that possible to draw simple arrow line with heads or arrow like below image.?
I have tried below code but that won't work.
let indices: [Int32] = [0, 1,1]
        let source = SCNGeometrySource(vertices: [vector1, vector2])
        let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)

A: For a shape like that you're better off creating a flat UIBezierPath for the arrow and then creating an SCNShape by extruding the path to get a three-dimensional geometry.

A: If the arrow will always be facing the camera, as in your attached image, you can use a SCNPlane and use the arrow image as a texture.
If it wont always face the camera, you'll probably want to give it some thickness. I don't agree with the other answer being a "better" solution than the approach you tried, if done correctly.
Obj C code (edit: added swift version below)
int vertcount = 48;
float verts[] = { -14.923, 11.824, 25.000, -64.923, 0.000, 0.000, -14.923, -11.824, 25.000, 46.077, -5.812, 16.800, 46.077, -5.812, -16.800, 46.077, 5.812, -16.800, 46.077, 5.812, 16.800, -14.923, -11.824, -25.000, -14.923, 11.824, -25.000, -14.923, 4.974, -9.969, -14.923, 4.974, 9.969, -14.923, -4.974, 9.969, -14.923, -4.974, -9.969 };

int facecount = 13;
int faces[] = {  3, 4, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 0, 1, 2, 3, 4, 5, 6, 7, 1, 8, 8, 1, 0, 2, 1, 7, 9, 8, 0, 10, 10, 0, 2, 11, 11, 2, 7, 12, 12, 7, 8, 9, 9, 5, 4, 12, 10, 6, 5, 9, 11, 3, 6, 10, 12, 4, 3, 11};

NSData *vertsData = [NSData dataWithBytes:&verts length:sizeof(verts)];

SCNGeometrySource *vertexSource = [SCNGeometrySource geometrySourceWithData: vertsData
semantic:SCNGeometrySourceSemanticVertex
vectorCount:vertcount
floatComponents:YES
componentsPerVector:3
bytesPerComponent:sizeof(float)
dataOffset:0
dataStride:sizeof(float)*3];

int polyIndexCount = 61;
NSData *indexPolyData = [NSData dataWithBytes:faces length:sizeof(int) * polyIndexCount];
SCNGeometryElement *element1 = [SCNGeometryElement geometryElementWithData:indexPolyData
primitiveType:SCNGeometryPrimitiveTypePolygon
primitiveCount:facecount
bytesPerIndex:sizeof(int)];

SCNGeometry *geometry1 = [SCNGeometry geometryWithSources:@[ vertexSource ] elements:@[ element1]];

//Assign the SCNGeometry to a SCNNode, for example:
//SCNNode *aNode = [[SCNNode alloc] init];
//aNode.geometry = geometry1;

Note it uses the polygon primitive type.
The vert list can be cleaned up a bit by rounding the floats.
This creates the following 3D arrow (without the vertices and edges visible):

EDIT: SWIFT version:
let vertcount = 48;
        let verts: [Float] = [ -1.4923, 1.1824, 2.5000, -6.4923, 0.000, 0.000, -1.4923, -1.1824, 2.5000, 4.6077, -0.5812, 1.6800, 4.6077, -0.5812, -1.6800, 4.6077, 0.5812, -1.6800, 4.6077, 0.5812, 1.6800, -1.4923, -1.1824, -2.5000, -1.4923, 1.1824, -2.5000, -1.4923, 0.4974, -0.9969, -1.4923, 0.4974, 0.9969, -1.4923, -0.4974, 0.9969, -1.4923, -0.4974, -0.9969 ];

        let facecount = 13;
        let faces: [CInt] = [  3, 4, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 0, 1, 2, 3, 4, 5, 6, 7, 1, 8, 8, 1, 0, 2, 1, 7, 9, 8, 0, 10, 10, 0, 2, 11, 11, 2, 7, 12, 12, 7, 8, 9, 9, 5, 4, 12, 10, 6, 5, 9, 11, 3, 6, 10, 12, 4, 3, 11 ];

        let vertsData  = NSData(
            bytes: verts,
            length: MemoryLayout<Float>.size * vertcount
        )

        let vertexSource = SCNGeometrySource(data: vertsData as Data,
                                             semantic: .vertex,
                                             vectorCount: vertcount,
                                             usesFloatComponents: true,
                                             componentsPerVector: 3,
                                             bytesPerComponent: MemoryLayout<Float>.size,
                                             dataOffset: 0,
                                             dataStride: MemoryLayout<Float>.size * 3)

        let polyIndexCount = 61;
        let indexPolyData  = NSData( bytes: faces, length: MemoryLayout<CInt>.size * polyIndexCount )

        let element1 = SCNGeometryElement(data: indexPolyData as Data,
                                          primitiveType: .polygon,
                                          primitiveCount: facecount,
                                          bytesPerIndex: MemoryLayout<CInt>.size)

        let geometry1 = SCNGeometry(sources: [vertexSource], elements: [element1])

        let material1 = geometry1.firstMaterial!

        material1.diffuse.contents = UIColor(red: 0.14, green: 0.82, blue: 0.95, alpha: 1.0)
        material1.lightingModel = .lambert
        material1.transparency = 1.00
        material1.transparencyMode = .dualLayer
        material1.fresnelExponent = 1.00
        material1.reflective.contents = UIColor(white:0.00, alpha:1.0)
        material1.specular.contents = UIColor(white:0.00, alpha:1.0)
        material1.shininess = 1.00

        //Assign the SCNGeometry to a SCNNode, for example:
        let aNode = SCNNode()
        aNode.geometry = geometry1
        //aNode.scale = SCNVector3(0.1, 0.1, 0.1)
        scene.rootNode.addChildNode(aNode)

Tested above Swift code to double check it works:

If you need it to be smaller, uncomment the .scale line and try different values to see how small you want it. If you end up wanting it for example to be scale 0.06, I suggest regenerating the vert list by multiplying the values in it by 0.06 and then remove the scale line.


text:
Q: App crashes without throwing any exception in windows phone 8.1 xaml I am creating a Windows phone 8.1 xaml application. And I used SlideView : a Facebook-like panel for Windows Phone. But app crashes each time while i navigating to a new page by a button click which is placed inside slide view. Navigation is successful from the button outside view.
The bad thing is like that it is not throwing any type of exceptions or details. Even it is not not hitting in the App UnhandledException event.
    public App()
    {
        this.InitializeComponent();
        this.UnhandledException += App_UnhandledException;
    }

    void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
       //not throwing exception here
    }

I want to know, when will happen this condition ? How to get the exception details of which results app crash ? I can fix the problem if I am able to get the exact issue.
Please provide me the solution. My sample is here

A: I don't know why but... If you simply add something to the secnod page and the problem goes away.
<Grid>
    <TextBlock Text="second" />
</Grid>

I too cannot capture the exception anywhere. I had similar issues before and what I had to was removing code piece by piece to make the exception go away... Clearly something is not right in the WinRT framework.
Update
No, the above answer still doesn't fix it. After some further investigation, I've found the right way to get rid of the crash is to call the Dispatcher. I believe this is a bug introduced in update 1. Please see this link for reference.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Frame.Navigate(typeof(second)));
}


text:
Q: Odd to_tsquery results for s:* and t:* I was experimenting with PostgreSQL's text search feature - particularly with the normalization function to_tsquery.
I was using english dictionary(config) and for some reason s and t won't normalize. I understand why i and a would not, but s and t? Interesting.
Are they matched to single space and tab?
Here is the query:
select
to_tsquery('english', 'a:*') as for_a,
to_tsquery('english', 's:*') as for_s,
to_tsquery('english', 't:*') as for_t,
to_tsquery('english', 'u:*') as for_u

fiddle just in case.
You would see 'u:*' is returning as 'u:*' and 'a:*' is not returning anything.

A: The letters s and t are considered stop words in the english text search dictionary, therefore they get discarded. You can read the stop word list under tsearch_data/english.stop in the postgres shared folder, which you can locate by typing pg_config --sharedir
With pg 11 on ubuntu/debian/mint, that would be
cat /usr/share/postgresql/11/tsearch_data/english.stop
Quoting from the docs,

Stop words are words that are very common, appear in almost every document, and have no discrimination value. Therefore, they can be ignored in the context of full text searching.

It is best to discard english grammar and think of words in a programmatic and logical way as described above. Full text search does not try to infer context based on sentence structuring so it has no use for these words. After all, it's called full text search and not natural language search.
As to how they arrived on the conclusion to add s and t to the stop word list, statistical analysis must have revealed these characters to be noise.


text:
Q: Converting time in string format to time stamp format does not work in Pyspark. It throws null My dataset:
+--------------------+----------+----------+-------------------+--------------------+--------+-------+---------+--------------------+
|          event_time|event_type|product_id|        category_id|       category_code|   brand|  price|  user_id|        user_session|
+--------------------+----------+----------+-------------------+--------------------+--------+-------+---------+--------------------+
|2019-10-01 00:00:...|      view|  44600062|2103807459595387724|                null|shiseido|  35.79|541312140|72d76fde-8bb3-4e0...|
|2019-10-01 00:00:...|      view|   3900821|2053013552326770905|appliances.enviro...|    aqua|  33.20|554748717|9333dfbd-b87a-470...|
|2019-10-01 00:00:...|      view|  17200506|2053013559792632471|furniture.living_...|    null| 543.10|519107250|566511c2-e2e3-422...|
|2019-10-01 00:00:...|      view|   1307067|2053013558920217191|  computers.notebook|  lenovo| 251.74|550050854|7c90fc70-0e80-459...|
|2019-10-01 00:00:...|      view|   1004237|2053013555631882655|electronics.smart...|   apple|1081.98|535871217|c6bd7419-2748-4c5...|
|2019-10-01 00:00:...|      view|   1480613|2053013561092866779|   computers.desktop|  pulser| 908.62|512742880|0d0d91c2-c9c2-4e8...|

I am trying to convert event_time column to timestamp format, but it throws null. Tried several approches but could not fix it yet. Any help or suggestions is appreciated ?
root
 |-- event_time: string (nullable = true)
 |-- event_type: string (nullable = true)
 |-- product_id: string (nullable = true)
 |-- category_id: string (nullable = true)
 |-- category_code: string (nullable = true)
 |-- brand: string (nullable = true)
 |-- price: string (nullable = true)
 |-- user_id: string (nullable = true)
 |-- user_session: string (nullable = true)

Approach 1:
from pyspark.sql.functions import to_timestamp
df = df.withColumn("eventTimeStamp",
to_timestamp('event_time','yyyy/MM/dd HH:mm:ss'))
df.select('eventTimeStamp','event_time').show(20,
truncate=False)

+--------------+-----------------------+
|eventTimeStamp|event_time             |
+--------------+-----------------------+
|null          |2019-10-01 00:00:00 UTC|
|null          |2019-10-01 00:00:00 UTC|
|null          |2019-10-01 00:00:01 UTC|
|null          |2019-10-01 00:00:01 UTC|
|null          |2019-10-01 00:00:04 UTC|
|null          |2019-10-01 00:00:05 UTC|
|null          |2019-10-01 00:00:08 UTC|
|null          |2019-10-01 00:00:08 UTC|
|null          |2019-10-01 00:00:10 UTC|
|null          |2019-10-01 00:00:11 UTC|
|null          |2019-10-01 00:00:11 UTC|
|null          |2019-10-01 00:00:11 UTC|

Approach 2:
from pyspark.sql.functions import date_format

from pyspark.sql.functions import col
from pyspark.sql.functions import col, countDistinct

df = df.withColumn("Day", date_format(col("event_time"), "EEEE"))
df.show()

+--------------------+----------+----------+-------------------+--------------------+--------+-------+---------+--------------------+----+
|          event_time|event_type|product_id|        category_id|       category_code|   brand|  price|  user_id|        user_session| Day|
+--------------------+----------+----------+-------------------+--------------------+--------+-------+---------+--------------------+----+
|2019-10-01 00:00:...|      view|  44600062|2103807459595387724|                null|shiseido|  35.79|541312140|72d76fde-8bb3-4e0...|null|
|2019-10-01 00:00:...|      view|   3900821|2053013552326770905|appliances.enviro...|    aqua|   33.2|554748717|9333dfbd-b87a-470...|null|
|2019-10-01 00:00:...|      view|  17200506|2053013559792632471|furniture.living_...|    null|  543.1|519107250|566511c2-e2e3-422...|null|
|2019-10-01 00:00:...|      view|   1307067|2053013558920217191|  computers.notebook|  lenovo| 251.74|550050854|7c90fc70-0e80-459...|null|
|2019-10-01 00:00:...|      view|   1004237|2053013555631882655|electronics.smart...|   apple|1081.98|535871217|c6bd7419-2748-4c5...|null|

Please suggest how shall I fix the null values being generated?

A: I believe you should add timezone part in the pattern of the timestamp. Approach 1 could be written as following:
from pyspark.sql.functions import to_timestamp

df = (df
      .withColumn("eventTimeStamp",
                  to_timestamp('event_time', 'yyyy-MM-dd HH:mm:ss zzz')))
df.select('eventTimeStamp','event_time').show(20, truncate=False)

+-------------------+-----------------------+
|eventTimeStamp     |event_time             |
+-------------------+-----------------------+
|2019-10-01 00:00:00|2019-10-01 00:00:00 UTC|
|2019-10-01 00:00:00|2019-10-01 00:00:00 UTC|
+-------------------+-----------------------+


text:
Q: Turn off floats temporally I have written a command which puts content into a minipage to measures its height. It uses this information to insert "intelligent" pagebreaks, newpages, clearpages and warnings.
To do the measuring the content has to be put into a box, I guess this is unavoidable. Floats are forbidden.
I want this command to be applicable on everything. I dont want to measure the height of any float. That would make no sense as I dont know where they will be in the end. Most properly they will appear somewhere later in the document and will not influence the desired pagebreaking-behaviour.
So this is my Problem: I need to turn off all floats when measuring. Floats should be ignored.
This example shows what I want to do:
\documentclass{scrartcl}%
\usepackage{calc}%
\usepackage{blindtext}%

\newlength{\fooLength}%
\newsavebox{\fooBox}%

\newcommand{\fooCmd}[1]{%
%measure
%\TurnFloatsOFF (I need this)
\savebox{\fooBox}{\begin{minipage}{\linewidth}#1\end{minipage}}%
%\TurnFloatsON (I need this)
\settototalheight\fooLength{\usebox{\fooBox}}%
%do stuff
\ifdim\fooLength>3\baselineskip%
    \newpage#1%
\else%
    #1%
\fi%
}%

\begin{document}
\blindtext%
\fooCmd{\blindtext}%no problem
%\fooCmd{\begin{figure}\blindtext\end{figure}}%does not work
\end{document}

I have not yet found anything usefull. Maybe the comments-package can do the trick. It offers the following:
\excludecomment{figure}

This did not work though. Also, I need to deactivate all floats, not just the figures. Any suggestions?

A: Note that this will almost certainly result is much less intelligent page breaks than (La)TeX would give you left to its own devices. The best approach to page breaking is not to touch it until the document is in its final form and then, if necessary, tweak it manually to the least extent possible.
That is, don't try this at home!
The is, to say the least, extremely crude.
\documentclass{scrartcl}%
\usepackage{calc}%
\usepackage{blindtext}%

\newlength{\foolength}%
\newsavebox{\foobox}%
\makeatletter
\newcommand{\foocmd}[1]{%
%measure
%\TurnFloatsOFF (I need this)
\begingroup
\renewenvironment{figure}{\@gobble}{\relax}%
\renewenvironment{table}{\@gobble}{\relax}%
\renewcommand\caption[1]{\relax}%
\savebox{\foobox}{\begin{minipage}{\linewidth}#1\end{minipage}}%
\settototalheight\foolength{\usebox{\foobox}}%
% \TurnFloatsON (I need this)
% do stuff
\ifdim\foolength>3\baselineskip%
  \endgroup
    \newpage#1%
\else%
  \endgroup
    #1%
\fi%
}%
\makeatother
\begin{document}
\blindtext%

\foocmd{\blindtext\blindtext}% no problem

\foocmd{\begin{figure}\blindtext\caption{A figure}\end{figure}}% also works

\foocmd{\blindtext\blindtext}
\end{document}


text:
Q: Mail Infrastructure I want to have an infrastructure for our mail service. We had recently a problem with an mail server, because he was flagged as Spammer. The problem was that many mails goes over this server, and 30% couldn't get delivered (because a bad reputation). The thing is, we want to avoid such a problem in the future. But I don't know what is the best solution? I can imagine two solutions :
1 solution
We could create a server which is a replica from the original server and we could simply change the DNS record in case of an outage.
2 Solution would be to have more SMTP server which are responsible for sending mails (in front of an load balancer)? If one gets flagged, the service isn't down and emails gets delivered and we have enough time to find and fix the problem.
Much Appreciated!
Markus

A: As a general rule don't send bulk mail through your main server. If you really need to do any kind of bulk mailing use a third party service so that they can take the reputation hit. They also tend to be smarter about the delivery (spreading across multiple servers, spreading over time, etc) then your average person running a single SMTP server.