text:
Q: How to set 2 users socket.id into 2 variables, user1id and user2id in socket.io/node.js I've followed this chat tutorial http://cestfait.ch/content/chat-webapp-nodejs on creating a simple chat app, Ive been trying to limit this to just 2 users, and I wanted to create 2 variables called user1id, and user2id, I want them to be the socket.id of the client, like
// you set this value when the user1 connects
var user1id;

// you set this value when the user2 connects
var user2id;

// just for visualization, this is one of the questions I have on how to do this.
user1id = socket.id; user2id = socket.id;

the reason I want just 2 users and have them as user1 and user2 is so I can compare their messages, so I need an array of user1's and users 2's messages like
user1arr = []; user2arr = [];

and then just compare for example the "currentWord" variable of user1 and see if that matches anything in user2msgs[]. An example of user1's case below:
function receivedWord(userid, currentWord) {

// this means current player is 1
if( userid == user1id ) {

    // adds the word received to user 1 word array
    user1arr.push(currentWord);

    // compares received word with each word in user 2 array
    $.each(user2arr, function(u2word) {
        if(u2word == currentWord) {
            wordsMatch();
        }
    }
}

My code is basically that of the chat app I gave at the start of this post.
Thanks.

A: The problem that you will be having is that every time the user reloads the page, the socketID from socketIO will change. What you will need to do is attach something like a sessionID to the user so you know that even if he reconnects he is the same user. You will need to look at a webframe like expressJS or even connect which are highly flexible middlewares for nodeJS. I've accomplished such a thing with express, so let me get you started with a bit of code for this
//directories
var application_root = __dirname;

//general require
var express = require('express'),
        connect = require('connect'),
        http = require('http'),
        fs = require('fs');

//create express app
var app = express();

//create sessionStore
var sessionStore = new connect.session.MemoryStore();

//setup sessionKey
var secretKey = 'superdupersecret';

//configure express
app.configure(function() {

        //use body parser
        app.use(express.bodyParser());

        //override methods
        app.use(express.methodOverride());

        //cookies and sessions
        // BE AWARE: this lines have to be written before the router!
        app.use(express.cookieParser(secretKey));
        app.use(express.session({
                store: sessionStore,
                secret: secretKey,
                key: 'express.sid'
        }));

        //router
        app.use(app.router);

        //use static page in public folder
        app.use(express.static(path.join(application_root, 'public')));
});

//create the http server link to the new data http object of express 3
server = http.createServer(app);

//make server listen to 8080 and localhost requests
server.listen(8080, 'localhost', function() {
        console.log('Express Server running and listening');
});

//bind socket.io to express server by listening to the http server object
var io = require('socket.io').listen(server);

//set the authorization through cookies
io.set('authorization', function(data, accept) {

        //check if header data is given from the user
        if (!data.headers.cookie) {

                //return false if no cookie was given
                return accept('Session cookie required!', false);
        }

        //parse cookie into object using the connect method
        //NOTE: this line is a hack, this is due to the fact
        //that the connect.utils.parseCookie has been removed
        //from the current connect module and moved to an own
        //instance called 'cookie'.
        data.cookie = connect.utils.parseSignedCookies(require('cookie').parse(decodeURIComponent(data.headers.cookie)), secretKey);

        //save session id based on exress.sid
        data.sessionID = data.cookie['express.sid'];

        //get associated session for this id
        sessionStore.get(data.sessionID, function(err, session) {
                if (err) {
                        //there was an error
                        return accept('Error in session store.', false)
                } else if (!session) {
                        //session has not been found
                        return accept('Session not found', false);
                }

                //successfully got the session, authed with known session
                data.session = session;

                //return the accepted connection
                return accept(null, true);
        });

});

//connection handler for new io socket connections
io.sockets.on('connection', function(socket) {

        //parse handshake from socket to io
        var hs = socket.handshake;

        //show session information
        console.log('New socket connection with sessionID ' + hs.sessionID + ' connected');

});

Just read through the code and the comments to understand what they are doing. Basically what you are doing is the create an express server, make the socketIO listen to it, create a sessionStore to make it globally available, lock it with a secretKey and set it to the authorization method of socketIO. What socket then does is making handshakes with the users and then links it to a express session. That means that the express sessionID stays the same throughout the session while socketIO ids switch all the time.


text:
Q: How to Change Path of a Multi-Dimensional Array Using CakePHP Core Utility - Set How do I use Cakephp core utility - "Set" to change the format of this multi-dimensional array:
array(
  [Product]
     [offer_id]
         [0] => '1'
         [1] => '5'
)

to
array(
  [Product]
     [0]
         [offer_id] => '1'
     [1]
         [offer_id] => '5'
)

Thanks in advance for your help.

A: SET is not required and actually may be more cumbersome than what is required for this operation. Try using something like:
$test = array_values($array['Product']['offer_id']);
foreach($test as $value) {
    $products['Product'][]['offer_id'] = $value;
}
// show the array
pr($products);

This will accomplish what you are trying to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python ImportError in shell Bar
 +-Foo
 |  +-Foo.py
 |  +-__init__.py
 +-main.py

with Foo.py containing
class Foo
   ...

in main.py
 from Foo.Foo import Foo

When I execute
python main.py

in the directory Bar
I get the error
ImportError: No module named Foo.Foo

But when I just run the python interpreter in the Bar folder and type
from Foo.Foo import Foo

then I do not get an error.


text:
Q: How to get the maximum speed of CPU In regards to my CPU, most article (include the Wiki) told me that I must use "FSB", but I don't have such a value (see below) so I have some question about CPU:

Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz

What does the "3.40GHz" mean?

Clocks (Core #0)
  Core Speed : 801.4MHz <-1.4MHz more than Intel published
  Multiplier : x36.0    <-changing continuous, but most cases lower than 40
  Bus Speed : (empty)
  Rated FSB (<-graytext) : (empty)

How to understanding these values? Can I do something like 801.4*36/1000? I notice that windows8 taskmgr shown my CPU speed is "0.80GHz"
But some time later, it suddenly jump to 1.60GHz and back to 0.8 in few seconds Is my computer run in power saving mode? Or my CPU support something like turbo mode?
PS: CPU temperature always low enough (About 40°~60°).

A:
What does the "3.40GHz" mean?

Nothing, it's just a text string put in the CPU by the manufacturer. Your CPU's name is "Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz". Intel generally puts the "advertised" speed (the highest speed all cores can run at all the time under typical cooling conditions and default  settings) there.

Is my computer run in power saving mode? Or my CPU support something like turbo mode?

The core speed drops when the CPU is not under load to keep the CPU cooler. These CPUs do have a turbo mode that is limited by temperature, so keeping the CPU cool when it's not under load helps to leave more room for upping the clock when it is under load. Your CPU can turbo up to 3.8GHz at default settings.
Intel CPUs haven't had an FSB in a long time. All Core i3/i5/i7 CPUs have an integrated memory controller.

A: Your CPU supports both Turbo Boost and SpeedStep.
This means it can lower/increase its clock speed from 3.4GHz depending on how much load it is given. The higher the clock speed the better the performance, but power consumption and temperature are also increased. As it is a quad-core processor it also has the ability to temporarily deactivate cores in order to allow the other ones to run faster without exceeding the power/temperature limits.
According to Intel the maximum clock speed via Turbo Boost is about 3.8GHz. However, this is likely only possible with just one of the four CPU cores active.
The changes in clock speed will partly be influenced by the Power Options settings in Windows. If you set the current power plan to High Performance the CPU will tend to stay at a higher clock speed all the time, where as choosing Power Saver will make the CPU prefer lower power states.
To get a better idea of how the CPU is behaving, try downloading CPU-Z which is a very popular CPU monitoring tool:

Sadly I am stil running a Core 2 in this particular machine which is not the best example but it does still have some limited frequency scaling functionality.

A: I use System Mechanic by iolo software.  I was trying to resolve an issue with my computer not waking up from the sleep state.  As I reviewed the power plans, I noticed that System Mechanic provides one which runs your cpu (all cores) at their maximum rated speed.  When I switched to this plan, I noticed a definite difference in the speed of my system overall.
The computer not waking up was the result of an incompatibility with one of the removable drives I had plugged in.  It would keep the computer from waking up.  Once I removed it - problem solved.  Discovering the power plan and then switching to it was a bonus.

A: Modern CPUs reduce the clock speed automatically when idle. This is normally a good thing and works completely transparently to the user, e.g., Intel Speedstep technology. On the other hand, some CPUs can even go beyond their maximum speed, when they are not too hot, e.g., Intel TurboBoost. Note other CPU manufacturers have similar technology.
This way the user gets maximum CPU power at minimum power consumption.
It turns out that sometimes these technologies don't work as intended. I face that problem frequently with a program called Squid. The CPU usage when drawing in Squid on my Surface is low, which implies a low MHz speed of my CPU. As a consequence everything feels slow and there is noticeable lag when drawing.
Under Linux you can set the speed of a CPU core as "root user" with
echo  800000 > /sys/devices/system/cpu/cpuXX/cpufreq/scaling_min_freq
echo 1000000 > /sys/devices/system/cpu/cpuXX/cpufreq/scaling_max_freq

where XX is your CPU core, e.g., 0 for first core. 800000 is equivalent to 0.8 GHz, which is the minimum speed of my CPU. These commands would limit the CPU to operate only between 0.8 GHz and 1 GHz, which can be useful on a laptop to extend battery life. Setting the minimum and maximum scaling frequency to your maximum CPU speed would let run your computer at maximum speed.
Under Windows RM clock was the last program I used that permitted easy CPU speed manipulation. That program only worked with CPUs up to Pentium M/AMD Athlon. If anyone know of programs that allow easy clock manipulation, please add in the comment section.
Under Windows there is one option in the "Power Options" that permits manipulating the CPU speed, called "Minimum processor state" and "Maximum processor state". You may need to enable those settings by manipulating the Windows registry. So use at your own risk.
This article Power Options - Add or Remove "Min/Max processor state" describes how to enable and disable the settings.
So, for working with Squid, I set the minimum processor state to 70% and maximum to 99%. The reason to use 70% is that I don't want the CPU to run all the time in TurboBoost mode. When I need long battery life for my Surface I have a another power profile with minimum processor state set to 5% and maximum to 30%. The downside with the way Microsoft implements the manipulation of CPU speed is that it is not possible to have your CPU run at 100% workload with a clock speed of 1 GHz. Instead Microsoft power options will throttle clock speed AND the maximum amount of CPU time used at reduced clock speed. This is the difference to the way CPU speed can be reduced/increased under Linux as just mentioned.
E.g. if you set a processor state of 50% and the CPU runs only at 1.6 GHz of a 3.2 GHz CPU then you are actually only using 50% CPU time of a CPU that is running at 50% maximum CPU speed, hence you are using 25% CPU power compared to a CPU running 100% at 3.2 GHz speed. This is something to keep in mind, since low % values can make your computer really slower.


text:
Q: Json Parser Data I have create JSONPARSE data for my android apps. I using LogCat able to view Json respond using Log.d("id", id ) but it shown error when i want to set the textview value into id. Please help, Thanks. Below is the Code that i use for java and php
Below is my code.
Log cat :

MainActivity.Java

   private static String url_Retrieve =       "http://hospital.leeyengyang.com/android_connect/Retrieve.php";
    List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL

                JSONObject json2 = jsonParser.makeHttpRequest(url_Retrieve, "GET", params);

                // Check your log cat for JSON reponse
                Log.d("All Products: ", json2.toString());

                try {
                    // Checking for SUCCESS TAG
                    int success2 = json2.getInt(TAG_SUCCESS);

                    if (success2 == 1) {
                        // products found
                        // Getting Array of Products
                        JSONArray Retrieve = json2.getJSONArray("tracking");

                        // looping through All Products
                        for (int i = 0; i < Retrieve.length(); i++) {
                            JSONObject c = Retrieve.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString("Data");
                            String name = c.getString("Username");

                            Log.d("id", id);
                            Log.d("name", name);
                            // creating new HashMap

                            txtUpdate.setText(id);
                            // adding each child node to HashMap key => value

                        }
                    } else {
                        // no products found
                        // Launch Add New product Activity
                        Intent i = new Intent(getApplicationContext(),
                                Bluetooth.class);
                        // Closing all previous activities
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

Retrive.php
  <?php
// Locate WP Location
$location = $_SERVER['DOCUMENT_ROOT'];

include ($location . '/wp-config.php');
include ($location . '/wp-load.php');
include ($location . '/wp-includes/pluggable.php');

// array for JSON response
$response = array();

    date_default_timezone_set('Asia/Kuala_Lumpur');
    $date =  date("Y-m-d");
$sql="SELECT Data,Username FROM tracking Where Username='jin' AND Date= '".$date."'";

// Initial Add data to HM
$result = mysql_query($sql) or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tracking"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $tracking = array();
    $tracking["Data"] = $row["Data"];
    $tracking["Username"] = $row["Username"];

    // push single product into final response array
    array_push($response["tracking"], $tracking);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
}

else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";

// echo no users JSON
echo json_encode($response);
}
?>

JsonParser.Java

package com.example.Leeyengyang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

A: For setting int value into TextView use
txtUpdate.setText(""+id);
// OR
txtUpdate.setText(Integer.toString(id));

basically you need to convert int value to String. It does not set int value directly to TextView.
Make sure that you are updaing UI from Main Thread only.
Hope this helps !
Thanks.

A: You can't change your UI from outside of the UI thread (for example doInBackground() method of AsyncTask).
Although - you still can do this update in onPostExecute, that is called after background work has been done and is runningo on the main (UI) thread.
Also, consider to use one of libraries that can simplify whole process like Jake Wharton's Retrofit: http://square.github.io/retrofit/

A: SetText like that.
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

         txtUpdate.setText(id);
        }
    });

