text:
Q: How does Internet link bonding work? I have a slower "high-speed" Internet connection of 1.5Mbps DSL. I have often wondered if I could get a second line into my house and do a process called link bonding to join the two lines together and increase my bandwidth. There are various routers out there for this, I think I see, but I am still quite new to this.
So how does this work?
I mean, let's say I'm on SSH and connect to some Linux server. Does it connect over both DSL lines during that kind of transaction, or only one?
Or let's say I'm browsing a shopping website with https -- does it join the two lines together for that or only dedicate one of the lines for that?
Or, does it only show improvements if I do activity like load a web page, where responses might come from both ISP lines at once?

A: The above answers seem to relate to load balancing rather than link bonding. Below is a clip (note an appliance is needed at both ends of the connection - will your ISP allow you that?):
:
So I think the answers to your specific questions are: Yes, Yes, No (in order).

A: For the type of connection bonding you are talking about, your SSH session will use only 1 line.
Depending on the dual-wan router, they will have different types of settings to utilize both links. Line 2 could be used only as a backup. Alternatively, some LAN clients could be assigned Line 1, while other Line 2. Or it could be as simple as round-robin - one request goes over line 1, the other over line 2 and they flip-flop like that. Yet again, least utilized line could have a priority.
When it comes to file transfers, a single stream will utilize only 1 connection. If you want to speed up your downloads, you'd need use some download manager or similar tool that can have multiple files or parts of a file downloading at once.
When it comes to HTTPS.. I'm not sure..I suspect it might be problematic if you establish an HTTPS session with one connection and suddenly request comes in over another connection. I imagine routers won't do connection load-balancing for things that require persistent sessions.

A: Because of how TCP/IP work, it is very likely that each "line" would have it's own IP address. Most systems that require a direct connection (i.e. SSH) would only bound to one of those lines. In the case of Bit Torrent or Web Pages, there should be ways to have multiple connections, and I feel those would be where you would benefit from this.
Not all websites are made the same though, but I also believe that with HTTPS, most, if not all, sites would require you to contact them from ONE IP address during your transaction


text:
Q: Trying to Alternate Row Color in PHP I'm looking to alternate row colors using PHP function.  Here's what I have (although it does not work):
function row($year) {
    if($year%2)
        $color == "#FFF";
    else
        $color == "#000";
}

for ($year=2013; $year<=2023; $year++)
    {
    row($year);
    echo "
$year	$tdate
";
    }

Basically, if a year is odd I would like the color of the row to be white.  If even, black.

A:
From W3c
15.1.1 Background color - bgcolor  attribute has been deprecated in favor of style sheets for specifying background color information.

now what should you do is
function row($year) {
    return ($year % 2 == 0) ? "#FFFFFF" : "#000000";
}

for ($year = 2013; $year <= 2023; $year++) {
    echo "
$year	$tdate
";
}

however its looks like you are not aware of what == does  its a equal to operator its not assignment operator
what assignment operator do is assign right hand side value to left hand for example

what Comparison Operators(==) do is
$a == $b    Equal   TRUE if $a is equal to $b after type juggling.

second you also there is the scope of a variable

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
above is quoted from php manual to read more check this

A: Why don't you just use CSS with the nth-child selector?
tr:nth-child( 2n ) {
  background-color: #000;
}
tr:nth-child( 2n + 1 ) {
  background-color: #FFF;
}

Then no further attributes are needed on the
 element.
Besides the IE, most browsers support this. See the Browser compatibility of MDN.

A: function row($year) {
    $color = '';
    if($year%2)
        $color = "#FFF";
    else
        $color = "#000";

   return $color;
}

for ($year=2013; $year<=2023; $year++)
    {
    $color = row($year);
    echo "
$year	$tdate
";
    }

A: for ($year=2013; $year<=2023; $year++)
{
    echo "
$year	$tdate
";
}

A: You aren't saving the result of your function anywhere. Try this:
function row($year) {
    if($year%2)
        $color == "#FFF";
    else
        $color == "#000";
}

for ($year=2013; $year<=2023; $year++)
{
    $color = row($year);
    echo "
$year	$tdate
";
}

It's about variable scope.

A: you are not returning anything from function,do like this
function row($year) {
    if($year%2)
        $color == "#FFF";
    else
        $color == "#000";
return $color;
}

for ($year=2013; $year<=2023; $year++)
    {
    $color = row($year);
    echo "
$year	$tdate
";
    }

A: Just like other programming languages, you have to know when you're working with local variables and globals. In this case, you're trying to use a variable in one function that is local to another.
function row($year) {
    if($year%2 == 1)
        return "#FFF";
    else
       return "#000";
}

for ($year=2013; $year<=2023; $year++)
    {
    echo "
$year	$tdate
";
    }

A: <?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$dbname=""; // Database name
$tblname=""; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql="SELECT * FROM $tblname";
$result=mysql_query($sql);
// Define $color=1
$color="1";
echo '
Employee Details

';
echo '
';
while($rows=mysql_fetch_row($result)){
// If $color==1 table row color = #FFCCFF
if($color == 1){
echo "
$rows[0]	$rows[1]	$rows[2]	$rows[3]
";
// Set $color==2, for switching to other color
$color="2";
}
// When $color not equal 1, table row color = #FFC600
else {
echo "
$rows[0]	$rows[1]	$rows[2]	$rows[3]
";
// Set $color back to 1
$color="1";
}
}
echo '
';
mysql_close();
?>

In the above coding,first we select the data from the database and then we define a variable $color with the value 1. After while loop an if condition is added.If $color=1 then table row color will be #FFCCFF and inside the if condition we set the $color==2 for switching to other color.Now when $color not equal to 1 then table row color= #FFC600 and else condition executes.Under the else condition we again set the $color back to 1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to format a text excerpt in Latex? I'm using Overleaf to quote a paragraph as an excerpt in my paper. It's just several short sentences. Currently, I'm using
\begin{quote}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
\end{quote}

However, it does not contain a caption. I want to make it something like this image (with a caption, and the excerpt using a different font from the main text).
I'm new to Latex. How can I create this kind of excerpt?

A: The simplest method is to use \newtheorem.
\documentclass{article}
\usepackage{amsthm}

\theoremstyle{definition}
\newtheorem{excerpt}{Excerpt}

\begin{document}

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.

\begin{excerpt}
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
\end{excerpt}

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.

\begin{excerpt}
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
\end{excerpt}

\end{document}

Further customization is possible.


text:
Q: xslt 3.0 xml to JSON number format I would like to convert the following xml to JSON:
<?xml version='1.0' encoding='utf-8'?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
    <array key="ids">
        <number>3218087</number>
    </array>
</map>

using
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

    <xsl:output method="text" />

    <xsl:template match="/">
        <xsl:value-of select="xml-to-json(.)" />
    </xsl:template>

</xsl:stylesheet>

This gives me:
{"ids":[3.218087E6]}

What I need is
{"ids":[3218087]}

Any help would be highly appreciated.
Cheers
Przemek

A: The spec https://www.w3.org/TR/xpath-functions/#func-xml-to-json for a number element suggests:

An element $E named number results in the output of the string result
  of xs:string(xs:double(fn:string($E)))

and the cast to xs:string requires the E notation for values greater than 1000000 I think (https://www.w3.org/TR/xpath-functions/#casting-to-string).
So I don't think the xml-to-json result can be changed, unless a processor allows some options to choose a different formatting rule for numbers.


text:
Q: How to solve this problem in python (Python-3.6.3/Modules/binascii.gcda:Cannot open) tensorflow 1.14.0, Ubuntu 16.04
when I try to Run training file it give me this error:
profiling:/home/shalaw/Python-3.6.3/build/temp.linux-x86_64-3.6/home/shalaw/Python-3.6.3/Modules/arraymodule.gcda:Cannot open
profiling:/home/shalaw/Python-3.6.3/build/temp.linux-x86_64-3.6/home/shalaw/Python-3.6.3/Modules/_ssl.gcda:Cannot

here is my code:
python3.6 main.py \
    --output_dir /home/shalaw/handwritten-data/experiment_sign_semi_reg \
    --summary_dir /home/shalaw/handwritten-data/experiment_sign_semi_reg/log/ \
    --mode train \
    --train_dir /home/shalaw/handwritten-data/signatures/full_org \
    --val_dir /home/shalaw/handwritten-data/signatures/val \
    --val_dataset_name kaggle_signature \
    --learning_rate 0.0001 \
    --loss semi-hard \
    --decay_step 50000 \
    --decay_rate 0.1 \
    --stair True \
    --beta 0.9 \
    --loss_margin 0.5 \
    --max_iter 200000

also you can find full code here:
https://github.com/rmalav15/signature-recognition


text:
Q: Socket for 2 devices on same network not working I'm actually working on an ElectronJS Application and an Ionic App.
The Electron app has a Socket server (using SockJS) and the Ionic app the Socket client.
My problem is when i launch the two app on the same device, it's working fine, but, when the Electron App is launch on my computer and the Ionic app on my android device, it's not working.
I tried with my local IP, localhost, 0.0.0.0, 127.0.0.1. But no one works.
Electron :
const {ipcMain} = require('electron')
let app = require('express')();
const http = require('http').Server(app);
let io = require('socket.io')(http);

io.sockets.on('connection', function (socket) {
    console.log('socket connected');

    socket.on('disconnect', function () {
        console.log('socket disconnected');
    });

    socket.emit('text', 'wow. such event. very real time.');
});

var port = process.env.PORT || 9999;

http.listen(port, function(){
   console.log('listening in http://localhost:' + port);
});

Ionic :
import { Injectable } from '@angular/core';
import { HttpClient  } from '@angular/common/http';
import { Socket, SocketIoConfig } from 'ngx-socket-io';

@Injectable({
  providedIn: 'root'
})
export class CoreService {
  config: SocketIoConfig
  private socket: Socket
  constructor(private http:HttpClient) {
    this.config = { url: 'http://localhost:9999', options: { secure: true } };
  }

  connectSocket() {
    this.socket = new Socket(this.config)
    this.socket.connect()
    this.socket.on('text',(value) => {
      console.log(value)
    })
  }
}

If anyone can help me.
EDIT 1
I try much things. I have desactivate my firewall for testing and try this IP (Localhost, 0.0.0.0, local IP, 127.0.0.1) but no one works.
The communication works when i'm in the same computer (Ionic on emulator or web browser). But when i'm testing in my android device, it's not working. (I'm on the same network)
I have no error on ionic :
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/InputMethodManager: startInputReason = 1
I/HwSecImmHelper: mSecurityInputMethodService is null
I/HwSecImmHelper: mSecurityInputMethodService is null
I/HwSecImmHelper: mSecurityInputMethodService is null
I/HwSecImmHelper: mSecurityInputMethodService is null
I/HwSecImmHelper: mSecurityInputMethodService is null
I/HwSecImmHelper: mSecurityInputMethodService is null

