text:
Q: Ever since I was a child 'I have been confronted' vs. 'I am confronted' - which is better: Present Perfect or Present Simple? What is the meaning of this sentence?

Ever since I was a child, I have been confronted with questions about my 'real' parents and my 'real' country.

and what if I say
Ever since I was a child, I am confronted with questions about my 'real' parents and my 'real' country.

A: "I am" doesn't work because it refers to an action that happens now, where as "Ever since I was a child" refers to a whole period of time, most of which is in the past.  "I have been" refers to a continuous action over a period of time that began in the past and continues to the present, so that's what you want to use here.

A: Here, the preferred choice is 'present perfect'.
I am confronted... will not serve the purpose here. Because...
if you want to say that you are confronted with those gruesome questions from one point of time till now, you use have been.
Cambridge Dictionary defines it:

We use 'ever' before 'since' to emphasise that something has been true from the beginning of a specific period of time:

Why not the present?
It is occasionally used and used especially in sentences that talk about the 'change'.
Swan's PEU (Entry 522) says it:

In sentences with since (referring to time), we normally use present perfect and past prefect tenses in the main clause.
However, present and past tenses are also occasionally found, especially in sentences about changes

He further gives an example:

You are looking much better since your operation.


text:
Q: c# List Sort : by Chinese strokes I have a webpage, in which there is a sort that I have to order the list by Chinese strokes.
I have created an application containing code like this:
List<Student> stuList = new List<Student>() {
          new Student("上海"),
           new Student("深圳"),
            new Student("广州"),
             new Student("香港")
            };
        System.Globalization.CultureInfo strokCi = new System.Globalization.CultureInfo("zh-tw");
        System.Threading.Thread.CurrentThread.CurrentCulture = strokCi; ;
        //stuList.sort();

but there is an error: At least one object must implement IComparable.
What does this mean and how can I fix it?

A: You need to have your Student class implement the IComparable interface. This requires implementing a method CompareTo, which can simply return the result of calling CompareTo between the strings you're trying to order by.
For example, if the constructor initializes a name field, you might have something like this:
public class Student : IComparable
{
    private string name;

    public Student(string name)
    {
        this.name = name;
    }

    public int CompareTo(object other)
    {
        Student s = other as Student;
        if (s == null)
        {
            throw new ArgumentException("Students can only compare with other Students");
        }

        return this.name.CompareTo(s.name);
    }
}

A: Student must implement IComparable.

A: Rather than implement IComparable, why not just use a bit of LINQ?
stuList.OrderBy( s => s.Name ) //.ToList if you really want a List

A: public class Student : IComparable
{
    private string message = null;
    public Student(string message)
    {
        this.message = message;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // implement your logic, here is a example:
        if (obj != null)
            return message.CompareTo(((Student)obj).message);
        return int.MinValue;
    }

    #endregion
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connectivity between Control-M and Power BI Does any one have any idea about connectivity between Control-M and Power BI ?
I want to achive event based scheduling for Power BI Reports(Paginated Reports).
We are trying to implement even based scheduling in our project. Currenly , In existing architechture they are using control M for scheduling the crystal reports. Is there any other way ? Can we integrate Control M and Powerbi reports using some API ?
Thanks in advance.

A: Yes, you can use the PowerBI API to refresh data up to 8 times a day on Pro or 48 times a day on Premium. You could also use direct query to provide the report data on the fly.
POST https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/refreshes

Once the refresh completes you can mail out a link to the report and your users will get the latest.

A: Control-M supports CLI, API, the whole shooting match. There is a module (part of the standard Control-M package) called Application Integrator (confusingly referred to as AI) which allows people to create bespoke integrations and (if they wish) share them via a community hub. A BMC staff member has created an integration for Power BI and it can be downloaded here - https://communities.bmc.com/docs/DOC-125437 with a guide here (including the author's email - https://communities.bmc.com/docs/DOC-125436


text:
Q: Spring Boot Rest APi Connection Reset Exception Please help me understand this problem and solution.
I am doing an Integration with third party via Rest.
I have 2 apps where I am Integrating this service, The code works fine on 1 service and same code gives following error on other service.
both services are deployed on different servers.
Error Snap
Error
request sample
try{
        String result = "";
        HttpPost post = new HttpPost(url);
        post.setHeader("Authorization", "Basic **********************");
        post.setHeader("Content-Type", "application/json");

        // json formatted data
        String jsonBody = "***********************************************";
        LOGGER.info("json body = "+jsonBody);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                SSLContexts.createDefault(),
                new String[] { "TLSv1.2" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

         // send a JSON data
        post.setEntity(new StringEntity(jsonBody));

        try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
             CloseableHttpResponse response = httpClient.execute(post)) {

            result = EntityUtils.toString(response.getEntity());
            LOGGER.info("Result = "+result);
        }

        return result;
    }catch (Exception e){
        LOGGER.info("Exception = "+e);
    }
        return null;
}

What I have tried so far

*

*use http/https with url (No success)

*tried different Rest Client (okhttp,Unirest,Apache Http) (no success)

*used curl request from server (request is successful)

*tested via postman (request is successful)


text:
Q: JMeter: Add/remove body HEADERS for parameters in multipart/form-data I'm having hard time  to change the header parameters(Content-Type: text/plain; charset=US-ASCII to Content-Type: application/json ) for POST call in JMeter - sending JSON Text as mutlipart/form-data parameter with content application/json.
Tried this code snippet - sampler.getHeaderManager().remove(1)- its not helping to remove body headers.
--v_23LkJlLQpYLpcElRptQYb74v7-UeP
Content-Disposition: form-data; name="symbol"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit

{"name":"man_234","Id":"7d12d44c2"}
--v_23LkJlLQpYLpcElRptQYb74v7-UeP--

Can you Please leave me suggestions to get through

A: If you want to amend Content-Type: text/plain; charset=US-ASCII bit in the request body you need to do it in a different way, to wit: in JSR223 PreProcessor use the following code:
def oldBody = sampler.getArguments().getArgument(0).getValue()
def newBody = oldBody.replaceAll('Content-Type: text/plain; charset=US-ASCII','Content-Type: application/json')
sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('',newBody,'')

However your approach might not be the best one as in case of multipart request each FormData entry can have its own Content-Type so instead of amending request you need to build it in a different way. See Testing REST API File Uploads in JMeter article for example of building a multipart request manually.


text:
Q: Passando informação para uma outra Activity Bom dia estou tentando passar 2 dados de uma activity para outra mas não estou conseguindo segue abaixo o código relevante na primeira Activity :
 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri contactData = data.getData();
            Cursor c =  getContentResolver().query(contactData, null, null, null, null);
            if (c.moveToFirst()) {

                String phoneNumber="";
                String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                if ( hasPhone.equalsIgnoreCase("1"))
                    hasPhone = "true";
                else
                    hasPhone = "false" ;

                if (Boolean.parseBoolean(hasPhone))
                {
                    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
                    while (phones.moveToNext())
                    {
                        phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                    phones.close();
                    Bundle bundle = new Bundle();
                    bundle.putString(name, String.valueOf(name));
                    bundle.putString(phoneNumber, String.valueOf(phoneNumber));

                }
                //mainActivity.onBackPressed();
                // Toast.makeText(mainactivity, "go go go", Toast.LENGTH_SHORT).show();

            //    tvname.setText("Name: "+name);
              //  tvphone.setText("Phone: "+phoneNumber);
              //  Log.d("curs", name + " num" + phoneNumber);
            }
            c.close();
        }
        finish();

    }

Segue abaixo o código relevante da Segunda Activity :
 intent = getIntent();
 Bundle getBundle = null;
 getBundle =  intent.getExtras();
 Bundle bundle = intent.getExtras();
 String name = bundle.getString("name");
 String phone = bundle.getString("phoneNumber");
 messageContact = name+'\n'+ phone;

A: Você chama o bundle corretamente, mas falta passar o bundle pelo "Intent".
Segue exemplo (Com bundle):
        Bundle bundle = new Bundle();
        bundle.putString("id_do_item", "seu_dado");
        Intent intent = new Intent(context, MinhaOutraActivity.class);
        intent.putExtra(bundle);
        startActivity(intent);

Para acessar na outra view,use o seguinte codigo:
id_user = getIntent().getExtras().getString("id_do_item");

A: Erro
O seu erro é estar criando um novo bundle e não passá-lo para activy, ou poderia usar o bundle do onCreate.

Como fazer
Há 2 formas:
Sem o Bundle (porque seu intent já tem um próprio no onCreate)
public void teste2(View v) {

    Intent i = new Intent(this,Teste.class);
    i.putExtra("site","site2.com");
    startActivity(i);
}

Com um novo Bundle:
public void teste(View v) {

    Intent i = new Intent(this,Teste.class);

    Bundle bd = new Bundle();
    bd.putString("site","google.com");

    i.putExtras(bd);
    startActivity(i);
}

Com novo bundle, usando o putExtras.
Com o bundle do onCreate, seria o putExtra.


text:
Q: How to change a digit in string to integer rather than its ASCII code? Question : Write a program in a C++ to display the sum of digits present in a text file.
-->
#include<iostream.h>
#include<fstream.h>
int main()
{
 ifstream f1("Fees.txt");
 int sum=0;
 char n;
 while(f1.eof()==0)
 {
  f1>>n;
  if(isdigit(n))
   {
   sum=sum+n;
   }
 }
    cout<<sum;
}

I know the program's not working because string is changed to digit,( 1 changes to its ASCII code 49 instead of 1)
Please guide me
And is there a better way to approach the question?
UPDATE Ok so I changed the line sum+=n to sum+=n-'0'.
Still the program only seems to be working when there is a special character in addition to numbers in the text file Fees.txt.
  Example:
1 2 9

This does not work
1 2 9ok

This does work, any idea what's going on here?

A: As you point out, the ASCII codes for digits do not start at zero, which is your problem. Luckily though, they do lie in a continuous range, so all you need to do is change the line:
sum=sum+n;