I hope this will help you!


text:
Q: Cannot Diagnose Neo4j REST API Inquiry Failure I'm messing with some code in Scala (2.9.2) to query a neo4j (2.2.0) server using REST API via Jersey (1.19) and Cypher.  My first transaction succeeds (HTTP 200) returning some nice XHTML.  The second more involved transaction containing a valid Cypher query returns 405 with no data or message.  It causes a stack dump in the server log.  The same query succeeds via the console to the same server.  I don't know how to proceed to diagnose the problem.  Details follow:
Here is the transaction and result via Cypher console:
neo4j-sh (?)$ match (p)-[r]->(n) where n.number = '15' return p,r,n;
+------------------------------------------------------------------------------------------------------------+
| p                                        | r                                     | n                       |
+------------------------------------------------------------------------------------------------------------+
| Node[1451]{name:"Elizabeth Maher Muoio"} | :REPRESENTS[1725]{inHouse:"Assembly"} | Node[1381]{number:"15"} |
| Node[1450]{name:"Reed Gusciora"}         | :REPRESENTS[1724]{inHouse:"Assembly"} | Node[1381]{number:"15"} |
| Node[1449]{name:"Shirley K. Turner"}     | :REPRESENTS[1723]{inHouse:"Senate"}   | Node[1381]{number:"15"} |
+------------------------------------------------------------------------------------------------------------+
3 rows
24 ms

Here is the Scala snippet:
val n4url = "http://dev.cosi.com:7474/db/data/"

// Make a client...
val c = Client.create // Uses jersey 1.19
//val cl = c.getClass.getName;     println("cl: "+cl);
c.addFilter(new HTTPBasicAuthFilter("neo4j","connected"))

// Dumb test of comms w server...
val resource = c.resource(n4url)
val response = resource.get(classOf[ClientResponse])
printf("\nGET on [%s], status code [%d]\n%s\n",n4url,response.getStatus(),
  response.getEntity(classOf[String]))
response.close

println("\n=== MOVING ALONG TO REAL INQUIRY ===")
val inq = n4url+"transaction/commit"
val res2 = c.resource(inq)
val query = "match (p)-[r]->(n) where n.number = '15' return p,r,n"
val payload = "{\"statements\" : [ {\"statement\" : \"" + query + "\"} ]}";
val resp2 = resource.
  accept(MediaType.APPLICATION_JSON).
  `type`(MediaType.APPLICATION_JSON).
  entity(payload).
  post(classOf[ClientResponse])
printf("POST [%s] to [%s], status code [%d], returned data: " +
  System.getProperty("line.separator") + "%s\n",
  payload,inq,resp2.getStatus,resp2.getEntity(classOf[String]))
resp2.close

Here is the output of the Scala program:
    GET on [http://dev.cosi.com:7474/db/data/], status code [200]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Root</title><meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href='http://resthtml.neo4j.org/style/rest.css' rel='stylesheet' type='text/css'>

Neo4j REST interface

Root

relationship_index	http://dev.cosi.com:7474/db/data/index/relationship

node_index	http://dev.cosi.com:7474/db/data/index/node

=== MOVING ALONG TO REAL INQUIRY ===
POST [{"statements" : [ {"statement" : "match (p)-[r]->(n) where n.number = '15' return p,r,n"} ]}] to [http://dev.cosi.com:7474/db/data/transaction/commit], status code [405], returned data:

Here is the server log fragment:
   FINE: Mapped exception to response: 405
javax.ws.rs.WebApplicationException
        at com.sun.jersey.server.impl.uri.rules.TerminatingRule.accept(TerminatingRule.java:66)
        at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:800)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
        at org.neo4j.server.rest.dbms.AuthorizationFilter.doFilter(AuthorizationFilter.java:120)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
        at org.eclipse.jetty.server.Server.handle(Server.java:497)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
        at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)
        at java.lang.Thread.run(Thread.java:745)

A: I referenced the wrong ClientResponse object in the second inquiry.  Fixed by changing:
val resp2 = resource.

to
val resp2 = res2.


text:
Q: Is BlackBerry supported by Titanium SDK? can anyone please let me know does is Blackberry supported by Titanium SDK or not. Actually i gone through many sites. I followed the procedure of installing it but after installation i can't find any BB plugins in Titanium. Please help me with this.

