text:
Q: Java GC Threading Bottleneck in Practice? How well optimized is Java's parallel collecting GC for multithreaded environments?  I've written some multithreaded Jython code that spends most of its time calling Java libraries.  Depending on which options I run the program with, the library calls either do tons of allocations under the hood or virtually none.  When I use the options that require tons of heap allocations, I can't get the code to scale past 6 cores.  When I use the options that don't require lots of allocations, it scales to at least 20.  How likely is it that this is related to a GC bottleneck, given that I'm using the stock Sun VM, the parallel GC and Jython as my glue language?
Edit:  Just to clarify, I won't necessarily think of stuff that's obvious to Java veterans because I almost never use Java/JVM languages.  I do most of my programming in D and the flagship CPython implementation of Python.  I'm using the JVM and Jython for a small one-off project b/c I need access to a Java library.

A: Since your question is about GC bottlenecks: you can eliminate that possibility by turning on GC logging and checking the logs - if there are large number of GC events with large pauses you can confirm/discount this theory. (However, in the scenario you describe, i would guess it is not a GC issue).

A: To me, problems with GC and multithreading are very real. I'm not saying the JVM is bad, it's just that the problem itself is very hard to deal with.
In one of our project, we had two applications running in a single JVM (app. server). When stressing them individually that was fine, but when both were stress together performance degraded in strange way. We finally split the apps. in two JVMs, and performance went back to normal (of course slower than when only one app was use, but reasonable).
Tuning the GC is extremely hard. Things can improve for 5 minutes, and then a major collection will block, etc. You might decide whether you want high throughput or low latency in the operations. High throughput is fine for batch processing, low latency is necessary for interactive application. Ultimately, the default parameters of the JVM were for us the one giving the best results!
That's not really an answer, rather a return on experience, but yes, to me GC and multi threading might be an issue.

A: The Java GC is generational. A collection of first generation is meant to take care of short-lived objects and is expected to run frequently. Running for a short interval several times per second is the expected behaviour if there are many short-lived allocations. (This should be a comment rather than an answer - I have no rep, sorry).
Also, depending on which VM you are using, you can choose between GC algorithms. The options will vary depending on which version and vendor of the VM you are using.
Some (old) info is here: http://java.sun.com/developer/technicalArticles/Programming/turbo/#The_new_GC

A: Threading performance can vary from one jdk version to another. In my experience, on jdk6u18, the parallel gc, enabled with -XX:+UseParallelGC (not the concurrent mark sweep gc), performs very well on a quad core with hundreds of very active threads. I consider it very unlikely that it would not scale beyond 6 cores.
The fact that Sun's hardware is based on processors with a high number of cores explains why they've put a lot of effort in new garbage collectors in recent years.
The parallel gc is not enabled by default because its single threaded performance is not as good as the default gc.


text:
Q: How to get _value properties in Vue 3 ref Hi I'm trying to get values from the _value property in Vue to no avail. How am I able to grab these values like accessKey, align, ariaAtomic etc. I'm trying to get the clientWidth.

Test

  const theRange = ref(null);
  console.log(theRange.value.clientWidth); // Throws error

A: This is how you can get it

<template>

nice

</template>

Here is an example.

Regarding Vue's lifecycle hooks, setup() doesn't have the element attached to the DOM yet, hence why you may not have anything regarding window-related properties of your object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is back emf of bldc trapezoidal? I am trying to understand why would the back emf in bldc be trapezoidal. Lets consider a simple motor with two stator coils placed opposite to each other. Lets say a bar magnet is kept as a rotor. If i manually crank the bar magnet and rotate it, then the back emf observed seems to be trapezoidal as per my reading. However, i have an alternate thought. If voltage induced in a coil is supposed to be proportional to rate of change of magnetic flux linkage, then when the bar magnet pole sweeps a coil area during its rotation, this should result in a constant voltage in the coil since field in coil due to magnet increases linearly as magnet pole approaches the coil. And when the pole moves away from the coil, as magnetic flux linkage decreases linearly, there would be negative voltage. Once bar magnet pole passes the coil area completely , then there will be no change in magnetic field  in the coil hence zero bemf. This results in a positive and negative pulse followed by zero voltage bemf. Why does the bldc emf not behave the way i mentioned?

A: For best performance, the drive current should match the back EMF waveform, whether it is trapezoid or sinusoid.
As the leading edge of a rotor pole or moving magnet leaves the stator fixed pole surface the amplitude drops at a linear rate according to the surface velocity of the rotor.  While the rotor pole surface is  smaller than the stator magnetic field, if/when they overlap for some distance, then the BEMF is constant during that arc path.
REF

Then a 3 phase


text:
Q: Blocks, Thread-safety, and NSMutableDictionary I am adding objects to the same NSMutableDictionary from several different blocks in Objective-C.  These blocks are all callback functions for some other process; that is, they will be called at some undetermined point in the future when the original process has finished.
My concern has to do with possibility of the NSMutableDictionary being operated on by two different blocks at the same time.  I know that if the two blocks are run on different threads, then this is a legitimate concern.  I just want to know if blocks are always run on different threads, making this a concern whenever I use blocks at all.

A: No, blocks are not always run on different threads. It depends entirely on what the block is and how you schedule it to be executed. Are you executing it yourself, adding it to an operation queue, using a GCD queue. The block could be run on any thread, including the main thread. You have control over whether it is run on the main thread or a background thread.
ThreadSafety


text:
Q: ignore missing files in loop - data did not show up I have thousands of files as you can see the year range below. Some of the dates of the files are missing so I want to skip over them. But when I tried the method below, and calling data_in, the variable doesn't exist.  Any help would be truly appreciated. I am new to python. Thank you.
path = r'file path here'
DataYears = ['2012','2013','2014', '2015','2016','2017','2018','2019', '2020']
Years = np.float64(DataYears)
NumOfYr = Years.size
DataMonths = ['01','02','03','04','05','06','07','08','09','10','11','12']
daysofmonth=[31,28,31,30,31,30,31,31,30,31,30,31]
for yy in range(NumOfYr):
    for mm in range (12):
        try:
            data_in = pd.read_csv(path+DataYears[yy]+DataMonths[mm]+'/*.dat', skiprows=4, header=None, engine='python')
            print('Reached data_in') # EDIT
            a=data_in[0] #EDIT
        except IOError:
            pass
            #print("File not accessible")

EDIT: Error added
Traceback (most recent call last):

  File "Directory/Documents/test.py", line 23, in <module>
    data_in = pd.read_csv(path+'.'+DataYears[yy]+DataMonths[mm]+'/*.cod', skiprows=4, header=None, engine='python')

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 448, in _read
    parser = TextFileReader(fp_or_buf, **kwds)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 880, in __init__
    self._make_engine(self.engine)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1126, in _make_engine
    self._engine = klass(self.f, **self.options)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 2269, in __init__
    memory_map=self.memory_map,

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/common.py", line 431, in get_handle
    f = open(path_or_buf, mode, errors="replace", newline="")

FileNotFoundError: [Errno 2] No such file or directory: 'Directory/Documents/201201/*.dat'

A: You can adapt the code below to get a list of your date folders:
import glob

# Gives you a list of your folders with the different dates
folder_names = glob.glob("Directory/Documents/")
print(folder_names)

Then with the list of folder, you can iterate through there contents. If you just want a list of all .dat files can do something like:
import glob

# Gives you a list of your folders with the different dates
file_names = glob.glob("Directory/Documents/*/*.dat")
print(file_names)

The code above searches the contents of your directories so you bypass your problem with missing dates. The prints are there so you can see the results of glob.glob().


text:
Q: How to validate array in Laravel with Request? I send to Laravel this JSON data:
[
  {"name":"...", "description": "..."},
  {"name":"...", "description": "..."}
]

I have a StoreRequest class extends FormRequest:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
        ];
    }
}

In my controller I have this code, but it doesn't work with array:
    public function import(StoreRequest $request) {
        $item = MyModel::create($request);

        return Response::HTTP_OK;
    }

I found this solution to handle arrays in the Request rules():
    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'name.*' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
            'description.*' => 'nullable|string|max:65535'
        ];
    }

How can I update the StoreRequest and/or the import() code to avoide duplicate lines in rules()?

A: As you have an array of data you need to put * first:
public function rules()
{
   return [
       '*.name' => 'required|string|min:1|max:255',
       '*.description' => 'nullable|string|max:65535',
   ];
}


text:
Q: java spring application with c3p0 pool generate java.lang.SQLException : some resource failed to close properly while closing we are using spring with c3p0 as the database pool, we use oracle 10g as the database.
when we launch the application,it continues show following error
 2012-5-7 13:12:43 com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask run
 Warning: Failed to destroy resource: com.mchange.v2.c3p0.impl.NewPooledConnection@20af46
 java.sql.SQLException: Some resources failed to close properly while closing com.mchange.v2.c3p0.impl.NewPooledConnection@20af46
  2012-5-7 14:45:51 com.mchange.v2.c3p0.impl.NewPooledConnection logCloseExceptions
  Info: [c3p0] Exceptions occurred while trying to close a PooledConnection's resources normally.
  2012-5-7 14:45:51 com.mchange.v2.c3p0.impl.NewPooledConnection logCloseExceptions
  Info: [c3p0] NewPooledConnection close Exception.
  java.sql.SQLException: More data can not be read from the socket
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1123)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1075)
    at oracle.jdbc.driver.T4C7Ocommoncall.receive(T4C7Ocommoncall.java:106)
    at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:465)
    at oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:1203)
    at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:549)
    at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:234)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.destroyResource(C3P0PooledConnectionPool.java
    at com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask.run(BasicResourcePool.java:964)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)

 In oracle trace file,we found the following error
  *** 2012-05-07 11:50:56.421
   ksedmp: internal or fatal error
   ORA-07445: An unexpected error: core dump [ACCESS_VIOLATION] [_evaopn2+153] [PC:0x1BBDFA9] [ADDR:0x0] [UNABLE_TO_READ] []
   Current SQL statement for this session:

Is the oracle error cause the above reason.we take a lot of time to find the problem but we have not found the problem. before we are using oracle 9i,and it did not have the problem.recently we upgrade to oracle 10g.where will be the problem? any idea will be very helpful.thanks!
    the c3p0 we used is com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar.


text:
Q: UIButton changing width when label changes I'm writing a calculator app with a shift key. When the shift key is pressed, some of the UIButtons' labels should change. The problem is that when they do, the widths also change and, because of certain design constraints, other buttons will resize themselves too. How to I lock the width of a button (either pragmatically or in the storyboard builder) so that it will never change (regardless of the contents of the button)
Thanks for any help in advance.

A: Buttons, like labels have an intrinsic size that's set by the width of their text plus some padding. If you want them to have a fixed width, then in IB, just give each button an explicit width from the menu, Editor --> Pin --> Width.