And i'm now using Socket.io instead of SockJS, but still not working..


text:
Q: Laravel cache is supposed to remember my API Secret for 1 hour, but it doesn't I'm trying to get a token from external API. Token lasts 1h, so I would like to put it in cache with a duration of 1 hour.
$seconds = 60*60;
$token = Cache::remember('nova_api_token', $seconds, function () use ($request, $credentials) {
            try {
                $response = Http::asForm()
                    ->withHeaders(["Content-Type" => "application/x-www-form-urlencoded"])
                    ->withBasicAuth($credentials->nova_id, $credentials->nova_secret)
                    ->post(config('nova.url') . "/v1/oauth2/token", [
                        "grant_type" => "client_credentials"
                    ]);
                $body = json_decode($response->body());
                return $body->access_token;
            } catch (\Exception $e) {
                return response()->json($e->getMessage(), $e->getCode());
            }
        });
        return $token;

I can get my token, but each time I send a post request, I get a different token.
What I expect is that the token would be the same during 1 hour.
Why is it happening ?

A: Usually it is the try/catch block as an interior function that causes problems try refactoring to:
try {
  $seconds = 60*60;
  $token = Cache::remember('nova_api_token', $seconds, function () use ($request, $credentials) {
        $response = Http::asForm()
                ->withHeaders(["Content-Type" => "application/x-www-form-urlencoded"])
                ->withBasicAuth($credentials->nova_id, $credentials->nova_secret)
                ->post(config('nova.url') . "/v1/oauth2/token", [
                    "grant_type" => "client_credentials"
                ]);
       $body = json_decode($response->body());
       return $body->access_token;
    });
    return $token;
} catch (\Exception $e) {
    return response()->json($e->getMessage(), $e->getCode());
}

A: Try with rememberForever and see if it is stored in redis.
And I would recommend using now()->addHour() instead of 60 * 60 as the function accepts timestamps as well.


text:
Q: Count numbers from row in CSV file So i have this csv file and one collumn looks like this:
1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728

Now i need to count how oftend a number occurs. I need this to make a graphic picture with matplotlib. So the graphic will show how much a number occurs (in this situation it's a event id)
so far i only have the code to print that row...
my_reader = csv.reader(open(csvpath))
for col in my_reader:
      print col[3]

how do i count how often a number in that specific collumn occurs?

A: Just create a mapping from number to count. The collections.Counter() class makes that easiest:
import collections

counts = collections.Counter()
for row in my_reader:
    counts[row[3]] += 1

Using a collections.defaultdict is also an option:
counts = collections.defaultdict(int)
for row in my_reader:
    counts[row[3]] += 1

or you can use a normal dict:
counts = {}
for row in my_reader:
    counts[row[3]] = counts.get(row[3], 0) + 1

A: You can use a simply dictionary.
my_reader = csv.reader(open(csvpath))
my_dict = {}
for row in my_reader:
    try:
        my_dict[row[3]] += 1
    except KeyError:
        my_dict[row[3]] = 0

A: This code will count total number in rows, if you want to particular row then use if condition before print statement and check if count==row_number exa: if count==3: and get total numbers.
         reader=csv.reader(open("first.csv"))
         count=0;
         for row in reader:
             count+=1
             print "total no in row "+str(count)+" is "+str(len(row))
             for i in row:
                 print i

A: You can use pandas to read your data, count the values and than plot it. Behind the scenes pandas uses numpy and matplotlib to achieve this.
read_csv and the plotting commands work for multiple columns too.
In [29]: df = pd.read_csv('data.csv', names=['my_data'])

In [30]: counts = df['my_data'].value_counts()

In [31]: counts
Out[31]:
1022     3
1042     3
1040     3
1035     3
11728    3
1036     2

In [32]: counts.plot(kind='barh')
Out[32]: <matplotlib.axes.AxesSubplot at 0x4f7f510>


text:
Q: Download S3 File in MVC I have below code to download file from S3
 public FileStreamResult Index(string key, string fileName)
        {

            GetObjectResponse resp = ReadS3Object("data", key);
            StreamReader sr = new StreamReader(resp.ResponseStream);

            var filresult = File(resp.ResponseStream, resp.ContentType);
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=fileName);
            Response.Flush();
            return filresult;

        }

and Ajax call like below
 $.ajax(
         {
             url: '/DownloadEstimation/Index',
             contentType: 'application/json; charset=utf-8',
             datatype: 'json',
             data: {
                 key: key,
                 fileName: fname
             },
             type: "GET",
             success: function () {
                   window.location = '/DownloadEstimation/'+ key + '/' + fname;
             }
         });

But it just call method, not prompting user to save the file
Any help highly appreciated.
Thanks


text:
Q: Forward Geocoding with CLGeocoder Issues I'm having an issue using forward geocoding on iOS5 with the geocodeAddressString function.
I have a MKMapView open up as a modal view to display different locations with data grabbed from the internet.  My issue is when I dismiss the modal view, and then open it up again.  On second try, only about half of my annotations are actually placed on the map.  On a third try, none show up.
I have a feeling my issue here has to do with memory management and the scope of the CLGeocoder, but I just can't figure it out.
I create all of my annotations in the ViewDidLoad function of the view controller containing the MapView.  Here is the code I use to get the coordinates of the addresses:
int locationCount = 0;
for(NSDictionary *date in locations)
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:[NSString stringWithFormat:@"%@, %@", [date objectForKey:@"venue"], [date objectForKey:@"location"]] completionHandler:^(NSArray *placemarks, NSError *error)
    {
        // if we find the exact location (including the venue string), create an annotation for the map
        if(placemarks && placemarks.count > 0)
        {
            CLPlacemark *topResult = [placemarks objectAtIndex:0];
            TourAnnotation *placemarkAnnotation = [[TourAnnotation alloc] initWithLocation:topResult.location andDetails:date];
            placemarkAnnotation.tag = locationCount;
            [tourMap addAnnotation:placemarkAnnotation];
        }
        // if not place an annotation at the center of the city
        else
        {
            [geocoder geocodeAddressString:[date objectForKey:@"location"] completionHandler:^(NSArray *placemarks, NSError *error)
             {
                 if(placemarks && placemarks.count > 0)
                 {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     TourAnnotation *placemarkAnnotation = [[TourAnnotation alloc] initWithLocation:topResult.location andDetails:date];
                     placemarkAnnotation.tag = locationCount;
                     [tourMap addAnnotation:placemarkAnnotation];
                 }
             }];
        }
    }];
    ++locationCount;
}

Any suggestions would be appreciated.

A: If it's memory issues have you considered how the annotation are dequeued and reused, the map view has a delegate method to do such a thing.
This tutorial may be of some assistance.
Ray Wenderlich map tutorial


text:
Q: Python SQL query returns "ORA-00936: missing expression" when I replace hard-coded value with variable I have a database full of information and I'm trying to write a python script that will pull some of the data and organize it into a report. Here's what I have so far:
import cx_Oracle
import pandas as pd

conn = cx_Oracle.connect('REDACTED')
cursor = conn.cursor()

# Currently hard-coded to return single known motor number
cursor.execute('SELECT MOTORID FROM MOTORS WHERE SERIALNUM=804')
# Returns [(11)]
lMotorID = cursor.fetchall()

# Query Assessments for list of how long the motor had run when assessment was taken
cursor.execute("SELECT DISTINCT RUNHOURS FROM ASSESSMENTS WHERE MOTORID = %s \
               ORDER BY RUNHOURS" % lMotorID[0])
# Returns [(0), (0.91), (8), (25), ...]
lHours = cursor.fetchall()

# Query for number of installed sensors by senor type
cursor.execute("SELECT SENSTYP, COUNT(STATUS) FROM HEALTH LEFT JOIN INSTRUMENTATION \
               ON HEALTH.INSTROID = INSTRUMENTATION.INSTROID LEFT JOIN ASSESSMENTS \
               ON HEALTH.ASSESSID = ASSESSMENTS.ASSESSID WHERE ASSESSMENTS.ASSESSID \
               IN (SELECT ASSESSID FROM ASSESSMENTS WHERE MOTORID = 11 AND RUNHOURS = %s) \
               GROUP BY SENSTYP ORDER BY SENSTYP" % lHours[2])
# Returns a 2-column dataframe with sensor type in column 0 and the total in column 1
dfTotal = pd.DataFrame(cursor.fetchall())