to
sum += (n - '0');

A: This has nothing to do with ASCII. The C and C++ standards require that the values of '0'..'9' be contiguous and increasing, so converting a character that represents a digit simply requires subtracting '0', regardless of the character encoding. So:
sum += n - '0';

will fix the problem.


text:
Q: dependent drop downlist generation I'm trying to make a dependent dropdown list using ajax and php but not able to get the desired result
here is my code of ajax
<html>
<head>
<title>findperson</title>
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var x=ddl1.value;
var service;
var url='service.php?data='+x;
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET",url);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
service=XMLHttpRequestObject.responseText;
for (var i=0;i<service.length;i++ ){
var opt = service[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
ddl2.appendChild(el);
}

}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="problem.php">
<select name="city" id="city"       onchange="configureDropDownLists(this,document.getElementById('service'))">
<option selected="selected" value="">City</option>
<option value="jhansi">Jhansi</option>
<option value="lucknow">Lucknow</option>
</select>
<select id="service">
<option selected="selected" value="">Service</option>
</select>
<input type="submit" name="proceed" value="Next"/>
</form>
</body>
</html>

this is my php file
<?php
include_once('db.php');
$db=new db();
$sql=$db->database_initialise();
$city=$_GET['data'];
$query="select service_name from service_offered where city='$city'";
if($result=$sql->query($query)){
if($result->num_rows >0){
    $i=0;
    while($row=$result->fetch_array()){
        $service[$i]=$row[0];
        $i++;
    }
  }
}
var_dump($service);
?>

problem is that in second dropdown list no changes occur on selecting a city

A: Replace var_dump($service)
echo json_encode($service);

A: Your issue is that you are returning the $service array from your PHP and accessing it in your AJAX as a string. service=XMLHttpRequestObject.responseText; returns a string object. In your for loop it looks like you are trying to index through an array. However, you can't index through a string like that and get what you are expecting.
The best thing is to use echo json_encode($service); like Leo suggested, then in your AJAX transform the responseText by using JSON.parse
var json = JSON.parse(XMLHttpRequestObject.responseText);

Then in the for loop
var opt = json[/*i or column name*/];

or
var opt = json.service_name[i];

Note: To return a JSON string in PHP, you have to set the header: header("Content-type: application/json");
Hope that helps!

A: A couple of problems here:

*

*your PHP is not sending the correct response. What you want to do is have PHP send a JSON response.

*once PHP sends this JSON response, you then need to parse this into an object

*Once your response is in object format, you can then iterate through the results.

Try this:
PHP (this is an example of what will be returned from your DB):
$response = array(
    array(
        "id" => "1",
        "name" => "something"
    )
);

header('Content-Type: application/json');
echo json_encode($response);

JS:
function configureDropDownLists(ddl1, ddl2) {
    var url = 'submit.php?data=' + ddl1.value;
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp) {
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var json = xmlhttp.responseText;
                var obj = JSON.parse(json);
                for (var i = 0; i < obj.length; i++) {
                    var opt = obj[i];
                    var el = document.createElement("option");
                    el.textContent = opt.name;
                    el.value = opt.id;
                    ddl2.appendChild(el);
                }
            }
        };

        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
}


text:
Q: How to set the info template on a wms layer In arcgisdynamicmapservicelayer I can set a template for the popup window like this:
setInfoTemplatesObject[tooltipObject.Laagindex] = { infoTemplate: new InfoTemplate(tooltipObject.Title, tooltipObject.Content) }
layer.setInfoTemplates(setInfoTemplatesObject);

Is there a way to do this with a WMS layer?
I'm looking for a way to do this in a WMS layer:

A: The WMS spec does not clearly define what the service has to return from the GetFeatureInfo method, so there API function to do this for WMSLayer. More info in this thread.


text:
Q: Did anybody steal my coins? I let my money hidden under some rocks near that path that goes through the green hills, close to the rainbow.
Here you have a picture of the exact location.

Please if somebody found some of my coins, or saw who could took them, please let me know.
I can offer a juicy bounty: I have bacon, unicorns, and unicorn bacon.
Thanks in advance!


text: Q: Free Spin Wheel refreshes in 28 days? In Bloons TD Battles, when you go to Quick Play, there is a little wheel you can spin every  couple of hours. (i think its 8).  When I spun it recently it says '28d 5hr' remaining... what? How?


text:
Q: Load Spark Dataframe into ElasticSearch using PySpark Cannot simply load spark dataframe into elasticsearch as written here here (es is running on localhost).
 What am I missing?
conf = SparkConf().setAppName("product_recommendation-server") \
                          .set('spark.jars', 'path/to/elasticsearch-hadoop-2.1.0.Beta2.jar') \
                          .set('spark.driver.memory', '2250m') \
                          .set('spark.sql.shuffle.partitions', '2000')

sc = SparkContext(conf=conf)
spark = SparkSession(sc)
sql_sc = SQLContext(sc)

spark_df = spark.read.csv(path, header=True)

spark_df.write.save(format="org.elasticsearch.spark.sql")

Py4JJavaError: An error occurred while calling o77.save. :
  java.lang.ClassNotFoundException: Failed to find data source:
  org.elasticsearch.spark.sql. Please find packages at
  http://spark.apache.org/third-party-projects.html


text:
Q: modify an existing column with basic operations I'm going to implement this function!
+-----+-----+
|name | age |
+-----+-----+
|Dong | 19  |
|Dung | 25  |
+-----+-----+

I want to increase column "age" by one like this:
+-----+-----+
|name | age |
+-----+-----+
|Dong | 20  |
|Dung | 26  |
+-----+-----+

pls help me solutions!!
There were twos solution which I thought:
1) using UPDATE sqlCommand.
    update x set a = a + 1 where a = "age"
2) create new column = old column + 1 then replace old column by new one.

A: 2 possible answer.

*

*Do you want to increase the age permanently? If yes, just update the data.
update tbl1 set age = age + 1;

*If you only want show the age + 1 when you view the data:
select name, age + 1 as age from tbl