A: Have you tried using [button sizeToFit]? Call it after you resize the subviews within and then you will likely want to apply some "padding" as this will size the view to exactly fit it's subviews.
UIView sizeToFit


text:
Q: Bar chart reduce number of labels by creating Others pretty new in excel and I'm currently working on a pivot table and want to create a bar chart.
I have around 15 row labels and 2 columns- row labels and percentages that looks something like this:
apples     0.1%
apricots   0.28%
guava      1.7%
.
.
.
.

oranges    40.25%

When I create a bar chart, it looks too much having too many on the y axis, so I want to create a label "Others" that is basically the sum of specific rows of the percentages in this case when the value is too small.
So I want it to look like
others        7.00%
kiwis        12.50%
pineapples   15.25%
grapes       25.00%
oranges      40.25%

A: Suppose you have a pivot table like this:

Put your cursor in the values column (column E in the picture above).
Then right click, Sort, Sort smallest to largest. Like this:

Now in the column that says "Row Labels", select the fruits you want to group as others. Then right-click and select 'Group'. Like this:

It will create a new level in the Row Labels column. You can see that it has grouped the selected fruits.
Type over the new group name with the name you want to use.
In my example, I typed 'Others' in cell D2:

Now right-click the original level of fruit name (the ones that aren't bold in the image above) and click on 'Remove "fruit"' (or whatever your column name is). This will leave you with this:

Now use Insert>Pivot Chart

If you want to change the order of the columns, you can optionally sort the items in the pivot table (either manually or A-Z or Z-A).


text:
Q: R use value of a variable as a data frame column name I am guessing this is simple for an experienced used...how can I use the value of a variable to assign it as a data frame column name?  Say I have a simple data frame df as below, and a variable n that changes value based on user input.  How could I insert a new data frame column  which has as it's name the value of n?  I would also ideally like to concatenate the value of n with a simple string.  Thank you.
df<-data.frame(a=c(1,1,1),b=c(2,2,2))

  a b
1 1 2
2 1 2
3 1 2

When I simply try to assign a new column as
n<-15
df$n<-c(3,3,3)

the name of the column is simply n.
  a b n
1 1 2 3
2 1 2 3
3 1 2 3

A: It's not the best idea to name a column with a number, but this will work:
df[,paste(n)] <- c(3,3,3)

A: You could also do:
 df <- cbind(df,c(3,3,3))
 names(df)[ncol(df)] <- n

Although, as previously pointed out, it is not good practice to give numbers as column names.


text:
Q: Problema ressetar $_POST Pessoal to com um problema nesse trecho de código, ele avalia se existe a variável $_POST['employee_id'] caso existir ela ira dar um update, se não existir ele da um insert! até ai tudo bem tudo funcionando, porem se eu der um update e depois for dar um insert ele executa o update no lugar do insert, acho porque a variável $_POST['employee_id'] deve ter ficado na memoria, lembrando que isso tudo ocorre via ajax sem refresh na pagina, já pesquisei sobre isso e não consegui resolver ja tenter dar unset na $_POST setala como um array null, como vcs podem vem... porem nada funcionou, Agradeço desde já!
// Se update
if(isset($_POST['employee_id']) AND $_POST['employee_id'] != '') {
    $id = $_POST['employee_id'];
    $user = Container::getModel("Client");
    $this->view->clients = $user->update($data, $id);

    if(isset($this->view->clients)){
        unset($_POST['employee_id']);
        $_POST = array();
        echo json_encode(["update"=>true,"msg"=>"Cadastro atualizado com sucesso!"]);exit;
    }else{
        echo json_encode(["status"=>false,"msg"=>"Desculpe ocorreu um Erro!"]);exit;
    }
// Se não insert
}else{
    $user = Container::getModel("Client");
    $this->view->clients = $user->insert($data);
    if(isset($this->view->clients)){
        $this->view->last_client = $user->find($this->view->clients);
        echo json_encode(["insert"=>true,"msg"=>"Cadastro realizado com sucesso!","clients"=>$this->view->last_client]);exit;
    }else{
        echo json_encode(["status"=>false,"msg"=>"Desculpe ocorreu um Erro!"]);exit;
    }
}

A: Resolvido com um simples $('#employee_id').val('');, Agradeço!


text:
Q: How to silence exception stack trace from Play framework stdout I'm receiving a,
java.lang.NullPointerException
    at play.core.server.netty.RequestBodyHandler$class.finish$1(RequestBodyHandler.scala:70)
    at play.core.server.netty.RequestBodyHandler$$anonfun$pushChunk$1$2$$anonfun$apply$2.apply(RequestBodyHandler.scala:53)
    at play.core.server.netty.RequestBodyHandler$$anonfun$pushChunk$1$2$$anonfun$apply$2.apply(RequestBodyHandler.scala:49)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:29)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

printed to the console when reloading a page in the Play framework. The cause is irrelevant for the purpose of this question. I've tried to suppress the message but can not seem to figure it out. Even with ALL logback logging turned OFF this is the only message that is still printed.
Where is it coming from and how do I stop it?

A: My guess is there is some code that is calling Exception.printStackTrace() rather that utilizing the logger. I did a quick google to figure out how to redirect standard error to a logger, but didn't immediately find the solution for ya. I know that log4j can do this.


text:
Q: How To Using Dataflow With Only BroadcastBlock And ActionBlock This is my first question in SO, i'm new using DataFlow with BroadcastBlock and ActionBlock, i hope i can get solution in here.
Here's the structure.
Model
class SampleModel
{
    public string Id { get; set; } = Guid.NewGuid().ToString();
    public bool Success { get; set; } = true;
    public object UniqueData { get; set; }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"Id - {Id}");
        sb.AppendLine($"Success - {Success}");
        sb.AppendLine($"UniqueData - {UniqueData}");
        string tmp = sb.ToString();
        sb.Clear();
        return tmp;
    }
}

DataFlow Logic
class CreateDownloadTask
{
    public async Task VeryLongProcess()
    {
        await Task.Run(async () =>
        {
            Console.WriteLine("Long Process Working..");
            await Task.Delay(TimeSpan.FromSeconds(5));
            Console.WriteLine("Long Process Done..");
        });
    }

    public async Task CreateSimpleBroadcastX<T>(T data)
    {
        Action<T> process = async model =>
        {
            Console.WriteLine("Working..");
            await VeryLongProcess();
            Console.WriteLine("Done");
        };

        var broad = new BroadcastBlock<T>(null);

        var action = new ActionBlock<T>(process);

        var dflo = new DataflowLinkOptions { PropagateCompletion = true };

        broad.LinkTo(action, dflo);

        await broad.SendAsync(data);

        broad.Complete();

        await action.Completion.ContinueWith(async tsk =>
        {
            Console.WriteLine("Continue data");
        }).ConfigureAwait(false);

        Console.WriteLine("All Done");
    }
}

Caller
var task = cdt.CreateSimpleBroadcastX<SampleModel>(new SampleModel
{
    UniqueData = cdt.GetHashCode()
});
task.GetAwaiter().GetResult();
Console.WriteLin("Completed");

I expect the result should be
Working..
Long Process Working..
Long Process Done..
Done
Continue data
All Done
Completed

But what i've got is
Working..
Long Process Working..
Continue data
All Done
Completed
Long Process Done..
Done

This is happen when ther is async-await inside of ActionBlock.
Now, the question is, is that possible to make the result as i expected without WaitHandle ?
That mean, ActionBlock.Completion will be wait until the Action or Delegate inside the ActionBlock is complete executed?
Or i'm i doing it wrong with that patter?
Thanks in Advance, and sorry for my bad english.

A: Your problem is here:
Action<T> process = async model => ...

That code creates an async void method, which should be avoided. One of the reasons you should avoid async void is because it is difficult to know when the method has completed. And this is exactly what is happening: the ActionBlock<T> cannot know when your delegate has completed because it is async void.
The proper delegate type for an asynchronous method without a return value that takes a single argument is Func<T, Task>:
Func<T, Task> process = async model => ...

Now that the asynchronous method returns a Task, the ActionBlock can know when it completes.


text:
Q: sh file can't work well but commands in sh can I'm using a bash shell to export some path,like this:
env.sh:
 export GOPATH=$GOPATH:$QBOXROOT/pili-zeus
 export PATH=$PATH:$QBOXROOT/pili-zeus/bin

after call sh env.sh,I call echo $GOPATH ,but nothing output,and I call export again to check the variables exported,but GOPATH isn't included.But when I copy these commands in the shell file,and execute them directly in command line,it can work!why this happens?I'm using mac.

A: You need to use source env.sh to get these variables stick to your context (i.e. terminal).
"source is a Unix command that evaluates the file following the command, as a list of commands, executed in the current context."
https://en.wikipedia.org/wiki/Source_(command)


text:
Q: ComboBox value is not updated on a event wxpython I am creating a ComboBox as:
combo= ['a', 'b', 'c']
self.stm_checkpoint_drop=wx.ComboBox(self.panel, -1, value='Options', choices=combo)
self.stm_checkpoint_drop.Bind(wx.EVT_COMBOBOX, self.oncombo)

def oncombo(self,event):
    selected = self.stm_checkpoint_drop.GetValue()

Variable selected remains the default value 'Options'. How do I get the value selected from the combo list stored in variable selected.

A: Not sure exactly why your code isn't working, there does not seem to be an obvious error. Check if this works and check against your code.
import wx

class Myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.my_choices = ["Option A","Option B","Option C"]
        self.panel = wx.Panel(self)
        self.cbx = wx.ComboBox(self.panel, -1, value="Choose an Option", pos=(10,30), size=(300,30),choices=self.my_choices)
        self.cbx.Bind(wx.EVT_COMBOBOX, self.on_selection)
        self.txt1 = wx.TextCtrl(self.panel, -1, "Selected Value", pos=(10,100), size=(300,30))
        self.txt2 = wx.TextCtrl(self.panel, -1, "Selected Selection", pos=(10,130), size=(300,30))
        self.txt3 = wx.TextCtrl(self.panel, -1, "Selected String", pos=(10,160), size=(300,30))

    def on_selection(self, evt):
        Choice = self.cbx.GetValue()
        self.txt1.SetValue(Choice)
        Choice = self.cbx.GetSelection()
        self.txt2.SetValue(str(Choice))
        Choice = self.cbx.GetStringSelection()
        self.txt3.SetValue(Choice)

if __name__ == "__main__":
    App = wx.App()
    Myframe().Show()
    App.MainLoop()


text:
Q: jqGrid - inline edit can not save result to database after edit I'm new to use jqGrid and there is a problem when I try to use the inline edit feature. Here is my code:

        My First Grid
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />

The problem is it could edit the row when I click it, and also can save temporarily after I press the enter. But when I reload the grid, it still shows the previous data before I eidt, which means it doesn't update the database. I wonder why and how to solve it?
Here is the example.php code:
    <?php