Because I want this to work for any motor, I want to replace the hard-coded MOTORID = 11 with a variable. I tried replacing the last query with this:
cursor.execute("SELECT SENSTYP, COUNT(STATUS) FROM HEALTH LEFT JOIN INSTRUMENTATION \
               ON HEALTH.INSTROID = INSTRUMENTATION.INSTROID LEFT JOIN ASSESSMENTS \
               ON HEALTH.ASSESSID = ASSESSMENTS.ASSESSID WHERE ASSESSMENTS.ASSESSID \
               IN (SELECT ASSESSID FROM ASSESSMENTS WHERE MOTORID = %s AND RUNHOURS = %s) \
               GROUP BY SENSTYP ORDER BY SENSTYP" % (lMotorID[0], lHours[2]))
dfTotal = pd.DataFrame(cursor.fetchall())

And that's when I get the ORA-00936 error. I don't understand why the query is complete with a hard-coded value, but not when the value is replaced by a variable (one that works in a previous query). Thanks in advance.

A: Need to fix the syntax for cursor.execute such as
cursor.execute('... WHERE MOTORID = :mt_id AND RUNHOURS = :run_hr', mt_id=lMotorID[0][0], run_hr=lHours[2][0])

prefixing the parameters by percentage sign is valid for MySQL connections through python, while Oracle accepts colons.
or another option would be using an ordered tuple :
cursor.execute('... WHERE MOTORID = :1 AND RUNHOURS = :2', (lMotorID[0][0],lHours[2][0]))


text:
Q: Apache HttpClient 4.5: Connection Resets I am using httpClient version 4.5 to connect with our external vendor site. We do not need any connection pool or persistent connection, so I am using the BasicHttpClientConnectionManager to create the HttpClient.
This works fine for minimal number of requests, but if I test this for 1TPS for 1 hour, by the end of the test, we start seeing intermittent connection resets. (guessing request count > 100)
I/O exception (java.net.SocketException) caught when processing request to {s}->https://apiURL:443: Connection reset
Please find below the code snippet for making connection.
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), new X509TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();

HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(1, false);

RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(Integer.parseInt(30000)).setConnectTimeout(Integer.parseInt(30000)).setConnectionRequestTimeout(30000).setCookieSpec(CookieSpecs.STANDARD).build();

CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRequestConfig).setRetryHandler(retryHandler).evictExpiredConnections().build();

HttpPost httpPost = new HttpPost(<endpoint>);
httpPost.setEntity(new UrlEncodedFormEntity(requestData));
httpResponse = httpClient.execute(httpPost);

I saw that fix for a similar issue reported is already available with version 4.5. (Ref: https://issues.apache.org/jira/browse/HTTPCLIENT-1655) provided by Oleg
If thats the case, not sure why I am still facing this issue. Could someone please help on this.
Thanks!

A: Hi Oleg,
I had been using the httpclient version 4.5.3 when I was still seeing the connection reset errors as posted above.
Later noticed that the fix for reset issue was committed to the version 4.5.1 (https://issues.apache.org/jira/browse/HTTPCLIENT-1655). So, just tried updating that particular version, ran a test and not seeing the connection reset errors any more.
I had expected that this fix should also be available in the higher versions starting from 4.5.1. But, I guess its somehow missed out in the higher versions, have verified that its still an issue with version 4.5.3 for sure.
So, conclusion is that the connection reset error was fixed using httpclient 4.5.1 jar.
Thanks!


text:
Q: Using SVN as total backup solution for multiple OS sharing data disk I just installed two Linux OS's on one laptop, dual-booting. I keep my important data on an EXT3 partition that I share between the OS's.
I was using CrashPlan for automated backup, but I suspect it would be sloppy if not a downright bad idea to install CrashPlan client on multiple OS's and ask it to back up the same data disk.  (I assume the two installations of CrashPlan would have a conflicting opinion of "where they left off" at the most recent backup). Same is probably true for many other automated sync/backup systems, e.g. Dropbox.  So, I'd like to replace CrashPlan with a more versatile, more predictable, more DIY backup solution that lets me back up the shared data partition regardless
Since I am paying for webspace, one good option might be to install Subversion and periodically backup selected folders from the command line. Will this work independent of which operating system I'm using at the time? (In other words, is all the information SVN needs to do its work contained within the backup file directory and/or the repository---not somewhere else on my local Linux installation)?

A: This depends on the backup client - the "subversion" client keeps the subversion information underneath the directories being backed up, while fsvs (which is more suitable for versioning configs) puts the backup information under /etc).
I agree with @IObO that version control is not ideal for backup (its slow and designed for different purpose), although its certainly a lot better then nothing, and viable if you only have a small amount of stuff.    Maybe have a look at BackupPC (for Windows and Linux) or rsync or rsnapshot (not used this with Windows, maybe you can use cygwin ?)
Also, I'd suggest against command line backups as they tend to get out of date because its a manual process.


text:
Q: Which package to install to use C/C++ compiler with Eclipse I want to develop C/C++ applications using Eclipse: should I install using
sudo apt-get install build-essential

or
sudo apt-get install gcc

A: It depends on how which applications you use, the gcc package contains the gcc, where the buil-essential package contains some additional dev-tools (e.g. make and g++).
A list of packages included in build-essential package can be found here.


text:
Q: How to make the jQuery autocomplete text area into a form field? I got the jQuery autocomplete form mostly working how I need it to work here: http://problemio.com/test.php
but there is one problem:  I can't get the area where the chosen items are listed to be a form field.  Right now it is just some uneditable text area and when I try to do a
var log = $("#log").val();

that gets nothing in the value, so I can't really submit it.
1) How do I make that area into a form field whose value can be retrieved upon form submission?
2) Also, how do people manage to allow the users to remove the items they had chosen?
Thanks!!

A: You can't get the value of a div element (there isn't one). That's what you're trying to do in your #add_category click handler on line 75 ($("#log").val() -- #log is a div)
You need to get the html or text from the div:
// change line 75 to
$("#log").html()
// or
$("#log").text()

OR
You can just change the html of the log area with a textarea:
//change

// to
<textarea id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></textarea>

A: To make the selected value go into a field you need to change the log() function to record it. You also need to make some means of removing the input, afterwards. Something like:
function log( message )
{
    $( "input[type=submit]" ).after('<input type="text" name="chosenvalues[]" value="' + message + '" readonly="readonly" />Remove');
    $( ".remover:last" ).click(function () {
        $(this).prev("input").remove();
    });
}