text:
Q: Conditional with find and parent methods chained I have the following HTML and I am trying to figure out how I can do something jQuery. I want to take the following and only do the following two lines of code if it can find a table with an id of myDatatable on the page. How would I right this I think it would be to trickle back to the parent and then try and do a find() but I'm not sure how I would right the conditional for it.
$('.panel-title').addClass('pull-left');
$('.panel-heading').append('
Add New
');

                        Users

                    ...table data here

A: Just check if there is any table on the page with id=myDatabase

                        Users

                    ...table data here

Also you can use has function of jQuery like this:
if($('#content').has('#myDatabase').length>0){
    $('.panel-title').addClass('pull-left');
    $('.panel-heading').append('
Add New
');
}


text:
Q: Restricting Swagger Files which are exposed to internet I am using swagger-jersey2-jaxrs of version 1.5.0. I am trying to disable the public access of swagger using the following url,
<domain>/swagger.json

Tried many possible solutions found from Google but no luck.
These are static implementation where there is no explicit swagger configuration or the properties configured.
Anyone else faced similar issue with legacy way of implementation?

A: Just removed,
io.swagger.jaxrs.listing
from web.xml file


text:
Q: Hadoop: what will happen when remove folder under /tmp/logs/hive/logs/hive CDH ver 5.3 install from Cloudera Manager.
My cluster using hive,and Other service setting is like this:
・yarn.nodemanager.remote-app-log-dir=/tmp/logs
・yarn.nodemanager.remote-app-log-dir-suffix=logs
・replication setting is 2
I have an trouble removing folder under /tmp/logs/hive/logs/.
Especially/tmp/logs/hive/logs/hive
I tried to delete /tmp/logs/hive/logs/hive/xxxxxxx.xxxxxxx by using hdfs commands ,but folder size is too big to remove.
even hadoop fs -ls /tmp/logs/hive/logs/hive/ did not work...(there was no answer from hdfs.(size is almost 3TB))
So instead, I decided to use [Hadoop fs -rmr /tmp/logs/hive/logs/hive/*]. But, I have no idea what will happen to my cluster if I use this command(I worry about somewhere will not able to be accessed, because of this  ).
Is there any problem? Or have a good idea to deal with this problem (I don't want to reboot my cluster).

A: HDFS directory /tmp/logs is the default location used for Mapreduce log aggregation; there is another critical property which is...

yarn.log-aggregation.retain-seconds: How long to wait before
  deleting aggregated-logs, -1 or a negative number disables the
  deletion of aggregated logs.One needs to be careful and not set
  this to a too small a value so as to not burden the distributed
  file-system.

  https://fr.hortonworks.com/blog/simplifying-user-logs-management-and-access-in-yarn/
A typical cluster purges MR logs after 5 to 30 days, depending on activity (and maybe compliance requirements). If you never purge anything, then you are bound to hit a wall sooner or later...!
 OK, if you really need to manually purge that stuff en masse, you can do it. It's a bit ridiculous to switch brutally from purge-nothing no purge-everything, but anyway.

For the blog post above, you can note that /tmp/logs must have access privileges set to 1777 i.e. "user read/write/execute,
group read/write/execute, other read/write/execute, and sticky bit set" (just like /tmp); and also its group ownership must match the primary group of the service account running NodeManager services.
In other words: anyone can create a sub-directory there; the sticky bit and group ownership tricks mean that both YARN and the creator can read/write/purge the logs files inside -- but no-one else.
Now the interesting part is that a new user launching its first MapReduce job will automatically create a new sub-dir named after him/her, plus a logs/ sub-sub-dir; and the first query that was ever run by HiveServer2 under hive service account created automatically the hive/ and hive/logs/ subdirs.
=> If you delete these subdirs, then they will be recreated automatically on the next run
=> but if you delete them while a HS2 session is running a query, then that query will probably crash and burn when trying to push its logs on HDFS!


text:
Q: Get a specific maximum element from a collection with objects I have an ArrayList, with objects in it, like:
private static List<Movies> movie= new ArrayList<Movies>();

And the contructor is: (where the "Type" is an enum)
public Movies(String name, int budget, int a, String director, Type action)

Now I know how to get the full first object, with:
Movies firstelement = movie.get(0);

But I would like to get somehow which movie had the most budget, and print it's director. How could I do that?

A: Assuming Movies has a getBudget method to return the budget,
you can get the stream of movies,
sort by budget in descending order,
and find the first match, if any:
Movies first = movie.stream()
  .sorted(Comparator.comparing(Movies::getBudget).reversed())
  .findFirst()
  .orElseThrow(() -> new IllegalStateException("List of movies is empty!"));

If you want to get just the director, you could extract that with a .map(...) after .sorted(...).

A: All you need is to sort your list by doing the following
List movies =  movie.stream().sorted(Comparator.comparing(Movie::getBudget()));
After this line do this
movies.get(0);

A: How about the old-fashioned way: run through the list and keep track of the highest-budget movie you've seen so far.  When you've seen all the movies on the list, you'll know which one has the highest budget of all.
Here's one way to do it:
Movie largestBudgetMovie = null;
for (Movie m : movie) {
    if (largestBudgetMovie == null ||
        m.getBudget() > largestBudgetMovie.getBudget())
          largestBudgetMovie = m;
}
if (largestBudgetMovie == null)
    System.out.println("The list was empty");
else
    System.out.println("The most expensive movie on my list was directed by " +
        largestBudgetMovie.getDirector());

Here's another:
if (movie.size() > 0) {
    Movie largestBudgetMovie = movie.get(0);
    for (int i = 1; i < movie.size(); ++i) {
        Movie m = movie.get(i);
        if (m.getBudget() > largestBudgetMovie.getBudget())
              largestBudgetMovie = m;
    }
    System.out.println("The most expensive movie on my list was directed by " +
        largestBudgetMovie.getDirector());
}
else
    System.out.println("The list was empty");


text:
Q: Initializing disposable resources outside or inside try/finally I have seen two ways of acquiring and disposing resources. Either:
Resource resource = getResource();
try { /* do something with resource */ }
finally { resource.close(); }

or:
Resource resource = null;
try { resource = getResource(); /* do something with resource */ }
finally { if (resource != null) resource.close(); }

I was wondering which style is preferable. The first one avoids the if condition, while the second one (I presume) handles the case of thread abort right after the assignment but before entering the try block. What other pros and cons do these styles have over each other? Which one should I preferably use?

A: first one is preferable

A: In C#, just use the using statement:
using (Resource resource = GetResource())
{
    /* Do something */
}

This is the idiomatic way of cleaning up resources, and relies on the resource in question implementing the IDisposable interface. (Java now has a similar try-with-resources statement, for resources implementing AutoCloseable.)
There's no risk of a thread abort in Java happening between the assignment and entering the try block - aborts only occur during sleeps and waits. EDIT: I can't actually find this in the spec, which is somewhat worrying. Hmm.

A: If getResource() throws an exception then resource will be null, getResource() does not return anything in the case of an exception. So, as long as getResource() can throw an exception, always check for null before calling resource.close(). I feel the best way to organize this code is to put everything inside the try block; make it clear clear that getResource() throws exceptions.


text:
Q: In rails 3.2 app, what is the best way to update a page when a background job is complete? My rails 3.2 app has a report page that frequently takes 90+ seconds to render, so I run the report-builder as a delayed_job task then display a "wait a minute" view (with a refresh button) until the content is ready (there is a content_ready flag used in the view to display either the "wait message" or the report, as appropriate). In my prototype, the user has to refresh the page manually until the content_ready is set (and then the report view is rendered).
I'd like to have the page refresh automatically when content_ready is true.
What's the simplest way to accomplish this, given it's a rarely-hit page and thus an inefficient method, such as telling the user's browser to poll the server (or redraw the whole page) every 10 seconds, is just fine?

A: Setup either a meta-refresh on the page or an ajax updater (if using jquery, see here) that checks a specific controller action that tells you whether the job is completed, or that the file exists in the location expected.
Or, and assuming you're using the delayed_job gem, check out the hooks that are provided as part of the job queuing execution. There is documentation on the gem's GH page.

A: I'd recommend the following strategy:

*

*After creating the delayed job, pass the id of the job back to the browser immediately.

*Expose an endpoint on your site that will return the status of the job.

*Use jQuery + setTimeout or setInterval to hit the endpoint.

*When the job is done, redirect the user to the appropriate page.

It's a pretty simple strategy, but it works.


text:
Q: downloaded image use as background image in my framelayout I have a downloaded file and i want to use as background image in my framelayout. I use this code but it gives me an error .
here is the line where i get the error:
fm.setBackgroundDrawable(dr);

and here is my whole code
public class MyAppActivity extends Activity {
private final String PATH = "/data/data/com.myapp/";  //put the downloaded file here
private Drawable imgsrc;
private FrameLayout fm;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
FrameLayout fm = (FrameLayout)findViewById(R.id.framelyt);
//Drawable drw = ImageOperations(this,url,filename)
Button btn = (Button)findViewById(R.id.postbutton);
btn.setOnClickListener(test);
 }

View.OnClickListener test = new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
    DownloadFromUrl("http://www.mydomain.com/radio/images/", "image.png");

    }
};

private void DownloadFromUrl(String imageURL, String fileName) {
    // TODO Auto-generated method stub
     try {
         URL url = new URL(imageURL + fileName); //you can write here any link
         File file = new File(PATH + fileName);

         if(file.exists())
         {
             file.delete();
         }

         long startTime = System.currentTimeMillis();
         Log.d("ImageManager", "download begining");
         Log.d("ImageManager", "download url:" + url);
         Log.d("ImageManager", "downloaded file name:" + fileName);

         /* Open a connection to that URL. */
         URLConnection ucon = url.openConnection();

         /*
          * Define InputStreams to read from the URLConnection.
          */
         InputStream is = ucon.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);

         /*
          * Read bytes to the Buffer until there is nothing more to read(-1).
          */
         ByteArrayBuffer baf = new ByteArrayBuffer(50);
         int current = 0;
         while ((current = bis.read()) != -1) {
                 baf.append((byte) current);
         }

         /* Convert the Bytes read to a String. */
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(baf.toByteArray());

         Bitmap bMap = BitmapFactory.decodeFile(PATH + fileName);
         BitmapDrawable dr = new BitmapDrawable(bMap);
        // Drawable d = new BitmapDrawable();
         fm.setBackgroundDrawable(dr);
         fos.close();
         Log.d("ImageManager", "download ready in "
                         + ((System.currentTimeMillis() - startTime) / 1000)
                         + " sec");

         //fm.setBackgroundDrawable(d);

 } catch (IOException e) {
         Log.d("ImageManager", "Error: " + e);
 }
}

}


text:
Q: Socks 5 UDP connection I m trying to connect to an UDP Socks5 proxy, but no server will reply to my initial handshake. Wire shark shows that the right signal is going to the server, but no reply is receive
#define PUT_BYTE(ptr,data) (*(unsigned char*)ptr = data)

static int Connect_proxy(SOCKET sock,sockaddr_in Rcv_address) {

char buff[200],*ptr;
sockaddr_in SenderAddrTemp;
int SenderAddrSize= sizeof(SenderAddrTemp);

ptr=buff;
int iResult;

PUT_BYTE(ptr++,5);
PUT_BYTE(ptr++,1);
PUT_BYTE(ptr++,0);

iResult = sendto(sock,
    buff, ptr-buff, 0, (SOCKADDR *) & Rcv_address, sizeof (Rcv_address));

if (iResult == SOCKET_ERROR) {
    wprintf(L"[Send]Conection request failed with error: %d\n",      WSAGetLastError());
    //closesocket(sock);
    //WSACleanup();
    return -1;

}
iResult = recvfrom(sock,buff, 200, 0, (SOCKADDR *) & SenderAddrTemp, &SenderAddrSize);
if (iResult==-1) {
    wprintf(L"[Recv] Connection request failed with error: %d\n", WSAGetLastError());
    return -1;
}
else
    if (iResult==2)  {
        wprintf(L"OK");
    }

    return 0;

}
The socket init is :
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
    wprintf(L"WSAStartup failed with error: %d\n", iResult);
    return 1;
}

//---------------------------------------------
// Create a socket for sending data
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (SendSocket == INVALID_SOCKET) {
    wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
    WSACleanup();
    return 1;
}

RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(8888);
RecvAddr.sin_addr.s_addr = inet_addr("114.207.246.173");

service.sin_family = AF_INET;
service.sin_addr.s_addr = htonl(INADDR_ANY);
service.sin_port = htons(0);

bind(SendSocket, (SOCKADDR *) &service, sizeof (service));

if (iResult == SOCKET_ERROR) {
    wprintf(L"bind failed with error %u\n", WSAGetLastError());
    closesocket(SendSocket);
    WSACleanup();
    return 1;
}
Connect_proxy(SendSocket,RecvAddr);

Thanks!

A: Fixed:
Although the socks connection will be UDP, the handshake must be done in TCP
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //this must became a TCP socket SOCK_STREAM