include("dbconfig.php");
$page = $_GET['page'];
$limit = $_GET['rows'];
$sidx = $_GET['sidx'];
$sord = $_GET['sord'];

if (!$sidx)
    $sidx = 1;

$db = mysql_connect("$dbhost", "$dbuser", "$dbpassword") or die("Connection Error: " . mysql_error());

mysql_select_db("$database") or die("Error connecting to db.");

$result = mysql_query("SELECT COUNT(*) AS count FROM app");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $row['count'];

if ($count > 0 && $limit > 0) {
    $total_pages = ceil($count / $limit);
} else {
    $total_pages = 0;
}

if ($page > $total_pages)
    $page = $total_pages;

$start = $limit * $page - $limit;

if ($start < 0)
    $start = 0;

$SQL = "SELECT id, name, status FROM app";
$result = mysql_query($SQL) or die("Couldn't execute query." . mysql_error());

header("Content-type: text/xml;charset=utf-8");

$s = "<?xml version='1.0' encoding='utf-8'?>";
$s .= "<rows>";
$s .= "<page>" . $page . "</page>";
$s .= "<total>" . $total_pages . "</total>";
$s .= "<records>" . $count . "</records>";

// be sure to put text data in CDATA
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $s .= "<row id='" . $row['id'] . "'>";
    $s .= "<cell>" . $row['id'] . "</cell>";
    $s .= "<cell>" . $row['name'] . "</cell>";
    $s .= "<cell>" . $row['status'] . "</cell>";
    $s .= "</row>";
}
$s .= "</rows>";
echo $s;
?>

A: First of all you should change the code
onSelectRow: function(id){
    if(appid && appid!==lastsel2){
        jQuery('#list').restoreRow(lastsel2);
        jQuery('#list').editRow(id,true);
        lastsel2=id;
    }
}

to something like
onSelectRow: function (id) {
    if (id && id !== lastsel2){
        jQuery('#list').restoreRow(lastsel2);
        jQuery('#list').editRow(id,true);
        lastsel2 = id;
    }
}

because currently you use undefined appid instead of id.
Moreover you should remove trailing comma at the end of colModel definition: change },] to }] and place semicolon after var lastsel2.


text:
Q: Transferring images to/from Android App through Cloud Endpoints to App Engine back-end I'm currently working on an app that requires images to be passed to and from an App engine back-end. Originally I planned on sending the images (they are only small - max 100kb - average 20kb) directly through the endpoint however when sending the data as a byte array through the endpoint I receive a JSON error (from the rest API) stating that the data has an invalid character. Is there a way around this?
My second attempt was to use use the BlobService and return an upload URL to the client using the below code:
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
UploadOptions uploadOptions = UploadOptions.Builder.withGoogleStorageBucketName("bucketname").maxUploadSizeBytes(1048576);
String url = blobstoreService.createUploadUrl("/uploaded", uploadOptions);

Then using a HTTP post on the android device to upload the image:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("data", new ByteArrayBody(data,"image/png","img.png"));
httppost.setEntity(entity);
String res = EntityUtils.toString( httpclient.execute(httppost).getEntity(), "UTF-8");

This seems to work and the image is uploaded. However, I have no idea how to get the blobkey of this uploaded image. Does anyone know? Also, the result from the HTTP post is a 404 error - because the "/uploaded" page does not exist I'm guessing?
Thirdly, when manually typing in the blobkey and using it to return and image serving url with this code:
    private String getImage(){
        return getThumbUrl(new BlobKey("encoded_gs_key:ZGNpbWcxMy93czZwZ2lUeXdpY0xvZ2xtZGpHZ2dn"));
    }

    private String getThumbUrl(BlobKey blobkey){
        ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(blobkey);
        try {
            return ImagesServiceFactory.getImagesService().getServingUrl(options);
        } catch(IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        } catch(ImagesServiceFailureException e) {
            e.printStackTrace();
            return null;
        }
    }

I receive the URL of the image however the image colors are all messed up. I am uploading indexed pngs... I'm not sure if the ImageService can handle them correctly. If it cant, how do I go about serving the image directly i.e. not through the ImageService but through BlobstoreService.serve()?
Here is an image of the resultant picture from the ImageService URL: http://i.imgur.com/EhfkJ9j.png
Cheers,
Ben

A: About the blob key, when you create the upload url you pass a paramenter with the name of your appengine page that gets called after upload. You need to implement that page ("uploaded") https://developers.google.com/appengine/docs/java/blobstore/#Java_Uploading_a_blob


text:
Q: Powershell: Copying a file to remote server using New-PSDrive I need to copy a file from my Windows server to another remote server using Webdav.
The first thing I do is map a network drive in PowerShell:
[String]$WebDAVShare = '\\xxx.xxxxx.xxx@SSL\DavWWWRoot\webdav'
New-PSDrive -Name "W" -PSProvider FileSystem -Root $WebDAVShare -Credential $cred

This works, I can see all remote files and dirs when I do a list. Now, when I want to copy a file I get an error:
Copy-Item ImportSheets\ToDo\xxxxx.xls -Destination W:\import\xxxxx.xls

Copy-Item : A device attached to the system is not functioning.
At D:\Automation-Scripts\drive.ps1:35 char:6
+      Copy-Item ImportSheets\ToDo\xxxxx.xls -Destination W ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand

Also when I try to copy the file in Python I get an error:
shutil.copy('ImportSheets\ToDo\xxxxx.xls', 'W:\import\xxxxx.xls')

or
copyfile('ImportSheets\\ToDo\\UHA_HP_DM_Autobot.xls', 'W:\\import\\UHA_HP_DM_Autobot.xls')

results in

FileNotFoundError: [Errno 2] No such file or directory: 'W:\\import\\xxxxx.xls'

I don't mind if the solution is in PowerShell or Python.


text:
Q: ESP32 - Guru Meditation Error when External load is plugged in I would like to power following ultrasonic sensor using the ESP32:
https://www.maxbotix.com/documents/HRXL-MaxSonar-WRS_Datasheet.pdf
Using this Heltec ESP32 board:
https://heltec.org/project/wireless-stick-lite/
This board comes with an 3.3V switch denoted as Vext or Ve that is controlled by GPIO Pin 21.
Everything works quite nicely besides it throws me an error if I plug in an external sensor on the Vext pin:
https://www.maxbotix.com/documents/HRXL-MaxSonar-WRS_Datasheet.pdf
The external sensor is an ultrasonic sensor with a nominal current consumption of below 3mA.
Please see the error here:

For the Vext pin, the error always occurs but strangely the error even occurs if I unplug the device during operation and plug it into the 3.3V port of the board.
This question is probably entirely related to the hardware design of the specific board but eventually you have some ideas why this Guru Meditation error can happen. Eventually due to some voltage spikes that occur while plugging the sensor in or off?
I can probably find a stable solution if I just leave the setup alone but I haven't experienced that error related to power issues.
Thank you!

A: Thank you @Codo : I've installed an ESP32 Backtrace program:
https://github.com/me-no-dev/EspExceptionDecoder
https://github.com/platformio/platform-espressif32/issues/105
https://github.com/me-no-dev/EspExceptionDecoder/issues
https://github.com/me-no-dev/EspExceptionDecoder/issues/26
And get some more information now from the Backtrace.


text:
Q: Calculate the sum of positive values smaller or equal to a number I am trying to calculate the sum of positive values smaller or equal to the entered number, for ex: 5 -> 1+2+3+4+5 = 15
I came up with this:

var num = Number(prompt("Enter a number "));
sum = 0;
i = num;

do {
    sum = sum += i;
    i--
    document.write(sum);
 } while (i > 0);

I don't understand what I am doing wrong.

A: i think this is correct code:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do
{
  sum += i;
  i--;
}
while (i > 0);
document.write(sum);

and i suggest you to use this formula : document.write((num * (num + 1)) / 2);

A: If you look closer to your task, you'll find out, that:
If Num = 1, the sequence to be summed is [1]
if Num = 2, the sequence is [1, 2]
if Num = 3, the sequence is [1, 2, 3]
You can imagine, that you have a square with sides equal to num, for example, when num = 4:
****
****
****
****

And you need to summ 1, 2, 3, 4:
***#
**##
*###
####

See? It's a square of a triangle.
It could be calculated by formula: num * (num + 1) / 2
So, you code could be:
var num = Number(prompt("Enter a number "));
document.write(num * (num + 1) / 2)

A: You should write the answer at the end of loop and make this simple sum += i;.

var num = Number(prompt("Enter a number"));
sum = 0;
i = num;
do {
  sum += i;
  i--;
}

while (i > 0);
document.write(sum);

A: You are writing the sum on each loop instead you have to print it finally. If you want to print the numbers then keep it an array and join them with + symbol before writing. To make it in ascending order change the loop condition.

var num = Number(prompt("Enter a number "));
sum = 0;
i = 1;
nums = [];
do {
  sum = sum += i;
  nums.push(i++);
}

while (i <= num);

document.write(nums.join(' + ') + ' = ' + sum);

A: Do with increment instead of decrements.And also show result of sum outside of loop .Not with in loop.And create array to append increment value.Finally print with document.write

var num=Number(prompt("Enter a number "));
sum = 0;
i = 1;
var a=[];
do {
   sum +=i;
   a.push(i)
   i++;
 }
 while (num >= i);
 document.write(a.join('+')+'='+sum)

A: var number = 5, // Your number
    result = 0;

while ( number !== 0 ) {
    result += number;
    number--;
}

document.write(result);

Fast and precious solution.

A: Here is the case with complete check and display as you need: JAVA
     public static void main ( String arg[]) {

    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();
    System.out.println("Number entered :  " + number);
    int sum =1 ;

    if(number > 1) {

        int nextNumber = 1;
        System.out.print(nextNumber);

        do {
            // sum of all the positive numbers
            nextNumber++ ;
            sum = nextNumber + sum;
            System.out.print( " + " + nextNumber);

        }while(nextNumber < number);

        System.out.print(" = " + sum);
    }
}

A:

var num = Number(prompt("Enter a number"));
sum = 0;

for (i = num; i > 0; i--) {
  sum += i;

}

document.write(sum);


text:
Q: Python Paramiko - Run command I'm try to run this script:
hostname = '192.168.3.4'
port = 22
username = 'username'
password = 'mypassword'
y = "2012"
m = "02"
d = "27"

if __name__ == "__main__":
   s = paramiko.SSHClient()
   s.load_system_host_keys()
   s.connect(hostname, port, username, password)
   command = 'ls /home/user/images/cappi/03000/y/m/d'
   s.close

The question is:
how can I put the variables y,m,d into the variable command ?

A: command = 'ls /home/user/images/cappi/03000/%s/%s/%s' %(y,m,d)