A: Currently, it is only for paid users, who can access the beta.
However, they have announced ( http://thinkmobile.appcelerator.com/press-releases/bid/142950/Appcelerator-s-300-000-Worldwide-Developers-to-Gain-Application-Support-on-Blackberry-10-Platform ) they will be supporting blackberry 10. But you'll have to wait for it.
Other than this, no support for blackberry.

A: I think they provide paid support for it and is still in beta for blackberry.


text:
Q: Approximation via central limit theorem I think I am stuck in front of a very standard exercise of statistics, thus an operative hint on what I should be doing would be considered a sufficient answer.
Define $$\mathcal{A}_n = \frac{1}{n} \sum_1^n X_i^2,$$ I am requested to use the $\mathsf{CLT}$ and the fact that $q_{0,05}(\mathcal{A}_1)=3,84$ to approximate the $0.95$-quantile  $q_{0,05}(\mathcal{A}_n)$ for the sample size $n=10^2$.

My considerations up to this point have been:

*

*$\mathcal{A_1} \sim \chi^2_1$

*$\sqrt{n}(\mathcal{A_n}-1) \to \mathcal{N}(0,1)$

*$n \cdot\mathcal{A_n} \sim \chi^2_n$

A: I think $\sqrt{n}(\mathcal{A_n}-1) \to \mathcal{N}(0,2)$ or $\sqrt{\frac n2}(\mathcal{A_n}-1) \to \mathcal{N}(0,1)$
I also suspect it is $q_{0.95}(\mathcal{A}_1)=3.84 \approx 1.96^2$
suggesting for a standard normal random variable $X \sim \mathcal{N}(0,1)$ you have $q_{0.975}(X)\approx 1.96$ (taking account of the two tails),
but it could be more useful to know $q_{0.90}(\mathcal{A}_1)\approx 2.706\approx 1.645^2$
and so $q_{0.95}(X)\approx 1.645$.
Putting those together suggests $q_{0.95}\left(\sqrt{\frac {100}2}(\mathcal{A}_{100}-1)\right) \approx 1.645$
and so $q_{0.95}\left(\mathcal{A}_{100}\right) \approx 1+ \frac{1.645}{\sqrt{50}} \approx 1.23$.  The exact answer seems to be closer to $1.24$


text:
Q: Sketch set $|z-1| = 1$ and the corresponding image of the map $w = z^2$ Dear MSE-community!
I have begun on a journey through Gamelin's Complex Analysis. In the first chapter, there is an exercise, which claims that $|z-1| = 1|$ corresponds to $r = 2\cos\theta$ if you change to polar coordinates. How exactly do you change to polar coordinates so you get $r = 2\cos\theta$?
I have myself tried to solve this exercise:
$$|z-1|=1 \iff (x-1)^2+y^2=1$$
So the domain is a circle with center $(1,0)$ and radius $1$. To obtain the image under the map $w = z^2$ we compute:
$$
z^2 = (x^2-y^2) + i(2xy)$$ which yield, when plugged into the equation of the domain: $$(x^1 - y^2 - 1)^2 + (2xy)^2 = 1 \iff x^4 - 2x^2y^2 - 2x^2 + y^4 + 2y^2 + 4x^2y^2 = (x^2+y^2)^2 + 2(y^2-x^2) + 1 = 1 \iff
|z|^4 - 2\text{Re}(z^2) = 0 \iff |z|^4 = 2\text{Re}(z^2)$$

I do not understand how the image $|z|^4 = 2\text{Re}(z^2)$ is sketched out, or translated into polar form.
All help is appreciated, thanks!

A: From your equation $(x-1)^2 + y^2 = 1$, use the substitution $x = r \cos \theta, y = r \sin \theta$. Expanding and rearranging that equation will give you $r = 2\cos \theta$.

A: Starting with $r=2 \cos \theta,$
$\displaystyle r=\frac{2x}{r}$
$r^2 = 2x$
$x^2 +y^2-2x +1 = 1$
$(x-1)^2 + y^2 =1$
$|z-1|=1.$
Here is some Mathematica code to plot the image (a cardiod) of $w=z^2.$
 Q = ( (x - 1)^2 + y^2 == 1);
 S = ImplicitRegion[Q, {x, y}];
 a = Region[S, Frame -> True]

 f = Evaluate[{x^2 - y^2, 2 x y}] &;
 F = TransformedRegion[F, f];
 b = Region[F, BaseStyle -> Red, Frame -> True]

A: As $|z-1|=1$, $z=1+\cos t+i\sin t$ for some $t$.
Here $r\cos\theta=1+\cos t$ and $r^2=(1+\cos t)^2+\sin^2 t=2+2\cos t=2(1+\cos t)=2r\cos\theta$.
So, $|z-1|=1$ can be written as $r=2\cos\theta$ in polar coordinates.

Note that $z=1+\cos t+i\sin t=2\cos^2\frac t2+2i\cos\frac t2\sin\frac t2$
$\omega=z^2=(2\cos^2\frac t2+2i\cos\frac t2\sin\frac t2)^2=4\cos^2\frac t2(\cos t+i\sin t)=2(1+\cos t)(\cos t+i\sin t)$
Here $r=2(1+\cos t)$ and
So, $r\cos\theta=2(1+\cos t)\cos t=r(\frac r2-1)$ and hence $r=2(1+\cos\theta)$, which describes a cardioid.

We have three sets of lengths and angles.
The first set measures a point on the circle from the centre of the red circle (i.e., $1$), with the length being $1$ and the angle being $t$.
The second set measures the same point on the circle from the origin, with the length $r$ and angle $\theta$. We can actually use simple geometry to show that $\theta=\frac t2$ and  $r=2\cos\theta$.
The third set measures a point on the blue cardioid (which is corresponding to the point on the circle) from the origin, with the length and the angle again denoted by $r$ and $\theta$. Notice that $r$ and $\theta$ in the second and the third set are different.

There is a problem in OP's approach. When we are talking about $z=x+iy$, we have $(x-1)^2+y^2=1$. But if we want to find the locus of $\omega$, we have to consider the graph of $Y$ against $X$, where $\omega=X+iY$. It means that we have to find an equation connecting $X$ and $Y$ with $X=x^2-y^2$, $Y=2xy$ and $(x-1)^2+y^2=1$. It is not correct to do the substitution getting $(x^2-y^2-1)^2+(2xy)^2=1$.


text:
Q: Angular Material Dialog - Edit value on dialog should not update on table row automatically I am not much familiar with Angular Material. But in my new application, I am using it and now I am facing some challenges with dialog.
I have a table with multiple rows and there I want to do an edit on it.
When I click on Edit a dialog box should open and I should able to edit the data.
There are two action buttons say Cancel and Update.
Update should save the data, close the dialog box and display updated data on the table.
Cancel should simply close the dialog box.

{{attachment.note}}

    <button mat-menu-item (click)="editAttachmentNote(attachment)">
         Edit
    </button>

openEditDialog(attachment): void {
    let dialogRef = this.dialog.open(AttachmentComponent, {
        data: { attachment: attachment }
    });

    dialogRef.afterClosed().subscribe((result: any) => {
        console.log(result);
        if(result){
            this.doc = result;
        }
    });
}

editAttachmentNote(attachment) {
    this.openEditDialog(attachment);
}

=== attachment component ===
export class AttachmentUploadComponent {
      constructor(public dialogRef: MatDialogRef<AttachmentComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any,
                private http: HttpClient) {

          if(!data.attachment) {
               data.attachment = new AttachmentDto();
               this.disableUpload  = false;
          }
          else {
               this.disableUpload  = true;
          }
      }
     onCancelClick() {
        this.dialogRef.close();
     }
}

<mat-form-field class="full-width">
    <textarea [(ngModel)]="data.attachment.note" [disabled]="!fileToUpload && !disableUpload" matInput matTextareaAutosize matAutosizeMinRows="1" matAutosizeMaxRows="3" placeholder="Note">
    </textarea>
</mat-form-field>

<button fxFlex="nogrow" mat-button (click)="onCancelClick()">Cancel</button>
<button *ngIf="disableUpload" fxFlex="nogrow" mat-button cdkFocusInitial (click)="updateAttachmentNote()">
    Update
</button>

But here what I am seeing is when I edit data in the Dialog box, data is automatically updating in the table which I am able to see in the background.
Can anyone help here?

A: You are passing reference in dialog, that's why whenever there is any change in attachment it will reflect automatically.
To avoid this you can pass value only by modifying your code as:
editAttachmentNote(attachment) {
    this.openEditDialog(JSON.parse(JSON.stringify(attachment)));
}


text:
Q: How do I get started with Virtual PC on Windows 7 Pro? I would like to set up a Virtual PC VM on my Windows 7 Pro host machine. On the Microsoft VPC page I chose to download only VPC, not the damned XP Mode poster child, and I got to download the file Windows6.1-KB958559-x86-RefreshPkg.msu.
After installing that and restarting, I have a Virtual PC start menu item, but all that does in open an Explorer window to my C:\Users\Brady\Virtual Machines folder. Where is the management GUI where I can create a new VPC etc?

A: There is a custom menu option for the folder for "Create virtual machine". The right click menu for an existing virtual machine will have a "Settings" menu item. Opening a virtual machine runs it.
The XP Mode is worthwhile to grab as it's a basically a free copy of XP Pro and has desktop integration.


text:
Q: Prove that the closed ball $\overline{B}(0,1) \subseteq \mathcal{C}([0,1], \mathbb{R})$ can't be covered by countably-many compact sets. For $\mathcal{C}([0,1],\mathbb{R})$ the space of continuous functions $f : [0,1] \to \mathbb{R}$, I'm asked to prove that $\overline{B}(0,1) = \{ f \in \mathcal{C}([0,1], \mathbb{R}) : ||f||_\infty \leqslant 1 \}$ can't be covered by countably-many compact sets in $\mathcal{C}([0,1],\mathbb{R})$. But I'm not sure where to even begin. Any ideas on how to start?

A: This actually holds in general for infinite-dimensional Banach Spaces, such as $\mathcal{C}([0, 1], \Bbb{R})$.
Suppose $X$ is a Banach Space. If $X$ is covered by countably many compact sets $(K_n)_{n \in \Bbb{N}}$, then because each set is closed, the Baire Category Theorem implies that at least one of the $K_i$s has a non-empty interior. That is, there exists some closed ball $x + rB_X \subseteq K_i$, where $r$ is some positive real number.
But then, this implies,
$$B_X \subseteq \frac{1}{r}(-x + K_i),$$
which is compact, hence $B_X$ is compact. A compact closed unit ball implies that $X$ is finite-dimensional. Thus, if $X$ is infinite-dimensional, no such compact sets can exist.

A: Suppose for each $n\in \mathbb{N}$, $C_n$ is compact. Then the $C_n$'s are equicontinuous; choose the $\delta_n$ as in the definition of equicontinuity of $C_n$. It is easy to construct a continuous function $f:[0,1] \rightarrow [-1, 1]$ whose graph has gradient greater than $\frac{1}{\delta_n}$ at $1/n$; the graph merely has to consist of countably many tents next to each other of required steepness. To make $f$ continuous just require that the tent width tends to $0$. Then $f\notin \bigcup\limits_n C_n$.


text:
Q: How ssl works in psql? In AWS RDS postgresql server side ssl has been forced using below config values.
rds.force_ssl   1
ssl 1

When I am trying to connect to postgres RDS host without specifying the sslmode and sslrootcert, it is allowing the ssl connection.
psql -h hostname.us-east-1.rds.amazonaws.com -p 5432 --user=username
psql (10.10 (Ubuntu 10.10-0ubuntu0.18.04.1), server 10.6)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

username=>

Since I did not specify the sslmode, it has taken default sslmode which is prefer. I would like to know:

*

*How is it encrypting the data in transit to the server?

*How is it selecting ssl protocol, ssl cipher and compression before sending the data packets to server?

*Since I am not specifying any sslrootcert, is it taking any default cert for ssl handshake with server?

Please explain.

A: *

*Isn't "ECDHE-RSA-AES256-GCM-SHA384" the answer to this?  If not, can you expand your question?

*As far as I know, this is just outsourced to the ssl library.  PostgreSQL doesn't do anything special, other than pass along the configuration options.

*It will take the sslrootcert from the default location if it finds one there (in which case, the validation would probably fail, if you didn't go out of way to put something appropriate there).  But if it does not find one, then you basically only get Diffie-Hellman protection.  It doesn't verify that the server's cert was actually signed by the claimed CA, nor that the cert "belongs" to the server's hostname.  You only get protection from eavesdroppers, not from MITM.  If the client wants MITM protection, it must set sslmode to a level higher than 'require'.

There is no mechanism implemented by which the server can force the client to validate the server's cert.


text:
Q: How to solve a problem of set theory I don't know the formula to use in a problem:
If a group of 400 persons, 250 persons speaks English, 200 speaks French, so the number of persons speaking both the languages is ?
And the answer is 80

A: Let $\;F,E\;$ be the set of people that speaks french (respecitvely, english), then use the formula:
$$|F\cup E|=|F|+|E|-|F\cap E|$$

A: To expand the answer further Let U = everyone
F = people who speak french
E = people who speak English
$F \cup E$ = people who speak French or English
$F \cap E$ = people who speak French and English
$(F \cup E)^c$ = people who speak neither French nor English.
There are two formulas: $|U| = |A^c| + |A|$
and $|A \cup B| = |A| + |B| - |A \cap B|$.
We can combine these to get $|U| = |(A \cup B)^c| + |A| + |B| - |A \cap B|$.
So $|U| = |(E \cup F)^c| + |F| + |E| - |E \cap F|$
So $200 = |(E \cup F)^c| + 200 + 250 - |E \cap F|$
So $|E \cap F| = 50 + |(E \cup F)^c|$
So the number of people who speak both French and English is 50 more than the number who speak neither.


text:
Q: Getting value from textboxes that depends on dropdown menu then adding the values I have the following codes. I don't know what part I got wrong. What it does is, a value will be shown in the textboxes, depending on the selected option in the dropdown. Then, the values in the two textboxes will be added. And its answer will be shown on the third textbox. The showing of values in the textbox is perfectly running, the only problem is it does not add and it does not show on the third textbox.
<select id="Dropdown1">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="c">C</option>
</select>

<select id="Dropdown2">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="text" id="total"/>

jquery
$(document).ready(function(){
    $("#Dropdown1").change(function(){
        if($(event.target).val() == 'A'){
            $("#Dropdown2").change(function(){
                if($(event.target).val() == '1'){
                    $('#txt1').val('10.00');
                    $('#txt2').val('15.00');
                }else if($(event.target).val() == '2'){
                    $('#txt1').val('45.00');
                    $('#txt2').val('23.00');
                }else {
                    $('#txt1').val('30.00');
                    $('#txt2').val('53.00');
                }
                if($(event.target).val() == 'B'){
                    $("#Dropdown2").change(function(){
                        if($(event.target).val() == '1'){
                            $('#txt1').val('11.00');
                            $('#txt2').val('17.00');
                        }else if($(event.target).val() == '2'){
                            $('#txt1').val('23.76');
                            $('#txt2').val('46.00');
                        }else {
                            $('#txt1').val('33.00');
                            $('#txt2').val('53.76');
                        }
                        if($(event.target).val() == 'C'){
                            $("#Dropdown2").change(function(){
                                if($(event.target).val() == '1'){
                                    $('#txt1').val('20.00');
                                    $('#txt2').val('17.00');
                                }else if($(event.target).val() == '2'){
                                    $('#txt1').val('23.76');
                                    $('#txt2').val('40.00');
                                }else {
                                    $('#txt1').val('37.00');
                                    $('#txt2').val('43.76');
                                }
                            });

javascript
function subtotal(){
    var a = document.getElementById("txt1").value;
    var b = document.getElementById("txt2").value;

    var stotal = parseInt(a)+ parseInt(b);
    document.getElementById("total").innerHTML = "$" + stotal;
}

A: You say you want to display it in third textbox so you have to set its value attribute, or val using jQuery.
Also it may be worth telling you that you've to use the radix part of parseInt. In your case it should be 10, I suppose and if you're damn sure of getting a number, you can well use Number(a) or +a which will convert it to number.
$('#total').val("$" + stotal);

A: Try
$('#total').val('$' + stotal);

instead of
document.getElementById("total").innerHTML = "$" + stotal;

...and where do you call the subtotal() function ?...I don't see it. It should be called every time a select changes, in your 'change' listeners (you could use .on() function instead).
Also you shouldn't mix DOM API (getElementById(...)) and jQuery ($('#...')) I think (not really a pb but less readable).
And to get rid of your conditionnals you could use your numeric values on the value attributes of your "options", and spare a lot of if() {} else {}, or use data-xxx attributes.

A: Here a working FIDDLE.
Too much eventlisteners and some logical errors.
New jQuery code:
$("#Dropdown1, #Dropdown2").change(function(){
    if($("#Dropdown1").val() == 'A'){
            if($('#Dropdown2').val() == '1'){
                $('#txt1').val('10.00');
                $('#txt2').val('15.00');
            }else if($('#Dropdown2').val() == '2'){
                $('#txt1').val('45.00');
                $('#txt2').val('23.00');
            }else {
                $('#txt1').val('30.00');
                $('#txt2').val('53.00');
            }
    }
     if($("#Dropdown1").val() == 'B'){
            if($('#Dropdown2').val() == '1'){
                $('#txt1').val('11.00');
                $('#txt2').val('17.00');
            }else if($('#Dropdown2').val() == '2'){
                $('#txt1').val('23.76');
                $('#txt2').val('46.00');
            }else {
                $('#txt1').val('33.00');
                $('#txt2').val('53.76');
            }
     }
     if($("#Dropdown1").val() == 'C'){
            if($('#Dropdown2').val() == '1'){
                $('#txt1').val('20.00');
                $('#txt2').val('17.00');
            }else if($('#Dropdown2').val() == '2'){
                $('#txt1').val('23.76');
                $('#txt2').val('40.00');
            }else {
                $('#txt1').val('37.00');
                $('#txt2').val('43.76');
            }
     }
     subtotal();
 });

EDIT:
Forgot the subtotal function:
function subtotal(){
  var a = document.getElementById("txt1").value;
  var b = document.getElementById("txt2").value;

  var stotal = parseInt(a)+ parseInt(b);
  $('#total').val("$" + stotal);
}

A: try this:

$(document).ready(function(){
  $("#Dropdown1").change(function(event){
          if($(event.target).val() == 'A'){
              $("#Dropdown2").change(function(event1){
                  if($(event1.target).val() == '1'){
                      $('#txt1').val('10.00');
                      $('#txt2').val('15.00');
                  }else if($(event1.target).val() == '2'){
                      $('#txt1').val('45.00');
                      $('#txt2').val('23.00');
                  }else {
                      $('#txt1').val('30.00');
                      $('#txt2').val('53.00');
                  }
                  subtotal();
              });
          }
           if($(event.target).val() == 'B'){
              $("#Dropdown2").change(function(event1){
                  if($(event1.target).val() == '1'){
                      $('#txt1').val('11.00');
                      $('#txt2').val('17.00');
                  }else if($(event1.target).val() == '2'){
                      $('#txt1').val('23.76');
                      $('#txt2').val('46.00');
                  }else {
                      $('#txt1').val('33.00');
                      $('#txt2').val('53.76');
                  }
                  subtotal();
              });
           }
           if($(event.target).val() == 'C'){
              $("#Dropdown2").change(function(event1){
                  if($(event1.target).val() == '1'){
                      $('#txt1').val('20.00');
                      $('#txt2').val('17.00');
                  }else if($(event1.target).val() == '2'){
                      $('#txt1').val('23.76');
                      $('#txt2').val('40.00');
                  }else {
                      $('#txt1').val('37.00');
                      $('#txt2').val('43.76');
                  }
      });
              subtotal();
           }

           });

 });
function subtotal(){
 var a = $("#txt1").val();
 var b = $("#txt2").val();

 var stotal = parseInt(a)+ parseInt(b);
 $('#total').val('$' + stotal);
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <select id="Dropdown1">
  <option >select</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="c">C</option>
 </select>

<select id="Dropdown2">
  <option >select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
 </select>

<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="text" id="total"/>

:


text:
Q: vbtab in reporting services 2008 expression i am trying to use tabs in reporting service 2008  expression on a particular textbox.
i have tried using three tabs (& vbTab & vbTab & vbTab &) between field name and value for two fields.
=iif(Trim(Fields!Field1.Value) <>"", "FVE1:" & vbTab & vbTab & vbTab &  Fields!Field1.Value & VbCrLf,"") & iif(Trim(Fields!Field2.Value) <>"", "RV:" & vbTab & vbTab & vbTab & Fields!Field2.Value,"" )

what i am trying to aceive is some thing like this
FEV1:   3.29
RV:     0.51

But i am unable to achieve this insted it get like below
FEV1:   3.29
RV:   0.51

any help will be much appeiciated.
thanks

A: If tabs do not work, try right-aligning with non-breaking spaces Chr(160):
(Line-wrapped for legibility)
= Iif(
  Trim(Fields!Field1.Value) <> "",
  "FVE1:" & Fields!Field1.Value.ToString().PadLeft(5, Chr(160)) & VbNewLine,
  ""
)
& Iif(
  Trim(Fields!Field2.Value) <> "",
  "RV:" & Fields!Field1.Value.ToString().PadLeft(5, Chr(160)),
  ""
)


text:
Q: cashu integration with asp.net I have to integrate cashu payment gateway in my web application, I am using the code provided by cashu implementaion guide. I have created a merchant accout on cashu, but unable to find the encryption key option.So, whenever a post the values I get invalid merchant token value error. Can, anyone help me out of this situation!
<form action="https://www.cashu.com/cgi-bin/pcashu.cgi" method="post">
<input type="hidden" name="merchant_id" value="merchanttest">
<input type="hidden" name="token" value="66a31cd699d8d9cb454df1f6cec30c2c">
<input type="hidden" name="display_text" value="Baseball Hat">
<input type="hidden" name="currency" value="CSH">
<input type="hidden" name="amount" value="125">
<input type="hidden" name="language" value="en">
<input type="hidden" name="session_id" value="asdasd-234-asdasd">
<input type="hidden" name="txt1" value="item27">
<input type="hidden" name="test_mode" value="1">
<input type="submit" value="Pay with cashU!">
</form>

A: I think you should not rely on example encryption key since obviously it is wrong and each merchant gets his own key.
Looking at http://docs.whmcs.com/CashU I found following:
"You can find the Encryption Keyword inside your CashU account by going to My Account > Payment Security.
This is where you also need to set the return url, which must be set to:
http://www.yourdomain.com/modules/gateways/callback/cashu.php
The Notification URL should be left blank."
Hope this helps


text:
Q: Vim Syntastic plugin not working for coffeescript 1.6.0+ I have the following syntastic settings inside my .vimrc:
"------------SYNTASTIC-----------
let g:syntastic_enable_signs=1
let g:syntastic_mode_map={ 'mode': 'active',
                     \ 'active_filetypes': [],
                     \ 'passive_filetypes': ['html', 'java'] }
let g:syntastic_coffee_checkers = ['coffeelint', 'coffee']
let g:syntastic_coffee_coffeelint_args = "--file [absolute path to]/coffeelint.json"
let g:syntastic_enable_signs=1
let g:syntastic_error_symbol='✗'
let g:syntastic_warning_symbol='⚠'

when I have coffeescript installed to 1.6.0+ (i.e. npm install -g coffee-script@1.6.3) syntastic doesn't seem able to detect any compilation errors, even though both coffee file.coffee and coffeelint file.coffee displays the error fine.
I ran :SyntasticCheck then :messages and no debug error surfaced.
I've also made sure that npm is part of the PATH: PATH="/usr/local/share/npm/bin:$PATH"
On the other hand, when coffeescript is installed at coffee-script@1.5.0 the errors DO in fact surface (everything works!), except that it doesn't pick up the coffeelint_args. This behavior might be expect from  https://github.com/scrooloose/syntastic/wiki/CoffeeScript%3A---coffee
Do I need to know something special to get syntastic working w/ coffeescript 1.6.0+ on Mac?

A: Here's the issue on github: https://github.com/scrooloose/syntastic/issues/694
The fix was to do a git fetch && git rebase or git pull from the syntastic git directory (assuming you're using pathogen)


text:
Q: how to create junit reports in eclipse? I want to generate junit reports in eclipse. I generated build.xml, than run my tests. I perform the steps described here http://earlwillis.wordpress.com/2012/01/31/getting-started-with-junit-reports/. But I get error
Buildfile: E:\eclipse\WebDriver\build.xml
build-subprojects:
init:
build-project:
 [echo] WebDriver: E:\eclipse\WebDriver\build.xml
[javac] E:\eclipse\WebDriver\build.xml:45: warning: 'includeantruntime' was not set,     defaulting to build.sysclasspath=last; set to false for repeatable builds
 build:
Sector:
[junit] Running Sector
[junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec
[junit] Test Sector FAILED
junitreport:
[junitreport] Processing E:\eclipse\WebDriver\junit\TESTS-TestSuites.xml to E:\DOCUME~1  \CONSUL~1\LOCALS~1\Temp\null35256633
[junitreport] Loading stylesheet jar:file:/E:/eclipse/plugins/org.apache.ant_1.8.2.v20120109-1030/lib/ant-junit.jar!/org/apache/tools/ant/taskdefs/optional/junit/xsl/junit-frames.xsl
[junitreport] : Error! The first argument to the non-static Java function 'replace' is not a valid object reference.
[junitreport] : Error! Cannot convert data-type 'void' to 'reference'.
[junitreport] : Fatal Error! Could not compile stylesheet
[junitreport] Failed to process E:\eclipse\WebDriver\junit\TESTS-TestSuites.xml

BUILD FAILED
E:\eclipse\WebDriver\build.xml:193: Errors while applying transformations: Fatal error during transformation

Total time: 2 seconds

If needed I can provide build.xml. In folder junit I don't see  any html files. What I do wrong?


text:
Q: Not able to implement background image in HTML email template in GMAIL/OUTLOOK I am trying to send a background image in email. I am using HTML email template without Letterhead. On Preview, I can see the background image but it is not displayed when send to email server. I have tested with GMAIL and outlook.
HTML email template

        testing background image

On Preview:

But In GMAIL/OUTLOOK, I am only seeing testing background image

A: You may use something like that, please change the width and  height values based on your expectations:

                            testing background image


text:
Q: AppleScript: How to write to text file in specific location (signaled by specific character)? I have a .txt file saved on my computer. I want my Automator application to add a bit of text to the .txt file (the text will be entered by the user). I already know how to append text or prepend text in AppleScript. However, I want the text to be inserted into a specific location.
For example, this is the contents of my .txt file entitled My Fruit Log.txt. This is what the .txt file looks like before the text is written to the file:

You can see where exactly I want the text to be saved in the file in this image:

Is what I want to do clear? I want the text to be written on the line directly above the first blank line found in the file. Note: It is not necessarily the second line from the top where I want the text to be written. Depending on what text has already been written to the file, the text might be saved on a lower line. For example:

The location where I want the text to be written must be at least the second line from the top, but it may also be as further down as the seventh line from the top. So, the most reliable way to articulate where I want to write the text is "on the line before the first instance of a blank line in the document."
Can this be accomplished in AppleScript?

A: Here's a shell script:
sed -i '' -e ':a' -e 'N' -e '$!ba' -e 's/\n\n/\
Write the new line you wish inserted in your file here\
\
/' ~/Desktop/file.txt

You can wrap this in a 'do shell script' if you really want AppleScript, but for an Automator script, you can use a Run Shell Script action and just use the shell script.

Here's an AppleScript wrapper for the script, where the TextToWrite variable and the Target_Filepath variable have been defined elsewhere per your comments:
set addline to "sed -i '' -e ':a' -e 'N' -e '$!ba' -e 's/\\n\\n/\\
" & TextToWrite & "\\
\\
/' \"" & Target_Filepath & "\""
do shell script addline

A: If I understand your question correctly, you what to write some new text content to the text file directly above the first blank line and if that's correct then here's an example of one way it can be done.
Note that sometimes the AppleScript do shell script command can get complex when having to escape certain instances of special charters, ordinary charters and or if multiple command lines are involved, etc.
So in the following example I'm going to limit the do shell script command to something as simple as I can that doesn't require lots of escaping while allowing for a variable filename and will return the byte count up to the first blank line in the file, as I believe this is the insertion point you're requesting for where the new text is to be written.
I will then use the byte count as the offset point as the reference point to where the new text would be written to the target text file. I'll do this by reading into variables from the start of the file up the offset and reading from the offset to the end of the file, then concatenate the three variables to one variable to write to the target file from the beginning of the file. Thus overwriting the old content with the combination of new and old content.

AppleScript code:
set filePathName to POSIX path of (path to desktop as string) & "My Fruit Log.txt"

try
    set offsetCount to (do shell script "grep -b -m1 '^$' \"" & filePathName & "\" | cut -f1 -d:")
end try
if offsetCount is equal to "0" or offsetCount is equal to "" then
    display dialog "The contents of the target file does not conform to the necessary requirements for processing and or may contain consecutive 0D Carriage Return Characters, instead of the 0A Line Feed Characters expected by default in macOS." buttons {"OK"} default button 1
    return
end if

set newContent to "I ate a strawberry at 1 am."

try
    set referenceNumber to open for access filePathName with write permission

    set oldContentUpToFirstBlankLine to read referenceNumber from 1 to offsetCount
    set oldContentFromFirstBlankLine to read referenceNumber from offsetCount to eof

    set allContent to oldContentUpToFirstBlankLine & newContent & oldContentFromFirstBlankLine

    write allContent to referenceNumber starting at 0
    close access referenceNumber

on error eStr number eNum
    display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with title "File I/O Error..." with icon caution
    try
        close access referenceNumber
    end try
    return
end try

Terminal output of "My Fruit Log.txt" before running AppleScript code:
$ cat "$HOME/Desktop/My Fruit Log.txt"
2016_11_09 -

2016_11_08 -
I ate a banana at 8 am.
I ate a kiwi at 11 am.
I ate a mango at 6 pm.

2016_11_07 -
I ate a pear at 6 am.
I ate a tangerine at 4 pm.
I ate a peach at 8 pm.
$

Terminal output of "My Fruit Log.txt" after running AppleScript code:
$ cat "$HOME/Desktop/My Fruit Log.txt"
2016_11_09 -
I ate a strawberry at 1 am.

2016_11_08 -
I ate a banana at 8 am.
I ate a kiwi at 11 am.
I ate a mango at 6 pm.

2016_11_07 -
I ate a pear at 6 am.
I ate a tangerine at 4 pm.
I ate a peach at 8 pm.
$

So as you can see, this inserts the new text content above the first blank line in the file.
Below we see the Event Log of the AppleScript Editor when the above AppleScrip code is run:
tell current application
    path to desktop as string
        --> "Macintosh HD:Users:me:Desktop:"
    do shell script "grep -b -m1 '^$' \"/Users/me/Desktop/My Fruit Log.txt\" | cut -f1 -d:"
        --> "13"
    open for access "/Users/me/Desktop/My Fruit Log.txt" with write permission
        --> 172
    read 172 from 1 to "13"
        --> "2016_11_09 -
"
    read 172 from "13" to eof
        --> "

2016_11_08 -
I ate a banana at 8 am.
I ate a kiwi at 11 am.
I ate a mango at 6 pm.

2016_11_07 -
I ate a pear at 6 am.
I ate a tangerine at 4 pm.
I ate a peach at 8 pm.
"
    write "2016_11_09 -
I ate a strawberry at 1 am.

2016_11_08 -
I ate a banana at 8 am.
I ate a kiwi at 11 am.
I ate a mango at 6 pm.

2016_11_07 -
I ate a pear at 6 am.
I ate a tangerine at 4 pm.
I ate a peach at 8 pm.
" to 172 starting at 0
    close access 172
end tell


text:
Q: Launch a Chrome App in Windows 8 Metro Mode from shortcut I have a chrome app I would like to launch into Chrome's Window's 8 mode from a shortcut on the start page. I can get the Chrome browser to launch in the mode using the --force-immersive flag, but this does not work when combined with the --appId=myAppId flag to launch my application. The app still launches in desktop mode.
Is it possible to launch a chrome app directly into metro/win8 mode from a shortcut rather than the Google Application Launcher? I have looked at other command-line switches for Chrome but have not found a combination that produces the desired behavior.

A: Unfortunately the short answer is no (unless it gets implemented in a Chrome after version 40).
The code in Chrome that handles --appId explicitly sets the desktop type to "NATIVE" (i.e. not Windows 8 mode). This is because the same shortcut is used regardless of the mode it is launched in, and we didn't want the mode Chrome was currently running in to affect Chrome Apps launched from the Desktop.
And, same as for Chrome, we can't assume that launching from the start page (rather than the Desktop) means you want to start the app in Windows 8 mode.
It's still a legitimate bug though. If you'd like to file a New Issue at http://crbug.com/ like "Not possible to launch a Chrome App in Windows 8 Mode from a Shortcut", we can investigate what it would take to add this feature. Make sure you put the bug number here too so I notice it.


text:
Q: Stuck in boot: Missing modules (cat /proc/modules; ls /dev) in BusyBox To solve a Wi-fi issue I did a fresh install of Ubuntu 22.04 from USB. After completing the installation process Ubuntu started rebooting. But it couldn't complete reboot as it stuck in this error menu. Please help me to solve this problem.
BusyBox initramfs error:
Missing modules (cat /proc/modules; ls /dev)
ALEART! UUID=a41ee097-5069-408d-abbd-4f50848aa357 does not exit.
Laptop Model: Lenovo Ideapad S340-14IWL
Image of the problem


text:
Q: MFC-ActiveX is not refreshed/repainted automatically I have a MFC-based ActiveX control, where some important things do not work. A size-event is never called and the controls contents are redrawn only when I click the border of the control (in ActiveX test container).
That's my code for the size-event in header file:
public:
    afx_msg void OnPaint();

...and in source file:
BEGIN_MESSAGE_MAP(CBeamConstruXCtrl, COleControl)
    ON_WM_SIZE()
    ON_WM_PAINT()
    ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()

void MyCtrl::OnPaint()
{
   //this is never called also when I change the size of the control in test container
}

Any ideas what is missing here?
Edit: just a clarification: OnSize() is called once in initialisation phase of the OCX, but never when I change the controls size.

A: As mentioned by Roger Rowland: OnDraw() does the trick.


text:
Q: How to Pass an object of VB Structure to VC++ dll structure? ------------------------------------VB Code------------------------------------
Public Class Form1

    Public Structure Test_Structure
        Dim xyz As Integer
        Dim abc As System.String
    End Structure

    Dim OBJ_Structure As New Test_Structure
    Dim OBJ_Dll As New Test_Dll

    Public Sub Temp()
        OBJ_Dll.Dll_Function(OBJ_Structure)
    End Sub
End Class

--------------------------------VC++ Code------------------------------------
Public ref Class Dll
{
    public ref struct Temp
    {
        int xyz;
        System::String^ abc;
    };

    int Dll_Function(Temp^ obj_Temp);
};

As Shown above, I want to pass object of VB Structure(unmanaged) into VC++ Structure(managed). But I get error of type-conversion. What should be solution of this.


text:
Q: How to prevent buttons from resizing when I scroll tableView I have a tableview with buttons which I resize with the below code to fit their labels:
class ResizableButtons: UIButton {
    override var intrinsicContentSize: CGSize {
          let labelSize = titleLabel?.sizeThatFits(CGSize(width: frame.width, height: .greatestFiniteMagnitude)) ?? .zero
          let desiredButtonSize = CGSize(width: labelSize.width + titleEdgeInsets.left + titleEdgeInsets.right, height: labelSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
          return desiredButtonSize
      }
}

It works pretty well.
The problem occurs when I try to scroll tableview down and up.

As you can see from the snapshots, buttons get resized. And it seems to happen only after I click on some button and start to scroll. If I scroll without clicking the sizes remains ok.
I believe the problem lays in how I set titles to the buttons. I do it with the following code :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//Every second row has a button.
     if indexPath.row % 2 == 0 {
     let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell") as! ReusableCell
     cell.button.setTitle(textAndButtonsArray[indexPath.row], for: .normal)
     cell.backgroundColor = UIColor.clear

//Checking if button was pressed before
     if pressedButtons.contains(indexPath.row) {
         print("Text for selected button at indexpath \(indexPath.row) is \(cell.button.titleLabel?.text)")
     }
}

So if I print into the console indexPath and textLabel for pressed buttons, it gives me correct indexPath. But the textLabel displayed in the console is from a different button. From the one that is 10 rows later than the actual pressed one.

Any ideas how I could fix it?
P.S. Don't pay attention to text and labels on the buttons, I wrote whatever came to my mind first :)

A: Try to resize your cell or buttons inside willDisplayCell and reset the button size in prepareForReuse. Call inside intrinsicContentSize button.layoutIfNeeded().

A: It seems I've found a solution. In the part where I resize the buttons, I need to change titleLabel to currentTitle. So it looks like this:
class ResizableButtons: UIButton {

    override var intrinsicContentSize: CGSize {
        let label = currentTitle
        titleLabel?.text = label
        let labelSize = titleLabel?.sizeThatFits(CGSize(width: frame.width, height: .greatestFiniteMagnitude)) ?? .zero
        let desiredButtonSize = CGSize(width: labelSize.width + titleEdgeInsets.left + titleEdgeInsets.right, height: labelSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
        return desiredButtonSize
}

    override func layoutSubviews() {
        super.layoutSubviews()
        titleLabel?.preferredMaxLayoutWidth = self.titleLabel!.frame.size.width
    }
}

Not sure why is that. But it seems that XCode is updating labels on the buttons with some sort of delay. And button.titleLabel doesn't always match with button.currentTitle
Also last few lines with layoutSubviews() seems to matter.


text:
Q: Prove that the limit $\lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} f(x_k)$ exists
Prove that the limit $\lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} f(x_k)$ exists given that $\lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} x_k^i$ exists for every $i \in \{0,1,\dots \}$ and $x_k \in (0,1).$ and $f$ is a continuous function on $[0,1]$.

At first, the sums look like Riemann sums to he me, but I don't think it will help me prove the existence of the limit. I feel like this is a nested limit argument. The presence of the index $i$  also bothers me. Here are my thoughts,
\begin{align}
\lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} f(x_k) &= f(\lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} x_k) \\
&=f(x)
\end{align}
where $x = \lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} x_k$ and the exchange of composition is justified by continuity. But this problem occurs in a chapter from the Weistrass Approximation thoerm, so I suspect something about him is needed? If I could get a hint it would be great.
Also it looks like $lim_{n \to \infty} \frac{1}{n} \sum_{k = 1}^{n} x_k^i$ is the polynomial I need.

A: Your reasoning is wrong because it assumes that $f$ is linear (or almost): you assumed
$$
f\left(\frac1n\sum_{k=1}^nx_k\right)=\frac1n\sum_{k=1}^nf(x_k);
$$
This fails for most continuous functions and most choices of $x_1,\ldots,x_n$.
If $p$ is a polynomial,  $p(t)=\sum_{j=0}^ma_jx^j$. Then, writing $y_j=\lim_{n\to\infty}\frac1n\sum_{k=1}^nx_k^j$,
$$
\lim_{n\to\infty}\frac1n\sum_{k=1}^np(x_k)=\lim_{n\to\infty}\frac1n\sum_{k=1}^n\sum_{j=0}^ma_jx_k^j
=\sum_{j=0}^ma_j\lim_{n\to\infty}\frac1n\sum_{k=1}^nx_k^j=\sum_{j=1}^na_jy_j
$$
exists.
Now, by Weierstrass, for each $m$ there exists a polynomial $p_m$ with $|f(t)-p_m(t)|<1/m$ for all $t\in(0,1)$. Then
$$
\left|\frac1n\sum_{k=1}^np_{m_1}(x_k)-\frac1n\sum_{k=1}^np_{m_2}(x_k)\right|\leq\frac1n\sum_{k=1}^n|p_{m_1}(x_k)-p_{m_2}(x_k)|\\ \leq\frac1n\sum_{k=1}^n|p_{m_1}(x_k)-f (x_k)|+|f (x_k)-p_{m_2}(x_k)|\leq\frac1n\,\sum_{k=1}^n\frac1 {m_1}+\frac1 {m_2}=\frac1 {m_1}+\frac1 {m_2}.
$$
Thus the numbers $\frac1n\sum_{k=1}^np_{1/m}(x_k)$ converge, and an estimation similar to the above one shows that $\frac1n\sum_{k=1}^nf(x_k)$ converges to that number.


text:
Q: Sentencias SQL en PHP Estoy intentando mostrar datos de una base de datos, pero no me funciona
Tengo una parte del código de una sentencia SQL que es:
$sql='SELECT * FROM titulos ORDER BY id DES LIMIT' . $this_page_first_result . ',' .  $results_per_page;

Y quiero que aparezca en el archivo PHP la última publicación, pero no surte efecto, aparecen los datos por el id 1,2,3,4 y así consecutivamente..
He incluido la palabra clave LIMIT para limitar el número de visualizaciones por página.
Funciona todo bien, muestra los resultados y la páginación, pero en el orden id de menor a mayor.

A: Prueba con esta sentencia
SELECT TOP 5  * FROM TABLE  ORDER BY column1 DESC;


text:
Q: my Android app is run correctly in emulator but I can't find it in the emulator's apps menu I'm using Android Studio V1.3 and I have a problem with exporting my app in emulator or real device!. when I run the app from Android Studio in the emulator, the app runs but app icon is not shown in emulator's apps menu, As well as when I export my program to apk and install it on my device, installation is always successful but the open button in install confirmation is not active and I can't find the app in apps menu to open it! <>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aidin.zardast.avecalc" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/app"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
    </activity>
    <activity
        android:name=".secondActivity"
        android:label="@string/title_activity_second" >
    </activity>
</application>
</manifest>

logcat
08-03 15:06:37.438  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ Not     late-enabling CheckJNI (already on)
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations,   referenced from method  android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc W/dalvikvm﹕ VFY: unable to resolve virtual method 412: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc W/dalvikvm﹕ VFY: unable to resolve virtual method 434: Landroid/content/res/TypedArray;.getType (I)I
08-03 15:06:39.478  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-03 15:06:42.938  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed 134K, 7% free 3014K/3216K, paused 34ms, total 35ms
08-03 15:06:43.118  11582-11582/com.aidin.zardast.avecalc I/dalvikvm-heap﹕ Grow heap (frag case) to 22.905MB for 20864016-byte allocation
08-03 15:06:43.148  11582-11591/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed 3K, 1% free 23386K/23592K, paused 27ms, total 27ms
08-03 15:06:45.018  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed 5K, 1% free 23394K/23592K, paused 26ms, total 27ms
08-03 15:06:45.128  11582-11582/com.aidin.zardast.avecalc I/dalvikvm-heap﹕ Grow heap (frag case) to 34.900MB for 12574128-byte allocation
08-03 15:06:45.188  11582-11591/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 1% free 35672K/35872K, paused 56ms, total 56ms
08-03 15:06:45.958  11582-11582/com.aidin.zardast.avecalc I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
08-03 15:06:45.958  11582-11582/com.aidin.zardast.avecalc W/dalvikvm﹕ VFY: unable to resolve virtual method 375: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
08-03 15:06:45.958  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-03 15:06:45.968  11582-11582/com.aidin.zardast.avecalc I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
08-03 15:06:45.968  11582-11582/com.aidin.zardast.avecalc W/dalvikvm﹕ VFY: unable to resolve virtual method 377: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
08-03 15:06:45.968  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-03 15:06:46.728  11582-11582/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed 11K, 1% free 35693K/35872K, paused 78ms, total 78ms
08-03 15:06:46.918  11582-11582/com.aidin.zardast.avecalc I/dalvikvm-heap﹕ Grow heap (frag case) to 53.383MB for 19360016-byte allocation
08-03 15:06:46.988  11582-11591/com.aidin.zardast.avecalc D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 1% free 54599K/54780K, paused 62ms, total 62ms
08-03 15:06:48.548  11582-11582/com.aidin.zardast.avecalc D/﹕ HostConnection::get() New Host Connection established 0xb8117848, tid 11582
08-03 15:06:48.658  11582-11582/com.aidin.zardast.avecalc W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-03 15:06:48.688  11582-11582/com.aidin.zardast.avecalc D/OpenGLRenderer﹕ Enabling debug mode 0
08-03 15:07:40.478  11582-11582/com.aidin.zardast.avecalc W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
08-03 15:08:01.868  11582-11582/com.aidin.zardast.avecalc W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-03 15:09:13.968  11582-11582/com.aidin.zardast.avecalc W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-03 15:09:26.118  11582-11587/com.aidin.zardast.avecalc I/dalvikvm﹕ threadid=3: reacting to signal 3
08-03 15:09:26.428  11582-11587/com.aidin.zardast.avecalc I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
08-03 15:09:28.988  11582-11582/com.aidin.zardast.avecalc W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-03 15:09:45.828  11582-11587/com.aidin.zardast.avecalc I/dalvikvm﹕ threadid=3: reacting to signal 3
08-03 15:09:46.288  11582-11587/com.aidin.zardast.avecalc I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
08-03 15:10:07.708  11582-11582/com.aidin.zardast.avecalc W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection

A: You need to set this to your launcher activity
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER"/>
           </intent-filter>


text:
Q: Mapping values inside pandas column I used the code below to map the 2 values inside S column to 0 but it didn't work. Any suggestion on how to solve this?
N.B : I want to implement an external function inside the map.
 df = pd.DataFrame({
   'Age': [30,40,50,60,70,80],
   'Sex': ['F','M','M','F','M','F'],
   'S'  : [1,1,2,2,1,2]
 })
 def app(value):
     for n in df['S']:
         if n == 1:
             return 1
         if n == 2:
             return 0
 df["S"] = df.S.map(app)

A: Don't use apply, simply use loc to assign the values:
df.loc[df.S.eq(2), 'S'] = 0

   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

If you need a more performant option, use np.select. This is also more scalable, as you can always add more conditions:
df['S'] = np.select([df.S.eq(2)], [0], 1)

A: Use eq to create a boolean series and conver that boolean series to int with astype:
df['S'] = df['S'].eq(1).astype(int)

OR
df['S'] = (df['S'] == 1).astype(int)

Output:
   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

A: You're close but you need a few corrections. Since you want to use a function, remove the for loop and replace n with value. Additionally, use apply instead of map. Apply operates on the entire column at once. See this answer for how to properly use apply vs applymap vs map
def app(value):
    if value == 1:
        return 1
    elif value == 2:
        return 0
df['S'] = df.S.apply(app)
   Age Sex  S
0   30   F  1
1   40   M  1
2   50   M  0
3   60   F  0
4   70   M  1
5   80   F  0

A: You can do:
import numpy as np

df['S'] = np.where(df['S'] == 2, 0, df['S'])

A: If you only wish to change values equal to 2, you can use pd.DataFrame.loc:
df.loc[df['S'] == 0, 'S'] = 0

pd.Series.apply is not recommend and this is just a thinly veiled, inefficient loop.

A: You could use .replace as follows:
df["S"] = df["S"].replace([2], 0)
This will replace all of 2 values to 0 in one line

A: Go with vectorize numpy operation:
df['S'] = np.abs(df['S'] - 2)

and stand yourself out from competitions in interviews and SO answers :)

A: >>>df = pd.DataFrame({'Age':[30,40,50,60,70,80],'Sex':
 ['F','M','M','F','M','F'],'S':
 [1,1,2,2,1,2]})

>>> def app(value):
        return 1 if value == 1 else 0
    # or app = lambda value : 1 if value == 1 else 0

>>> df["S"] = df["S"].map(app)

>>> df
   Age  S Sex
      Age  S Sex
   0   30  1   F
   1   40  1   M
   2   50  0   M
   3   60  0   F
   4   70  1   M
   5   80  0   F


text:
Q: I want call unix command in cocoa application,but it doesn't work, I want call unix command in cocoa application,but it doesn't work,
the command:"lua -v"
cocoa code:
NSArray *cmdArray = [cmd componentsSeparatedByString:@" "];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
[task setStandardOutput:pipe];
task.launchPath = cmdArray[0];
if(cmdArray.count > 1)
{
    task.arguments = [cmdArray subarrayWithRange:NSMakeRange(1, cmdArray.count - 1)];
}
[task launch] ;
NSData *data = [file readDataToEndOfFile];
[file closeFile] ;

NSString *grepOutput = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return grepOutput;

the data always is 0 byte

A: NSTask does not run a Unix "command", rather it runs a Unix "process", and the difference is crucial.
When your code is run in Xcode you should see "launch path not accessible" in the console window, this is your clue as to the problem. The documentation for launch tells you that an exception is thrown if the launch path is invalid.
When you type, say, "echo Hello" at the Unix command prompt you are entering data into a command interpreter, the "shell". The shell has to locate the application "echo" in order to start a process running it. The shell does this by searching through a set of directories specified by the PATH environment variable, in the case of "echo" it finds "/bin/echo". It is this path you must set the launchPath property to.
If you wish to use NSTask for this purpose you have two basic choices (a) have your code locate the "lua" binary itself or (b) use NSTask to run a shell and have that shell do its normal processing for you.
The standard "sh" shell is located at "/bin/sh". If you read it's manual page you will see it takes an option "-c string" which instructs it to treat string as command input. E.g consider the following Terminal transcript:
crd$ echo Hello
Hello
crd$ sh -c "echo Hello"
Hello
crd$

In the first case the shell found the binary for "echo" and executed that passing it "Hello". In the second it found the binary for "sh" and executed that passing it "-c" and "echo Hello", that process in turn found the binary for "echo".
So using NSTask you can invoke "/bin/sh" and pass it as arguments "-c" and your command line, the shell will then parse your command line just like in the Terminal and invoke your command, something along the lines of:
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
task.standardOutput = pipe;
task.standardError =pipe;  // capture any error messages the sh writes, could send to another pipe
task.launchPath = @"/bin/sh";
task.arguments = @[@"-c", cmd];

[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];

HTH


text:
Q: HIbernate "StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1" When an existing user makes a request the method first deletes the oldest record before saving the new request. The code below works fine IF the requests don't come in too rapidly (using an Oracle DB).
   public Request saveRequest(Request req)
   {
      String user = req.getUser();

      // Do a NamedQuery on the entity to pull all requests for user
      List<Request> requestList = getRequests(user);

      LOGGER.info("Request List size is " + requestList.size() + " for " + user);

      // Sort the list then delete the first/oldest request
      Comparator<Request> bySessionDate = Comparator.comparing(Request::getDate);
      Collections.sort(requestList, bySessionDate);

      LOGGER.info("Deleting request id " + requestList.get(0).getId());

      deleteById(requestList.get(0).getId());

      Request sreq = requestRepository.create(req);
      LOGGER.info("Saved request for user " + sreq.getUserId());
      return sreq;
   }

Output:
2021-01-20 00:39:12,167 INFO  [beez.service.RequestManager] (default task-4) Request List size is 250 for Bob
2021-01-20 00:39:12,168 INFO  [beez.service.RequestManager] (default task-4) Deleting request id 757A9B21E51D49199F2E182F68BC6BF7
2021-01-20 00:39:12,171 INFO  [beez.service.RequestManager] (default task-4) Deleted: 757A9B21E51D49199F2E182F68BC6BF7
2021-01-20 00:39:12,173 INFO  [beez.service.RequestManager] (default task-4) Saved request for user Bob
2021-01-20 00:39:15,375 INFO  [beez.service.RequestManager] (default task-3) Request List size is 250 for Bob
2021-01-20 00:39:15,375 INFO  [beez.service.RequestManager] (default task-3) Deleting request id 27239B85472C45EDA5495E98523295F3
2021-01-20 00:39:15,377 INFO  [beez.service.RequestManager] (default task-3) Deleted: 27239B85472C45EDA5495E98523295F3
2021-01-20 00:39:15,380 INFO  [beez.service.RequestManager] (default task-3) Saved request for user Bob

However, if the user were to submit requests in a very quick fashion, i.e. happy clicker, the same code generates a StaleStateException error.
2021-01-20 00:42:31,307 INFO  [beez.service.RequestManager] (default task-3) Request List size is 250 for Bob
2021-01-20 00:42:31,307 INFO  [beez.service.RequestManager] (default task-3) Deleting request id 55E43DF4D83E4BF5AD73DE47A49B0DA9
2021-01-20 00:42:31,310 INFO  [beez.service.RequestManager] (default task-3) Deleted: 55E43DF4D83E4BF5AD73DE47A49B0DA9
2021-01-20 00:42:31,313 INFO  [beez.service.RequestManager] (default task-3) Saved request for user Bob
2021-01-20 00:42:31,332 INFO  [beez.service.RequestManager] (default task-7) Request List size is 250 for Bob
2021-01-20 00:42:31,332 INFO  [beez.service.RequestManager] (default task-7) Deleting request id 55E43DF4D83E4BF5AD73DE47A49B0DA9
2021-01-20 00:42:31,492 ERROR [org.jboss.as.ejb3.invocation] (default task-7) WFLYEJB0034: EJB Invocation failed on component RequestManager for method public beez.entity.RequestManager service.RequestManager.saveRequest(beez.entity.RequestManager): javax.ejb.EJBTransactionRolledbackException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
.
.
.
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Seems like the code hasn't had time to complete the change before the next one came in causing the code to try to delete the same record twice. Other than changing the front end or something else before this method, is there a way around this?
I've tried the @Transactional and @Lock options with no success. Spent a lot of time in this thread but the solutions either didn't work or didn't apply:
Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

A: If users clicking rapidly is not expected, strongly recommend you to think of Debouncing API requests in front to skip back to back requests/events.
As you said rightly issues is happening because of inconsistency between what entities loaded to a individual session and current state of database.
This can be solved in multiple ways like using pessimistic locking with (select for update) comes with performance bottle necks, synchronizing the method .... etc
Simplest way to handle this is deleting using a JPA query and ordering at database level, so this always works on the current state of record table.
delete from request where id= (select req.id from request req left join user usr on usr.id = req.userId where usr.userId=? order by req.date LIMIT 1)

Please correct the above query according t your Entity design.


text:
Q: Dropdown does not populate when last item deleted from gridview I am having trouble determining where the bug is for this problem.
I have an ASP.NET Master.Page web application that has a Gridview.  I am using the jquery-chosen plugin for a dropdown list in the EmptyDataTemplate (or FooterControl if there is data).
On initialization if there is no data for the grid, the dropdown is populated and displays correctly. If the grid has items in it and I delete all of them, so that there is no data, the dropdown does not display any data.  The DataBound event is called and the DataTable has all of the correct data in it. It is bound to the dropdown.  But do items appear in the list.
This is my markup:

    <asp:GridView ID="DelegateInfoGridView" runat="server"
        AutoGenerateColumns="false" Caption="Delegate Information"
        CaptionAlign="Top" CssClass="grid" RowStyle-Wrap="true"
        HorizontalAlign="Left" ShowFooter="true"
        AllowPaging="true" PageSize="5"  ShowHeaderWhenEmpty="false" onrowediting="DelegateInfoGridView_RowEditing"
        onrowcancelingedit="DelegateInfoGridView_RowCancelingEdit" onrowdeleting="DelegateInfoGridView_RowDeleting"
        onrowupdating="DelegateInfoGridView_RowUpdating"
        ondatabound="DelegateInfoGridView_DataBound"
        onrowcommand="DelegateInfoGridView_RowCommand">
        <Columns>
             <asp:TemplateField HeaderText="Recipient ID">
                <ItemTemplate>
                    <asp:Label ID="deligvLblRecipientID" runat="server" Text='<%# Bind("RecipientID") %>'></asp:Label>
                </ItemTemplate>
             </asp:TemplateField>

             <asp:TemplateField HeaderText="Delegate" ItemStyle-Wrap="false">
                <ItemTemplate>
                    <asp:Label ID="deligvLblRecipientName" runat="server" Text='<%# Bind("RecipientName") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
                                        data-placeholder="Choose delegate…" class="chosen-single">
                    </asp:DropDownList>
                </FooterTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Active">
                <ItemTemplate>
                    <asp:Label ID="deligvLblActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'></asp:Label>
                </ItemTemplate>
                 <EditItemTemplate>
                    <asp:DropDownList ID="deligvDDLActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'>
                        <asp:ListItem>Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
                        <asp:ListItem Selected="True">Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
                 <ItemTemplate>
                    <asp:Button ID="deligvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
                                Text="Edit" CssClass="gridActionbutton">
                    </asp:Button>
                     <asp:Button ID="deligvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete" ClientIDMode="Static"
                                Text="Delete" CssClass="gridActionbutton"  OnClientClick="return confirm('Are you sure you want to delete this Delegate Information?')" >
                    </asp:Button>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:Button ID="deligvUpdateButton" runat="server" CausesValidation="False" CommandName="Update"
                                    Text="Update" CssClass="gridActionbutton"></asp:Button>
                     <asp:Button ID="deligvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                                    Text="Cancel" CssClass="gridActionbutton"></asp:Button>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Button ID="deligvAddButton" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
                                CssClass="gridActionbutton">
                    </asp:Button>
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>

                Recipient ID
                Delegate
                Active
                Action

                    No Delegates were found for you. Delegates can be added by clicking the 'Add Delegate' Button.

                    <asp:DropDownList ID="deligvDDLRecipientName" runat="server" ClientIDMode="Static"
                                        data-placeholder="Choose delegate…" class="chosen-single">
                    </asp:DropDownList>

                     <asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
                        <asp:ListItem Selected="True">Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>

                    <asp:Button ID="deligvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
                        CssClass="gridActionbutton">
                    </asp:Button>

        </EmptyDataTemplate>
     </asp:GridView>

This is my DataBound event:
 protected void DelegateInfoGridView_DataBound(object sender, EventArgs e)
    {
        try
        {

            m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);

            //Get the Footer controls that have the new entry data
            Control tFooterControls = getFooterControls(DelegateInfoGridView);
            DropDownList ddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
            m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
            DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
            ddlRecipientNames.DataSource = tdtAllDelegates;
            ddlRecipientNames.DataTextField = "RecipientName";
            ddlRecipientNames.DataValueField = "RecipientID";
            ddlRecipientNames.DataBind();
            ddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
        }
        catch (Exception ex)
        {
            //TO DO: Response.Redirect("~/Error.aspx");
        }
    }

Why won't the dropdown display the items after all items are deleted but will correctly display if initially there are no items in the gridview to display?
I tried triggering an update for the chosen dropdown but that is called initially, before the data is retrieved.
I don't know if there is a bug in the code-behind or do I need to add something in the javascript.
Thanks.
UPDATE
The problem is not with the chosen plugin.  I removed the attribute from the DropDown list that changes it to a 'chosen' style and the problem still exists.  So the asp:DropDownList will not populate after the user deletes all of the items in the grid.  But if the grid is initialized with no items, the DropDown is correctly populated.
UPDATE
I got a suggestion to use the 'RowDeleted' event to bind the dropdown.  However, the event is not firing.  I added the event to the markup:
onrowdeleted="DelegateInfoGridView_RowDeleted"

This is the event that is never called:
 protected void DelegateInfoGridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        try
        {
            m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);

            //Get the Footer controls that have the new entry data
            Control tFooterControls = getFooterControls(DelegateInfoGridView);
            DropDownList tddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
            m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
            DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
            tddlRecipientNames.DataSource = tdtAllDelegates;
            tddlRecipientNames.DataTextField = "RecipientName";
            tddlRecipientNames.DataValueField = "RecipientID";
            tddlRecipientNames.DataBind();
            tddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
        }
        catch (Exception ex)
        {
            //TO DO: Response.Redirect("~/Error.aspx");
        }
    }

What is different about the RowDeleted event that it will not fire?

A: The problem was that I was checking if the FooterControl was null.  If it was, I got the EmptyTemplateData control.  When you delete all of the rows, the FooterControl is not null, but it needs to get the EmptyTemplateData control.
So, I changed the logic to check for Grid Row Count > 0 instead of a null FooterControl.
That fixed the problem..


text:
Q: printing unique key-value and skipping the same value-key in dict I have this dictionary and I don't want to print (the key and the value) if they already exist (as value and key) or vice versa.
I want to print (orange and apple) and (Strawberry and Grapes) for once.
{
'Orange'    : 'Apple',
'Orange'    : 'Banana',
'Strawberry': 'Grapes',
'Apple'     : 'Orange',
'Blackberry': 'Banana',
'Cherry'    : 'Fig',
'Grapes'    : 'Strawberry'
 }

Expexted output:
Orange Apple
Orange Banana
Strawberry Grapes
BlackBerry Banana
Cherry Fig

A: Having duplicate keys sort of violates the purpose of a dictionary in python. There are ways around it like here but I wouldn't suggest it.


text:
Q: ymaps actionend - как отключить событие для map.panTo? или аналог dragend от google? Вопрос по яндекс картам.
Есть ли в яндекс картах событие dragend как в гугл картах?
Есть следующий алгоритм

*

*Перетаскивание карты (drag или мышью)

*Детект адреса по координатам (обращение к api) => .then

*this.map.panTo(center) - передвижение карты на ближайший адрес

Проблема заключается в том, что ymap реагирует на действие пользователя
и на panTo - одинаково. Вызывает событие actionend.
Вопросы

*

*Есть ли событие как dragend в googleMaps

*Можно ли задетектить, что собитие было вызвана с помощью this.map.panTo || this.map.setCenter?

Пример кода - набросок
                this.map.events.add('actionend', e => {

                    const state = this.map.action.getCurrentState();
                    const zoomLevel = state.zoom;

                    this.calcAddress()
                        .then(({ center }) => {
                            this.map.panTo(center, zoomLevel)
                        });
                });

A: В API Яндекс.Карт actionend будет приходить всегда.
panTo возвращает Promise, подпишитесь на него.