text:
Q: Dynamic Schedules getting lost while resque forks a new process I'm using resque-scheduler to schedule dynamic crons based on user's input. My server stack is using Ubuntu 12.04 with passenger + nginx configuration.
I've set Resque::Scheduler.dynamic = true
and using set_schedule method with persist: true option to schedule dynamic jobs
At first the problem was it was giving me some Passenger error:-
Redis::InheritedError (Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking.

So i introduced the following block to my resque initializer:-
PhusionPassenger.on_event(:starting_worker_process) do |forked|
  if forked
    # Reconnect Resque Redis instance.
    Resque.redis.client.reconnect
  end
end

Now after each restart or scheduling a new dynamic job, it loads my static schedules and dynamic schedules are being lost. Even it is updating schedules o random time and loads only static schedules.

A: The problem of loading dynamic schedules is there in the gem version. Please refer to latest resque scheduler release at github, this should fix the issue(fixed about 10 days back).


text: Q: Can an element have infinitely many factors while each of its chain of factors eventually stabilize? Is it possible to find an integral domain $R$, and $a\in R^*\backslash U(R)$, such that $a$ has infinitely many not equivalent factors, whereas each chain of factors of $a$, $a_0=a>a_1>a_2>\cdots$ will eventually stabilize, i.e., $\exists n,~ a_{n}\sim a_{n+1}\sim a_{n+2}\sim\cdots$? Here $x>y\iff y\mid x$.


text:
Q: Change cookies when doing jQuery.ajax requests in Chrome Extensions I have wrote a plugin for facebook that sends data to testing-fb.local. The request goes through if the user is logged in.
Here is the workflow:

*

*User logs in from testing-fb.local

*Cookies are stored

*When $.ajax() are fired from the Chrome extension

*

*Chrome extension listen with chrome.webRequest.onBeforeSendHeaders

*Chrome extension checks for cookies from chrome.cookies.get

*Chrome changes the Set-Cookies header to be sent

And the request goes through.
I wrote this part of code that shoud be this:
function getCookies (callback) {
  chrome.cookies.get({url:"https://testing-fb.local", name: "connect.sid"}, function(a){
    return callback(a)
  })
}

chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    getCookies(function(a){

// Here something happens

    })
  },
  {urls: ["https://testing-fb.local/*"]},
  ['blocking']);

Here is my manifest.json:
{
  "name": "test-fb",
  "version": "1.0",
  "manifest_version": 1,
  "description": "testing",
  "permissions": [
    "cookies",
    "webRequest",
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
        {
          "matches": ["http://*.facebook.com/*", "https://*.facebook.com/*"],
          "exclude_matches" : [
            "*://*.facebook.com/ajax/*",
            "*://*.channel.facebook.tld/*",
            "*://*.facebook.tld/pagelet/generic.php/pagelet/home/morestories.php*",
            "*://*.facebook.tld/ai.php*"
          ],
          "js": ["jquery-1.8.3.min.js", "allthefunctions.js"]
        }
      ]
}

In allthefunction.js I have the $.ajax calls, and in background.js is where I put the code above which however looks not to run..
In summary, I have not clear:

*

*What I should write in Here something happens

*If this strategy is going to work

*Where should I put this code?

A: Chrome changes the Set-Cookies header to be sent, i believe you want to send a Custom Cookie header for an HTTP request, because Set-Cookie header  is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system.
Please note all Cookie API() methods are asynchronous, ensure your call back drives your functionality;
I tried to replicate your workflow with this sample demonstration
Demonstration
Background page looks for all requests to http://www.w3schools.com/html/default.asp and modifies cookie details
background.js
// Adding Event Listener for Changing Cookie Details in Header
chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {

    // Look for header details here
    detail = "requestHeaders";
    headers = details[detail];

    // Iterate through all headers information
    for (header in headers) {

        // Stop at Cookie Information
        if (headers[header].name == "Cookie") {

            // Do your desired functionality either modifying/delet cookies etc

            //chrome.cookies.get({url:"<your url>", name: "<your parameter>"}, function(Cookies){
            //console.log("Cookies  "+Cookies);
            return {
                requestHeaders: details.requestHeaders
            };
            //});

        }
    }

},
//Sample URL used
{
    urls: ["http://www.w3schools.com/html/default.asp"]
},

// Block Web Request and request for header information

['blocking', "requestHeaders"]);

allfunctions.js
Simple AJAX Call to an asp page
 //Do an AJAX Call
 function ajaxCall() {
     $.post("http://www.w3schools.com/html/default.asp", function (data) {
         console.log("POST Completed " + data);
     });
 }
 ajaxCall();

manifest.json
Ensured manifest has all permissions
{
  "name": "test-fb",
  "version": "1.0",
  "manifest_version": 2,
  "description": "testing",
  "permissions": [
    "cookies",
    "webRequest",
    "tabs",
    "<all_urls>",
    "webRequestBlocking"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": ["jquery.js", "allthefunctions.js"]
        }
      ]
}

With this i was able to track request headers for AJAX Call and modify cookie information, let me know if you need more information.


text:
Q: assert_match the path of image_url with the json_response I have written a test to assert_match the path of image_url with the json_response.
In cards_controller_test.rb,
def test_index
  get :index, { client: "e59db1f42d665da2c8bae1196d7f042d91ef4b33295554024d7eb59ab9f298fc", sig: "e0ZHbZqCB8Tf4kWWxShEFyoJf5c" }
  assert_response :success
  assert_match "/system/cards/marketing_images/816/119/124/original/d712c1fe45ab90f2cb058dec0ea4370e1968d54d.png", json_response["marketing_image_url"]
end

Currently, the test is green. But I must use model.attachment.url to generate the url & then match it with response. Not sure how this can be done.


text:
Q: How to display a protected Blog into a WebView (setHttpAuthUsernamePassword) I would like to show a protected Blog into a webview.
The blog is on Google's blogger.com
The username & password are provided by the app itself (so that the user does not have to type in anything):
I'm using the following code but it does not work, as it is asking the user to type in its username and password (at the first log only, then it is saved and it works fine)? What's wrong ? What should I be using as 'realm' in :
webview.setHttpAuthUsernamePassword(URL_WebView, "", getString(R.string.username), getString(R.string.password));

The whole code so far :
public class Main extends Activity {
/** Called when the activity is first created. */

String URL_WebView = "http://myblog.blogspot.com/";

public static Context mContext;
static SharedPreferences prefs;

static int log_number;
Boolean terms_agreed;

//GoogleAnalyticsTracker tracker;
//static String analytics_tracker = "UA-11967031-29";

WebView webview;
private static final FrameLayout.LayoutParams ZOOM_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    this.webview = (WebView)findViewById(R.id.webkitWebView1);

    mContext = this;

    reading_the_prefs();
    log_number = log_number + 1;

    if (log_number >= 2) {
        if ((!terms_agreed)){
            TermsDialog();
        }
    }

    /*
    tracker = GoogleAnalyticsTracker.getInstance();
    tracker.start(analytics_tracker, this);
    tracker.trackPageView("/Main");
    */

    // adding the zoom controls ...
    FrameLayout mContentView = (FrameLayout) getWindow().getDecorView().findViewById(android.R.id.content);
    final View zoom = this.webview.getZoomControls();
    mContentView.addView(zoom, ZOOM_PARAMS);
    zoom.setVisibility(View.GONE);

    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    webview.setWebViewClient(new MyWebViewClient ());

    //webview.savePassword(URL_WebView, getString(R.string.username), getString(R.string.password));
    webview.setHttpAuthUsernamePassword(URL_WebView, "", getString(R.string.username), getString(R.string.password));
    webview.loadUrl(URL_WebView);

}

//======================================================================================

private class MyWebViewClient extends WebViewClient {

    public void onReceivedHttpAuthRequest(WebView view,
            HttpAuthHandler handler, String host, String realm) {

        handler.proceed(getString(R.string.username), getString(R.string.password));
        Log.i("Hub","Host ="+host+" with realm ="+realm);
    }

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Log.e("Hub", "Error: " + description);
        Toast.makeText(Main.this, "Oh no! " + description, Toast.LENGTH_LONG).show();
    }
}

//======================================================================================

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 99, 3, "Exit").setIcon(android.R.drawable.ic_menu_delete);
    menu.add(0, 999, 2, "Terms of Service").setIcon(android.R.drawable.ic_menu_agenda);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
    case 99:
        finish();
        break;
    case 999:
        //tracker.trackPageView("/TERMS_OF_SERVICE");
        TermsDialog();
        break;
    }
    return super.onOptionsItemSelected(item);
}

// =================================================================================
public void TermsDialog(){

    AlertDialog.Builder ad = new AlertDialog.Builder(this);
    ad.setIcon(R.drawable.icon);
    // custom Title - that's the way I found to center it !
    TextView title = new TextView(mContext);
    title.setText(R.string.TermsDialog_Title);
    title.setBackgroundColor(Color.BLACK);
    title.setPadding(10, 10, 10,10);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.WHITE);
    title.setTextSize(20);
    // to center the TITLE :
    ad.setCustomTitle(title);

    ad.setView(LayoutInflater.from(this).inflate(R.layout.terms_dialog,null));

    ad.setPositiveButton(R.string.TermsDialog_Yes,
            new android.content.DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int arg1) {
            //OK, save accepted Terms and Service into the Prefs.
            terms_agreed = true;
            //tracker.trackPageView("/Terms_agreed");
            saving_the_prefs();
        }
    }
    );

    ad.setNegativeButton(R.string.TermsDialog_No,
            new android.content.DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int arg1) {
            terms_agreed = false;
            //tracker.trackPageView("/Terms_NOT_agreed");
            saving_the_prefs();
            finish();
        }
    }
    );

    ad.setCancelable(false);

    ad.show();
}

// =================================================================================
private void reading_the_prefs() {

    prefs = getSharedPreferences("Market_Wrap", 0);
    log_number = prefs.getInt("log_number" , 0);
    terms_agreed = prefs.getBoolean("terms", false);
    Log.i("Hub", "log_number="+log_number);
    Log.i("Hub", "terms_agreed="+terms_agreed);

}
// =================================================================================
public void saving_the_prefs() {

    prefs = getSharedPreferences("Market_Wrap", 0);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putInt("log_number", log_number);
    editor.putBoolean("terms", terms_agreed);
    editor.commit();
}
// =================================================================================

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

    //tracker.dispatch();
    //tracker.stop();
    saving_the_prefs();
}
// =================================================================================

}
I have tried to follow the advice here but it looks like
public void onReceivedHttpAuthRequest(WebView view,
            HttpAuthHandler handler, String host, String realm) {

        handler.proceed(getString(R.string.username), getString(R.string.password));
        Log.i("Hub","Host ="+host+" with realm ="+realm);
    }