A: Using the new format specifications, you can access arguments by name:
'ls /home/user/images/cappi/03000/{year}/{month}/{day}'.format(year=y, month=m, day=d)

A: Python has lots of ways to perform string formatting.  One of the simplest is to simply concatenate the parts of your string together:
#!/usr/bin/env python
import paramiko

hostname = "192.168.3.4"
port = 22
username = "username"
password = "mypassword"
y = "2012"
m = "02"
d = "27"

def do_it():
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    command = "ls /home/user/images/cappi/03000/" + y + "/" + m + "/" + d
    stdin, stdout, stderr = s.exec_command(command)
    for line in stdout.readlines():
        print line
    s.close()

if __name__ == "__main__":
    do_it()

A: I prefer
command = f"ls /home/user/images/cappi/03000/{y}/{m}/{d}"


text:
Q: C: Reading file with a starting point A simple question but I can't find the answer in my book. I want to read a binary file to seed a random number generator, but I don't want to seed my generator with the same seed each time I call the function, so I will need to keep a variable for my position in the file (not a problem) and I would need to know how to read a file starting a specific point in the file (no idea how). The code:
void rng_init(RNG* rng) {
  // ...

  FILE *input = fopen("random.bin", "rb");
  unsigned int seed[32];
  fread(seed, sizeof(unsigned int), 32, input);

  // seed 'rng'...

  fclose(input);
}

A: You can use ftell() to read the current position of the file, and fseek() to jump to a specific position, e.g.
long cur = ftell(f);
fseek(f, 0, SEEK_START);   // jump to beginning
fread(...)
fseek(f, cur, SEEK_START); // returning to previous location.

A: You can use fseek to move to a random position within a file.
fseek takes a third parameter that tells what the position is relative to.
SEEK_SET - the absolute position from the start of the file
SEEK_CUR - the position relative to where you currently are in the file
SEEK_END - the position relative to the end of the file

A: Just fseek before you read anything!


text:
Q: VS Code Extension: How to make my extension load npm package from user workspace rather the bundled with my extension? I'm building a custom VS Code extension to some stuff. Basically, I'm relying on a few npm packages to get the job done.
But I would to like to do something like vscode-eslint extension does: if user have eslint package installed, it will use the local package instead the bundled one.
Basically I want to do this behavior:

Would this be possible with VSCode?
PS: I tried to study vscode eslint extension, but I was not able to understand how it handles this situation.


text:
Q: Spark streaming DStream RDD to get file name Spark streaming textFileStream and fileStream can monitor a directory and process the new files in a Dstream RDD.
How to get the file names that are being processed by the DStream RDD at that particular interval?

A: fileStream produces UnionRDD of NewHadoopRDDs. The good part about NewHadoopRDDs created by sc.newAPIHadoopFile is that their names are set to their paths.
Here's the example of what you can do with that knowledge:
def namedTextFileStream(ssc: StreamingContext, directory: String): DStream[String] =
  ssc.fileStream[LongWritable, Text, TextInputFormat](directory)
    .transform( rdd =>
      new UnionRDD(rdd.context,
        rdd.dependencies.map( dep =>
          dep.rdd.asInstanceOf[RDD[(LongWritable, Text)]].map(_._2.toString).setName(dep.rdd.name)
        )
      )
    )

def transformByFile[U: ClassTag](unionrdd: RDD[String],
                                 transformFunc: String => RDD[String] => RDD[U]): RDD[U] = {
  new UnionRDD(unionrdd.context,
    unionrdd.dependencies.map{ dep =>
      if (dep.rdd.isEmpty) None
      else {
        val filename = dep.rdd.name
        Some(
          transformFunc(filename)(dep.rdd.asInstanceOf[RDD[String]])
            .setName(filename)
        )
      }
    }.flatten
  )
}

def main(args: Array[String]) = {
  val conf = new SparkConf()
    .setAppName("Process by file")
    .setMaster("local[2]")

  val ssc = new StreamingContext(conf, Seconds(30))

  val dstream = namesTextFileStream(ssc, "/some/directory")

  def byFileTransformer(filename: String)(rdd: RDD[String]): RDD[(String, String)] =
    rdd.map(line => (filename, line))

  val transformed = dstream.
    transform(rdd => transformByFile(rdd, byFileTransformer))

  // Do some stuff with transformed

  ssc.start()
  ssc.awaitTermination()
}

A: For those that want some Java code instead of Scala:
JavaPairInputDStream<LongWritable, Text> textFileStream =
        jsc.fileStream(
            inputPath,
            LongWritable.class,
            Text.class,
            TextInputFormat.class,
            FileInputDStream::defaultFilter,
            false
        );
JavaDStream<Tuple2<String, String>> namedTextFileStream = textFileStream.transform((pairRdd, time) -> {
        UnionRDD<Tuple2<LongWritable, Text>> rdd = (UnionRDD<Tuple2<LongWritable, Text>>) pairRdd.rdd();
        List<RDD<Tuple2<LongWritable, Text>>> deps = JavaConverters.seqAsJavaListConverter(rdd.rdds()).asJava();
        List<RDD<Tuple2<String, String>>> collectedRdds = deps.stream().map( depRdd -> {
            if (depRdd.isEmpty()) {
                return null;
            }
            JavaRDD<Tuple2<LongWritable, Text>> depJavaRdd = depRdd.toJavaRDD();
            String filename = depRdd.name();
            JavaPairRDD<String, String> newDep = JavaPairRDD.fromJavaRDD(depJavaRdd).mapToPair(t -> new Tuple2<String, String>(filename, t._2().toString())).setName(filename);
            return newDep.rdd();
        }).filter(t -> t != null).collect(Collectors.toList());
        Seq<RDD<Tuple2<String, String>>> rddSeq = JavaConverters.asScalaBufferConverter(collectedRdds).asScala().toIndexedSeq();
        ClassTag<Tuple2<String, String>> classTag = scala.reflect.ClassTag$.MODULE$.apply(Tuple2.class);
        return new UnionRDD<Tuple2<String, String>>(rdd.sparkContext(), rddSeq, classTag).toJavaRDD();
});

A: Alternatively, by modifying FileInputDStream so that rather than loading the contents of the files into the RDD, it simply creates an RDD from the filenames.
This gives a performance boost if you don't actually want to read the data itself into the RDD, or want to pass filenames to an external command as one of your steps.
Simply change filesToRDD(..) so that it makes an RDD of the filenames, rather than loading the data into the RDD.
See: https://github.com/HASTE-project/bin-packing-paper/blob/master/spark/spark-scala-cellprofiler/src/main/scala/FileInputDStream2.scala#L278


text:
Q: Resolve route 53 private hosted zone names in my network I have created an AWS VPC and connected my network to it over VPN. I have a private hosted zone within route 53 and the DNS records in it resolve fine in my EC2 instances on the same VPC.
Is there any way to resolve these records from my network too, since they are connected over VPN?

A: The only way is to use the DNS server within the VPC; depending on what DNS server your using in your non-AWS network, there may be a way to configure it to forward requests to the AWS DNS server for the relevant private domain.


text:
Q: Ubuntu 12.04 --- grub-efi-amd64-signed failed to install into /target/ I have HP Pavillion 14-n009tu laptop (i-5, 4GB) with Windows-8 OS installed on it.
I am trying to install ubuntu 12.04 as a dual boot OS on Windows8.
I have disabled fast boot and secure boot options also.
I am facing following error while installing ubuntu 12.04:
grub-efi-amd64-signed failed to install into /target/. Without GRUB boot loader,
the installed system will not boot

I have created three partitions:

*

*38GB-ext4- Root mounted

*08GB-ext4- /home

*10GB Swap area

Please guide me how to resolve this problem.

A: Hey Ramji Had the exact same problem.
What fixed my problem was that i went through the steps again and made sure I was connected to the Internet the second time.
go through the process again (don't partition again because the hard drive is still partitioned ) but this time chose the option to format the partitions so that you erase the information that was loaded before the installation failed.
look at the comments here
Why 12.04 Fails to install grub-efi to /target/?
if you are still having problems follow this instructions
http://www.everydaylinuxuser.com/2013/09/install-ubuntu-linux-alongside-windows.html

A: I solved the problem by creating a 200MB FAT32 partition in the beginning of the disk with the flags boot and esp. Creating a partition with this configuration was suggested by boot-repair tool after I got the error you mentioned and I tried to fix it using such tool.
I hope this helps! Good luck!

A: It is a bug. If you are installing using a pendrive, just modify the filename grub-efi-amd64-signed_1.9~ubuntu12.04.4+1.99-21ubuntu3.10_amd.deb in directory /pool/main/g/grub2-signed/ by adding 64 at the end before .deb. It works 100%.
https://bugs.launchpad.net/ubuntu/+bug/1633913

A: I worked around this issue in Linux Mint 16 by running the following command before starting the install:
sudo dpkg --remove-architecture i386

It's probably caused by installing both 32- and 64-bit versions of all packages, in case only one of them exists (or maybe to support heterogeneous clusters that have both 32-bit and 64-bit CPUs). In the case of grub-efi-amd64 (which is part of grub-efi-amd64-signed), both versions exist, but they declare conflicts with each other so that they can't both be installed on the same system.

A: I had a same problem while installing Ubuntu 16.04 as well as while installing Mint.
The following steps fixed my problem:

*

*Install Ubuntu/Mint whichever you want (after the installation or in-between, you'll get this error).

*Start o. with live boot.

*Install boot repair.

*Follow steps in that.

That's it. Restart your PC and remember to remove the bootable medium you used.

A: Disable the "Fast Boot" and "secure Boot" options in Boot Options menu. Select Legacy Boot. Restart the installation process. Create a boot partition >1MB during installation. This solved the issue for me in UBUNTU 16.04 LTS installation.
Partitions created:
/boot       - 2048 MB
swap        - 10000 MB
/           - 50000 MB
/home       - 100000 MB
Marked remaining to be unused.


text:
Q: Show and hide a column based on value in filter in worksheet - Tableau 2022 I am new to Tableau development and have a requirement to show a column in the worksheet based on the value in a filter (unique value shown from the SQL table).
Let's say in the filter if I have selected "A" then I have to show all the columns and if I selected "B" then I have to hide 1 column in the worksheet.

A: You can configure this with the parameter in two different views.
If conditions first get enabled then View1 should show. else View2 should show.


text:
Q: Decomposing a number into powers of 2 Hi I need to decompose a number into powers of 2 in swift 5 for an iOS app I'm writing fro a click and collect system.
The backend of this system is written in c# and uses the following to save a multi-pick list of options as a single number in the database eg:
choosing salads for a filled roll on an order system works thus:
lettuce = 1
cucumber = 2
tomato = 4
sweetcorn = 8
onion = 16

by using this method it saves the options into the database for the choice made as (lettuce + tomato + onion) = 21 (1+4+16)
at the other end I use a c# function to do this thus:
for(int j = 0; j < 32; j++)
    {
    int mask = 1 << j;
    }

I need to convert this function into a swift 5 format to integrate the decoder into my iOS app
any help would be greatly appreciated

A: In Swift, these bit fields are expressed as option sets, which are types that conform to the OptionSet protocol. Here is an example for your use case:
struct Veggies: OptionSet {
    let rawValue: UInt32

    static let lettuce = Veggies(rawValue: 1 << 0)
    static let cucumber = Veggies(rawValue: 1 << 1)
    static let tomato = Veggies(rawValue: 1 << 2)
    static let sweetcorn = Veggies(rawValue: 1 << 3)
    static let onion = Veggies(rawValue: 1 << 4)
}

let someVeggies: Veggies = [.lettuce, .tomato]
print(someVeggies) // => Veggies(rawValue: 5)

print(Veggies.onion.rawValue) // => 16

OptionSets are better than just using their raw values, for two reasons:
1) They standardize the names of the cases, and gives a consistent and easy way to interact with these values
2) OptionSet derives from the SetAlgebra protocol, and provides defaulted implementations for many useful methods like union, intersection, subtract, contains, etc.
I would caution against this design, however. Option sets are useful only when there's a really small number of flags (less than 64), that you can't forsee expanding. They're really basic, can't store any payload besides "x exists, or it doesn't", and they're primarily intended for use cases that have very high sensitivity for performance and memory use, which quick rare these days. I would recommend using regular objects (Veggie class, storing a name, and any other relevant data) instead.