text:
Q: Creating a TCP Pipeline architecture with ZeroMQ and PHP? After seeing ZeroMQ is the answer (http://vimeo.com/20605470), by Ian Barber, i got excited about testing out the pipeline pattern presented by him. However, he uses an IPC example: https://github.com/ianbarber/ZeroMQ-Talk/tree/master/worker
How this should work with TCP? How can i instantiate workers through TCP instead of process forking?

A: It will look almost exactly the same, but instead of using ipc:// sockets names you would use tcp:// socket names.  So instead of this:
$work->bind("ipc:///tmp/work");
$ctrl->bind("ipc:///tmp/control");

You might have this:
$work->bind("tcp://*:8080");
$ctrl->bind("tcp://*:8081");

This has the work socket listening on port 8080 and the ctrl socket listening on port 8081.  Your connect operations would look something like:
$work->connect("tcp://1.2.3.4:8080");

(Assuming the ip address of your server was 1.2.3.4).


text:
Q: plotting from two different data files in a single graph gnuplot I have two different data files named try_giants.dat and parameters_ks.dat. I want to plot 3rd column of 1st file vs. 2nd column of 2nd file.

A: With datafiles D1.csv
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4

and D2.csv
0 10
0 20
0 30
0 40
0 50

you can plot the third column of D1.csv on the x-axis and the second column of D2.csv on the y-axis with
plot "< paste D1.csv D2.csv" u 3:5 w l

The paste command merges corresponding or subsequent lines of files giving you this output:
0 1 0   0 10
0 1 1   0 20
0 1 2   0 30
0 1 3   0 40
0 1 4   0 50

Hence, the third column of this file is the third column of D1.csv and the fifth column is the second column of D2.csv resulting in this plot:


text:
Q: While installing, debian does not show my individual partitions In my dual boot PC, I am trying to install Debian. This is how my disk partition looks like.

When i try to create a partition in the debian installation it shows this 250GB entirely. When i select that partition it is asking if it can remove the entire contents in the partition. I have my windows and ubuntu installed already. How to come out of this problem.
Thanks in advance,
Chidambaram


text: Q: When you change the sign of the exponent in an exponential function like $e^x$ into $e^{-x}$, what is it called? When you change the sign of $x$ in $e^x$ to $e^{-x}$, is it called getting the conjugate even though its not a complex number in the form of $e^{jx}$? I'm just confused some people I talk to refer to it as conjugate because I thought the term was only applicable to complex numbers and I guess binomials where you change the sign of the middle term.


text:
Q: Adding each character in a line of input file to list, and adding each list to another list after each line Basically what I am trying to do is read in each character from each line into a list, and after each line, add that list into another list (one list per line in input file, each list containing all the individual characters of each line)
This is what I have so far but it doesnt seem to be working and I can't figure out why.
allseq = []
with open("input.txt", "r") as ins:
    seq = []
    for line in ins:
        for ch in line:
            if ins != "\n":
                seq.append(ch)
            else:
                allseq.append(seq)
                seq[:] = []

print(allseq)

A: Strings in Python can be easily converted into literal lists of characters! Let's make a function.
def get_char_lists(file):
    with open(file) as f:
        return [list(line.strip()) for line in f.readlines()]

This opens a file for reading, reads all the lines, strips off extraneous whitespace, sticks a list of the characters into a list, and returns that last list.

A: Even though there is an easier way (@Pierce answer), there are two problems with your original code.  The second is important to understand.
allseq = []
with open("input.txt", "r") as ins:
    seq = []
    for line in ins:
        for ch in line:
            if ch != "\n":         # Use ch instead of ins here.
                seq.append(ch)
            else:
                allseq.append(seq)
                seq = []           # Don't clear the existing list, start a new one.

print(allseq)

Test file:
this is
some input

Output:
[['t', 'h', 'i', 's', ' ', 'i', 's'], ['s', 'o', 'm', 'e', ' ', 'i', 'n', 'p', 'u', 't']]

To clarify why the 2nd fix is needed, when you append an object to a list, a reference to the object is placed in the list.  So if you later mutate that object the displayed content of the list changes, since it references the same object.  seq[:] = [] mutates the original list to be empty.
>>> allseq = []
>>> seq = [1,2,3]
>>> allseq.append(seq)
>>> allseq                # allseq contains seq
[[1, 2, 3]]
>>> seq[:] = []           # seq is mutated to be empty
>>> allseq                # since allseq has a reference to seq, it changes too.
[[]]
>>> seq.append(1)         # change seq again
>>> allseq                # allseq's reference to seq displays the same thing.
[[1]]
>>> allseq.append(seq)    # Add another reference to the same list
>>> allseq
[[1], [1]]
>>> seq[:]=[]             # Clearing the list shows both references cleared.
>>> allseq
[[], []]

You can see that allseq contains the same references to seq with id():
>>> id(seq)
46805256
>>> id(allseq[0])
46805256
>>> id(allseq[1])
46805256

seq = [] Creates a new list with a different ID, instead of mutating the same list.

A: If you, or anyone else, prefer a one liner, here it is (based on Pierce Darragh's excellent answer):
allseq = [list(line.strip()) for line in open("input.txt").readlines()]


text:
Q: Creating Range Buckets of column I am having one base table named test_table on which I am doing calculation of the age and it is coming as per expectation.
Here is the query I am using for age calculation.
select acol,
       DATEDIFF(hour,CONVERT(DATEADD('SECOND', (epoch_time)/1000, DATE '1970-01-01'), DATE), CURRENT_TIMESTAMP()) AS age
from test_table;

But now I want to create different range of age column which will be displayed as a result by modifying the existing query.
Range would be :
1000-2000

2000-3000

3000-4000

ACOL       AGE
MAG        1168
MAG        2168
MAG        3168
MAG        1100
MAG        2168
PNB        1672
MUM        1600
MUM        2696
MUM        3696
MUM        1696

Result after successful query has to look like below table.
ACOL 1000-2000  2000-3000 3000-4000
MAG      2          2          1
PNB      1          0          0
MUM      2          1          1

I know that we can do this using select case but not able to build the working query.
can anyone help me in this.
thanks in advance.

A: You can use conditional aggregation with a CASE expression:
SELECT t.ACOL,
       SUM(CASE WHEN t.AGE >= 1000 AND t.AGE < 2000 THEN t.AGE ELSE 0 END) AS `1000-2000`,
       SUM(CASE WHEN t.AGE < 3000 THEN t.AGE ELSE 0 END) AS `2000-3000`,
       SUM(CASE WHEN t.AGE < 3000 AND t.AGE < 4000 THEN t.AGE ELSE 0 END) AS `3000-4000`
FROM
(
    SELECT ACOL,
           DATEDIFF(HOUR, CONVERT(DATEADD(SECOND, (epoch_time)/1000, DATE '1970-01-01'), DATE), CURRENT_TIMESTAMP()) AS AGE
    FROM test_table
) t
GROUP BY t.ACOL

A: SELECT ACOL,
       COUNT(CASE WHEN AGE >= 1000 AND AGE < 2000 THEN AGE ELSE NULL END) AS `1000-2000`,
       COUNT(CASE WHEN AGE >= 2000 AGE < 3000  THEN AGE ELSE NULL END) AS `2000-3000`,
       COUNT(CASE WHEN AGE >= 3000 AND AGE < 4000 THEN AGE ELSE NULL END) AS `3000-4000`
FROM (select ACOL,DATEDIFF(hour,CONVERT(DATEADD('SECOND', (epoch_time)/1000, DATE '1970-01-01'), DATE), CURRENT_TIMESTAMP()) AS AGE FROM test_table )
GROUP BY ACOL

Modified the from clause...
Working ...
:)


text:
Q: How to constrain the GridLayout's width to be less than the parent's width? I have a GridLayout defined in the XML layout file as:
    <GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="4"
    android:useDefaultMargins="true" >

    <Button android:text="ababababababababababababababababababababab" />
    <Button android:text="ababababababababababababababababababababab" />
    <Button android:text="ababababababababababababababababababababab" />
    </GridLayout>

Because the width is match_parent, I expected the GridLayout to arrange the buttons such that only as many buttons are shown per row as are necessary to keep the width of the row less than the parent's width.
However, this is not the result I am seeing. The three buttons are all showing up in the first row extending beyond the parent's width as shown in the image below. What is the way to achieve the output that I am looking for?

A: Is GridLayout a requirement? How about having LinearLayout instead and giving each view equal weights?
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />
                </LinearLayout>

Or replacing GridLayout with TableLayout and wrapping your buttons into TableRow like so:
            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TableRow>
                    <Button android:text="ababababababababababababababababababababab" />
                    <Button android:text="ababababababababababababababababababababab" />
                    <Button android:text="ababababababababababababababababababababab" />
                </TableRow>
            </TableLayout>


text:
Q: Fastest way to run large number of COUNTs or maybe a good substitute for that In my program I have to run thousands of COUNT operations each with different conditions.
E.g.
SELECT COUNT(*) FROM Contacts WHERE X='value1' AND Y='value2';
SELECT COUNT(*) FROM Contacts WHERE Z='value3' AND S='value4' AND H='value5';

The number of these operations equals the number of records in my Contacts table. So as the number of contacts increase I am going to have to run more COUNTs.
As one might expect, the queries are going to take a long time to complete. So I am looking for a way to make them run faster. I read the answer to this question in which the user recommends running
SELECT
   Total_Rows= SUM(st.row_count)
FROM
   sys.dm_db_partition_stats st

Instead of normal COUNT. I am wondering if this is really a time-saver?
The problem I am having with comparing the two operations is that for a specific COUNT, the execution time becomes less with second and third runs. Apparently SQL server caches some query results. So I am unable to see which one is truly faster. I am putting my queries between
set statistics time on
--query
set statistics time off

to see the exact run time. Is there a way to compare the two or is there a way in general to make the COUNTs faster?

A: You can just select from the table once, but for each individual condition perform a conditional count as the COUNT function will ignore a null.
SELECT CountAll = COUNT(*)
, CountCond1 = Count(case when x = 'value1' and y='value2' then 1 else null end)
, CountCond2 = Count(case when z = 'value3' and S='value4'  and H='value5' then 1 else null end)
FROM Contacts ;


text:
Q: Google Sheets: How to display the result of a formula rather than the formula itself? I'm using formulas to fetch text from a sheet to another but the text is often too long to be read in the cell itself. The formula bar is no help either because it shows the formula itself, rather than the result.
Does anyone have any suggestions to work this out?
Thanks

A: Try text wrapping in your menu. This will expand your cell.

A: You could allow overflow, text wrapping, or increase the row/column size to the size needed.


text:
Q: python matplotlib plot table with multiple headers I can plot my single-header dataframe on a figure with this code:
plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
    rowLabels=['  {}  '.format(i) for i in df.index], rowLoc='center',
    rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
    colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))

My question is: is it possible to plot a dataframe with multiindex columns? I want two separate "rows" for my multi-headers, so tuples in one header row is not good. If it is possible I want apply the above styles (colors) on both headers (it would be brilliant to set different colors for the multi headers).
Here is an example dataframe:
df = pd.DataFrame([[11, 22], [13, 23]],
    columns=pd.MultiIndex.from_tuples([('main', 'sub_1'), ('main', 'sub_2')]))

Result:
             main
    sub_1   sub_2
0      11      22
1      13      23

A: OK, I used a "trick" to solve this problem: plot a new table with only one cell, without column header and without row index. The only cell value is the original top header. And place this new table on the top of the old (single-header) table. (It is not the best solution but works...).
The code:
df = pd.DataFrame([[11, 22], [13, 23]], columns=['sub_1', 'sub_2'])

# First plot single-header dataframe (headers = ['sub_1', 'sub_2'])
plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
    rowLabels=['  {}  '.format(i) for i in df.index], rowLoc='center',
    rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
    colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))

# Then plot a new table with one cell (value = 'main')
plt.table(cellText=[['main']], cellLoc='center', bbox=[0.225, 1.15, 0.7, 0.05],
    cellColours=[['Lavender']])


text:
Q: Picasso error loading image? I'm trying to use the Picasso library but it is not working. I think my error is with the Picasso.with(Context) i might be using wrong parameter. I included the code for the MainActivity and ListClass. The picture is not loaded and does not appear in the app just white space.
UPDATE!! the " which i was missing has nothing to do with the error. just wrong copy. it gives me error on the this
MainActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.widget.FrameLayout;
import android.widget.Button;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener   {

    ListView list;
    imageHandler imagess = new imageHandler();

    String[] web = {"Trial "};
    Integer[] imageId = { R.drawable.ic_menu_camera };
    //Drawable[] imageId = { imagess.LoadImageFromWebOperations("http://egyptianstreets.com/wp-content/uploads/2016/08/satelliteegypt-400x240.jpg")};

    Handler handler;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        listClass adapter = new
                listClass(MainActivity.this, web, imageId);
        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
            }
        });

    }

ListClass that i used the Picasso library to load the picture from the URL;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.webkit.WebView;
import com.squareup.picasso.Picasso;