never gets triggered (in MyWebViewClient) for whatever reason ?
EDIT : Maybe I need to implement a client-side OAuth on Android ?
like here

A: From setHttpAuthUsernamePassword, you need to pass in the host of the site: so if you are accessing (for example) http://www.google.com with username and password from your code and realm Protected, you would do
webview.setHttpAuthUsernamePassword("www.google.com", "Protected", getString(R.string.username), getString(R.string.password));

You can get the realm by looking at the published realm in your browser: for example, in Firefox if you open http://tools.dynamicdrive.com/password/example/ you will see that the following text in the caption: A username and password are being requested by http://tools.dynamicdrive.com. The site says: "Restricted Area. In this case the realm is Restricted Area.


text:
Q: Adding ArrayList into Another ArrayList I have an ArrayList in my program and some part of the program I'm parsin an soap object and every item is one tempArraylist.After the item iteration is finished I'm adding this ArrayList into another Arraylist my problem is it's not adding the content it is adding the reference of the tempArray.How can I add the value of array not reference of it.
Here is my code.
for (int i = 0; i < count; i++)
   {
       tempContents.clear();

       Log.i(TAG , String.valueOf(count));

       Object property = response2.getProperty(i);

       if (property instanceof SoapObject)
       {
           SoapObject category_list = (SoapObject) property;

           for(int j = 0 ; j<tags.size() ; j++)
           {
               if(category_list.getProperty(tags.get(j)).toString().contains("Resim"))
               {
                   String tempResim = "htttp://www.balikesir.bel.tr/";
                   tempResim += category_list.getProperty(tags.get(j)).toString();
                   tempContents.add(tempResim);
               }
               else
               {
                   if(category_list.getProperty(tags.get(j)).toString().equals("anyType{}"))
                   {continue;}
                   tempContents.add(category_list.getProperty(tags.get(j)).toString());

               }
           }
           for(int k = 0 ;k < tempContents.size() ; k++ )
               Log.i("For ici 5 minare",tempContents.get(k));
           Log.i("For disi 4 minare","Asdas asdas");
           contents.add(tempContents);
       }

    }

A: Use public boolean addAll(Collection<? extends E> c)
contents.addAll(tempContents);

What addAll(Collection c) does ?
From Java docs,
/**
 * Appends all of the elements in the specified collection to the end of
 * this list, in the order that they are returned by the
 * specified collection's Iterator.  The behavior of this operation is
 * undefined if the specified collection is modified while the operation
 * is in progress.  (This implies that the behavior of this call is
 * undefined if the specified collection is this list, and this
 * list is nonempty.)
 *
 * @param c collection containing elements to be added to this list
 * @return <tt>true</tt> if this list changed as a result of the call
 * @throws NullPointerException if the specified collection is null
 */

EXAMPLE
List test = new ArrayList();
test.add("A");
test.add("B");
test.add("C");
test.add("D");
List test1 = new ArrayList();
test1.add("E");
test1.add("F");
test1.add("G");
test1.add("H");
test1.add("I");

//test.add(new ArrayList(test1));  // Dont use this if u want to add content and not entire arrayList as its output will be [A, B, C, D, [E, F, G, H, I]]

test.addAll(test1);
System.out.println(test);

Output
[A, B, C, D, E, F, G, H, I]

Important Notes
1. Use test.add(test1.clone());  Only if test1 reference is of
    ArrayList type and not of List type as List does not implements Cloneable Interface
2. Dont Use test.add(new ArrayList(test1)); ,if u want to add content and not entire arrayList as its output will be [A, B, C, D, [E, F, G, H, I]].

A: Use something like this instead:
contents.add(new ArrayList(tempContents));

Alternative:
contents.add(tempContents.clone());

Alternative 2:
contents.addAll(tempContents);

Choose 1 or 2 for inserting the whole ArrayList as one item and 3 for adding all the items as separate items to the list.


text:
Q: ¿Como acceder a las propiedades de una instancia? lamento las molestias pero he empezado a aprender cómo crear objetos en PHP, sin embargo no me deja acceder a las propiedades mediante "->".
Este es mi código, me gustaría que en la pantalla se aparecieran las ruedas que tiene $Coche1:
class Coche{

  public $ruedas;
  public $color;

  function Prueba(){
    $this->color="azul";
    $this->ruedas=5;

  }
 }

 $Coche1=new Coche;

 echo $Coche1->ruedas;

Muchísimas gracias por su ayuda.

A: Para conseguir lo que deseas tienes dos formas:

*

*Mediante el método __construct(), que se carga al inicializar la clase, de este modo:

class Coche
{
  public $ruedas;
  public $color;

  public function __construct()
  {
    $this->color  = "azul";
    $this->ruedas = 5;
  }
}

$Coche1 = new Coche();

echo $Coche1->ruedas;

*Llamando al método Prueba() antes de preguntarle las ruedas, así:

class Coche
{
  public $ruedas;
  public $color;

  function Prueba()
  {
    $this->color  = "azul";
    $this->ruedas = 5;
  }
}

$Coche1 = new Coche();
$Coche1->Prueba();
echo $Coche1->ruedas;

Ya nos diras si te funcionan.


text:
Q: Getting a video from Google Photos returns an empty file I'm working on an application that allows the user to import videos and edit them. The applications allows the user to import local videos, or videos from Google Photos or Drive. The following code was working
Intent i = new Intent();
i.setType("video/mp4");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_CODE);

and then, on the onActivityResult method, I copy to file from Photos or Drive
if (resultCode == RESULT_OK) {
    Uri uri = data.getData();

    try {
       File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
       File app_directory = new File(storage, APP_NAME);
       if (!app_directory.exists())
           app_directory.mkdirs();

       String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
       String filename = String.format("VID_%s.mp4", timestamp);

       File file = new File(app_directory, filename);

       InputStream is = getContentResolver().openInputStream(uri);

       OutputStream output = new FileOutputStream(file);

       byte[] buffer = new byte[4096];
       int read;

       while ((read = is.read(buffer)) != -1)
            output.write(buffer, 0, read);

       output.flush();
       output.close();
    } catch (FileNotFoundException e) {
       Toast.makeText(this, "File Not Found", Toast.LENGTH_LONG).show();
       Log.e(TAG, "File Not Found", e);
    } catch (IOException e) {
       Toast.makeText(this, "Could not save the file", Toast.LENGTH_LONG).show();
       Log.e(TAG, "IOException", e);
    }
}

However since the latest update of the Google Photos app I'm only getting very small file that I cannot open with any application, and sometimes for oldest videos I'm getting a FileNotFoundException
I have tried a couple of solutions, like changing the intent to request the file like this
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/mp4");
startActivityForResult(i, REQUEST_CODE);

or getting the InputStream through a FileDescriptor
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

InputStream is = new FileInputStream(fileDescriptor);

With the same result


text:
Q: Type error when reading properties of a function argument in javascript Here is the definition of the constructor function.
function Box (options) {
console.log(options);
this.x = options.x || 10;
this.y = options.y || 10;
this.width = options.width || 100;
this.height = options.height || 100;
this.color = options.color || '#000';
}

This throws a Typeerror stating it cannot read property of undefined at this.x = options.x || 10;
I am trying to create an array of Box objects. Here's the code.
for(var i=0; i<100; i++){
boxes[i] = new Box({
    x: 10+i,
    y: 10+i,
    width: 2*i,
    height: 3*i,
    color: randomColor(0, 255, 0, 255, 0, 255, .5)
});
}

Am I missing something here. Any help would be really appreciated.

A: The code you've quoted won't have the error you've quoted. You would get that error, though, if you called new Box() without passing anything in (because within Box, options would be undefined). From the comments, it sounds like that's what happened. You can defend against it using || again, at the top:
function Box (options) {
    console.log(options);
    options = options || {}; // <== here
    this.x = options.x || 10;
    this.y = options.y || 10;
    this.width = options.width || 100;
    this.height = options.height || 100;
    this.color = options.color || '#000';
}

Side note: Using || to default things is sometimes error-prone. For instance, in your Box function, what if I do this?
var b = new Box({
    x: 0,
    y: 0,
    width: 20,
    height: 20,
    color = "#888"
});
console.log(b.x); // 10 -- huh?!