A: You can just use a while loop, like this :
var j = 0
while j < 32 {
    var mask = 1 << j
    j += 1
}

Here is a link about loops and control flow in Swift 5.

A: Hi I figured it out this is my final solution:
    var salads = "" as String
    let value = 127
    var j=0
    while j < 256 {

        let mask=1 << j
        if((value & mask) != 0) {
            salads.append(String(mask) + ",")
        }
        j += 1
    }
    salads = String(salads.dropLast()) // removes the final ","
    print(salads)

This now feeds nicely into the in clause in my SQL query, thanks you all for your help! :)


text:
Q: Sliding expiration with Spring Security I'm using Spring Security and I've noticed that, when a user logs in, the authentication cookie will be valid for about a day. It doesn't seem to 'refresh' this expiration date - the cookie expires after a day, even if 5 minutes before the end of that day I've made a request to the server on a secured URL.
How can I set up sliding expiration for authentication cookies?

A: Its quite easy to add custom filter that will inspect the cookie and re-set it to later expiration if needed (to see the proper way of doing those, you can take a look at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter and org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#setCookie), though I'd consider not extending the cookie expiration by the same amount as successful login (but just beyond the session expiration); in addition, I'd guess there is no need to touch cookie on each request, but only if there is a certain minimal amount of time left to the cookie expiration.


text:
Q: How do JSF view technologies translate client-side? So I understand that JSPs are a mixture of a client-side code (DHTML, JS, CSS, etc.) and Java. In this way, JSPs are kind of like pure PHP or pure ASP. When the web container receives a request for a JSP, it compiles the Java inside the JSP, executes it and then returns the resultant client-side code in the HTTP Response.
I also understand that an alternative to JSPs are Servlets, or a Servlet/templating combo, like FreeMarker. The servlets contain pure Java (business logic), and the templates contain presentation logic.
What I don't understand is how JSF-derived technologies like RichFaces, PrimeFaces and ICEFaces turn Java code into client-side code that can run in a browser.  I've also heard that the major draw to these frameworks are the "rich" UI controls they come with, but am having a tough time connecting all the dots.
Do these frameworks get compiled to JS like the GWT does? If that's the case then I would assume that these rich UI controls would be the same as, say, jQuery UI controls that are just pure JS.
If that's not the case then I just don't understand (at all) how these frameworks turn server-side code into "stuff" that can execute client-side.
Thanks in advance!

A:
What I don't understand is how JSF-derived technologies like RichFaces, PrimeFaces and ICEFaces turn Java code into client-side code that can run in a browser

The HTML is generated by encodeXxx() methods of UIComponent and/or Renderer implementations. Those methods are invoked during render response phase, starting with the UIViewRoot which delegates the call all the way through the entire component tree hierarchy.
JSF implementations such as Mojarra and practically all component libraries are open source. To take the JSF standard <h:inputText> component as an example, start looking at com.sun.faces.renderkit.html_basic.TextRenderer class to see all the HTML generating code.

Do these frameworks get compiled to JS like the GWT does?

Absolutely not. Open a JSF page in browser, rightclick and View Source. It's all just HTML code, if necessary along with auto-included CSS/JS files. With GWT it's one and all JS code.
See also:

*

*Java EE 6 tutorial - Creating custom components - to learn how to program it yourself.

*What is the difference between JSF, Servlet and JSP?

*What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?

A: No, JSF is not something like GWT. The idea is different. But let's start from the beginning.
Servlets are not really alternative to JSP. JSP is a technology, which is responsible for View part in Model-View-Controller design pattern. Servlets usually play role of the Controller.
In a typical scenario Servlet receives request from the user, parses it and calls bussines logic (Model) - it could be just the set of java classes or EJB components or whatever else which calculates something, talks to database, etc. Then Servlet gets the data from bussines logic (if any) and redirects user to a proper View element - JSP, pure HTML page, some template engine, etc.
JSF is sort of a layer over JSP + Servlets that makes programmers' live easier (although many would strongly diagree with that :) )
JSF page is basically a JSP page, that uses set of specialized tags - components (JSF native tags or RichFaces tags or ICE Faces tags). These tags can be written in Java, can boundle JavaScript, CSS. The final effect is that these tags generate HTML representing "component", for instance fancy table with sorting capabilites.
So you have for instance  component that you place on JSP page and it represents nicely looking table.
In addition JSF is armed with standard controller, which is not written in Java, but is a set of navigation rules between pages written in XML.
One more element are JSF Beans, which are bounded to JSF pages and are automatically filled with data taken from these pages. It is often quite straighforward - user fills the form, which is a part of JSF page (form also use specialized tags - components). Once this form is submitted the JSF Bean class is filled with data and action method is called. The action method returns a string, which is used to identify page to which user should be redirected (the rule is taken from XML controller configuration).
So in case JSF the frontend part is generated in backend - JSF tags (or components, as people call them) are interpreted in the backend and the backend generates HTML from them.
This could be contrasted with thechnologies, which separates frontend and backend. Backend receives and returns data in the form of XML or, more often, JSON and exchanges them with frontend part of the application. Frontend could be written in JavaScript, Flex, etc. So backend and frontend are totally separated.


text:
Q: Why can't I append string to byte slice as the Go reference specified? Quote from the reference of append of Go

As a special case, it is legal to append a string to a byte slice, like this:
  slice = append([]byte("hello "), "world"...)

But I find I can't do that as this snippet:
package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s) //*Error*: can't use s(type string) as type byte in append
    fmt.Printf("%s",a)
}

What have I done wrong?

A: You need to use "..." as suffix in order to append a slice to another slice.
Like this:
package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s...) // use "..." as suffice
    fmt.Printf("%s",a)
}

You could try it here: http://play.golang.org/p/y_v5To1kiD


text:
Q: Knockout.js template-wide semi-global variables Is there any way to define (in lack of a better term)"semi-global" variables for KO?
I'd like to make a variable available to a single KO template regardless of context while keeping it from the actual global scope and other templates.
The objective is to have a set of helper functions that are only available to that one template in any binding context(e.g. inside KO's foreach) without using $parent, just like globals are always accessible without any special syntax. Example below:
// Template 1 - helpers.foo has been set for this Template or ViewModel

// Template 2 - helpers.foo is not set for this Template or ViewModel

A: I'm not sure yet but I think I found the solution. After browsing through KO documentation for the n'th time I found this: Supplying additional values to descendant bindings.
For those of you who tl;dr:
I can use that custom binding handler to expose any variable to the template in every subcontext, which is exactly what I was looking for. In other words this becomes possible:
ViewModel

HTML

In my case the custom binding wrapper can be applied automatically upon load for every template, so this seems like a great solution for me!
I'll try this method and post a follow-up if it happens that I've overlooked something. This question will be left open for a short while because I can't accept my own answer so quickly. Meanwhile feel free to post your solutions, I'm sure there are more approaches to solving this.

A: You should define new custom binding that fetches values from your "helper". Just for simple example:
// your "semi-globally" accessible helpers
var helpers = {
    foo: function(text){ return "" + text + ""; },
    boo: function(text){ return "" + text + ""; }
};

// custom binding
ko.bindingHandlers.helpers = {
    init: function(element, valueAccessor) {
        var opts = valueAccessor();
        element.innerHTML = helpers[opts.name].apply(element, opts.args);
    }
};

// two different primitive ViewModels without any ref to helpers
function VM_1 () { this.name = "vm-1"; }
function VM_2 () { this.name = "vm-2"; }

// binding models
ko.applyBindings(new VM_1, document.getElementById("vm-1"));
ko.applyBindings(new VM_2, document.getElementById("vm-2"));

HTML:

http://jsfiddle.net/ostgals/GfBJ9/1/


text:
Q: How to split time slots evenly between vendors, with remainders I have a massage booking app where-by users can book multiple sessions with a length in minutes. The session length can go between 30 minutes to 2 hours but are in slots of 30 minutes.
Vendor = Someone giving massages.
Client = Someone receiving them
Each vendor cannot have more than 4 clients each. The client can book multiple people with multiple vendors.
They can book the length of the session in minutes per person, the number of people, and the number of vendors.
Now my question is, how can I split the 30-minute time slots between each of the vendors evenly depending on the length per person and the number of people? I tried to have a go myself but cannot figure this out. Below is my attempt.
Each vendor can have up to 4 hours in 30-minute slots. There are some examples inside the code.
I created a JS fiddle, please access it here
And here is an example of the code and my attempt that only partially works.
// Examples

// WORKS
// 3 vendors have 2 hours. 1 has 3 hours
// const lengthInMinutes = 60
// const hours = lengthInMinutes / 60;
/* const numberOfClients = 7
const numberOfVendors = 3 */

// WORKS
// 3 vendors have 2 hours.
// const lengthInMinutes = 60
// const hours = lengthInMinutes / 60;
/* const numberOfClients = 6
const numberOfVendors = 3 */

// WORKS
// 2 vendors have 2 hours, 1 has 1 hour.
// const lengthInMinutes = 60
// const hours = lengthInMinutes / 60;
/* const numberOfClients = 5
const numberOfVendors = 3 */

// WORKS
// 1 vendor has 4 hours
// const lengthInMinutes = 60
// const hours = lengthInMinutes / 60;
/* const numberOfClients = 4
const numberOfVendors = 1 */

// WORKS
// 3 vendor has 1 hours. One has 2
// const lengthInMinutes = 60
// const hours = lengthInMinutes / 60;
/* const numberOfClients = 4
const numberOfVendors = 3 */

// BROKEN
// 4 vendors have 2 hours, 2 has 1 hour
const lengthInMinutes = 60
const hours = lengthInMinutes / 60;
const numberOfClients = 10
const numberOfVendors = 6

let totalHours = numberOfClients * hours;
console.log("totalHours: " + totalHours)

let hoursPerVendor = Math.round(totalHours / numberOfVendors);
let hoursRemainder = (totalHours / numberOfVendors) % 1;

let vendorHours = new Array(numberOfVendors).fill(0).map((i) => {
    return hoursPerVendor
})

console.log("Hours remainder: " + hoursRemainder)
if (hoursRemainder !== 0.0) {
  if (hoursRemainder > 0.5) {
    // Take one hour off.
    vendorHours[vendorHours.length - 1] = vendorHours[vendorHours.length - 1] - 1
  }
  if (hoursRemainder < 0.5) {
    // Add one hour on.
    vendorHours[vendorHours.length - 1] = vendorHours[vendorHours.length - 1] + 1
  }
}

console.log(vendorHours)

A: I figured it out for anyone else stuck.
const lengthInMinutes = 60
const numberOfClients = 2
const numberOfVendors = 2

const totalMinutes = lengthInMinutes * numberOfClients
console.log("TotalMinutes: " + totalMinutes)

const totalSlots = ((totalMinutes / 30));
console.log("TotalSlots: " + totalSlots)

const slotsPerVendor = totalSlots / numberOfVendors
console.log("SlotsPerVendor: " + slotsPerVendor)

let currentVendorIndex = 0;
let vendors = new Array(numberOfVendors).fill(0).map((i) => i)

// Loop over slots and add them to each vendor
new Array(totalSlots).fill(0).map((i) => {
    if (currentVendorIndex > vendors.length - 1) {
    currentVendorIndex = 0;
  }
  if (vendors[currentVendorIndex] < 240) {
    vendors[currentVendorIndex] = vendors[currentVendorIndex] + 30
    currentVendorIndex++;
  }
})

console.log(vendors)


text:
Q: Can't Clear ArrayList everytime the method runs public void incorrectlive() {
ArrayList<String> Wor = new ArrayList<>();
ArrayList<String> Def = new ArrayList<>();
    LinearLayout layout = (LinearLayout) findViewById(R.id.WW);

    Scanner sc, sc2;
    int count = 0;
    try {
        Wor.clear();
        Def.clear();
        sc = new Scanner(openFileInput("w.txt"));
        sc2 = new Scanner(openFileInput("d.txt"));
        while (sc.hasNextLine() && sc2.hasNextLine()) {
            Q = sc.nextLine();
            Wor.add(Q);
            D = sc2.nextLine();
            Def.add(D);
            count++;
        }
        sc.close();
        sc2.close();

    } catch (Exception e) {
        Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
    }

    for (int i = 0; i < count; i++) {
        String wr = Wor.get(i);
        String dr = Def.get(i);
        addword(wr, dr, layout);
    }
}