public class listClass extends ArrayAdapter<String>{

    //Next three lines introduces Variables to use in the class
    private final Activity context;
    private final String[] web;
    private final Integer[] imageId;

    //Constructor to get Web, Image and context to set adapter
    public listClass(Activity context,  String[] web, Integer [] imageId) {

            super(context, R.layout.list, web);
            this.context = context;
            this.web = web;
            this.imageId = imageId;

    }

    //Public method to ...
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.list, null, true);

        TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
        txtTitle.setText(web[position]);
        Picasso.with(this).load("http://egyptianstreets.com/wp-content/uploads/2016/08/egyptischemoefti.jpg").resize(60,60).into(imageView").resize(50,50).centerCrop().
                into(imageView);
        return rowView;
    }
}

A: Looks like you got the " wrong. Your image URL seems to have been copied wrong. Stuff like 'resize(60,60).into(imageView)' are/should not be part of the URL for the image. They might have come in accidentally.
Use this
Picasso.with(this).load("http://egyptianstreets.com/wp-content/uploads/2016/08/egyptischemoefti.jpg").resize(60,60).centerCrop().into(imageView);

Edit :
Maybe the context you are giving to Picasso is not right. You need to give it the activity context that you are initializing in the constructor.
Maybe this :
Picasso.with(this.context).load("http://egyptianstreets.com/wp-content/uploads/2016/08/egyptischemoefti.jpg").resize(60,60).centerCrop().into(imageView);

A: Here error is you are using library in wrong way.
"  is not valid here.
Also you have used .into(imageView) and resize(..) twice.
Try this.
 Picasso.with(context).load("http://egyptianstreets.com/wp-content/uploads/2016/08/egyptischemoefti.jpg").resize(60,60).centerCrop().
            into(imageView);


text:
Q: Automatic stopped getting locaton from gps We are facing the problem that is getting the location from GPS frequently in background service but some times stopped location automatically in open area while I am sure that service is continuous running and do not affect deep sleep situation also in device idle mode. Please, some body help.
initLocationManager() method is calling one-minute interval through background service.
 private void initLocationManager() {
 Log.e(TAG, "initializeLocationManager");
 if (mLocationManager == null) {
    mLocationManager = (LocationManager)
 getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
 }
 if (mLocationListeners == null) {
    mLocationListeners = new MyLocationListener();
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                Constant.LOCATION_INTERVAL,
                Constant.LOCATION_DISTANCE, mLocationListeners);
    } catch (SecurityException ex) {
        mLocationManager = null;
        mLocationListeners = null;
        WritingFile.getInstance().writeFile(Constant.ERROR_LOG, true,
   AppManager.getInstance().getCurrentDateTime() + ex.getMessage() +
   "20" + "\n");
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        mLocationManager = null;
        mLocationListeners = null;
        WritingFile.getInstance().writeFile(Constant.ERROR_LOG, true,
      AppManager.getInstance().getCurrentDateTime() + ex.getMessage() +
    "21" + "\n");
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    } catch (RuntimeException ex) {
        mLocationManager = null;
        mLocationListeners = null;
        WritingFile.getInstance().writeFile(Constant.ERROR_LOG, true,
   AppManager.getInstance().getCurrentDateTime() + ex.getMessage() + "22"
   + "\n");
        Log.d(TAG, "System Exception! Thread has no looper." +
    ex.getMessage());
    } catch (Exception ex) {
        mLocationManager = null;
        mLocationListeners = null;
        WritingFile.getInstance().writeFile(Constant.ERROR_LOG, true,
   AppManager.getInstance().getCurrentDateTime() + ex.getMessage() + "23" +
   "\n");
    } catch (Throwable ex) {
        mLocationManager = null;
        mLocationListeners = null;
        WritingFile.getInstance().writeFile(Constant.ERROR_LOG, true,
  AppManager.getInstance().getCurrentDateTime() + ex.getMessage() + "24"
   + "\n");
    }
    }

    }

    private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
    if (location == null) {
        //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
    AppManager.getInstance().getCurrentDateTime() + " NULL" + "\n");
        return;
    }
    //lastUpdatedTime =
    Constant.SIMPLE_DATE_FORMAT.format(location.getTime());
    if (location.getAccuracy() < 50) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        // WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
   lastUpdatedTime + " "+location.getLatitude() + ","+
   location.getLongitude() + "AC"+ "\n");
    } else {
        if (latitude == 0.0 || longitude == 0.0) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
        //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
   lastUpdatedTime + " "+location.getLatitude() + ","+
   location.getLongitude() + "NON AC"+ "\n");
    }
}

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
    switch (status) {
        case LocationProvider.AVAILABLE:
            //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
  AppManager.getInstance().getCurrentDateTime() + " AVAILABLE" + "\n");
            //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
 "Last Update Time" + lastUpdatedTime + "\n");
            break;
        case LocationProvider.OUT_OF_SERVICE:
            //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
  AppManager.getInstance().getCurrentDateTime() + " OUT_OF_SERVICE" + "\n");
            // WritingFile.getInstance().writeFile(Constant.COORDINATE,
  true, "Last Update Time" + lastUpdatedTime + "\n");
            removeLocationManager();
            mLocationManager = null;
            mLocationListeners = null;
            break;
        case LocationProvider.TEMPORARILY_UNAVAILABLE:
            //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
    AppManager.getInstance().getCurrentDateTime() + "
    TEMPORARILY_UNAVAILABLE" + "\n");
            //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
   "Last Update Time" + lastUpdatedTime + "\n");
            removeLocationManager();
            mLocationManager = null;
            mLocationListeners = null;
            break;
    }
    }

    @Override
    public void onProviderEnabled(String provider) {
    //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
    AppManager.getInstance().getCurrentDateTime() + " PROVIDER ENABLEE" +
    "\n");
    }

@Override
public void onProviderDisabled(String provider) {
    //WritingFile.getInstance().writeFile(Constant.COORDINATE, true,
   AppManager.getInstance().getCurrentDateTime() + " PROVIDER DISABLE" +
   "\n");
   }
  }


text:
Q: Cognito login works fine but getting 400 error in browser strange one this, I am using angular 7 and using API gateway with authentication.
My problem is that on both using amplify and amazon-cognito-identity-js I get a 400 error in the browser.  All works fine but the error persists.
See below:-
Auth.configure({
      mandatorySignIn: false,
        // REQUIRED - Amazon Cognito Identity Pool ID
        identityPoolId: 'eu-west-1:ssssssssssss',
        // REQUIRED - Amazon Cognito Region
        region: 'eu-west-1',
        // OPTIONAL - Amazon Cognito User Pool ID
        userPoolId: 'eu-west-1_ssssssssssss',
        // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
        userPoolWebClientId: 'sssssssss',
     })
    const user = Auth.signIn(userName, password).then(res =>
      {});

In the browser I get :-
POST https://cognito-idp.eu-west-1.amazonaws.com/ 400 error
However, the code works, any idea why this could be happening?
Thanks for your help


text:
Q: HTML Videos not playing on deployed site, really choppy So, i'm creating a website and everything is cool but the videos are really choppy and wont load. I've never had this issue before and I'm not getting any errors in the console.
Problem: Video is choppy and wont load, plays choppy and laggy
Solution I would like: To be pointed in the right direction with how I can fix this so that the video plays normally when a user presses play.
This is my code:
<div class="col-12">
                <video width="320" height="240" class="pt-3" controls preload="auto">
                    <source src="/videos/video1.MP4" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video2.MOV" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video3.MOV" type="video/mp4"> Your browser does not support the video tag.
                </video>
                <video width="320" height="240" controls class="pt-3" preload="auto">
                    <source src="/videos/video4.MP4" type="video/mp4"> Your browser does not support the video tag.
                </video>
            </div>
        </div>

I need this done in like.. an hour so can someone please help me? Thank you.

A: Have you tried not preloading the videos?


text:
Q: How to configure react-app-rewired to add a postcss plugin How can I customize react-app-rewired config in CRA v5 to add a postcss plugin, for example this one? I checked react-app-rewired documentation and github issues, but didn't find out how to do that.

A: You can try the react-app-rewire-postcss library that does exactly what you need. There might be issues with PostCSS version, but you can definitely use the library's code as a hint about how what you need can be implemented.


text:
Q: Unwanted start menu items roaming with user profile Our users are setup with roaming profiles in Active Directory.
The trouble is that when they install some application on, say, machine A and it creates a start menu shortcut in C:\Users\userid\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\, then these start menu shortcuts will roam to other machines, even though the applications aren't installed on these other machines, thus creating broken links.
Surely this can't be right?

A: Since nobody else has really clarified, let me expand on the other replies.
The Start Menu that a user sees when they log on to a system is actually an amalgamation of the 'All Users' Start Menu which lives in %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu on Vista or later, or %ALLUSERSPROFILE%\Start Menu on 2000/XP/2003 systems, and the per-user Start Menu which lives in the user's profile.
Programs that install on the system (i.e. not in the users profile) should put their shortcuts in the All Users Start Menu so that anyone who logs onto the system can see the shortcuts. Lots of (usually older) installers don't do this and they end up putting their shortcuts in the profile of the user that installed the program, even though the program's executable is available to all users in the Program Files folder. It's bad practise but it happens, and I suspect that this is what you're seeing in your roaming profiles.
Other programs can install themselves on a per-user basis - the executable lives inside the user's profile and therefore the shortcut should only appear on that user's Start Menu. Google Chrome is a good example of this and it's the right thing to do in this case.

A: Sure it's right. The Start Menu is part of the user profile (except in the case where you redirect the Start Menu) so anything written to the start menu is going to roam with the user profile. It doesn't matter whether or not the program is acatually installed on that computer/server.