b.x should be 0, not 10. That happens because || works like this: It evaluates its left-hand operand and, if that value is "truthy," results in that value; if the value is "falsey," though, it evaluates and the right-hand operand instead and uses that as its result. The falsey values include 0 (they're: 0, "", undefined, null, NaN, and of course, false), but 0 seems like it could easily be a valid value for x.
For those kinds of situations, you might use hasOwnProperty or in:
function Box (options) {
    console.log(options);
    options = options || {};
    this.x = options.hasOwnProperty("x") ? options.x : 10;
    this.y = options.hasOwnProperty("y") ? options.y : 10;
    this.width = options.width || 100;    // Maybe here too, if you want to allow 0 as a width
    this.height = options.height || 100;  // Maybe here too, if you want to allow 0 as a height
    this.color = options.color || '#000';
}

you can also use in, although it's slower on most JavaScript engines because it checks the prototype chain:
function Box (options) {
    console.log(options);
    options = options || {};
    this.x = "x" in options ? options.x : 10;
    this.y = "y" in options ? options.y : 10;
    this.width = options.width || 100;    // Maybe here too, if you want to allow 0 as a width
    this.height = options.height || 100;  // Maybe here too, if you want to allow 0 as a height
    this.color = options.color || '#000';
}


text:
Q: NHibernate / Npgsql throws exception during CreateSchema while debugging UnitTest I have two C# projects, Model and ModelTest. Model consists of ActiveRecord objects (wrapper around Hibernate). In ModelTest I created a simple unit test:
[TestClass]
public class UnitTest1
{
    [TestInitialize]
    public void Init()
    {
        Model.Init();
        Model.CreateSchema();
    }

    [TestMethod]
    public void TestMethod1()
    {
    }
}

Model.Init() registers all types of assembly Model with ActiveRecord.
Model.CreateSchema() wraps ActiveRecordStarter.CreateSchema(), which calls CreateSchema() of NHibernate.
This code works fine, if I run the unit test, but it fails if I "debug" the unit test. In debug mode, an exception occurs in CreateSchema():
NpgsqlException: 'ERROR: 42P01: table "user" does not exist'

The exception seems to be raised during the SQL call "drop table user cascade", which obviously fails if the database is empty before running the test. I assume the drop is sent always before creating a new table.
Does Npgsql behave differently in debug mode, regarding the outcome of a drop query?

A: I had the exact same problem as Tarnschaf -- SchemaUpdate.Create(...) would fail and the offending sql was drop table "tablename" cascade which resulted in the same "table does not exist" error mentioned above.
It turns out that one of the projects had an reference to a Nhibernate-related assembly that was no longer in the same location.  I'm not sure why this didn't show up when the solution was cleaned & rebuilt.  Removing all references from the project and re-adding them solved the problem (for me).
Just posting this in case it helps someone else down the road.  The Nhibernate exception was less than helpful.


text:
Q: How to prevent others from reverse-resolving my IP address? I have a self-managed dedicated server.
My hosting provier assigns a hostname associated with a static IP.
eg. myhost.dedicated-server.com and 123.123.123.123
I'm hosting multiple domains using 123.123.123.123
When internet users perform a ping to one of my domains:
eg. ping mydomain.com
The result is showing:
PING mydomain.com (123.123.123.123) 56(84) bytes of data.
64 bytes from myhost.dedicated-server.com (123.123.123.123): icmp_seq=1 ttl=49 time=173 ms

I don't want to display my reverse-resolving hostname to the public users.
How can this be accomplished?
A working example is when I ping cloudflare.com
It shows:
PING cloudflare.com (198.41.214.162) 56(84) bytes of data.
64 bytes from 198.41.214.162: icmp_seq=1 ttl=53 time=278 ms

A: If you really want to do this, you have to speak to your provider. It's their IP, so only they're able to change the reverse DNS record.

I don't think it's professional and clean to display hostname.hosting-provider.com.

I don't think so, and, for example, if you're running a MX, it's assumed best practice and quite wise to have matching forward and reverse DNS records.

A: First, you can ask your provider to set the PTR to a value you need/like. They should be willing to change the record.
If not, it isn't a fatal issue either. Your ping example is really irrelevant - nearly no one is going to do this anyway and most of those who might do it understand why the name is different and don't care - it's absolutely not "unprofessional".
The main area where the PTR gets important is with mail, but even that can be configured to work with the generic name, but is also the area why the provider should be willing to set the PTR for you.


text:
Q: Moving WP site to another Domain. Images and content missing I developed a wordress site at: http://acenetsolution.com/activelearningwp/
I have manually moved the site to: http://activelearningpartnersltd.com/ on a different server.
But now, i can't see any images on the site and content is missing. However, pages are working fine.
I can see all the images are uploaded on server but they are not displaying.
When i upload a new image in wordpress the URL for the image comes as: http://activelearningpartnersltd.com/home/activey2/public_html/activelearningpartnersltd.com/wp-content/uploads/2016/04/logo-1.png
It should be like: http://activelearningpartnersltd.com/wp-content/uploads/2016/04/logo-1.png
My widgets are also not displaying in wp-admin.
Anything i did wrong?

A: Use This process

*

*download your server database file.

*now open your database file in notepad++ editor

*now find "http://acenetsolution.com/activelearningwp/" and replace url = "http://activelearningpartnersltd.com/" replace all

now upload this database on server


text:
Q: How to get userID from snapshot ? (Realtime Database) what i want to do is getting the userID from snapshot and put it in a route argument to navigate to a user page and get all of user data from Realtime database, so far here is what i have done:

*

*but it didn't work and for sure it has returned a null error.

*You can find a comment below before each snapshot which i need to get the id from in home.dart and user_detail.dart

home.dart
 import 'package:flutter/material.dart';
    import 'package:firebase_database/firebase_database.dart';
    import 'package:idevice_me/providers/project_provider.dart';
    import 'package:idevice_me/screens/user_detail_screen.dart';
    import 'package:provider/provider.dart';

    class HomeWidget extends StatefulWidget {
      const HomeWidget({ Key? key }) : super(key: key);

      @override
      State<HomeWidget> createState() => _HomeWidgetState();
    }

    class _HomeWidgetState extends State<HomeWidget> {

      var _isInit = true;

      @override
      void didChangeDependencies(){
        if(_isInit){
           Provider.of<ProjectProvider>(context, listen: false).readData();
        }
        _isInit = false;
        super.didChangeDependencies();
      }
      @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          stream: Provider.of<ProjectProvider>(context, listen: false).readData(),
          builder: (ctx, AsyncSnapshot snapshot){
            if(snapshot.connectionState == ConnectionState.waiting){
                    return const Center(child: CircularProgressIndicator());
                  }
            if(snapshot.hasData){
    //--------------------
    //This is the snapshot
    //--------------------
             final userSnapshot = snapshot.data!.snapshot.children.toList();

              return Column(
                children: [
                 const SizedBox(height: 20,),
                  Padding(
                    padding: const EdgeInsets.only(right: 15.0, left: 15.0),
                    child: TextFormField(
                              decoration: InputDecoration(
                                labelText: 'Search',
                                labelStyle: TextStyle(fontSize: 14,color: Colors.grey.shade400,fontWeight: FontWeight.w600),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(30),
                                  borderSide: BorderSide(color: Colors.grey.shade300),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(30),
                                  borderSide: const BorderSide(color: Colors.blue),
                                ),
                                floatingLabelBehavior: FloatingLabelBehavior.auto,
                              ),
                              key: const ValueKey('search'),
                                validator: (value){
                                  if(value!.isEmpty || value.length < 2){
                                    return 'Please enter at least 2 characters';
                                  }
                                  return null;
                                },
                                keyboardType: TextInputType.text,
                                onSaved: (value){
                                 // _userName = value!;
                                },

                            ),
                  ),
                         const SizedBox(height: 20,),
                  Expanded(
                    child: ListView.builder(
                      itemCount: userSnapshot.length,
                      itemBuilder: (BuildContext ctx, i)=> Column(
                        children: [
                          // ignore: sized_box_for_whitespace
                          GestureDetector(
                            onTap: (){
                              Navigator.of(context).pushNamed(
                                UserDetailScreen.routeName,

    //------------------------------------------------------
    //Here is the argument which should take the snapshot id
    //------------------------------------------------------

                                arguments: userSnapshot[i].toString(), //convert it toString() because it's coming from a List
                                );
                            },
                            child: Container(
                              height: 160,
                              width: 350,
                              child: Card(
                                elevation: 5,
                                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                                child: Column(
                                  children: [
                                    const SizedBox(height: 20,),
                                    Padding(
                                      padding: const EdgeInsets.only(right: 20.0, left: 20.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          const Text('Name:', style: TextStyle(fontSize: 18),),
                                          Text(
                                            userSnapshot[i].child('username').value,
                                            style: const TextStyle(fontSize: 18),
                                            ),
                                        ],
                                      ),
                                    ),const SizedBox(height: 10,),
                                    Padding(
                                      padding: const EdgeInsets.only(right: 20.0, left: 20.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          const Text('Email:', style: TextStyle(fontSize: 18),),
                                          Text(
                                          userSnapshot[i].child('email').value,
                                          style: const TextStyle(fontSize: 18),
                                          ),
                                        ],
                                      ),
                                    ),
                                    const SizedBox(height: 10,),
                                    Padding(
                                      padding: const EdgeInsets.only(right: 20.0, left: 20.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          const Text('Date:', style: TextStyle(fontSize: 18),),
                                          Text(
                                          userSnapshot[i].child('dateTime').value.toString(),
                                          style: const TextStyle(fontSize: 18),
                                          ),
                                        ],
                                      ),
                                    ),
                                    const SizedBox(height: 10,),
                                    Padding(
                                      padding: const EdgeInsets.only(right: 20.0, left: 20.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          const Text('Phone:', style: TextStyle(fontSize: 18),),
                                          Text(
                                          userSnapshot[i].child('phone').value.toString(),
                                          style: const TextStyle(fontSize: 18),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      )
                      ),
                  ),
                ],
              );
            }
            return const Center(child: Text('There is something wrong!'),);
          },
          );
      }
    }

user_detail.dart
import 'package:flutter/material.dart';
import 'package:idevice_me/widgets/user_detail_widget.dart';
import 'package:firebase_database/firebase_database.dart';

class UserDetailScreen extends StatelessWidget {
  static const routeName = 'user-screen';
  const UserDetailScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
//------------------------
//Extracted snapshot here
//------------------------
    final userID = ModalRoute.of(context)!.settings.arguments as String;
    return Scaffold(
      key: scaffoldKey,
      body: Column(
        children: [
          const SizedBox(height: 30,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                  IconButton(
                  icon: const Icon(Icons.notes_outlined,),
                  onPressed: ()=> scaffoldKey.currentState!.openDrawer(),
                  ),

                 const Text(
                  'i-Device',
                   style: TextStyle(fontSize: 23),
                   ),

                  Padding(
                    padding: const EdgeInsets.only(right: 10.0),
                    // ignore: sized_box_for_whitespace
                    child: Container(
                      height: 40,
                      width: 40,
                      child: const Icon(Icons.home)

            ),
                  ),

            ],

          ),

            Expanded(
             child: StreamBuilder(
//--------------------------------
//used snapshot here as the userID
//--------------------------------
               stream: FirebaseDatabase.instance.ref().child('users').child(userID).onValue,
               builder: (ctx, AsyncSnapshot snapshot){
                 if(snapshot.connectionState == ConnectionState.waiting){
                   return const Center(child: CircularProgressIndicator(),);
                 }

                 if(snapshot.hasData){
                   final userData = snapshot.data.snapshot.value;
                   return Column(
                     children: [
                       const SizedBox(height: 20,),
                      Text(userData['username']),
                     ],
                   );
                 }
                 return const Center(child: Text('Something went wrong!'),);
               }
               ),
             ),
        ],
      ),

    );
  }
}

So how can i get the userID from snapshot and trigger it into argument to navigate to user detail page?

A: You should create a model containing all your person information and when you get data from firebase you should convert it from json format to model format. After setting all the variables in the detail model and adding all the data, you must give the parameter to the page you want to show the person detail.

Here is example model

  class UserModel {
  String uid;
  String email;
  String name;
  String surname;
  String pathOfPhoto;
  String phoneNumber;

  UserModel(
    this.uid,
    this.email,
    this.name,
    this.surname,{
    this.pathOfPhoto,
    this.phoneNumber,
  });

  UserModel.fromMap(Map snapshot)
      : uid = snapshot['uid'] ?? '',
        email = snapshot['email'] ?? '',
        name = snapshot['name'] ?? '',
        surname = snapshot['surname'] ?? '',
        pathOfPhoto = snapshot['pathOfPhoto'] ?? '',
        phoneNumber = snapshot['phoneNumber'] ?? '';

  toJson() {
    return {
      "uid": uid,
      "email": email,
      "name": name,
      "surname": surname,
      "pathOfPhoto": pathOfPhoto,
      "phoneNumber": phoneNumber,
    };
  }
}


text:
Q: Change Monodevelop background colour in Ubuntu This is not a technical question but a question about ease of usage of an IDE.
I have recently started Monodevelop(Ver 5.9.4) in Linux(Ubuntu).
The issue I face is that the coding window is white and its stress-full for my eyes as I am used to code in darker backgrounds. How can I change it?
Please help. I have looked other places but I am not convinced.

A: Go to Edit > Preferences >  Syntax Highlighting
This wouldn't change everything in the GUI, but it will change the part where you are staring at the code to black background.


text:
Q: Jupyter lab shortcut modification This question is related to this question:
In Jupyter Lab, execute editor code in Python console
I would like to update the shortcut to execute code from the editor to the console. The default one is Shift + Enter. But I have tried to update couple of the default shortcut and can't get the one that does execute the code from the editor to the terminal.
WARNING: One of the answer suggest using :
{
// List of Keyboard Shortcuts
"shortcuts": [
    {
        "command": "notebook:run-in-console",
        "keys": [
            "F9"
        ],
        "selector": ".jp-Notebook.jp-mod-editMode"
    },
]

}
But this is not what I want as this one is to run code from a .ipynb (notebook) to the console and not the editor (.py) to the console.

A: You should use:
    {
        "command": "runmenu:run",
        "keys": [
            "F9"
        ],
        "selector": "[data-jp-code-runner]"
    }

In general to find the command you want simply go to the Keyboard Shortcuts and in the left panel "System Defaults" search for the known default shortcut (there might be a few results, as the shortcuts are context sensitive, with context defined by the CSS selector).


text:
Q: Rmagics and Rpy2 broken on Windows 10. All computational results go out to Windows Console not Jupyter output cells. RWinOut hack no longer works Rmagics and Rpy2 broken on Windows 10.  All computational results go out to Windows Console not Jupyter output cells. The RWinOut hack no longer works.
As soon as I use RWinout, I get a fatal error that requires me to restart Jupyter NB server, it kills the Jupyter Notebook Python kernel.
I have tried installing in 3 different conda environments, using conda alone, Anaconda Navigator, or pip.
 It always comes back to same code error after all packages are installed.  There are a few people offering step-by-step manual procedures for installing R, then rpy2, then special supporting packages, then Jupyter, etc.  That is too tedious for regular data scientists and analysts.
Rpy2 needs to be rewritten to support Windows 10.
I want this to work, because Python-R NBs with Plotly-Dash, Jupyter NB extensions like Qgrid, and others make nice combinations for richly interactive data science applications, without having to run additional servers like RShiny or others.
I can load rpy2 and use its functions and objects, but not R cell magics.

#

Here's my version information:
R version: ('3', '6.0', '', 76424)
Rpy2 veresion: 2.9.4
Python version 3.7.4:
jupyter core : 4.5.0
jupyter-notebook : 6.0.1
qtconsole : 4.5.5
ipython : 7.8.0
ipykernel : 5.1.2
jupyter client : 5.3.3
jupyter lab : 1.1.4
nbconvert : 5.6.0
ipywidgets : 7.5.1
nbformat : 4.4.0
traitlets : 4.3.3
7.8.0
Everything was installed in this environment using Anaconda Navigator, or conda from the command console, unless pip install was required for something that didn't have a conda package.
Conda is the strongly preferred package manager for anything to do with the Jupyter ecosystem, because it is designed to be language-agnostic.

#

The R inline magics produce output into the Jupyter Output Cell, but R cell magics put the results out to the Windows Console that I used to start the Jupyter Notebook.
As soon as I run RWinOut, the errors below show up and the kernel dies.
I also get the following messages in the Windows Console:
Loading required package: R.oo
Loading required package: R.methodsS3
R.methodsS3 v1.8.0 (2020-02-14 07:10:20 UTC) successfully loaded. See ?R.methodsS3 for help.
R.oo v1.23.0 successfully loaded. See ?R.oo for help.
Attaching package: 'R.oo'
The following object is masked from 'package:R.methodsS3':
    throw
The following objects are masked from 'package:methods':
    getClasses, getMethods
The following objects are masked from 'package:base':
    attach, detach, load, save
R.utils v2.9.2 successfully loaded. See ?R.utils for help.
Attaching package: 'R.utils'
The following object is masked from 'package:utils':
    timestamp
The following objects are masked from 'package:base':
    cat, commandArgs, getOption, inherits, isOpen, nullfile, parse,
    warnings

The strange thing is that inline R magics work okay, but NOT Cell magics.
When I run RWinOut as follows:
!curl -O "https://raw.githubusercontent.com/vitorcurtis/RWinOut/master/RWinOut.py"

%reload_ext RWinOut

I get a long string of errors (below). It also kills the Python kernel for the Jupyter NB.
The rpy2.ipython extension is already loaded. To reload it, use:
  %reload_ext rpy2.ipython

ValueError                                Traceback (most recent call last)
<ipython-input-25-49c9701f263c> in <module>
----> 1 get_ipython().run_line_magic('reload_ext', 'RWinOut')

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2312                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2313             with self.builtin_trap:
-> 2314                 result = fn(*args, **kwargs)
   2315             return result
   2316

<C:\ProgramData\Anaconda3\lib\site-packages\decorator.py:decorator-gen-67> in reload_ext(self, module_str)

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\magics\extension.py in reload_ext(self, module_str)
     61         if not module_str:
     62             raise UsageError('Missing module name.')
---> 63         self.shell.extension_manager.reload_extension(module_str)

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\extensions.py in reload_extension(self, module_str)
    128                 self.loaded.add(module_str)
    129         else:
--> 130             self.load_extension(module_str)
    131
    132     def _call_load_ipython_extension(self, mod):

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\extensions.py in load_extension(self, module_str)
     85                               dir=compress_user(self.ipython_extension_dir)))
     86             mod = sys.modules[module_str]