i want to clear the contents of Wor & Def every time incorrectlive() runs but it isn't happening. There are no errors in Catlog, it only keeps on re adding the older ones which causes repeatations

A: Try placing your clear(); methods outside of your try/catch block...
Your program may also have a logic error depending on the context of which you called this method. Anything using the static keyword may cause some issues.

A: SO i found the solution...the problem was with the files which were used... so i flushed them using PrintStream. Thanks for the support


text:
Q: How to implement Excel vbA in C# Can you help me rewriting the following Excel VB code to C#?
Range("C9:E11").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
    Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False

A: What you're looking for is Excel Automation. Pretty much this means using a set of COM objects provided by Excel to remote control Excel from another application.
Anything you can do with with VBA you can achieve with Automation (OK, almost anything).
If you google for "Excel Automation C#" you'll get lots of hits. How to automate Microsoft Excel from Microsoft Visual C# .NET was the first returned to me, and looks like a good place to get started.
Hope this helps,

A:  using Excel = Microsoft.Office.Interop.Excel;
 ...
 object mis = Type.Missing;

 Excel.FormatCondition cond =
    (Excel.FormatCondition)range.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue,
    Excel.XlFormatConditionOperator.xlEqual, "=1",
    mis, mis, mis, mis, mis);
    cond.Interior.PatternColorIndex = Excel.Constants.xlAutomatic;
    cond.Interior.TintAndShade = 0;
    cond.Interior.Color = ColorTranslator.ToWin32(Color.White);
    cond.StopIfTrue = false;


text:
Q: How to use Function VB.NET Insert To Database? i using function with vb.net. i'm query sql to datagridview and insert data from datagridview to Databse By function.
But Error in function: The name 'EXHBK13004' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.
i want using function with insert to database.
Table Clother
Name     Type
No (PK)  int
Code     nvarchar(12)
RClother int
CIDetail int
PO       nvarchar(50)

Code (Button Save)
Private Sub btSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSave.Click

    For i As Integer = 0 To DgvItem.Rows.Count - 1
        sendPDTStatus = FInsertClother(CStr(DgvItem.Rows(i).Cells(0).Value), CInt(DgvItem.Rows(i).Cells(1).Value), CInt(DgvItem.Rows(i).Cells(2).Value), _
        DgvItem.Rows(i).Cells(3).Value)
    Next

End Sub

Code Function
Public Function FInsertClother(ByVal Code As String, ByVal RClother As Integer, ByVal CIDetail As Integer, ByVal PO As String)
            Dim Tr As SqlTransaction
            Dim sqlCom As New SqlCommand

            Dim sqlInsert As String
            Dim ReturnValue As Integer

            Tr = Conn.BeginTransaction
            sqlCom.Connection = Conn

            sqlInsert = "INSERT INTO Clother "
            sqlInsert &= "(Code,RClother,CIDetail,PO) "
            sqlInsert &= "VALUES(" & Code & "," & RClother & "," & CIDetail & "," & PO & ")"

            sqlCom.Transaction = Tr
            sqlCom.CommandText = sqlInsert
            sqlCom.CommandType = CommandType.Text

            ReturnValue = sqlCom.ExecuteScalar << Line Error
            If ReturnValue = 0 Then
                Tr.Commit()
            Else
                Tr.Rollback()
            End If
     Return ReturnValue
End Function

I try Debug this result
Name                 Value
sqlCom.CommandText   "INSERT INTO Clother (Code,RClother,CIDetail,PO) VALUES(050030543003,5022,30543,EXHBK13004/3)"

sqlInsert            "INSERT INTO Clother (Code,RClother,CIDetail,PO) VALUES(050030543003,5022,30543,EXHBK13004/3)"

Only field "PO" don't insert to database.
Thanks you for your time. :))

A: First of all I would remove the string concatenation and use a parameterized query to avoid parsing problems and Sql Injections (In your code you have passed two strings without using quotes and this will surely fail the insert because string fields require a quote delimiter)
Then I remove also the Transaction because, as it stands now the loop executes and confirms a single command for each row.
Also you seems to have a global connection object and this is a bad practice, you should open the connection and close it as soon as possible without keeping it open for the lifetime of your application.
Public Function FInsertClother(ByVal Code As String, ByVal RClother As Integer, ByVal CIDetail As Integer, ByVal PO As String)

    Dim sqlInsert As String
    Dim ReturnValue As Integer

    sqlInsert = "INSERT INTO Clother " & _
                "(Code,RClother,CIDetail,PO) " & _
                "VALUES(@code, @clot, @id, @po)"

    Using sqlCom = new SqlCommand(sqlInsert, conn)
        sqlCom.Connection = Conn
        sqlCom.Parameters.AddWithValue("@code",Code)
        sqlCom.Parameters.AddWithValue("@clot", RClother)
        sqlCom.Parameters.AddWithValue("@id",CIDetail)
        sqlCom.Parameters.AddWithValue("@po",PO)
        ReturnValue = sqlCom.ExecuteNonQuery
        Return ReturnValue
    End Using
End Function

A very useful enhancements would be to open the connection on the button click and pass it to this function. So when you have finished to loop over the rows you could close the connection via a Using Statement

A: You need to put the string values in quotes.
sqlInsert &= "VALUES('" & Code & "'," & RClother & "," & CIDetail & ",'" & PO & "')"

That said, you should not build a query string using concatenation. This makes your query subject to a SQL Injection attack. Instead, you should use a parametrized query. (as Steve shows in his answer).


text:
Q: generate random dates within a range in numpy How can I generate random dates within a range of dates on bimonthly basis in numpy? One way I can think of is generating two sets of random integer arrays:
bimonthly1 = np.random.randint(1,15,12)
bimonthly2 = np.random.randint(16,30,12)

I can then generate the dates, with the 'day' values from the above two arrays for each month. However, this will require me to explicitly pass month and year data. A solution would be to generate the desired date_range first and substitute the 'days' in the range with the above array values. But for a large array, this may not be the best solution. This method will require operation on each and every element of the range.
I would appreciate any pointers on how to do this in numpy more efficiently.

A: You could create the date range a priori, e.g. using pandas's date_range, and convert it to a numpy array. Then, make random choices from this array of dates using numpy.random.choice.

A: There is a much easier way to achieve this, without needing to explicitly call any libraries beyond numpy.
Numpy has a datetime datatype that is quite powerful: specifically for this case you can add and subtract integers and it treats it like the smallest time unit available. for example, for a %Y-%m-%d format:
exampledatetime1 = np.datetime64('2017-01-01')
exampledatetime1 + 1
>>
2017-01-02

however, for a %Y-%m-%d %H:%M:%S format:
exampledatetime2 = np.datetime64('2017-01-01 00:00:00')
exampledatetime2 + 1
>>
2017-01-01 00:00:01

in this case, as you only have information down to a day resolution, you can simply do the following:
import numpy as np

bimonthly_days = np.arange(0, 60)
base_date = np.datetime64('2017-01-01')
random_date = base_date + np.random.choice(bimonthly_days)

or if you wanted to be even cleaner about it:
import numpy as np

def random_date_generator(start_date, range_in_days):
    days_to_add = np.arange(0, range_in_days)
    random_date = np.datetime64(start_date) + np.random.choice(days_to_add)
    return random_date

and then just use:
yourdate = random_date_generator('2012-01-15', 60)

A: What if you define a start date as the first of the month and then add a random timedelta?
e.g.
import datetime
d0 = datetime.datetime.strptime('01/01/2016', '%d/%m/%Y')

from calendar import monthrange
max_day = monthrange(d0.year, d0.month)[1]

import numpy as np
random_dates_1 = []
random_dates_2 = []
for i in range(10):
    random_dates_1.append( d0 + datetime.timedelta(days=np.random.randint(0, int(max_day/2))) )
    random_dates_2.append( d0 + datetime.timedelta(days=np.random.randint(int(max_day/2), max_day+1)) )