A: Yes it can - Look in the users profile folder and you will notice a Start Menu folder that will show up when the user logs in.


text:
Q: Connecting to Lubuntu desktop via VNC I have installed Lubuntu desktop on a Ubuntu 20.03 LTS server. The desktop works fine when I log on to it locally. I can see the SDDM and I can chose between various sessions for the desktop (Lubuntu, LXDE, LXQt).
However, I set up a vnc server and I configured (as per the instructions I found online) the ~/.vnc/xstartup fileto looks like this:
#!/bin/sh
xsetroot -solid grey
export XKL_XMODMAP_DISABLE=1
openbox &
/usr/bin/lxsession -s Lubuntu &

When I connect though, all I can see is a grey screen. Any ideas?
Thanks a lot!

A: This was what I have in my ~/.vnc/xstartup and it worked.
#!/bin/bash
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
exec startlxqt

My VNC server is TigerVNC.  One caveat, though the VNC session worked, the VNC client (RealVNC viewer in my case) wouldn't display Network Manager Applet (nm-applet).  I tried LXDE with Debian 11, nm-applet was also missing.  Therefore, I suspected it may a bug in Lubuntu.  Switching to Xfce4, the nm-applet did show up in RealVNC viewer.


text:
Q: Generate unique id for object on both client and server I have a simple class which exists on both the client and the server in a package.
import {Random} from 'meteor/random'
import {EventEmitter} from 'events'

export class MySpecialClass extends EventEmitter {
  constructor() {
    super()
    // ... omitted
    this._id = Random.id()
  }
}

However, when I instance this class, it would seem that the generated id is different for both client and server.
Is there a way to generate a unique id on an instance of an object for both client and server?

A: You will have a different instance of your class on your server and each client so it makes sense that the random id is different for each. To have the same id you'd need to create it on the server and then have the client obtain that id via meteor method
Or you could store the ids in a Meteor collection, in which case the data will be synchronized between the server and client.


text:
Q: Motivation of $p$-spin glass model In general, the $p$-spin glass model focuses on $p$-body interactions like
$${\displaystyle H({\boldsymbol {\sigma }})=\sum_{i_1,...,i_p} J_{i_{1},\ldots i_{p}} \sigma _{i_{1}}\cdots \sigma _{i_{p}}.}$$
But what is the physical significance of this Hamiltonian? Does there exist any system that has this p-body interaction among p spins? It makes sense to me only when it looks like the Ising model, i.e. p=2 and sum over all adjacent sites...


text:
Q: Does Devise work only with STI models? I'm having troubles in understanding how devise works when you try to customize its behaviour.
I have two different models to handle: Society and Collaborator, and the registration form has to be in the same view for both of them.
So I have to override the "devise registration controller create method" by writing a new controller which handles both models.
And here comes the pain.
From here "Devise form within a different controller" and here, I know that I have to define those new helpers, to make devise works:
module ContentHelper
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
end

And the create method which I want to override is this:
def create
build_resource

if resource.save
  if resource.active_for_authentication?
    set_flash_message :notice, :signed_up if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_up_path_for(resource)
  else
    set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
    expire_session_data_after_sign_in!
    respond_with resource, :location => after_inactive_sign_up_path_for(resource)
  end
else
  clean_up_passwords resource
  respond_with resource
end

end
I can't figure out how to make it works without compromising warden functionality. (build_resource). Any suggestion? I can't find any solution with no STI use!

A: It sounds like you are going to have a complicated model setup that might plague you down the track.  If you have two different "user" models that are needed, maybe you can still have a User model and then also have Society and Collaborator models that each "has_one :user".  That way on signup you create the user record, and the Society or Collaborator method (whichever was selected).  That way devise (and your all your authentication) is just linked to the User model and it stays simple.
In general, if you find yourself fighting against the grain, it's a good idea to re-evaluate what you are doing.  Unless you are doing something groundbreaking, there is a good chance things shouldn't be so difficult.

A: you can define variables in all the views of devise, for example
@type = :society

and
def resource_name
    @type
end

then you can use the original controllers and views, and just add it in the AplicationHelper
PD: for User.new, you can use a string in a eval condition, something like
@res = "Society"

then
@resource ||= eval(@res).new


text:
Q: mail interface cancel button not working ios - MFMailComposeViewController class I have a webview object (aWebView) which was added on top of current window like this -
UIWindow *webWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 20, 320,460)];
[webWindow addSubview:aWebView];
[webWindow makeKeyAndVisible];

I have a ViewController (viewcontrollerobj) which is subView of aWebView -
[webView addSubview:viewcontrollerobj.view];

Then I am calling sendInAppMail method in the ViewController-
[sviewcontroller sendInAppMail];

SendInAppMail looks like this -
    MFMailComposeViewController *mailController = [[[MFMailComposeViewController alloc] init] autorelease];
    if([MFMailComposeViewController canSendMail])
    {
        [mailController setMessageBody:@"hello" isHTML:NO];
        [mailController setSubject:@"subject"];
        mailController.mailComposeDelegate = self;
        [self presentModalViewController:mailController animated:YES];
        [mailController release];
    }

didFinishWithResult looks like this -
- (void)mailComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result) {
        case MFMailComposeResultCancelled:
            break;
        case MFMailComposeResultSent:
            break;
        default:
            break;
    }

    [self dismissModalViewControllerAnimated:YES];
}

Mail viewcontroller shows up fine. The problem is that when I hit cancel it shows the delete/save draf t option and after clicking either delete/save the mail viewcontroller doesn't go away!
When I look at console it shows this log message -
"Presenting action sheet clipped by its superview. Some controls might not respond to touches. On iPhone try -[UIActionSheet showFromTabBar:] or -[UIActionSheet showFromToolbar:] instead of -[UIActionSheet showInView:]."
I am not using UIActionSheet anywhere and haven't used in the past so I am not able to understand what it is saying.
I looked at this - https://stackoverflow.com/a/6015957/516938
But it seems like the solution given is very specific to a situation.

A: Not sure this is the issue, but this is the first thing I would look at.
Based on the error message that you got it sounds like either one of the views (the aWebView or the one from viewcontrollerobj that you defined) doesn't allow enough space for the MFMailComposeViewController, meaning that the dimensions of it are smaller than the MFMailComposeViewController requires. It isn't actually clipping the content, so you see it, but it is blocking the touches so that they don't get to the MFMailComposeViewController.
I hope that is clear enough - I had a hard time describing my thoughts here correctly.


text:
Q: IOS Simulator bug with my view I want to believe this is a simulator bug, but, can somebody please explain what is going on?
Im running a simple View on my storyboard: (as you can see, the view with green background is my superview). The thing is when I run my app on a simulator (sometimes, not always) my superview doesn't get scaled and I get a black screen!! My view has checked true the Use Autolayout field, cause some things inside need to have constraints.

I can't give constraints to my view because, it's the superview
And yes, I have debugged with the UI and this is the thing, my superview is not resizing.

A: Okay I solved, for sure is a bug of Xcode. For me was very strange, so, I decided to delete my View Controller and add all my elements again.


text:
Q: Getting error as char cannot be dereferenced in java Getting char cannot be dereferenced error , while writing following code
for(int i =1;i<=m;i++){
    for(int j =1;j<=l;j++){
        if(A.charAt(i-1).equals(B.charAt(j-1))){
            arr[i][j] = arr[i][j-1] + arr[i-1][j-1];
        }
        else{
            arr[i][j] = arr[i][j-1];
        }
    }
}

on line if(A.charAt(i-1).equals(B.charAt(j-1)))