---> 87             if self._call_load_ipython_extension(mod):
     88                 self.loaded.add(module_str)
     89             else:

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\extensions.py in _call_load_ipython_extension(self, mod)
    132     def _call_load_ipython_extension(self, mod):
    133         if hasattr(mod, 'load_ipython_extension'):
--> 134             mod.load_ipython_extension(self.shell)
    135             return True
    136

c:\Users\rlysakow\Desktop\00-PayEquity-WIP\RWinOut.py in load_ipython_extension(ip)
     39         # loading magic and libraries
     40         ip.run_line_magic('load_ext', 'rpy2.ipython')
---> 41         ip.run_line_magic('R', 'library(R.utils)')
     42         ip.run_line_magic('config', 'Application.verbose_crash=True')
     43

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2312                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2313             with self.builtin_trap:
-> 2314                 result = fn(*args, **kwargs)
   2315             return result
   2316

<C:\ProgramData\Anaconda3\lib\site-packages\decorator.py:decorator-gen-133> in R(self, line, cell, local_ns)

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

C:\ProgramData\Anaconda3\lib\site-packages\rpy2\ipython\rmagic.py in R(self, line, cell, local_ns)
    755             if result is not ri.NULL:
    756                 with localconverter(converter) as cv:
--> 757                     res = cv.ri2py(result)
    758                 return res
    759

C:\ProgramData\Anaconda3\lib\functools.py in wrapper(*args, **kw)
    838                             '1 positional argument')
    839
--> 840         return dispatch(args[0].__class__)(*args, **kw)
    841
    842     funcname = getattr(func, '__name__', 'singledispatch function')

C:\ProgramData\Anaconda3\lib\site-packages\rpy2\robjects\pandas2ri.py in ri2py_vector(obj)
    137 @ri2py.register(SexpVector)
    138 def ri2py_vector(obj):
--> 139     res = numpy2ri.ri2py(obj)
    140     return res
    141

C:\ProgramData\Anaconda3\lib\functools.py in wrapper(*args, **kw)
    838                             '1 positional argument')
    839
--> 840         return dispatch(args[0].__class__)(*args, **kw)
    841
    842     funcname = getattr(func, '__name__', 'singledispatch function')

C:\ProgramData\Anaconda3\lib\site-packages\rpy2\robjects\numpy2ri.py in ri2py_sexp(obj)
    157 def ri2py_sexp(obj):
    158     if (obj.typeof in _vectortypes) and (obj.typeof != VECSXP):
--> 159         res = numpy.asarray(obj)
    160     else:
    161         res = ro.default_converter.ri2py(obj)