A: Here is a pure numpy implementation that creates two arrays of datetimes for each month of the year. The first array has random values from the first half of each month and the second array from the second half of each month.
import datetime
from calendar import monthrange
import numpy as np

arr_first = np.array([])
arr_second = np.array([])

for i in range(1, 13):
    base = datetime.datetime(2016, i, 1)
    max_days = monthrange(2016, i)[1]
    first = np.random.randint(0, max_days // 2)
    second =np.random.randint(max_days // 2, max_days)
    arr_first = np.append(arr_first, base + datetime.timedelta(days=first))
    arr_second = np.append(arr_second, base + datetime.timedelta(days=second))


text:
Q: Can't get data from Googlesheet using esp32 and Arduinojson I'm new to esp32 and now I'm trying to Get data using ArduinoJson,
In my googlesheet "A1" have a number and I want to let esp32 to get it,
I send my googlesheet to internet and use the url:https://spreadsheets.google.com/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1.
and my number is at object > feed > entry > 0 > content > $t.
Here's a problem:When I use esp32 to get this json data,I can't get it,even my esp32 connected to googlesheet
Here is my full code if you need:
#include <ArduinoJson.h>
#include <WiFi.h>
#include <SPI.h>

WiFiClient client;

const char* ssid = "wwwwwwwww";
const char* password = "wwwwwwww";
const char* server = "spreadsheets.google.com";
const char* resource = "/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1";

const unsigned long HTTP_TIMEOUT = 10000;  // max respone time from server
const size_t MAX_CONTENT_SIZE = 1024;       // max size of the HTTP response

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

struct clientData {
  char item[8];
};

void setup() {
  Serial.begin(9600);
  while (!Serial) {

  }
  Serial.println("Serial ready");
  Serial.print("Connecting to wifi: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if(connect(server)) {
    if(sendRequest(server, resource) && skipResponseHeaders()) {
      clientData clientData;
      if(readReponseContent(&clientData)) {
        printclientData(&clientData);
      }
    }
  }
  disconnect();
  wait();
}

bool connect(const char* hostName) {
  Serial.print("Connect to ");
  Serial.println(hostName);

  bool ok = client.connect(hostName, 80);

  Serial.println(ok ? "Connected" : "Connection Failed!");
  return ok;
}

bool sendRequest(const char* host, const char* resource) {
  Serial.print("GET ");
  Serial.println(resource);

  client.print("GET ");
  client.print(resource);
  client.println(" HTTP/1.1");
  client.print("Host: ");
  client.println(host);
  client.println("Connection: close");
  client.println();

  return true;
}

bool skipResponseHeaders() {
  // HTTP headers end with an empty line
  char endOfHeaders[] = "\r\n\r\n";

  client.setTimeout(HTTP_TIMEOUT);
  bool ok = client.find(endOfHeaders);

  if (!ok) {
    Serial.println("No response or invalid response!");
  }
  return ok;
}

bool readReponseContent(struct clientData* clientData) {
  const size_t bufferSize = 5*JSON_ARRAY_SIZE(1) +
  JSON_ARRAY_SIZE(5) + 10*JSON_OBJECT_SIZE(1) +
  6*JSON_OBJECT_SIZE(2) + 7*JSON_OBJECT_SIZE(3) +
  JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(15);
  DynamicJsonBuffer jsonBuffer(bufferSize);

  JsonObject& root = jsonBuffer.parseObject(client);

  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

  strcpy(clientData->item, root["feed"]["entry"][0]["content"]["$t"]);

  return true;
}

void printclientData(const struct clientData* clientData) {
  Serial.print("Time = ");
  Serial.println(clientData->item);

}

void disconnect() {
  Serial.println("Disconnect");
  client.stop();
}

void wait() {
  Serial.println("Wait 20 seconds");
  delay(20000);
}

Serial Output:
Connecting to wifi: wwwwwwwwww
..
WiFi connected
IP address:
xxx.xxx.x.xx
Connect to spreadsheets.google.com
Connected
GET /feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1
JSON parsing failed!
Disconnect
Wait 20 seconds

A: If I based on your json output and calculate the bufferSize using ArduinoJson Assistant, I get this:
const size_t capacity = 5*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(5) + 10*JSON_OBJECT_SIZE(1) + 6*JSON_OBJECT_SIZE(2) + 7*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(15) + 2270;

Noticed the + 2270 at the end? Your parsing json failed because your are short of 2270 bytes in bufferSize (i.e. your bufferSize is too small).
Updte
I didn't try to debug your code, but I have my web client code handy with me so I just run and it works for me.
My code is based on HTTPClient which is part of ESP32 Arduino Core that you can further read about it at ESP-Arduino github. It is based on Arduino WifiClient that you used but with much simpler and easy to use API, especially for getting response payload. I would recommend you take a look.
I add ArduinoJson to my code to see if there is any issue on parsing the received json, but mines is based on v6 syntax, you can convert it to v5 syntax if you still feel it is easier for you to use v5. BTW, the json document contains Unicode, I have to add #define ARDUINOJSON_DECODE_UNICODE 1 on the top of the program in oder to make it work, otherwise I will get an deserialization error: NotSupported.
#define ARDUINOJSON_DECODE_UNICODE 1
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>

HTTPClient http;

const char* ssid = "your_SSID";
const char* password = "your_password";

const char* url = "https://spreadsheets.google.com/feeds/cells/1RICYSv0y0wEEu-PhcCL45jZmh7DlFSAsbW8Bie0inbA/1/public/values?alt=json&range=A1";

void setup() {
  Serial.begin(115200);
  while (!Serial) {}

  Serial.print("Connecting to wifi: "); Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(200);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("IP address: "); Serial.println(WiFi.localIP());

  http.begin(url);
  int httpCode = http.GET();  //send GET request

  if (httpCode != 200) {
    Serial.print("Error on HTTP request: ");
    Serial.println(httpCode);
  } else {
    String payload = http.getString();
    Serial.println(payload);

    // the following is based on ArduinoJson v6 API
    StaticJsonDocument<4000> doc;
    DeserializationError err = deserializeJson(doc, payload);
    if (err) {
      Serial.print("deserialization error ");
      Serial.println(err.c_str());
    }

    JsonObject feed = doc["feed"];
    const char* clientData = feed["entry"][0]["content"]["$t"];
    Serial.println(clientData);
  }

  http.end(); //Free the resources

}

void loop() {

}


text:
Q: Date format conversion to YYYY-MM-DD HH:MIN:SEC in Apache Hive I am loading data to a hive table from a csv file. File is having a field named last_updated_date and it's value is in format "20200412013000771+0000".
I need to covert it into "YYYY-MM-DD HH:MIN:SEC".

A: You can either chop it up with lots of substrings and rebuild it with concats, or strip off the irrelevant characters at the end and use unix_timestamp and from_unixtime.
Since you don't care about milliseconds, you only want the first 14 chars. Here's how I'd go about it:
select from_unixtime (unix_timestamp(substring('20200412013000771+0000',1,14), 'yyyyMMddhhmmss'))

Which returns
2020-04-12 01:30:00


text:
Q: Volume Control in UIImagePickerController I want to make the max volume notice voice when user take a photo or start to record a video.
Is it possible and not be rejected by appStore??

A: Celestial.framework has an AVSystemController class that lets you get and set the current volume. Unfortunately it is a private class so Apple won't accept it in AppStore submission
Instead,you can show the volume slider to set it by user.
Like this:
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:window.bounds] autorelease];
[window addSubview:volumeView];
[volumeView sizeToFit];


text:
Q: When is an "instance" being created? I've been reading articles about OOP with python, specifically this one.
The autor of that article has a description and then a code example:

The Python syntax to instantiate a class is the same of a function
  call

>>> b = int()
>>> type(b)
<type 'int'>

By this I infer "instance" exist at the moment of the execution and not before. When you execute type(b) that's the instance of the class int().
But then I read this stack overflow answer:

Instance is a variable that holds the memory address of the Object.

Which makes me a little be confused about the term. So when I assign a variable at the moment of the execution the "instance" is created?
Finally this explanation in ComputerHope points to the fact that instances are the same as variable assigments:
function Animal(numlegs, mysound) {
this.legs = numlegs;
this.sound = mysound;
}
var lion = new Animal(4, "roar");
var cat = new Animal(4, "meow");
var dog = new Animal(4, "bark");

The Animal object allows for the number of legs and the sound the
  animal makes to be set by each instance of the object. In this case,
  all three instances (lion, cat, and dog) have the same number of legs,
  but make different sounds.

Could anyone actually provide a clear definition of when an instance exits?

A: Generally in OOP

Classes and objects are the two main aspects of object oriented
  programming. A class creates a new type where objects are instances of
  the class.

As explained here.
Thus everytime an object is created, it is called an instance.
Python makes no difference in this concept, however things are a little different from other languages like Java for instance.
In fact in Python everything is an object, even classes themselves.
Here is a brief explanation of how it works:
Considering this snippet:
>>> class Foo:
...     pass
...
>>> type(Foo)
<type 'type'>
>>>

Class Foo is type type which it is a metaclass for all classes in Python
(There is however a distinction between 'old' and 'new' classes, more here, here and here).
Class type being a class, is an instance of itself:
>>> isinstance(type, type)
True

So Foo despite being a class definition, is treated like an object by the interpreter.
Objects as instances are created whit statements like foo = Foo(), foo being an object inherits from object class.
>>> isinstance(foo, object)
True

This class provides all the methods an object needs, such as __new__() and __int__() (new, init). In short the former is used to create a new instance of a class, the latter is called after the instance has been created and is used to initialize values like you did with Animal.
The fact that everything is an object also mean that we can do funny pieces of code like this one:
>>> class Foo:
...     var = 'hello'
...
>>> foo = Foo()
>>> foo.var
'hello'
>>> foo.other_var = 'world'
>>> foo.other_var
'world'
>>> Foo.other_var
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute 'other_var'
>>> Foo.var
'hello'
>>>

Here I added an attribute on an object at runtime. That attribute will be unically in foo, the class itself or any other instances won't have it.
This is called Instance variable and class variable.
Hope it all makes sense to you.
TL;DR
In Python everything (class definitions, functions, modules, etc..) are all treated like objects by the interpreter. Therefore 'everything' is an instance.

A:
I've been reading articles about OOP with python, specifically this
  one.
The autor of that article has a description and then a code example:

The Python syntax to instantiate a class is the same of a function
    call

>>> b = int()
>>> type(b)
<type 'int'>

Also read the sentence before that:

Once you have a class you can instantiate it to get a concrete object (an instance) of that type, i.e. an object built according to the structure of that class.

So an instance of a class is an object that has that class as its type.

By this I infer "instance" exist at the moment of the execution and
  not before.