A: charAt returns a primitive char which does not have methods such as equals.
To compare primitives, you can use ==:
if(A.charAt(i-1) == B.charAt(j-1)) {


text:
Q: Aligning images like google image search does Google shows its images like this:

But then when I try to do it, I get this:

It seems this will need something more than just float:left, but what? The images will be of unknown height and width. But I put in a max-height and max-width check so it doesn't get too crazy.
Note: rowtable is just an array that holds the picture name (id). I cut some stuff out to clean the code.
function imageResize($image) {

$maxWidth  = 500;
$maxHeight = 395;

$size = getimagesize($image);
if ($size) {
    $imageWidth  = $size[0];
    $imageHeight = $size[1];
    $wRatio = $imageWidth / $maxWidth;
    $hRatio = $imageHeight / $maxHeight;
    $maxRatio = max($wRatio, $hRatio);
    if ($maxRatio > 1) {
        $outputWidth = $imageWidth / $maxRatio;
        $outputHeight = $imageHeight / $maxRatio;
    } else {
        $outputWidth = $imageWidth;
        $outputHeight = $imageHeight;
    }
    //echo 'width="'.$outputWidth.'" height="'.$outputHeight.'"';
return 'width="'.$outputWidth.'" height="'.$outputHeight.'"';
}

}
        $image = "images/screenshots/$rowtable[id].png";
        ?>

<img src="<?php echo "images/screenshots/$rowtable[id].png"; ?>" <?php echo imageResize($image); ?>>

UPDATE:
After watcher's comment, it works. But how can I get this?

So have a wide picture center vertically, rather than sticking to the top.

A: Google's Image Search puts the images into an ordered list, with each list element having the following styles:
.rg_li {
    display: inline-block;
    margin: 0 12px 12px 0;
    overflow: hidden;
    position: relative;
    vertical-align: top;
}

A: may that's you want http://jsfiddle.net/sandeep/EAGQH/28/
css:
ul li {
    display:inline-block;
    margin:10px 0 0 10px;
    text-align: center;
}

img{vertical-align:middle}

A: You could look at how Google does it in Firebug (or any equivalent tool).  I just did, and apparently they wrap each image in a div (actually, a
) with height set to the height of the image and vertical padding set to make up the difference.  For example, here's one of them from a search I just ran:

(See watcher's answer for the styles applied to the class rg_li.)  Apparently, they also adjust the height of each line dynamically to match the height of the tallest image on it, so if I resize the window, the padding values get recomputed.
But anyway, if you just want a bunch of images vertically centered, you don't need any of this trickery.  Just wrap all the images together in a
 or
 and style them with vertical-align: middle.

  ...

You can even do this without CSS if you want, by using the old HTML align attribute, like this:

  ...


text:
Q: convergence of the product The expression
$\prod_{n=1}^{\infty}(1 - \frac{1}{3n + 2})$
what is the value of the product if $n$ varies from $1$ to $\infty$.
My approach:
I took the log of each term
making it $\sum_{n=1}^{\infty}log(1 - \frac{1}{3n+2})$ so the original product becomes

$\prod_{n=1}^{\infty}(1 - \frac{1}{3n + 2})$  = $e^(\sum_{n=1}^{\infty}log(1 - \frac{1}{3n+2})^)$
now $\frac{1}{3n+2} < 1 \space \forall \space n \space \ge1 $ Now $log(1 + x) \approx x$ so we can write $log(1 - \frac{1}{3n+2}) \space \approx \frac{-1}{3n+2}$ taking limit of which will turn out to $-\infty$ and thus the product should converge to $0$.
Am I correct?

A: Yes, correct, but could be more precise.
For example, use $1+x\le e^x$, so that $\log(1+x)\le x$ for $x>-1$, thus
$$\log(1-\frac1{3n+2})\le -\frac1{3n-2}$$
so their sum indeed converges to $-\infty$.


text:
Q: How jQuery can prevent showing HTML element title even if it has title attribute in its tag? I have a link like the below one, and I want to prevent showing it's title attribute on mouse over event. But I must keep it and I can not remove it.
Test

How can I do it using jQuery ?

A: After many times, accidentally I found a link that solves the problem. So I decided to put it here ...
Thanks for its writer
http://jsfiddle.net/vkDcG/
HTML:

jQuery:
$(".fancybox")
    .attr('rel', 'gallery')
    .fancybox({
        beforeLoad: function() {
            this.title = $(this.element).attr('caption');
        }
    });

A: There are a few hacks on Stack Overflow (disable tooltip, suppress tooltip). I think this is the cleanest and it doesn't need jQuery:
https://stackoverflow.com/a/457382/1325290
// Suppress tooltip display for links that have the classname 'suppress'
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    if (links[i].className == 'suppress') {
        links[i]._title = links[i].title;
        links[i].onmouseover = function() {
            this.title = '';
        }
        links[i].onmouseout = function() {
            this.title = this._title;
        }
    }
}

Leave out the if...suppress part if you don't want it.

A: The only idea I have - is prevent mouseover event form being trigger. Posiibly this solution will work:
$("a[title='Titlte is a test']").mouseover(function(e) {
    e.preventDefault();
});

If this will not help you then you can hack this with some opacity element placed over you a element - this actually will do the same - mouseover evenet wouldn't be tiggered. Note: you shoukd trigger click event on link when it will be catcjed on opacity element:
$("Opacity element id").click(function(e) {
    $("a[title='Titlte is a test']").click()
});

And similarly with mousedown/up events if they are used

A: The technique is to hide the title on mouseove and restore in on mouseout.
$("a#test").mouseover( function(e){

    var myLink = $('a#test');

    myLink.hover(
        function() {
            old_title = $(this).attr('title');
            $(this).attr('title','');
        },
        function() {
            $(this).attr('title', old_title);
        }
    );
});

A: Here's my solution using modern jQuery:
jQuery(document.body)
  .on('mouseover', 'a[title]', null, function(event) {
    $(this).attr('data-title', $(this).attr('title')).removeAttr('title');
  })
  .on('mouseout', 'a[data-title]', null, function(event) {
    $(this).attr('title', $(this).attr('data-title')).removeAttr('data-title');
  });

This handles all existing and future a-tags on the page, and causes very minimal memory-overhead, because it creates only a single pair of event-handlers for all elements - on hover, it moves the value from the title attribute to a data-title attribute, which it removes again when the mouse leaves the element.

A: For me, I didn't care what the content of the title tag was so this was cleaner for me. I just did:
$('a').hover(function() {

    $(this).attr('title', '');

});

Which stopped the title tag from showing.


text:
Q: Could not execute the TestNG file due to error in xml I am using xml for parameter test I am getting below error while running

It is strongly recommended to add <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> at the top of your file, otherwise     TestNG may fail or not work as expected.

here is my xml file for review
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="none">
    <test name="Test">
        <parameter name="browser" value="firefox"/>
        <parameter name="browser" value="chrome"/>
        <classes>
            <class name="PracticeExample.NewTest"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

A: The error message is quite clear, just write
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

instead of simply
<?xml version="1.0" encoding="UTF-8"?>

and the upper warning will go away.

A: Thanks for your replay I tried this and it works fine
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite" parallel="tests">

  <test name="Test">
   <parameter name = "browser" value="firefox"/>
   <parameter name = "browser" value = "chrome"/>

    <classes>
      <class name="PracticeExample.NewTest"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->


text:
Q: basic average (median) model outperforms more sophisticated statistical and machine learning models Let us say I have 3 categorical features with 3 levels each (there are actually more but I just use this as an example):
F1 = {F1_L1, F1_L2, F1_L2}
F2 = {F2_L1, F2_L2, F2_L2}
F3 = {F3_L1, F3_L2, F3_L2}

There is also one continuous dependent variable Y. I have a few 100 samples from this scenario. Overall there are 3 * 3 * 3 = 27 bins/combinations given the above categorical feature details. In order to 'predict' Y given a 'new' sample, I currently simply take the median Y value of the present combinations' bins (if I do not have the combination I use the global (marginal?) median). Hope that makes sense.
This works quite well and could be deemed null model I presume. I have tried to use simple OLS and quantile regression models and more sophisticated models like gradient boosting with hyper parameter search etc. on training data but on unseen data these models are over fitted and my basic 'null model' performs OK. I guess complex interactions cannot be captured by my simple null model. Am I missing something or could it be that something so simple works?
PS:
Some R code to make this hopefully clearer:
expand.grid(
  F1 <- c('L1', 'L2', 'L3')
  , F2 <- c('L1', 'L2', 'L3')
  , F3 <- c('L1', 'L2', 'L3')
)

results in 27 combinatons:
   F1 F2 F3
1    L1   L1   L1
2    L2   L1   L1
3    L3   L1   L1
4    L1   L2   L1
5    L2   L2   L1
6    L3   L2   L1
7    L1   L3   L1
8    L2   L3   L1
9    L3   L3   L1
10   L1   L1   L2
11   L2   L1   L2
12   L3   L1   L2
13   L1   L2   L2
14   L2   L2   L2
15   L3   L2   L2
16   L1   L3   L2
17   L2   L3   L2
18   L3   L3   L2
19   L1   L1   L3
20   L2   L1   L3
21   L3   L1   L3
22   L1   L2   L3
23   L2   L2   L3
24   L3   L2   L3
25   L1   L3   L3
26   L2   L3   L3
27   L3   L3   L3

A: I think this is a basic bias-variance tradeoff. Your dataset is not so large, and your simple model does not have a lot of variance (it doesn't overfit) but it is biased. However your complex models overfit, i.e. have low bias but huge variance (It's also not clear by what you mean by "performs OK").


text:
Q: Google javascript maps getCurrentPosition How can i use :
navigator.geolocation.getCurrentPosition()

to get the coordinates of the current position .
This is the example from google site :
function initialize() {
 var mapOptions = {
   zoom: 6
 };
 map = new google.maps.Map(document.getElementById('map-canvas'),
     mapOptions);

 // Try HTML5 geolocation
 if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
       var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);

       var infowindow = new google.maps.InfoWindow({
            map: map,
            position: pos,
            content: 'Location found using HTML5.'
            });
        map.setCenter(pos);
      }, function() {
           handleNoGeolocation(true);
         });
 } else {
   // Browser doesn't support Geolocation
      handleNoGeolocation(false);
 }
}

I tried replacing the var pos part to myPos which is a global variable , but it didn't work.
I mean i always get myPos undefined after the initialize() function .
what is the correct way to get the latitude and longitude navigator.geolocation.getCurrentPosition()  in initialize function which is called when the form (window) loads ?

A: .getCurrentPosition() is an asynchronous function, so it takes a callback that's executed once it has those coordinates e.g.
navigator.geolocation.getCurrentPosition(function(position){
  console.log(position);
});

which will give you something like this:
{
  "timestamp": 1421093714138,
  "coords":
    {
      "speed": null,
      "heading": null,
      "altitudeAccuracy": null,
      "accuracy": 20,
      "altitude": null,
      "longitude": -122.4091036,
      "latitude": 37.7837543
    }
}

inside the callback you pass .getCurrentPosition you can even update variables, assuming they're declared beforehand. I'm guessing the reason your myPos variable is undefined is because there's a problem with the way you're hooking up to the google maps API. If you aren't using google maps, and just want to get a location, you can do something like this:
var myPos;

navigator.geolocation.getCurrentPosition(function(position){
  myPos = position;
});