C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order)
    536
    537     """
--> 538     return array(a, dtype, copy=False, order=order)
    539
    540

ValueError: Buffer for this type not yet supported.

I could not find any hacks or procedures to eliminate this last error.
I don't have time or skill right now to hack ipython extensions to get rpy2 to work.
Anyone have similar experiences with rpy2 ?  How did you solve the problems?


text:
Q: How to handle synchronization of frequent concurrent read/writes on a Java ArrayList I have a Java class that contains an ArrayList of transaction info objects that get queried and modified by different threads on a frequent basis. At a basic level, the structure of the class looks something like this (currently no synchronization is present):
class Statistics
{
    private List<TranInfo> tranInfoList = new ArrayList<TranInfo>();

    // This method runs frequently - every time a transaction comes in.
    void add(TranInfo tranInfo)
    {
        tranInfoList.add(tranInfo);
    }

    // This method acts like a cleaner and runs occasionally.
    void removeBasedOnSomeCondition()
    {
        // Some code to determine which items to remove

        tranInfoList.removeAll(listOfUnwantedTranInfos);
    }

    // Methods to query stats on the tran info.
    // These methods are called frequently.
    Stats getStatsBasedOnSomeCondition()
    {
        // Iterate over the list of tran info
        // objects and return some stats
    }

    Stats getStatsBasedOnSomeOtherCondition()
    {
        // Iterate over the list of tran info
        // objects and return some stats
    }
}

I need to ensure that read/write operations on the list are synchronized correctly, however, performance is very important, so I don't want to end up locking in every method call (especially for concurrent read operations). I've looked at the following solutions:
CopyOnWriteArrayList
I've looked at the use of a CopyOnWriteArrayList to prevent ConcurrentModificationExceptions being thrown when the list is modified while iterating over it; the problem here is the copy required each time the list is modified... it seems too expensive given how often the list will be modified and the potential size of the list.
ReadWriteLock
A ReadWriteLock could be used to synchronize read/write operations while allowing concurrent read operations to take place. While this approach will work, it ends up resulting in a lot of synchronization code in the class (this isn't the end of the world though).

Are there any other clever ways of achieving this kind of synchronization without a big performance penalty, or are one of the above methods the recommended way? Any advice on this would be greatly appreciated.

A: I'd use Collections.synchronizedList() until you know for sure that it is indeed the crucial performance bottle neck of your application (needless to say I doubt it is ;-)). You can only know for sure through thorough testing. I assume you know about "premature optimization"...
If then you strive to optimize access to that list I'd say ReadWriteLock is a good approach.

A: Another solution that may make sense (especially under heavy read/write) is ConcurrentLinkedQueue (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html). It is a pretty scalable implementation under contention, based on CAS operations.
The one change that's required to your code is that ConcurrentLinkedQueue does not implement the List interface, and you need to abide by either the Iterable or the Queue type. The only operation you lose really is random access via index, but I don't see that being an issue in your access pattern.


text:
Q: My javascript quiz app doesn't work properly I'm following this guide: http://javascriptissexy.com/how-to-learn-javascript-properly/ and I'm trying to build a javascript quiz app detailed at week 6.
Here's the instruction:

*

*It is a simple quiz that has radio button choices, and it will show
the quiz taker his or her score upon completion.

*The quiz can show any number of questions and any number of choices.

*Tally the user's score and display the final score on the last page.
The last page will only show the score, so remove the last question.

*Use an array to store all the questions. Each question, along with
its choices and correct answer, should be stored in an object.

*Dynamically (with document.getElementById or jQuery) remove the
current question and add the next question, when the user clicks the
"Next" button. The Next button will be the only button to navigate
this version of the quiz.

*You can ask for help in the comments below or preferably on Stack
Overflow. You will likely to get a prompt and accurate answer on
Stack Overflow.

I figured out how to display quiz and radio button choices. However, When I choose correct answer on my quiz, it doesn't count user's score and When I choose wrong answer it counts user's score. For example, first question's correct answer is "Seoul", but it counts my score only if I choose berlin.
I figured out that 'qi' variable is causing the problem, so I replaced
    allQuestions[qi].answer

to
    allQuestions[qi+1].answer

but then my last question doesn't display.
PS: Sorry for my english... I tried my best
Here's my code: https://jsfiddle.net/METROSTILE/0f3aev1u/1/

var allQuestions = [{
    question: "What is capital of Korea?",
    choices: ["Seoul", "Tokyo", "Hanyang", "Berlin"],
    answer: 0
}, {
    question: "What is 5 + 7 * 11?",
    choices: [132, 121, 77, 82, 0],
    answer: 3
}, {
    question: "When was hani born?",
    choices: ["5/1", "2/3", "11/5", "2/26"],
    answer: 0
}];

$(function() {
    var qi = 0;
    var userScore = 0;
    var $questionArea = $("#question");
    var $choiceArea = $("form");

    $("#next").on("click", function() {
        if (qi < allQuestions.length) {
            //If choice is correct,
         if ($("input:checked").val() == allQuestions[qi].answer) {
                userScore++;
            }

            showNextQuestion();

            qi++;

        } else {
            $("form").remove();
            $questionArea.text(userScore);
        }
    });

    //Shows next question
    function showNextQuestion() {
        var $question = allQuestions[qi].question; //store new question
        //get how many choice

        $questionArea.text(""); //Delete current question if any
        $questionArea.text($question); //add new question

        $choiceArea.find(".choice").remove();
        for (var i = 0; i < allQuestions[qi].choices.length; i++) { //add choices
            var choice = allQuestions[qi].choices[i];
            $choiceArea.append("
<input type='radio' name='choices' value='" + i + "'>" + choice + "</input>
");
        }
    }
});
h1 {
 text-align: center;
}

h3 {
 text-align: center;
}

form {
 text-align: center;
}

.wrapper {
 text-align: center;
 margin-top: 30px;
}

li {
 list-style: none;
}

QUIZ!!!

  <form>

  </form>

   <input type="button" name="next" value="Next Question" id="next" />

A: Handle the current question (if any), then increment qi. Then check if we've run out of questions:
var qi = -1;
// ...

$("#next").on("click", function() {
  if (qi >= 0)
    if ($("input:checked").val() == allQuestions[qi].answer) {
      userScore++;
    }

  ++qi;

  if (qi < allQuestions.length) {
    showNextQuestion();
  }
  else {
    $("form, #next").remove();
    $questionArea.text(userScore);
  }
});

var allQuestions = [{
  question: "What is capital of Korea?",
  choices: ["Seoul", "Tokyo", "Hanyang", "Berlin"],
  answer: 0
}, {
  question: "What is 5 + 7 * 11?",
  choices: [132, 121, 77, 82, 0],
  answer: 3
}, {
  question: "When was hani born?",
  choices: ["5/1", "2/3", "11/5", "2/26"],
  answer: 0
}];

$(function() {
  var qi = -1;
  var userScore = 0;
  var $questionArea = $("#question");
  var $choiceArea = $("form");

  $("#next").on("click", function() {
    if (qi >= 0)
      if ($("input:checked").val() == allQuestions[qi].answer) {
        userScore++;
      }

      ++qi;

    if (qi < allQuestions.length) {
      showNextQuestion();
    } else {
      $("form, #next").remove();
      $questionArea.text(userScore);
    }
  });

  //Shows next question
  function showNextQuestion() {
    var $question = allQuestions[qi].question; //store new question
    //get how many choice

    $questionArea.text(""); //Delete current question if any
    $questionArea.text($question); //add new question

    $choiceArea.find(".choice").remove();
    for (var i = 0; i < allQuestions[qi].choices.length; i++) { //add choices
      var choice = allQuestions[qi].choices[i];
      $choiceArea.append("
<input type='radio' name='choices' value='" + i + "'>" + choice + "</input>
");
    }
  }
});
h1 {
  text-align: center;
}
h3 {
  text-align: center;
}
form {
  text-align: center;
}
.wrapper {
  text-align: center;
  margin-top: 30px;
}
li {
  list-style: none;
}

QUIZ!!!

<form>

</form>

  <input type="button" name="next" value="Next Question" id="next" />

A: After a bit of debugging I found that on click of next button , you tried to recieve the value of radio button even before the quiz started;
var allQuestions = [{
        question: "What is capital of Korea?",
        choices: ["Seoul", "Tokyo", "Hanyang", "Berlin"],
        answer: 0
    }, {
        question: "What is 5 + 7 * 11?",
        choices: [132, 121, 77, 82, 0],
        answer: 3
    }, {
        question: "When was hani born?",
        choices: ["5/1", "2/3", "11/5", "2/26"],
        answer: 0
    }];

    $(function() {
        var qi = 0;
        var userScore = 0;
        var $questionArea = $("#question");
        var $choiceArea = $("form");

        var quiz_started = false; // flag , to see if the quiz has started or not

        $("#next").on("click", function() {

            if(!quiz_started)
            {
            quiz_started = true;
            showNextQuestion();

            }

            if (qi < allQuestions.length) {
                if ($("input:checked").val() == allQuestions[qi].answer) {
                    userScore++;
                }

                showNextQuestion();

                qi++;

            } else {
                $("form").remove();
                $questionArea.text(userScore);
            }
        });

        //Shows next question
        function showNextQuestion() {
            var $question = allQuestions[qi].question; //store new question
            //get how many choice

            $questionArea.text(""); //Delete current question if any
            $questionArea.text($question); //add new question

            $choiceArea.find(".choice").remove();
            for (var i = 0; i < allQuestions[qi].choices.length; i++) { //add choices
                var choice = allQuestions[qi].choices[i];
                $choiceArea.append("
<input type='radio' name='choices' value='" + i + "'>" + choice + "</input>
");
            }
        }
    });


text:
Q: Good text and reference in real analysis I have just started reading real analysis. The topics include sequences, series, continuity, differentiability, integration, series of functions , calculus in higher dimensions etc.
I am in need of a text and a reference book.
Can someone please tell me about it?
The text should not be very broad as I need something to finish before my exam.But the reference should be broad, with full of exercise and examples. Hint to exercise will help me a lot.
Waiting for your response.