Yes, correct. "Instance" and "instance of" are runtime concepts in Python.

When you execute type(b) that's the instance of the
  class int().

Not quite.
The int instance here starts existing when int() is called.1 This process is what's called "instantiation" and the result (which is returned by this call, and in this example then assigned to b) is the "instance" of int.

But then I read this stack overflow answer:

Instance is a variable that holds the memory address of the Object.

Oh well, that's not quite correct. It's the object itself (the value at that memory address, if you will) that's the instance. Several variables may be bound to the same object (and thus the same instance). There's even an operator for testing that: is
>>> a = 5
>>> b = a
>>> a is b
True

Which makes me a little be confused about the term. So when I assign a
  variable at the moment of the execution the "instance" is created?

No, then the instance is bound to that variable. In Python, think of variables just as "names for values". So binding an object to a variable means giving that object that name. An object can have several names, as we saw above.
You can use an instance without assigning it to any variable, i.e., without naming it, e.g. by passing it to a function:
>>> print(int())
0

Finally this explanation in ComputerHope points to the fact that
  instances are the same as variable assigments:
function Animal(numlegs, mysound) {
this.legs = numlegs;
this.sound = mysound;
}
var lion = new Animal(4, "roar");
var cat = new Animal(4, "meow");
var dog = new Animal(4, "bark");

The Animal object allows for the number of legs and the sound the
    animal makes to be set by each instance of the object. In this case,
    all three instances (lion, cat, and dog) have the same number of legs,
    but make different sounds.

Unfortunately, that explanation on ComputerHope will probably confuse most readers more than it helps them. First, it conflates the terms "class" and "object". They don't mean the same. A class is a template for one type of objects. Objects and templates for a type of objects aren't the same concept, just as cookie cutters aren't the same things as cookies.
Of course, [for the understanding] it doesn't particularly help that in Python, classes are (special, but not too special) objects (of type type) and that in JavaScript until the class concept was introduced, it was customary to use plain objects as templates for other objects. (The latter approach is known as "prototype based object orientation" or "prototype based inheritance". In contrast, most other object oriented languages, including Python, use class-based object orientation / class-based inheritance. I'm not quite sure in what category modern ECMAScript with the class keyword falls.)

Could anyone actually provide a clear definition of instance?

Like I wrote further up:
An instance of a class is an object that has that class as its type.
So an "instance" is always an "instance of" something. That also answers the linguistic take on the question in the title

When should I call it "instance"?

You should call it "instance" when you want to call it "instance of" something (usually of a class).

1 I haven't told the whole truth. Try this:
>>> a = int()
>>> b = int()
>>> a is b
True

Wait what? Shouldn't the two invocations of int have returned new instances each, and thus two distinct ones?
That what would have happened with most types, but some built-in types are different, int being one of them. The makers of the CPython implementation are aware that small integers are used a lot. Thus they let CPython create new ones all the time, they just have it re-use the same integer (the same object / instance) each time the same value is required. Because Python integers are immutable, that doesn't usually cause any problems, and saves a lot of memory and object-creation-time in computation-intensive programs.
The Python standard allows implementations to make this optimization, but AFAIK doesn't require them to. So this should be considered an implementation detail and your program logic should never rely on this. (Your performance optimizations may rely on it, though.)


text:
Q: Stop form refreshing when validation fails Laravel I have the following code:
Modal:
<form class="form-signin" role="form" method="POST" action="{{ url('/login') }}">

        @include('application.errors')
        ...
        <button type="submit" class="btn btn-hp-modal underline btn-signup-modal">Log in</button>

</form>

Controller:
public function login( Request $request ) {
    ...
    // If the login attempt was unsuccessful
    return $this->sendFailedLoginResponse($request);
}

protected function sendFailedLoginResponse(Request $request)
{
    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ]);
}

application.errors:
@if ($errors->any())

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

The issue I am having is that after I click on Log in, it refreshes the page regardless of successful or unsuccessful validation. The message appears if I open the modal after the page is refreshed, but I would like the modal to stay in case it actually goes into sendFailedLoginResponse.
Any help would be appreciated!

A: If you want to stop the page from refreshing on submit, you need to have a client-side validation check with JavaScript.
And to prevent the form from submitting, you need to use event.preventDefault() or a return false on your form submit handler.
It looks like you're submitting to your server here, which means you cannot do what you want. If you want to achieve a client-side validation and prevent page reload when it fails, you must use JavaScript.
Here is a pseudocode example:
$('#form').submit(function (e) {
    if ($('#username').value() === '') {
        // Show some validation message here...

        // Prevent default and return.
        return e.preventDefault();
    }

    // Submit to API via AJAX call.
});

A: I found another way:
Shove a GET request in the validation return to fetch some previous data, it won't fix the refresh, but at least you can recover data as the user gets redirected:
   // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        //let's send some data back (Orlando,Florida):
        return Redirect::to('auth/register?city=Orlando&State=Florida')
            ->withErrors($validator)
            ->withInput(Input::except('password', 'password_confirmation'));

    }else{
     //validation success
    }


text:
Q: terraform) how to stop instance after running script(inline)? I create 30 instance to run crawl script, and want to stop aws instances after complete running this command, python3 aws_crawl.py, but I cannot find how to stop current aws instance by command line.
Please see my main.tf code below:
resource "aws_instance" "crawl_worker" {
  ami             = "${var.ami_id}"
  instance_type   = "t3a.nano"
  security_groups = ["${var.aws_security_group}"]
  key_name = "secret"
  count = 10
  tags =  {
    Name = "crawl_worker_${count.index}"
  }

  connection {
    type = "ssh"
    host = "${self.public_ip}"
    user = "ubuntu"
    private_key = "${file("~/secret.pem")}"
    timeout = "50m"
  }

   provisioner "remote-exec" {
                            inline = [
                            "python3 aws_crawl.py"
                            ]
                           }
    }


text:
Q: How to sort dict list with multiple key attributes - python I am trying to sort list dict based on two key parameters - "id" and "type". Imagine you have a list like the below
dict_list = [
    { "id" : 1, "type" : "snippet", "attribute" :'test'},
    { "id" : 2, "type" : "snippet", "attribute" :'hello'},
    { "id" : 1, "type" : "code", "attribute" : 'wow'},
    { "id" : 2, "type" : "snippet", "attribute" :'hello'},
 ]

The end result should be like this.
dict_list = [
    { "id" : 1, "type" : "snippet", "attribute" : 'test' },
    { "id" : 2, "type" : "snippet", "attribute" : 'hello' },
    { "id" : 1, "type" : "code", "attribute" : 'wow' },
]

I tried this method but it only produces a unique list based on only "key" attribute.
unique_list = {v['id'] and v['type']:v  for v in dict_list}.values()

How can I generate a unique list based on two key parameters?

A: seen_items = set()
filtered_dictlist = (x for x in dict_list
                     if (x["id"], x["type"]) not in seen_items
                     and not seen_items.add((x["id"], x["type"])))
sorted_list = sorted(filtered_dictlist,
                     key=lambda x: (x["type"], x["id"]),
                     reverse=True)

I think should first filter and then sort it how you want ...
you can use itemgetter to make it more elegant
from operator import itemgetter
my_getter = itemgetter("type", "id")
seen_items = set()
filtered_values = [x for x in dict_list
                   if my_getter(x) not in seen_items
                   and not seen_items.add(my_getter(x))]
sorted_list = sorted(filtered_dictlist, key=my_getter, reverse=True)


text:
Q: Shapable terrain in Unity3D? I want to make a shapable world (and maybe also procedurally generated), but I don't know how to make it via script.
There are a few examples whom I have a few questions about:
Minecraft
It is easy to make a procedurally generated shapable world from cubes, but I don't know how to make it optimal. Does unity strong enough the handle a lot of cubes?
Landmark
In this game you can shape the world and it uses Unity like terrain. It's is similar to Minecraft but it's not as cubic. (So when you dig in the ground, you dig ~like in real life. So you don't dig cube by cube like in Minecraft)
Is it possible to shape the terrain runtime?
Thanks for your help in advance!

A: You can modify the Unity built in terrain's heightmap: TerrainData.SetHeights. You will need to define some kind of a brush like draw crater, depends on your needs.

A:
It is easy to make a procedurally generated shapable world from cubes

Short answer, no it is not easy. You would have to use some type of noise to generate a heightmap (like voxel noise, here's a blog tutorial)

[Is] unity strong enough the handle a lot of cubes?

No, on it's own unity will not handle the amount of cubes needed for a minecraft clone very well. Statistically speaking you will never be able to see all 6 faces of a cube, so rendering all 6 is wasteful. Also, each cube will have it's own collider which will quickly clutter. Also you do not need to render a cube if it is blocked by other cubes. All this requires complex optimization code to make it run efficiently as you are modifying the terrain and moving through the world.

Is it possible to shape the terrain runtime?

Yes, here's some code I stole from this question:
function Start()
{
    terrain = GetComponent(Terrain);
    var nRows = 50;
    var nCols = 50;
    var heights = new float[nRows, nCols];
    for (var j = 0; j < nRows; j++)
        for (var i = 0; i < nCols; i++)
            heights[j,i] = Random.Range(0.0,1.0);
    terrain.terrainData.SetHeights (0,0,heights);
}

and here's the documention on TerrainData.SetHeights()
https://docs.unity3d.com/ScriptReference/TerrainData.SetHeights.html


text:
Q: why user with db_owner & db_BackupOperator database role is unable to restore database? I'm in sysadmin server role on the server .
All Programmers are in dbCreator Server role , So they can create databases for themselves and they have in db_owner & db_Backupoperator database role for their own databases.
All programmer have remote desktop access to the server just like me . I would like every Programmer be able to backup and restore their own databases .
But When they are trying to restore , in Specifying back-up dialog , when user click on add button they get this error ( while i can restore ).
C:\Program files\Microsoft SQL Server\mssql10_50.sql2008\backup
Cannot access the specified path or file on the server .
Verify that you have the necessary security privileges and that the path or file exists

I appreciate any help .

A: "Their database" for the dbcreator means owner in the sys.databases.owner_sid sense
Not members of db_owner.
The actual rights needed are described under RESTORE (and my added bold)

If the database being restored does not exist, the user must have CREATE DATABASE permissions to be able to execute RESTORE. If the database exists, RESTORE permissions default to members of the sysadmin and dbcreator fixed server roles and the owner (dbo) of the database (for the FROM DATABASE_SNAPSHOT option, the database always exists).
RESTORE permissions are given to roles in which membership information is always readily available to the server. Because fixed database role membership can be checked only when the database is accessible and undamaged, which is not always the case when RESTORE is executed, members of the db_owner fixed database role do not have RESTORE permissions.

A: You need to check that the path where the backups exist is accessible for the user account used by the SQL Server service. Check permissions for the backup folder and its files and see if the SQL service account is in the list.