Oh, and make sure you allow the website to access your location. In chrome, you get a bar on the top of you page saying "< website url > wants to use your computer's location [Deny] [Allow]"
Edit:
Two things wrong. You only have access to that variable inside the scope of the callback function — only once that function runs will tmpPos be defined. As I said above, .getCurrentPosition is an asynchronous function. Meaning it sets up a process to grab your geolocation, but does other stuff in the meantime (in your case, it moves on and tries to update other variables to information it doesn't have yet).
Additionally, you're calling the initialize function inside of itself, so that will create an infinitely looping function that never ends. To fix this, try:
function initialize(){
navigator.geolocation.getCurrentPosition(function(position){
  // create the map here, because we only have access to position inside of this function
  // even if we store in a global variable, it only gets updated once this callback runs

  var currentPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}

initialize();


text:
Q: How to insert comma in the value which is present in Hyperlink column in gridview Here is my markup:
<asp:TemplateField HeaderText="Loss" SortExpression="Loss"
     HeaderStyle-CssClass="StrongText" HeaderStyle-Font-Bold="true"
     HeaderStyle-Font-Size="Medium" HeaderStyle-ForeColor="Blue"
     HeaderStyle-Font-Underline="true" HeaderStyle-VerticalAlign="Bottom"
     ItemStyle-Width="3%" ItemStyle-HorizontalAlign="Left"
     ItemStyle-VerticalAlign="Bottom" HeaderStyle-HorizontalAlign="Left">
     <ItemTemplate>
         <asp:HyperLink runat="server" ID="HyperLink8"
              NavigateUrl='<%#"db_LossofPay.aspx?UserID="+ Eval("User ID")%>'
              Text='<%# Eval("Loss","{0}")%>'
              ForeColor="BLUE" Target="_blank"></asp:HyperLink>
         <asp:Label ID="lblLoss" runat="server"></asp:Label>
     </ItemTemplate>
</asp:TemplateField>

Could you please help me with this? In BoundField I wrote DataFormatString="{0:N2}" which works fine, but I got stuck when using in hyperlink (template field)

A: Try with this:
<asp:HyperLink runat="server" ID="HyperLink8"
 NavigateUrl='<%#"db_LossofPay.aspx?UserID="+   Eval("User ID")%>'
 Text='<%# Eval("Loss","{0:#,##0.00}") %>' ForeColor="BLUE" Target="_blank" />

A: Try
Text='<%# String.Format("{0:N2}", DataBinder.Eval(Container.DataItem, "Loss"))%>'


text:
Q: org.json.JSONException: JSONObject["values"] is not a JSONArray." This my json array.
[
  {
    "type":"select",
    "label":"Select",
    "className":"form-control",
    "name":"select-1497355331262",
    "values":[
              {
                "label":"Option 1",
                "value":"option-1",
                "selected":true
               },
             {
              "label":"Option 2",
              "value":"option-2"
             },
            {
              "label":"Option 3",
              "value":"option-3"
            }
         ]
       }
]

My Appraoch :
JSONArray js = null;
            try {
                js = new JSONArray(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject obj = null;

            for (int i = 0; i < js.length(); i++) {

                try {
                    obj = js.getJSONObject(i);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    type = obj.getString("type");
                } catch (JSONException e) {
                    type = null;
                }

                System.out.println("Type : " + type);

                try {
                    JSONArray jContent = obj.getJSONArray("values");
                    System.out.println(jContent.toString());
                    for (int iterate = 0; iterate < jContent.length(); iterate++) {
                        JSONObject inner = jContent.getJSONObject(iterate);
                        String inner_label = (String) inner.get("label");

                        System.out.println(inner_label);

                        String val = (String) inner.get("value");
                        boolean sel;
                        try {
                            sel = (boolean) inner.get("selected");

                        } catch (JSONException j) {
                            sel = false;
                        }
                        System.out.print(inner_label);
                        System.out.print(" " + val);
                        System.out.println(" " + sel);

                    }

                } catch (JSONException e) {
                    System.out.println("There is some error");
                }

                try {
                    label = obj.getString("label");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    access = obj.getBoolean("access");
                } catch (JSONException e) {
                    access = false;
                }

                try {
                    role = obj.getString("role");
                } catch (JSONException e) {
                    role = null;
                }

                try {
                    subtype = obj.getString("subtype");
                } catch (JSONException e) {

                    subtype = null;
                }

                try {
                    maxlength = obj.getString("maxlength");
                } catch (JSONException e) {

                    maxlength = null;
                }

                try {
                    name = obj.getString("name");
                } catch (JSONException e) {

                    name = null;
                }

                try {
                    description = obj.getString("description");
                } catch (JSONException e) {

                    description = null;
                }

                try {
                    classname = obj.getString("className");
                } catch (JSONException e) {

                    classname = null;
                }

                try {
                    placeholder = obj.getString("placeholder");
                } catch (JSONException e) {

                    placeholder = null;
                }

                try {
                    value = obj.getString("value");
                } catch (JSONException e) {

                    value = null;
                }

                try {
                    required = obj.getBoolean("required");
                } catch (JSONException e) {

                    required = false;
                }
                try {
                    toggle = obj.getBoolean("toggle");
                } catch (JSONException e) {
                    toggle = false;
                }
                try {
                    inline = obj.getBoolean("inline");
                } catch (JSONException e) {
                    inline = false;
                }
                try {
                    enableother = obj.getBoolean("other");
                } catch (JSONException e) {
                    enableother = false;
                }
                try {
                    multipleFiles = obj.getBoolean("multiple");
                } catch (JSONException e) {
                    multipleFiles = false;
                }
                try {
                    style = obj.getString("style");
                } catch (JSONException e) {
                    style = null;
                }
                try {
                    min = obj.getString("min");
                } catch (JSONException e) {
                    min = null;
                }
                try {
                    max = obj.getString("max");
                } catch (JSONException e) {
                    max = null;
                }
                try {
                    step = obj.getString("step");
                } catch (JSONException e) {
                    step = null;
                }
                try {
                    rows = obj.getString("rows");
                } catch (JSONException e) {
                    rows = null;
                }

I am able to get all other objects values I am unable to read the values array. I have written the code for it but its directly going to the catch block printing the error message "There is some error". Thnaks  for the help.

A: Solved...Values was not an array it was an object....So here's what I did. It worked.
 try {

                String j2 = obj.getString("values");
                JSONArray jContent = new JSONArray(j2);
                                    for (int iterate = 0; iterate < jContent.length(); iterate++) {
                        JSONObject inner = jContent.getJSONObject(iterate);
                        String inner_label = (String) inner.get("label");

                        System.out.println(inner_label);

                        String val = (String) inner.get("value");
                        boolean sel;
                        try {
                            sel = (boolean) inner.get("selected");

                        } catch (JSONException j) {
                            sel = false;
                        }
                        System.out.print(inner_label);
                        System.out.print(" " + val);
                        System.out.println(" " + sel);

                    }


text:
Q: what kind of type should I use in java to call this C function with JNI? I get this problem when I wanna call a native C function in java on android use JNI. I pass a pointer to structure as a parameter in that C function, and allocate memory to that pointer.
So please tell me how can I call this C function in java? I googled for a long time but get no rewards.
Codes like this, A is the name of structure :
JNIEXPORT int JNICALL
Java_pkgname_NativeTools_create(JNIEnv *env, jclass jclazz, A **ptr) {
    *ptr = (A*) malloc(sizeof(A));
    if (*ptr != NULL ) {
        return 0;
    } else {
        return -1;
    }
}

and I don't know how to write the native interface :
public class NativeTools{
    static {
        System.loadLibrary("LibName");
    }

    // TODO don't know what type in JNI should I use to declare this native function?
    public static native int create(?);
}

thanks a lot and sorry for my poor english :(

A: You can't do it like this. You can use only JNI datatypes as C function parameters. Anyway, there is nothing like structs or even pointers in Java. What was it, that you wanted to create on Java side and then "pass it to C" ? The nearest to pointer you could get is a reference type jobject, but C doesn't understand it as simply as you tried. It's a reference to JVM object, not C struct. It's only meant as a parameter to further JNI calls (which calls back to JVM).
There are tools which could help you improving the datatype interoperability (SWIG,JNA), but given the apparent fundamental misunderstanding, you should start with some basic reading:
http://192.9.162.55/docs/books/jni/html/jniTOC.html

(can't do a proper link, SO forbids IP addresses)


text:
Q: How to customize silly "Hello from Twilio!" SMS reply? (sent out when recipient doesn't use known keyword) I'm sending out SMS in an application. Some portion of the users use the well known unsubscribe keywords like STOP, stop and alike. Some people reply back like there was human on the other end. Like "Why am I getting this message".
Here comes the interesting thing: in such case Twilio replies with a silly "Hello from Twilio!" SMS, which confuses the recipient even more (the recipient is involved with a service with company X and doesn't know at all that we use Twilio for SMS delivery).
Where can I change that message? I'm using the Twilio API to send SMS from our back-end, I don't have any messaging service configured (and I don't even want to have any unless I have to) just as I don't want any "Advanced Opt-Out for Messaging Services" because I don't want to override or customize any unsubscribe keywords or anything. I just want to have a more meaningful reply SMS than the silly "Hello from Twilio!".

A: Twilio developer evangelist here.
In your phone number configuration, which you can find by navigating to your list of phone numbers then clicking on the phone number, you can scroll down to find the messaging section. It looks a bit like this:

You may have a demo URL set in the field for what happens when "A message comes in". That demo URL is likely returning the "Hello from Twilio!" response to incoming messages.
To override this, you can either remove the URL entirely, or set it to your own response. You can use this to alert your users that the number is not monitored, or just not respond. To do this, I'd recommend using a TwiML Bin as they let you host static TwiML that can react like this.
If you want to use a TwiML Bin to stop the number responding at all, set up a TwiML Bin with this TwiML:
<Response/>

If you'd like to send a message of your own in response, use this TwiML:
<Response>
  <Message>Thanks for messaging, but messages to this number are not monitored. If you want to opt out of messages, send STOP.</Message>
</Response>

Fill in your own message, of course.