text:
Q: How to make an animation using PyPlot.jl with multiple axes? I would like to create an animation of two axes. In the simple example illustrated below, I would like to plot two matrices using imshow as a function of time.
Coming from python, I would create an animation using matplotlib.animation similar to this:
using PyCall
@pyimport matplotlib.animation as anim
using PyPlot
import IJulia

A = randn(20,20,20,2)

fig, axes = PyPlot.subplots(nrows=1, ncols=2, figsize=(7, 2.5))
ax1, ax2 = axes

function make_frame(i)
    ax1.clear()
    ax2.clear()
    ax1.imshow(A[:,:,i+1, 1])
    ax2.imshow(A[:,:,i+1, 2])
end

withfig(fig) do
    myanim = anim.FuncAnimation(fig, make_frame, frames=size(A,3), interval=20, blit=false)
    myanim[:save]("test.mp4", bitrate=-1, extra_args=["-vcodec", "libx264", "-pix_fmt", "yuv420p"])
end

This however just creates a blank animation.
Do I need to use an init_func in the FuncAnimation? Do I need to enable blitting? Or can I update the artist using a set_data attribute?

A: Don't use IJulia for this routine. If you plan to include the routine in a notebook, just run the code and then view the file you create, without using withfig. withfig is causing your animation creation to abort for some reason, probably because it expects something within an IJulia environment to be set differently.
This works:
using PyCall
@pyimport matplotlib.animation as anim
using PyPlot

A = randn(20,20,20,2)
fig, axes = PyPlot.subplots(nrows=1, ncols=2, figsize=(7, 2.5))
ax1, ax2 = axes

function make_frame(i)
    ax1.clear()
    ax2.clear()
    ax1.imshow(A[:,:,i+1, 1])
    ax2.imshow(A[:,:,i+1, 2])
end

myanim = anim.FuncAnimation(fig, make_frame, frames=size(A,3), interval=20, blit=false)
myanim[:save]("test.mp4", bitrate=-1, extra_args=["-vcodec", "libx264", "-pix_fmt", "yuv420p"])
# now you can call your video viewer on "test.mp4"


text:
Q: How does a FAST tree look in practice? I am looking at FAST: Fast Architecture Sensitive Tree Search on Modern CPUs and GPUs by Kim et al. and Index Search Algorithms for Databases and Modern CPUs by Gross, in order to find inspiration on how to further optimize B+trees to utilize SIMD lines, cache lines, and page sizes. In those documents they show these diagrams:

After reading the descriptions ("5.1.1 Building the Tree" in the first link, and pg 30-32 in the second link), I still don't have a visualization of what exactly they are doing to optimize the layout of the tree for these 3 features. What would the structure of the tree look like in pseudo-JavaScript or pseudo-C code or JSON? How does it differ from a regular B+tree? (Obviously JS doesn't have these features available, but just wondering what the shape of the tree is generally, and where things go.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Object initialization sequence in scala in an inherent hierarchy I'm new to scala from java and confused by sequence of object initialization of scala in an inherent hierarchy. IIRC, in Java, if an object of sub-class is initialized, constructor of its base class is invoked before any code of its own constructor. While in scala, I get totally different behavior. Consider the following example:
class Point(val x: Int, val y: Int){
    val name = this.makeName;

    def makeName: String = {
        println("makeName at super.");

        "[" + x + ", " + y + "]";
    }

    override def toString: String = name;
}

class ColorPoint(override val x: Int, override val y: Int, var color: String) extends Point(x, y) {

    // key statement
    println(name);

    override def makeName: String = {
        println("makeName at sub.");

        super.makeName + ":" + myColor;
    }

    val myColor = color;

    override def toString: String = name;
}

Let's just consider byte code of constructor of ColorPoint dumped with javap. If the code include the key statement println(name); the byte code is
public ColorPoint(int, int, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_3
   2:   putfield        #13; //Field color:Ljava/lang/String;
   5:   aload_0
   6:   iload_1
   7:   iload_2
   8:   invokespecial   #18; //Method Point."<init>":(II)V
   11:  getstatic       #24; //Field scala/Predef$.MODULE$:Lscala/Predef$;
   14:  aload_0
   15:  invokevirtual   #28; //Method name:()Ljava/lang/String;
   18:  invokevirtual   #32; //Method scala/Predef$.println:(Ljava/lang/Object;)V
   21:  aload_0
   22:  aload_3
   23:  putfield        #34; //Field myColor:Ljava/lang/String;
   26:  return

We can see field myColor is initialized after invokespecial, i.e. after initialization of the base class.
If I comment out the statement println(name); the byte code is:
public ColorPoint(int, int, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_3
   2:   putfield        #13; //Field color:Ljava/lang/String;
   5:   aload_0
   6:   aload_3
   7:   putfield        #15; //Field myColor:Ljava/lang/String;
   10:  aload_0
   11:  iload_1
   12:  iload_2
   13:  invokespecial   #20; //Method Point."<init>":(II)V
   16:  return

We see that field myColor is initialized just before invokespecial, i.e. before base is initialized.
Then what's the reason? Any document/article specifies this kind of behavior?
BTW, version of my scala is 2.7.7final (OpenJDK Server VM, Java 1.6.0_20). Thanks and Best Regards!

A: The compiler is simply executing things in order. There is some documentation here.
https://github.com/paulp/scala-faq/wiki/Initialization-Order
The main part from it is the following.

*

*Superclasses are fully initialized before subclasses.

*Otherwise, in declaration order.


text:
Q: SSIS - 2nd Script Task not being executed in Foreach Loop Container I have 2 script tasks in my foreach loop container in an SSIS package. See picture. The first script task Determine which file is presented gets executed just fine. However, the second one Archive Broker File does not get executed at all.
I can see in the progress that the script tasks gets validated but no execution at all. The only thing it needs to do is to rename a file and move it to a different location.
Any idea what's going on especially since the first script task gets executed without any issues.
Thanks,
Daniel

A: Cause
It will not be executed if the three data flow tasks are not executed since you are using precedence constraints (link between tasks) with Logical AND condition
Solution
Double click on any precedence constraint going from any Data Flow Task to the script Task and change the condition to Logical OR
Info from official documentation
Based on Precedence Constraints official documentation:

Logical AND Select to specify that multiple precedence constraints on the same executable must be evaluated together. All
  constraints must evaluate to True.
This type of precedence constraint appears as a solid green,
  highlighted or blue line.
Logical OR Select to specify that multiple precedence constraints on the same executable must be evaluated together. At
  least one constraint must evaluate to True.
This type of precedence constraint appears as a dotted green,
  highlighted, or blue line.

Other helpful articles
You can read more about precedence constraints in the following article:

*

*Working with Precedence Constraints in SQL Server Integration Services

*Using Expressions On Precedence Constraints in Integration Services

*Using Precedence Constraints In SSIS


text:
Q: Grouping range of values in to fixed number of buckets of arbitrary size I have a table containing metadata of ~100k files and my specific use-case is to produce a simple histogram of the file sizes (in bytes). All I know in advance is the number of buckets/bins I'd like to partition the data.
Let's say I want 100 buckets; let's also say that the current max file size (in bytes) is 12,345,678. Then each bucket will be floor(12345678/100) in size (123,456). Hence the buckets will increment as follows:
0 - 123,455
123,456 - 246,911
...
12,222,222 - 12,345,678

All the examples I can find on StackOverflow and elsewhere seem to rely on the SQL developer knowing in advance each of the bucket ranges and hardcode (fine if there are only a handful), or you know in advance the amount to increment rather than being based on the max value in the table.
The closest I've got to something useful is from this answer that I've adapted to calculate the bucket size based on the max value:
SELECT floor(t.file_size_bytes / b.bucket_size) bucket, count(*) count
FROM file_metadata t
CROSS JOIN (SELECT floor(max(file_size_bytes)/100) bucket_size FROM file_metadata) b
GROUP BY bucket
ORDER BY bucket;

Which gives something like:
bucket | count
--------------
0      | 56215
1      | 2024
2      | 1060
...
92     | 1
99     | 1

I don't mind that the bucket number starts at zero, but it would be ideal if

*

*There were no missing rows - if a bucket has no items then show zero.

*I could get the start and end range values for each bucket that the query determined. For example, if there were 100 buckets, each 1000 wide then showing something like:

bucket | b_start | b_end | count
---------------------------------------
0      | 0       | 999   | 56215
1      | 1000    | 1999  | 2024
2      | 2000    | 2999  | 1060
...


text:
Q: What is the best design pattern to register data "chunks"? I have a library which can save/load on disk "chunks" which are POD structs with constant size and unique static CHUNK_ID field. So load looks somethink like this.
void Load(int docId, char* ptr, int type, size_t& size)...

If you want to add new chunk you just add struct with new CHUNK_ID and use Save Load functions to it.
What I want is to force all "chunks" to have functions like PrintHumanReadable, CompareThisTypeOfChunk etc(Ideally program should not compile without such functions). Also I want to mark/register/enumerate all chunk-structs.
I have a few ideas but all of them have problems.

*

*Create base class with pure virtual functions PrintHumanReadable, CompareThisTypeOfChunk.
Problem:breaks pod type and requires library rewriting.

*Implement factory which creates chunk struct from CHUNK_ID. Problem: compiles when I add new chunk without required functions.

Could you recomend elegant design solution for my problem?

A: Implement a simple code generator.  You can use something like Mako or Cheetah (both Python libraries).  Make a text file containing all the class names, then have the generator build the factory method and a series of methods which aren't really used but which refer to the desired methods in all the classes.  This will also make it straightforward to enumerate the classes (again, using generated code).

A: The proper design pattern for this is called "use Boost.Serialization". It's really the best tool for writing objects to a format and then reading them back later. It can write in text, binary, and even XML formats (and others if you write a proper stream for them). It's can be non-intrusive, so you don't need to modify the objects to serialize them. And so forth.
Once you're using the proper tool for this job, you can then use whatever class hierarchy or other method you like to ensure that the proper functions for an object exist.
If you can't/won't use Boost.Serialization, then you're pretty much stuck with a runtime solution. And since the solution is runtime rather than compile time, there's no way to ensure at compile time that any particular chunk ID has the requisite functions.


text:
Q: Importing cyrillic text to illustrator via xml variable I'm working on a a little project that takes information from sql through php and saves into xml files which are then imported into illustrator.
The problem is that when using Cyrillic text in the xml file it does not appear once imported into illustrator just a blank space.
below is a simple one variable xml file I have been using to try to crack the problem.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN"    "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd" [
    <!ENTITY ns_graphs "http://ns.adobe.com/Graphs/1.0/">
    <!ENTITY ns_vars "http://ns.adobe.com/Variables/1.0/">
    <!ENTITY ns_imrep "http://ns.adobe.com/ImageReplacement/1.0/">
    <!ENTITY ns_custom "http://ns.adobe.com/GenericCustomNamespace/1.0/">
    <!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">
<!ENTITY ns_extend "http://ns.adobe.com/Extensibility/1.0/">
]>
<svg>
<variableSets  xmlns="&ns_vars;">
    <variableSet  varSetName="binding1" locked="none">
        <variables>
            <variable  category="&ns_flows;" varName="Variable1" trait="textcontent"></variable>
        </variables>
        <v:sampleDataSets  xmlns:v="&ns_vars;" xmlns="&ns_custom;">
            <v:sampleDataSet  dataSetName="Data Set 1">
                <Variable1>

Пена Для Ванн

                </Variable1>
            </v:sampleDataSet>
        </v:sampleDataSets>
    </variableSet>
</variableSets>
</svg>

any help would be greatly appreciated, this has been holding the project up for days now!

A: For normal XML, specify the language using an xml:lang attribute:

Пена Для Ванн

I am assuming Russian, but you can look at the specs to find the correct language.  Also maybe read this doc for help with this problem.
But also make sure that the font used to display the text within Illustrator shows Cyrillic correctly.
If none of that works, try putting it in CDATA tags as well.

A: I have had a problem with importing XML with links in CS5. Solved by updating the  Illustrator. Try to update yours.


text:
Q: PHP, urlencoding is encoding wrong string Sorry for this noobish question but I got stuck on this.
So what I am trying to do is:
to pass this data
$lines = 'Line 1\n Line 2\n Line 3\n';
array('lines' => $lines);

and I have to send this to another website via API
but the thing is, that when I send my API connection file
uses urlencode to encode the data that I am sending via API
and while doing this encoding, php turns
'Line 1\n Line 2\n Line 3\n'

to
'Line 1%5Cn Line 2%5Cn Line 3%5Cn'

and when this data goes via API, the other website doesnt understand these lines.
What should I do, to pass this line uneffected by urlencode? I tried adding " " since it will make it as one string alone but it doesnt work since I have to get those lines as $lines.
Thanks for your help.


text:
Q: What is the correct way for exception handling with OpenMP tasks? How should try-catch blocks be placed when your code uses OpenMP tasks? Should a try-catch block be defined inside each task or can a single try-catch block encompass all tasks? In other words consider this code:
int main()
{

    #pragma omp parallel
    {
        #pragma omp single
        {
            try
            {
              #pragma omp task
              { /*some code here*/ }

              #pragma omp task
              { /*some code here*/ }
            }
            catch(Exception &e)
            {
              //I want to do something here whenever one of the tasks throws an exception
            }
        }
    }

}

Is the above code correct if I want to catch any exception thrown by one of the tasks, in order to lets say print an error message corresponding to the exception and abort the program? Or do I need to define a try-catch block inside each task, like this?:
int main()
{

    #pragma omp parallel
    {
        #pragma omp single
        {
            #pragma omp task
            {
              try
              {
                /*some code here*/
              }
              catch(Exception &e)
              {
                //print an error message here if there is an exception in the task and abort the program
              }
            }

            #pragma omp task
            {
              try
              {
                /*some code here*/
              }
              catch(Exception &e)
              {
                //print an error message here if there is an exception in the task and abort the program
              }
            }

        }
    }

}

Or do I need a try-catch block inside each task but also surrounding all the tasks?

A: The OpenMP 5.1 specification states:

When any thread encounters a task generating construct, one or more explicit tasks are generated. Execution of explicitly generated tasks is assigned to one of the threads in the current team, subject to the thread's availability to execute work. Thus, execution of the new task could be immediate, or deferred until later according to task scheduling constraints and thread availability. Threads are allowed to suspend the current task region at a task scheduling point in order to execute a different task. If the suspended task region is for a tied task, the initially assigned thread later resumes execution of the suspended task region. If the suspended task region is for an untied task, then any thread may resume its execution. Completion of all explicit tasks bound to a given parallel region is guaranteed before the primary thread leaves the implicit barrier at the end of the region.

The specification also states:

A throw executed inside a parallel region must cause execution to resume within the same parallel region, and the same thread that threw the exception must catch it.

This means that the first code will generally not work because the runtime can execute a task later or even in another thread (waiting for work). In your example, the exception need to be catch in the inner code of all tasks in which you want to track an exception. However, it doe not means you need to copy the try-catch block in every tasks. You can define a function for that or a lambda with templates if you need to capture some local variable.
Here is an example:
// You can add more parameter to tune the error message regarding
// the code of the task. The error management could even be
// specialized another lambda.
template <typename FunType>
void catchExceptions(FunType lambda)
{
    try
    {
        lambda();
    }
    catch(Exception& e)
    {
        // Print an error message here if there is an exception in
        // the task and abort the program.
    }
}

int main()
{
    #pragma omp parallel
    #pragma omp single
    {
        #pragma omp task
        catchExceptions([&](){
            /*some code here*/
        });

        #pragma omp task
        catchExceptions([&](){
            /*some code here*/
        });
    }
}


text:
Q: Running gstreamer app in OpenVino using Windows subsystem in Linux (WSL2) My system main OS is  Windows-10 OS and installed WSL2 in subsystem.
Openvino is installed in Linux under WSL2. The reason is dlstreamer-gst is supported only in linux.
When I test the following test app, it works only for fps and display is not working.
If I run app as
./vehicle_pedestrian_tracking.sh person-bicycle-car-detection.mp4 10 CPU fps

I can see the output as
FpsCounter(1sec): total=346.54 fps, number-streams=1, per-stream=346.54 fps
FPSCounter(average): total=340.06 fps, number-streams=1, per-stream=340.06 fps
Got EOS from element "pipeline0".
Execution ended after 0:00:02.456260800
Setting pipeline to NULL ...
Freeing pipeline ...

When I run for display,
./vehicle_pedestrian_tracking.sh person-bicycle-car-detection.mp4 10 CPU dispaly

I have error as
ERROR: from element /GstPipeline:pipeline0/GstFPSDisplaySink:fpsdisplaysink0/GstXvImageSink:xvimagesink0: Could not initialise Xv output
Additional debug info:
../sys/xvimage/xvimagesink.c(1778): gst_xv_image_sink_open (): /GstPipeline:pipeline0/GstFPSDisplaySink:fpsdisplaysink0/GstXvImageSink:xvimagesink0:
Could not open display (null)
ERROR: pipeline doesn't want to preroll.
Failed to set pipeline to PAUSED.
Setting pipeline to NULL ...
Freeing pipeline ...

Is it display is not available in WSL subsystem?

A: Use MobaXTerm with WSL2 and change the command of xvimagesink to ximagesink in vehicle_pedestrian_tracking.sh.

A: My solution is I can't display but I can save to file as
gst-launch-1.0 filesrc location=video1.avi ! decodebin ! video/x-raw ! queue ! gvadetect model=/home/nyan/intel/dl_streamer/models/intel/vehicle-detection/FP16/model_fp16.xml model-proc=./model_proc/vehicle-detection.json inference-interval=10 threshold=0.6 device=CPU ! queue ! gvafpscounter ! filesink location=output.avi


text:
Q: c program is not asking value at a scanf funtion, it just going forward without asking c program is not asking value at a scanf funtion, it just going forward without asking
Here is my code....
#include <stdio.h>

int main() {

    float p, r, t, si;
    char A;

    printf("Principle Amount : ");
    scanf("%f", &p);

    printf("Rate of Intrest : ");
    scanf("%f", &r);

    printf("Time Period : ");
    scanf("%f", &t);

    si = ( p * r * t ) / 100;

    printf("Simple Intrest = %.2f \n", si);

    printf("Do you want to know the incremented amount ?\n");
    printf("Y for yes & N for no : ");
    scanf("%c", &A);

    if (A == 'Y') {
        printf("Incremented amount will be = %f", p + si);
    }
    else if (A == 'N') {
        printf("Thank You 4 using :-) ");
    }
    else {
        printf("INVALID INPUT");
    }
    return 0;
}

Log:
Principle Amount : 10000
Rate of Intrest : 5
Time Period : 2
Simple Intrest = 1000.00
Do you want to know the incremented amount ?
Y for yes & N for no : INVALID INPUT

It should ask me Y or N after "Y for yes & N for no : ", but it is abruptly taking the else condition.


text:
Q: Display a nested list with Primefaces dataTable I have a problem to display a string as a header of an row and a list of strings, which are the propertys of the header. Unfortunately, the data table is not displayed. I want to use p:columns to later sort and filter my data. What is the right approach to display a nested list in a Primefaces DataTable?
My bean:
public class MyBean implements Serializable {

private List<TableData> tableData = new ArrayList<TableData>();

public void fillData(){
this.tableData.add(new TableData("Key1", valueList));
this.tableData.add(new TableData("Key2", valueList2));
this.tableData.add(new TableData("Key3", valueList3));
...
...
...
}
  public List<TableData> getTableData() {
    return tableData;
  }

  public void setTableData(List<TableData> tableData) {
    this.tableData = tableData;
  }
}

My model:
public class TableData {

  private String key;
  private List<String> values = new ArrayList<String>();

  public TableData(String key, List<String> values) {
    this.key = key;
    this.values = values;
  }

  public String getKey() {
    return key;

  }

  public void setKey(String key) {
    this.key = key;
  }

  public List<String> getValues() {
    return values;
  }

  public void setValues(List<String> values) {
    this.values = values;
  }

}

My .xhtml
<p:dataTable value="#{myBean.tableData}" var="data">
  <p:columns value="#{data.values}" var="value">
        <f:facet name="header">
            <h:outputText value="#{data.key}" />
        </f:facet>
        <h:outputText value="#{value}" />
  </p:columns>
</p:dataTable>

A: This helped me alot to solve my Problem. My problem was, i used the wrong data structure.


text: Q: Uniformly magnetized sphere While working on a uniformly magnetized sphere, I have come across this problem: How does the boundary value equation $$\vec n.(\vec B_2-\vec B_1)=0$$ lead to the equation $$\phi_{out}|_{r=a}=\phi_{in}|_{r=a}$$ where, a is the radius of the sphere and $\phi$ is scalar potential?


text:
Q: How to create a new conda env based on a yml file but with different Python version I have a conda environment with python=3.6.0 and all it's dependencies. Now I would like to use this yaml file to create another environment with the same dependencies but with python=3.7.0 without the need for installing the packages with right version one by one.

A: *

*Export a minimal version of the environment:
conda env export -n old_env --from-history > env.yaml

*In the dependencies list of the YAML there should be a python entry, if not you can add one. Edit it to have the Python version you want.

*Create the new environment:
conda env create -n new_env -f env.yaml

A: # Activate old environment
conda activate so
# Save the list of package to a file:
conda list > log
# Extract the package name but not the version or hash
cat log | awk '{print $1}' > log2
# make the list of packages
tr '\n' ' ' < log2 > log3
# print the list of packages
cat log3

Use notepad to replace python by python==3.7. Then create a new environment with the edited list of packages.
conda create --name so2
conda activate so2
conda install _libgcc_mutex ... python==3.7 ... zstd

Conda will try to install all packages with the same name but different version.


text:
Q: What's the best way of forcing a DataGridView Cell to accept numeric input only? Currently I'm using:
Private Sub dgvStock_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvStock.CellEndEdit
    Select Case Me.dgvStock.Columns(e.ColumnIndex).Name
        Case "Quantity", "Unit Cost"
            If Not IsNumeric(Me.dgvStock(e.ColumnIndex, e.RowIndex).Value) Then
                Me.dgvStock(e.ColumnIndex, e.RowIndex).Value = 0
            End If
    End Select
End Sub

but is there a more elegant solution? It would be better to prevent the non-numeric input in the first place rather than fix it after entry.

A: The solution you have posted might work better if you listened for the KeyPress event rather than the CellEndEdit event. You could then check for valid values as the user types in the text box and revert to the previous value if the entered value is not valid.
Or alternatively, and this is not exactly what you are asking for, but you could have some sort of visual indicator to tell the user what they are typing is invalid, for example changing the ForeColor to Red? This would inform the user of the bad data while not confusing him or her with a text box that refuses certain key presses. That combined with your current post entry check might be a nice solution.

A: You may also set the ErrorText property of the row and check a flag or the error text at the RowValidating Event. If an error exists, set Cancel to true. Don't forget to set the errortext to an empty string when the value gets valid.
UPDATE:
I just tried this and came to better solution:
Check the value in the CellValidating event and set the errortext, because here you can cancel the validation. The currently entered value can be retrieved through the property grid[e.ColumnIndex, e.RowIndex].EditedFormattedValue


text:
Q: How to add compute shader functionality to a dx9 application targeting dx11 hardware I'm using a dx9 app I cannot update to dx11.
I have some compute shaders I want to port to this app, but I don't know what can I use to write directly to dx9 textures and possibly buffers(it's realtime graphic so coping data around is not acceptable).
It have to work on Intel , Amd and Nvidia gpus (all dx11 ready) so CUDA is not an option.
I don't know if you can share resources between dx11 and dx9 devices, but it will solve all my problems.The actual scenario is to take a rendertarget from dx9 and share it.
Aquire it in dx 11 process it by the compute shader and write the content in a shared dx11 texture i can bind in dx9 for rendering.
I was also oriented torward opencl as I have read of some dx9 interop online.
I tryed to download Amd app sdk, but in documentation i didn't find any reference to dx9 interop(some words about dx10 but all documentation is focused around opengl interoperation).I haven't checked opencl sdk from other vendors.
also c++ amp seems to not work with dx9.
Do you know if this is possible and if so what gpgpu solution that can do the job if i cannot use Dx11<->Dx9 shared resource thing?


text:
Q: How to interrupt a thread in executor service in Spring Boot? I'm creating a batch job in Spring Boot and executing the batch job in a single thread executor service. The code in the nutshell is like this:
Controller:
class TestController {
    // Autowired service and the executorService
    @PostMapping
    public Boolean runTask() {
        es.submit(new BatchTask(service))
        return true;
    }
}

Task:
class BatchTask extends Callable<Void> {
    private BatchService service;
    // Constructor
    @Override
    public Void run() {
        service.runTask();
        return;
    }
}

Service:
class BatchService {
    private Repository repo;
    public void runTask() {
        try (Stream<String> lines = Files.lines(someFileHere)) {
           Iterator<String> it = lines.iterator();
           while (it.hasNext()) {
               // Validate record, update database, etc
               if (Thread.currentThread().isInterrupted()) {
                   // Log params, etc
                   throw new InterruptedException();
               }
           }
        } catch (InterruptedException ex) {
            // Cleanup, update databases, mark record status as paused in db
        }
        // empty lines here, no process any longer after the catch
    }
}

I'm trying to create the test for the interrupted case. The problem is it didn't set the thread interrupted flag even though I called the shutdownNow() method on the executor service or if using a single Thread instance, the interrupt() method causing the process to proceed until the end. I have created a single file that has enough records for a long process for this test.
The test is basically:
@Test
public void test() {
    ExecutorService es = Executors.newSingleThreadedExecutor();
    es.submit(new BatchTask());
    es.shutdownNow();
    // assert record's status in database should be paused
}

Am I missing something here? I'm open to suggestions or better ways to do this. Thanks.
Edit: this is for a graceful shutdown. I'm using MongoDB as my database.

A: I don't really see the problem. If I execute this minimal test case, the cleanup part is called as expected.
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Hello {
  public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(new BatchTask());
    Thread.sleep(1_00);
    es.shutdownNow();
  }

  static class BatchTask implements Callable<Void> {
    private BatchService service = new BatchService();

    @Override
    public Void call() throws Exception {
      service.runTask();
      return null;
    }
  }

  static class BatchService {
    public void runTask() throws IOException {
      try {
        while (!Thread.currentThread().isInterrupted()) {
          System.out.println("not yet interrupted");
        }
        throw new InterruptedException();
      } catch (InterruptedException ex) {
        System.out.println("Cleaning up: " + Thread.currentThread().isInterrupted());
      }
    }
  }
}

I clearly see the message Cleaning up: true being printed after a few not yet interrupted messages. So my best guess would be that either, your operation is executed faster than the thread is being interrupted. Try putting some sleeps here and there to see what happens. Or your interruption check in your actual code base has a flaw somewhere.


text:
Q: Verify triginometric result of cubic equation $x^3-x^2-p^2x+p^2=0$ Consider the following cubic function,
$$f(x):=(x+p)(x-p)(x-1)=x^3-x^2-p^2x+p^2$$
where $p\in(0,1)$ is a fixed parameter.
Then the sum of the absolute value of the three roots is
$$S_1:=1+2p$$
On the other hand, if I use the trigonometric root formula to calculate the absolute sum, I obtained
$$ S_2:=\frac{4}{3} \sqrt{1+3p^2}\, \cos \Bigg(\frac{1}{3}\arccos\Bigg(\frac{1-9p^2}{(1+3p^2)^{\frac{3}{2}}}\Bigg)-\frac{\pi}{3}\Bigg)+\frac{1}{3}$$
Then, obviously, the $\textbf{following is true}$ $$S_1=S_2 \quad \forall p\in(0,1)$$
$\textbf{Question:}$ Is there a way to verify $S_1=S_2$ by direct calculation?
(I've tried with the Taylor series of the $\arccos(x)$ but I've not succeded.)

A: Let
$$ \theta = \arccos \left(\frac{1-9p^2}{(1+3p^2)^{\frac{3}{2}}} \right)-\pi$$
Then,
$$ S_2=\frac{4}{3} \sqrt{1+3p^2}\, \cos \frac{\theta}3+\frac{1}{3}\tag1$$
and
$$\cos\theta =-\frac{1-9p^2}{(1+3p^2)^{\frac{3}{2}}}=4\cos^3\frac{\theta}3 - 3\cos\frac{\theta}3$$
Factorize
$$\left(2\cos\frac{\theta}3 - \frac{1+3p}{\sqrt{1+3p^2}} \right)
\left(2\cos^2\frac{\theta}3 + \frac{1+3p}{\sqrt{1+3p^2}} \cos\frac{\theta}3
+\frac{3p-1}{1+3p^2}\right) =0 $$
to get
$$\cos\frac{\theta}3 = \frac{1+3p}{2\sqrt{1+3p^2}}$$
Plug into (1) to obtain
$$ S_2
=\frac{4}{3} \sqrt{1+3p^2}\cdot \frac{1+3p}{2\sqrt{1+3p^2}}+\frac{1}{3}
=1+2p=S_1
$$


text:
Q: How to change user of docker service? I'm having problem because i've installed & started docker as a "bad_user". The problem is that this container generates static files (its jekyll/jekyll image), and those files are owned by "bad_user" so i cannot edit them (i know i could add myself to bad_user group or own the dir by chown -R but it would be painful to do every time, and it just bugs me :).
I have tried to reinstall docker & removing /etc/docker directory without any effect. Every time i reinstall it (docker service/manager) runs as "bad_user" and overwrites directory owner.
My question is:
Would that be possible to make docker running under "docker" user ? I have already created that user with that group (yes, i have reinstalled docker-ce under that user already).
Im working on debian-based distro.
I guess in my case its docker daemon issue, somehow when its syncrhonizing shared volume files it gives permission to bad_user instead of user who is running container.
PS. This is the command i run if that matters:
docker run --rm -p 8000:8000 \
  --volume="/home/docker/blog:/srv/jekyll" \
  -it tocttou/jekyll:3.5 \
  jekyll serve --watch --port 8000

A: Okay i figured it out. It turns out that when you run linux container that creates some files on the shared volume (the -v argument makes shared volume), the file permissions will be for user with grup id = 1000 and id = 1000. In my case user with id=1000 was "bad_user". If you want to workaround that you can use --user and specify user id that you're running under.
The key is to remember that linux permissions are just numbers, for host filesystem number 1000 is (in my case) "bad_user" and 10001 is "docker_user". If you check permissions from inside of the container you'll might see that user id = 1000 means very different user than on your host system.
I hope that next people who will encounter this issue will find that userful.
You can find more information here: https://dille.name/blog/2018/07/16/handling-file-permissions-when-writing-to-volumes-from-docker-containers/


text:
Q: FA: Inactivity, disconnecting from the service Error
*V/FA: Activity resumed, time: 710539857
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 4
I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=75f5f87c-7328-4690-a1a6-f6363ce20d91, tags={ com.actofit.coach_pro.worker.GetClubInvitesWorker, GetClubInvitesWorker } ]
V/FA: Inactivity, disconnecting from the service*
Farther Process is not working.
I try below steps:
Uninstall the app from your mobile/emulator.
Then go to the File option in the main menubar in the android studio.
Then click on Invalidatecasha/restart.


text:
Q: Tomcat 7 manager /text interface does not work I've just setup a new Tomcat 7.0.59 installation and added the Tomcat Manager application to web-apps. I'm able to login and use the web interface to manager via http://host:8080/manager/html as I could with Tomcat 6. The Tomcat 7 documentation (http://tomcat.apache.org/migration-7.html#Manager_application) states:

Note that the URL for the text interface has changed from "" to "/text"

The problem that I have is that using the /text URI attribute doesn't work.

*

*http://host:8080/manager/list  (works)

*http://host:8080/manager/text/list (returns 404)

Is there some configuration setup that I need to do in order to get this to work properly?

A: Edit your tomcat-users.xml to have a user with the manager-script role. It should look something like this:
<tomcat-users>
    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <user username="<username>" password="<password>" roles="manager-gui,manager-script"/>
</tomcat-users>

On my ubuntu system, the file is located in /etc/tomcat7/tomcat-users.xml

A: Ok, so the recommendations for the manager-script role were important to solving my issue and for that I thank dnault and James for your feedback as I missed that in the documentation.
The biggest issue for the /manager/text not working was a bonehead mistake on my part. We breakout the catalina_home directory from the binary distribution of Tomcat. If I need manager for an installation, I create a symlink from the catalina_home/web-apps directory to the distribution web-apps/manager directory. In doing so, I linked it to the Tomcat 6 distro instead of Tomcat 7.
Changing the symlink and adding the manager-script solved my issue.

A: I think the root cause is server refuse maven's write action, Here my solution:
<user username="xxx" password="xxx" roles="manager-gui,manager-script,manager-jmx,manager-status"/>


text:
Q: screen command process id First of all sorry for my bad english and i am new at linux.
When i do this, it can write process id to pid file
start () {
    echo -n "Starting someserver.jar: "

    java -jar /home/someserver/someserver.jar &
    echo $! > /home/hcserver/hcserver.pid
}

And know i am using this command but it can't write to pid file
start () {
    echo -n "Starting someserver.jar: "

    screen -S someserver java -jar /home/someserver/someserver.jar
    echo $! > /home/someserver/someserver.pid
}

How can i get process id or fix this?
Edit:
root@server:/home/someserver# ps -ef | grep java
root      4332     1  0 22:03 ?         SCREEN -S someserver java -jar /home/someserver/someserver.jar
root      4333  4332  0 22:03 pts/0     java -jar /home/someserver/someserver.jar
root      4363  3222  0 22:04 pts/3     grep java

I want to write 4333 process id to pid file

A: So, you're trying to replace a script that starts a long-running java command in the background with one that runs it in screen?
I think there are actually two problems with your screen attempt. First off, that screen command won't exit/background until the java command is finished (or an interactive user types some things). Secondly, $! isn't really going to do quite what you want here.
In order to get screen to background properly, use:
screen -d -m -S someserver java -jar /home/someserver/someserver.jar

The -d -m combo will start screen in a detached (background) state, which is generally what you want for a startup script. It will automatically exit and cleanup if the java process exits.
So, now that you've got screen properly backgrounded at startup time, you still need to get the pid of the process so that you can control (or at least stop) it. But it's actually fairly tricky to capture that pid. I think you could do it by some combination of parsing screen -ls output, parsing /proc/ data and/or parsing ps output, but it would be tricky. By far, the easiest thing to do, instead, is to use screen itself to control that process. That is, in your stop() routine, instead of killing the pid of the java proccess, do something like this:
stop () {
  echo -n "Stopping someserver.jar: "
  screen -X -S someserver quit
}

That will tell the screen session (which you've already identified via -S earlier) to kill all processes under its control and exit.
If you really need the process id of the child process, something like this should do the trick:
cd /var/run/screen/S-$(whoami)
parentpid=$(ls *.someserver | cut -d. -f1)
pid=$(ps --ppid $parentpid -ho pid)

A: Not 100% sure I understand your question, but lets try :
$! would work from the parentshell, not from inside the child process
$! is for a background process, screen is not exactly a background process
Also screen -S will not detach the screen, you probably need more screen options
you probably want something like
screen -dmS

also from inside the screen you can try $$ and $BASHPID
you could find the pid of the screen using
screen -list | grep someserver | cut -f1 -d'.' | sed 's/\W//g'

killing the pid of the screen should also kill whatever is running inside the screen
if you re sure the pid of the detached screen is not enough for you try using pgrep to get the pid of the java stuff


text:
Q: What other shielding material than lead is effective against gamma rays? As the question in the title states I am wondering what material can be effectively used to shield gamma rays apart from lead? I believe concrete is often used, but it is nowhere near as effective as lead (6 cm to match 1 cm of lead as I understand it). I also hear significant bodies of water helps, as does tightly packed dirt, but surely there must be other materials that shield nearly as effectively as lead?

A: There are three processes by which gamma rays interact with matter: the photoelectric effect, Compton scattering, and pair production.
The photoelectric effect is an interaction between the gamma ray and an electron. It's forbidden by conservation of energy and momentum unless there is some other body present as well, such as an atomic nucleus. For this reason, the probability of the photoelectric effect is proportional not just to the density of electrons but also approximately to $Z^n$, where $Z$ is the atomic number and $n$ is about 4 to 5.
Compton scattering can occur without the presence of anything besides an electron, so it only depends on electron density.
Pair production goes like $Z^2$ at typical gamma-ray energies.
For these reasons, the best shielding against gamma rays is achieved with a substance that has a high density of electrons (which correlates with a high mass density) and also a high $Z$. Lead has these properties. It's also cheap. There are elements with a higher $Z$, such as bismuth, polonium, and uranium, but they aren't cheap, and their atomic numbers are only slightly higher.

A: There is nothing magical about lead for this purpose. The driving factor is the number of electrons per unit volume, which reduces (to a first approximation) to the mass density.
You get very good (better than lead) shielding performance from gold, tungsten, mercury, etc; and quite reasonable performance from iron or copper.
Question for the student: why is lead such a common choice for this application?

A: Lead is used commonly for two reasons. Being heavy metal it occupies less space; cheaper than other metals like Gold; and significantly absorbs low and medium energy gamma radiation.
Materials like concrete can also be used but occupies much space because thick concrete is needed. Detailed data is available on the Internet and in books on Radiological Physics and Radiation Protection. However, Research on newer shielding materials is very much needed.

A: I have read that closed-cell-foam is an excellent barrier against high energy radiation. Closed-cell-foam is more commonly known as "foam rubber," and a high density version of it is what Tempur-Pedic matresses are made of.


text:
Q: Почему качество Java GUI существенно снижается после упаковки в exe? Я использую jpackage для того чтобы преобразовать jar файл в exe, при этом exe файл будет обеспечивать внутренняя JRE. В результате преобразования получились хорошие результаты, JRE весит около 38,5 мб.
Когда я запускаю exe, качество GUI в два раза ХУЖЕ, чем в обычном jar! Кроме того окно нового exe файла самостоятельно увеличивается. Таким образом, появляются очень странные изменения, как будто exe файл пытается имитировать окно jar файл. Хочу отметить, что я использую libGdx для GUI.
Часть gradle desktop
task dist(type: Jar) {
manifest {
    attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
destinationDirectory = file("$buildDir/lib")

}
jpackageImage.dependsOn dist
dist.dependsOn classes
eclipse.project.name = appName + "-desktop"
runtime {
options = ['--strip-debug',
'--compress', '2',
'--no-header-files',
'--no-man-pages',
'--strip-native-commands',
'--vm', 'server']
modules = ['java.base' ,
'java.desktop',
'jdk.unsupported']
distDir = file(buildDir)
jpackage {
    jpackageHome = 'C:\\Program Files\\Java\\jdk-17.0.2'
    mainJar = dist.archiveFileName.get()
    if (osName.contains('windows')) {
        imageOptions = ["--icon", file("../icons/icon.ico")]
    } else if (osName.contains('linux')) {
        imageOptions = ["--icon", file("../icons/icon.png")]
    } else if (osName.contains('mac')) {
        imageOptions = ["--icon", file("../icons/icon.icns")]
    }
}

}
Сравнение:


text:
Q: Laravel migrate Я установил laravel, мне в архиве отправили 5 миграций (create_user_table) и т.д. Я работаю через MAMP. Запускаю phpMyAdmin, создаю базу данных. В .env в DB_DATABASE прописываю название базы, после ввожу php artisan migrate.
Получаю вот это:
SQLSTATE[HY000] [1049] Unknown database 'operator_service' (SQL: select * from information_schema.tables where table_schema = operator_service and table_name = migrations and table_type = 'BASE TABLE')
  at C:\MAMP\htdocs\Users\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671
    667▕         // If an exception occurs when attempting to run a query, we'll format the error
    668▕         // message to include the bindings with SQL, which will make this exception a
    669▕         // lot more helpful to the developer instead of just the database's errors.
    670▕         catch (Exception $e) {
  ➜ 671▕             throw new QueryException(
    672▕                 $query, $this->prepareBindings($bindings), $e
    673▕             );
    674▕         }
    675▕
     }
    675▕
  1   C:\MAMP\htdocs\Users\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [1049] Unknown database 'operator_service'")
  2   C:\MAMP\htdocs\Users\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct()

Ошибку гуглил. Делал php artisan config:cache; clear. Нашел вот такое решение: 'unix_socket' => env('DB_SOCKET', '/Applications/MAMP/tmp/mysql/mysql.sock'),, не уверен, что оно подходит. Подскажите как быть дальше?

A: Попробуйте выставить в .env эту строку "DB_HOST", вот так:
DB_HOST=127.0.0.1


text:
Q: Android Cursor error - Make sure cursor is initialised correctly I've set up a Cursor which I want to return a listview of contacts who have a phone number. So, in each cell, I'll have the contact name and then phone number underneath. This code mostly does the job :
// this query only return contacts with phone number and is not duplicated
        phones = getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI,
                null,
//                we only want contacts that have a name and a phone number. If they have a phone number, the value is 1 (if not, it is 0)
                ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'" + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                null,
                ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

And then when it comes to extracting information and putting it in each cell :
        while (phones.moveToNext()) {

            String name = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

I'm getting an error, part of the code which is:
04-07 10:43:46.489  17742-17760/com.example.chris.contactlistcustomlistview E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 134 rows, 34 columns.
04-07 10:43:46.489  17742-17760/com.example.chris.contactlistcustomlistview W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x416168e0)
04-07 10:43:46.489  17742-17760/com.example.chris.contactlistcustomlistview E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
            at android.database.CursorWindow.nativeGetString(Native Method)

So, the cursor is hopping from Contacts.Contracts to ContactsContract.CommonDataKinds.Phone and it doesn't like it. But how else can I get the phone number of a user ? As far as I know, it's not in ContactsContracts.Contacts. Should I reinitialize the cursor or something before going to CommonDataKinds and how would I do this?

A: Have you tried calling phones.moveToFirst() before phones.moveToNext()? It moves to the first row. This is because your current query returns a Cursor object positioned before the first entry.
You can try writing:
if (phones.moveToFirst()) {

       while (phones.moveToNext()) {
                    // etc

A: if (phones != null) {
    phones.moveToFirst();
}


text:
Q: What conditions cause a party to naturally occur? According to the change log for Terraria 1.3.2 (emphasis is mine):

Parties have now been added! You can start your own via the Party Girl's Party Center or the Town NPCs may start one, if certain conditions are met

What conditions must be met for a party to naturally occur? The wiki entry on the Party event doesn't list anything specific.

A: According to this link, a party has a random chance of naturally occurring at dawn, and no conditions need to be met for a party to be naturally hosted- but I'd guess you'd need at least one NPC in your world to act as the host for a party.
Edit:
 I've tested the theory and have conformed that a party can naturally occur in a world without the need for a party machine. The world I used was a small, non-Expert mode pre-hardmode world. The only NCPs that had moved in were the guide, merchant, dye trader, arms dealer, demolitionist, nurse, painter, clothier, mechanic and dryad.


text:
Q: Is it possible to create an operating system using Python? Is it possible to make a minimalistic operating system using Python?
I really don't want to get into low-level code like assembly, so I want to use a simple language like Perl, Python. But how?

A: Unfortunately Python is classified as a very high level programming language. It cannot be used, for example, to directly access hardware and perform low-level data structure manipulation. It is completely dependent on something to abstract the hardware from it, and that is the Kernel. It is, however, technically possible to create an operating system centered on Python, that is; have only the very low level stuff in written in C and assembly and have most of the rest of the operating system written in Python.
This article discusses with more detail what languages are suitable for writing operating system kernels.

A: You can certainly run Python without an OS, as shown by the The Intel BIOS Implementation Test Suite (BITS) Project. The scripting guide explains:
"... includes Python APIs to access various low-level functionality of the hardware platform, including ACPI, CPU and chipset registers, PCI, and PCI Express. You can write scripts to explore and test platform functionality, using the full power of Python in 32-bit ring 0, without an OS in the way.. "
Now, BITS is a BIOS testing platform specific to Intel hardware, and not meant to run a custom Python based OS, but that doesn't mean you couldn't try it...

A: I have ported Python interpreter to run in my operating system as a userspace program, it was the first program - and so far the only - that I ported; from this experience, I'd say it would certainly possible to write lots of the operating system functionality in Python; you can certainly even embed Python in the kernel with rather minimal feature support.
However you need to write assembly and C for the interrupts, low level memory management and so. In my case, I built a specially modified Python 2.5.2 against the Newlib C library; in minimal case you just need to provide heap memory management for the Newlib library, and you can have Python running on top of it.
As such, Python interpreter does not contain its own heap implementation, and it does depend on the C library, so you cannot run it on bare metal right away, but much more of the operating system kernel as is conventionally written, could also could be written in Python.
The special case of course are the microkernels, where much of the functionality is in userspace as services; these can be more naturally implemented in any preferred programming language, Python included.

A: I suggest you find a good textbook on operating system design, and study that.  I'm pretty sure you won't find such a book with Python source code; C is more likely.  (You might find an older textbook that uses Pascal instead of C, but it's really not that different.)
Once you have studied operating systems design enough to actually be able to write an operating system, you will know enough to have your own opinions on what languages would be suitable.


text:
Q: JavaScript: what is the fastest hexadecimal string to ArrayBuffer algorithm? Looking for a performant algorithm for parsing any-length hexadecimal strings into Uint8Arrays. I specifically care about use with Chrome and Firefox's engines.
A common approach used in code snippets:
function hex2bytes(string) {
  const normal = string.length % 2 ? "0" + string : string; // Make even length
  const bytes = new Uint8Array(normal.length / 2);
  for (let index = 0; index < bytes.length; ++index) {
    bytes[index] = parseInt(normal.substr(index, 2), 16); // Parse each pair
  }
  return bytes;
}

Another common (bad) approach is to split the string using the regular expression /[\dA-F]{2}/gi and iterate over the matches with parseInt.
I've found a much faster algorithm using charCodeAt:
function hex2bytes(string) {
  const normal = string.length % 2 ? "0" + string : string; // Make even length
  const bytes = new Uint8Array(normal.length / 2);
  for (let index = 0; index < bytes.length; ++index) {
    const c1 = normal.charCodeAt(index * 2);
    const c2 = normal.charCodeAt(index * 2 + 1);
    const n1 = c1 - (c1 < 58 ? 48 : 87);
    const n2 = c2 - (c2 < 58 ? 48 : 87);
    bytes[index] = n1 * 16 + n2;
  }
  return bytes;
}

Can I do better?


text:
Q: Como pegar o item pesquisado com autocomplete? Tenho um autocomplete que funciona perfeitamente. Como que eu faço para pegar o item pesquisado e colocar dentro de uma div? Tipo pesquiso x-salada e quando clicar ele coloque x-salada dentro da div. A função AutoCompleteSelectHandler(event, ui) não retorna nada.
// BUSCA COM AUTOCOMPLETE
var resultadoLanche = [];
// Captura o retorno do retornaCliente.php
$.ajax({
  url: urlBase + "produtos?filter[categoria_id]=" + idcategoria,
  method: 'GET',
  success: function(retorno)
  {

    retorno.data.forEach(function(item)
    {
      resultadoLanche.push(item.nome);

    });
  },
  error: function(XMLHttpRequest, textStatus, errorThrown)
  {
    alert("Status do Servidor: " + textStatus);
    alert("Erro do Servidor: " + errorThrown);
  }
});

// ativar o autocomplete
$('#buscarProduto').autocomplete(
  {
    source: resultadoLanche,
    select: function(event, ui)
    {
      $('#buscarProduto').val(ui.item.value);
    },
    minLength: 3
  }
);

function AutoCompleteSelectHandler(event, ui)
{
  alert('teste');
var teste = $('#buscarProduto').val(ui.item.value);

}

A: Tenta substituir:
$('#buscarProduto').val(ui.item.value);

Pelo ID da respectiva div e a função .text()
$('#divParaExibir').text(ui.item.value);

A: Não é necessário o uso da função AutoCompleteSelectHandler neste caso.
Basta aqui no seu select
select: function(event, ui)
{
  $('#buscarProduto').val(ui.item.value);
},

você substituir o código $('#buscarProduto').val(ui.item.value); para $('#buscarProduto').html(ui.item.value);. Se o value existir, será inserido na div. Normalmente o val() insere e captura informações de inputs.
Faz esse teste e vê se consegue resolver!


text:
Q: Transfer Eth through smart contract to other account? In the below code eth will be transferred in the form of Wei by default, but I want the amount will transfer in the form of Ether, how can I do that?
function (uint amount) public payable {
someaddress.transfer(amount);
}

A: Wei is the smallest unit of Ether, specifically 1 ETH == 1,000,000,000,000,000,000 (or 1e18) wei.
The transfer() function always accepts the amount in wei. So if you want to pass just 1 as the input param, meaning that you want to send 1 full ETH, you can multiply the value by 1e18 effectively converting ETH to wei.
function (uint ethAmount) public payable {
    uint weiAmount = ethAmount * 1e18;
    someaddress.transfer(weiAmount);
}

Note: There's also the ether global unit, but in the current Solidity version (0.8), this can be used only in combination with number literals - not with variables.
uint weiAmount = 1 ether; // ok

uint weiAmount = ethAmount ether; // syntax error


text:
Q: OSError: [WinError 10049] How do I tackle this error? I am trying to stream a video feed from a Raspberry Pi to my machine using python. Therefore, I need to connect a socket to the server.
(Streaming video directly at 192.168.0.6:8081 from RPi before executing these)
On my computer I execute this code:
import numpy as np
import cv2
import socket

class VideoStreamingTest(object):

    def __init__(self):
        self.server_socket = socket.socket()
        self.server_socket.bind(('192.168.0.6', 8081))
        self.server_socket.listen(0)
        self.connection, self.client_address = self.server_socket.accept()
        self.connection = self.connection.makefile('rb')
        self.streaming()

def streaming(self):
    try:
        print ("Connection from: ", self.client_address)
        print ("Streaming...")
        print ("Press 'q' to exit")

        stream_bytes = ' '
        while True:
            stream_bytes += self.connection.read(1024)
            first = stream_bytes.find('\xff\xd8')
            last = stream_bytes.find('\xff\xd9')
            if first != -1 and last != -1:
                jpg = stream_bytes[first:last + 2]
                stream_bytes = stream_bytes[last + 2:]
                #image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_GRAYSCALE)
                image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
                cv2.imshow('image', image)

                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
    finally:
        self.connection.close()
        self.server_socket.close()

if __name__ == '__main__':
    VideoStreamingTest()

During compiling it raises this error:
Traceback (most recent call last):

File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 43, in <module>
    VideoStreamingTest()

File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 11, in __init__
    self.server_socket.bind(('192.168.0.6', 8081))

OSError: [WinError 10049] The requested address is not valid in its context

EDIT: This is also giving
Traceback (most recent call last):
  File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 47, in
<module>
    VideoStreamingTest()
  File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 17, in
__init__
self.connection = self.socket.create_connection(('192.168.0.6', 8081))
AttributeError: 'socket' object has no attribute 'create_connection'

So I tried to replace create_connection with connect_ex and it still is giving erros.. :(
class VideoStreamingTest(object):
    def __init__(self):

    #self.server_socket = socket.socket()
    #self.server_socket.bind(('192.168.0.6', 8081))
    #self.server_socket.listen(0)

    #self.connection, self.client_address = self.server_socket.accept()
    #self.connection = self.connection.makefile('rb')
    #self.streaming()
    self.socket = socket.socket()
    self.connection = self.socket.create_connection(('192.168.0.6', 8081))
    #self.socket.connect(('192.168.0.6', 8081))
    self.streaming()

def streaming(self):

    try:
        #print ("Connection from: ", self.client_address)
        print ("Streaming...")
        print ("Press 'q' to exit")

        stream_bytes = ' '
        while True:
            stream_bytes += self.connection.read(1024)
            first = stream_bytes.find('\xff\xd8')
            last = stream_bytes.find('\xff\xd9')
            if first != -1 and last != -1:
                jpg = stream_bytes[first:last + 2]
                stream_bytes = stream_bytes[last + 2:]
                #image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_GRAYSCALE)
                image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
                cv2.imshow('image', image)

                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
    finally:
        self.connection.close()
        self.socket.close()

if __name__ == '__main__':
    VideoStreamingTest()

A: You have to change the IP address in the bind command of the socket to the IP address of device which is offering the server, i.e. the address of your own pc. The code you posted here is not going to do what you want to do: it will create a new server and will not act as a client which can connect to a server!
This lines
self.server_socket.bind(('192.168.0.6', 8081))
self.server_socket.listen(0)

have to be replaced with
self.socket.connect(('192.168.0.6', 8081))

Edit: Maybe it is better to use the create_connection function, as it operates on a higher API level. So you will end up with this initialization method:
def __init__(self):
    self.socket = socket.socket()
    self.connection, _ = self.socket.create_connection(('192.168.0.6', 8081))
    self.streaming()

In the streaming method you then have to remove this line, also:
print ("Connection from: ", self.client_address)


text:
Q: What's the proper way to configure a bridged network that has their own internet at each end? I'm needing to connect two houses on the same property together, about 1400ft apart. I need to simultaneously access and login to a Quickbooks file on the other computer all using Windows, and of course cloud storage doesn't work with Quickbooks. We're going to put up a wireless bridge outside to connect the houses together. Each location has their own internet and preferably use their own internet.
I'm trying to find the best way to configure the network at each household. Should I configure each with their own subnet? I.E. 192.168.1.# and 192.168.2.#? Then somehow program a static route in a router so one computer can see the shared directory of another computer on the other network? But I thought on routers you have to disable NAT and/or DHCP in able to program a static route which may cause issues.
Or should I install a router in the middle of the bridge and have the bridge go through the WAN port so I could possibly block ports 67 and 68 that are responsible for DHCP so one household doesn't get a DHCP IP from the other household and keep both on the same subnet?
Or should I enable DHCP at both locations and assign one household from .1 to .128 and other household .128 to .254? I don't know how that would work to keep DHCP isolated to their own house.
Any help would be much appreciated.

A: Assuming you only require a one-way connection from the network without QuickBooks to the one hosting it, you can connect your networks with a standard consumer router. Here's how that would look:
For the following, assume House A has QuickBooks, and House B wants to connect to QuickBooks.

*

*Configure each home's network with its own separate IP subnetwork address, gateway, DNS, DHCP, etc.

*Connect the new router's LAN port to House A's network. Assign it an IP address on that network. Disable DHCP services on the router.

*Connect House B, via the wireless bridge, to the router's WAN port. Configure the WAN port with an IP address valid on House B's network.

*Configure any required port forwarding rules to connect traffic from House B to the computer in House A hosting QuickBooks. Alternately you can configure the router to put the IP address of the QuickBooks host in the router's DMZ. This would serve as a giant "forward all ports" rule.

*Add a static route on the QuickBooks computer that points traffic destined to the IP subnetwork of house B to the LAN interface of the router. Alternately, if House A's router can be configured with static routes, put it there.
What you'll end up with looks like this:

House B PC --> bridge --> Router (with port forwarding) --> House A PC w/QuickBooks

Because you use a router to separate the networks, no broadcast or other traffic will go between them, except for the traffic you specifically allow with the port forward rules.
To Connect to QuickBooks
From House B, connect to the IP address of the router's WAN interface. Your connection will be forwarded to the PC in House A hosting QuickBooks. Easy-peezy.
From House B's perspective, the router's WAN IP address is the QuickBooks computer. From House A's perspective,  the router's LAN port is a dead-end. Attempts to connect to it don't go anywhere since there's nothing being hosted in House B to connect to.

On another note, QuickBooks is picky about the quality of the network connection between the application and its database. I see it often kick users connecting over high quality wireless links. If you run into trouble because of needing to use the wireless bridge, consider using Remote Desktop or a similar remote PC access solution to connect the the PC in House A and run QuickBooks there directly.


text:
Q: Sharing keys and certificates between SQL Server 2014 server for encrypted backup and restoration I have six SQL Server 2014 servers.  I am not using TDE, Transparent Data Encryption, on any server.
I would like to be able to take an encrypted backup of a database on ANY server and restore that backup to ANY OTHER server.
What actions do I need to take on each server with the service master key, master database key,  and certificate? I would like to use the minimum number of keys, certificates, and backup files for these keys and certificates.
What actions do I need to take if I add an additional SQL Server 2014 to the group?
Thank you all.  Server Fault and Stack Overflow have helped me many times in the past.

A: SQL Server has two primary applications for keys: a service master key (SMK) generated on and for a SQL Server instance, and a database master key (DMK) used for a database.
The SMK is automatically generated the first time the SQL Server instance is started and is used to encrypt a linked server password, credentials, and the database master key. The SMK is encrypted by using the local computer key using the Windows Data Protection API (DPAPI).
The DPAPI uses a key that is derived from the Windows credentials of the SQL Server service account and the computer's credentials. The service master key can only be decrypted by the service account under which it was created or by a principal that has access to the machine's credentials.
The database master key is a symmetric key that is used to protect the private keys of certificates and asymmetric keys that are present in the database. It can also be used to encrypt data, but loker it has length limitations that make it less practical for data than using a symmetric key.
When it is created, the master key is encrypted by using the Triple DES algorithm and a user-supplied password. To enable the automatic decryption of the master key, a copy of the key is encrypted by using the SMK. It is stored in both the database where it is used and in the master system database.
The copy of the DMK stored in the master system database is silently updated whenever the DMK is changed. However, this default can be changed by using the DROP ENCRYPTION BY SERVICE MASTER KEY option of the ALTER MASTER KEY statement. A DMK that is not encrypted by the service master key must be opened by using the OPEN MASTER KEY statement and a password.
or visit https://msdn.microsoft.com/en-us/library/bb964742.aspx


text:
Q: Getting facebook id of all persons who shared a particular video uploaded on youtube Let's say I uploaded a video on youtube and someone shared that video on facebook by clicking the "share" button on youtube. How could I get the facebook id or username of that person. I  tried using the youtube gdata api and also tried facebook graph api, but could not succeed. I am quite sure that it is possible as i have seen this functionality implemented on a website.

A: This is only possible for the developers of the YouTube Facebook application to know about. You can get all friends of the current user who shared a particular video.
For example,
SELECT link_id, owner, owner_comment, created_time, title, summary, url, picture, image_urls FROM link WHERE owner in (select uid2 from friend where uid1 = me() limit 5) and strpos(url, 'lmDTSQtK20c') >= 0
Not quite efficient but it works.
A second way would be to use /search
/search?q=http://www.youtube.com/watch?v=YOUTUBEID&type=post
That should search public posts


text:
Q: DDD - Invariant enforcement using instance methods and a factory method I'm designing a system using Domain-Driven design principals.
I have an aggregate named Album.
It contains a collection of Tracks.
Album instances are created using a factory method named create(props).
Rule 1: An Album must contain at least one Track.
This rule must be checked upon creation (in Album.create(props)).

Also, there must a method named addTrack(track: Track) so that a new Track can be added after the instance is created. That means addTrack(track: Track) must check the rule too.
How can I avoid this logic code duplication?

A: Well, if Album makes sure it has at least one Track upon instantiation I don't see why addTrack would be concerned that rule could ever be violated? Did you perhaps mean removeTrack?
In that case you could go for something as simple as the following:
class Album {
  constructor(tracks) {
    this._tracks = [];
    this._assertWillHaveOneTrack(tracks.length);
    //add tracks
  }

  removeTrack(trackId) {
    this._assertWillHaveOneTrack(-1);
    //remove track
  }

  _assertWillHaveOneTrack(change) {
    if (this._tracks.length + change <= 0) throw new Error('Album must have a minimum of one track.');
  }
}

Please note that you could also have mutated the state first and checked the rule after which makes things simpler at first glance, but it's usually a bad practice because the model could be left in an invalid state if the exception is handled, unless the model reverts the change, but that gets even more complex.
Also note that if Track is an entity, it's probably a better idea not to let the client code create the Track to preserve encapsulation, but rather pass a TrackInfo value object or something similar.


text:
Q: Three.js tween camera.lookat I'm attempting to tween the camera.lookAt in Three.js using Tween.js with little success.
This works
    selectedHotspot = object;

    var tween = new TWEEN.Tween(camera.lookAt( object.position),600).start();

But rotates the camera directly to the object.position.
How do I get a nice smooth rotation?
This is the render function
  function update() {

    lat = Math.max(-85, Math.min(85, lat));
    phi = THREE.Math.degToRad(90 - lat);
    theta = THREE.Math.degToRad(lon);

    target.x = 512 * Math.sin(phi) * Math.cos(theta);
    target.y = 512 * Math.cos(phi);
    target.z = 512 * Math.sin(phi) * Math.sin(theta);

    if(!selectedHotspot)
        camera.lookAt(target);

    renderer.render(scene, camera);

}

UPDATE
OK I can't actually tween the camera on anything. I think there must be something else wrong. Should there be something else in the render function?

A: Quaternion version of mrdoob's answer
// backup original rotation
var startRotation = camera.quaternion.clone();

// final rotation (with lookAt)
camera.lookAt( lookAt );
var endRotation = camera.quaternion.clone();

// revert to original rotation
camera.quaternion.copy( startRotation );

// Tween
var lookAtTween = new TWEEN.Tween( camera.quaternion ).to( endRotation, 600 ).start();

A: For a positional tween (but you get the gist) I am using this code which does have a duration parameter and does move the camera smoothly:
function setupTween (position, target, duration)
{
    TWEEN.removeAll();    // remove previous tweens if needed

    new TWEEN.Tween (position)
        .to (target, duration)
        .easing (TWEEN.Easing.Bounce.InOut)
        .onUpdate (
            function() {
                // copy incoming position into capera position
                camera.position.copy (position);
            })
        .start();
}

and I call it like so:
setupTween (camera.position.clone(), new THREE.Vector3 (x, y, z), 7500);

to get a 7.5 seconds smooth tween.

A: I think your code should look something like this:
// backup original rotation
var startRotation = new THREE.Euler().copy( camera.rotation );

// final rotation (with lookAt)
camera.lookAt( object.position );
var endRotation = new THREE.Euler().copy( camera.rotation );

// revert to original rotation
camera.rotation.copy( startRotation );

// Tween
new TWEEN.Tween( camera ).to( { rotation: endRotation }, 600 ).start();

A: I use controls.target to tween camera'rotation and it work well.
createjs.Tween.get(controls.target)
.to({
  x: tweenPos.x,
  y: tweenPos.y - 11,
  z: tweenPos.z + 0.001
}, 800,createjs.Ease.linear);

A: Thanks all,
I gave up trying to tween the camera and instead added
if (target.y < selectedHotspot.position.y - 2)
        lat += 0.1;
    else if (target.y > selectedHotspot.position.y + 2)
            lat -= 0.1;

    if (target.x < selectedHotspot.position.x - 5)
        lon += 0.5;
    else if (target.x > selectedHotspot.position.x + 5)
        lon -= 0.5;
    else {

        camera.lookAt(selectedHotspot.position);

        if (camera.fov > selectedHotspot.bubble.distance*0.05){
            camera.fov -= 0.1;

        }
        if(sceneReady)
            loadScene();
    }

    camera.updateProjectionMatrix();

To a function called in the render loop. This works well.


text:
Q: Post validation failed: Path '...' is required when using react-hooks-form I want to upload a form that enctype is multipart/formdata with react-hooks-form. req.body gets the formdata but req.data shows this error message: "Post validation failed: title: Path title is required., body: Path body is required." and form is not being posted. If I send the data like this axios({req.data: dataForm}} req.data shows this message "Post validation failed: postImg: Cast to string failed for value "{ '0': {} }" at path "postImg""
The reason why I use the react-hooks-form that upload image file to the server. If there is another solution without react-hooks-form I am open.

const AddPost = () => {
    const { register, handleSubmit } = useForm();
    const onSubmit = async (dataForm) => {
        console.log(dataForm);
        try {
            const res = await axios({ method: 'POST', url: 'http://localhost:5000/posts/addpost', body: dataForm });
            console.log(res);
            //clearInput();
        } catch (err) {
            console.log(err);
        }
    }
    return (
        <>
        <Container>
                <Form /*action="/posts/addpost"*/ onSubmit={handleSubmit(onSubmit)} autoComplete="off" encType="multipart/form-data">
                    <Form.Group>
                        <Row>
                            <Col xs={12} className="text-center mt-2">
                                <Form.Label>
Add a Memory
</Form.Label>
                            </Col>
                            <Col xs={12} md={6} className="my-2 offset-md-3">
                                <Form.Control {...register('title')} required placeholder="Type Title"></Form.Control>
                            </Col>
                            <Col xs={12} md={6} className="my-2 offset-md-3">
                                <FontAwesomeIcon icon={faEdit} className="text-dark mx-1"></FontAwesomeIcon>
                                <Form.Label className="mx-1">Details of Memory</Form.Label>
                                <Form.Control {...register('body')} required placeholder="Details" as="textarea" rows={3}></Form.Control>
                            </Col>
                            <Col xs={12} md={6} className="my-2 offset-md-3">
                                <FontAwesomeIcon icon={faTag} className="text-dark mx-1"></FontAwesomeIcon>
                                <Form.Label className="mx-1">Tags</Form.Label>
                                <Form.Control {...register('tags')} placeholder="#sunrise etc." required ></Form.Control>
                            </Col>
                            <Col xs={12} md={6} className="my-2 offset-md-3">
                                <Form.Label className="label-file-upload" htmlFor="image-upload">Add Image</Form.Label>
                                <Form.File {...register('postImg')} id="image-upload" required  type="file" />
                            </Col>
                        </Row>
                    </Form.Group>

                        <Button type="submit" className="bg-light text-dark border-light form-btn px-5 mb-5">Add Memory</Button>

                </Form>
        </Container>
        </>
    )
}

export default AddPost;

A: Use connect-multiparty, busboy etc. and also express-fileupload packages on the backend side.
For example:

// index.js
import fileUpload from "express-fileupload";

app.use(fileUpload({createParentPath: true}));
app.use(cors());
app.use(express.json({ extended: true })); //bodyParser
app.use(express.urlencoded({extended: true })); //bodyParser

app.use('/posts', postsRoutes);

//post.js
import connectMultiparty from "connect-multiparty";
const multipartMiddleware = connectMultiparty();

router.post('/addpost', async(req, res) => {
  // create and save your data to database
}, multipartMiddleware);


text:
Q: Batch Script service stop start issue on other server Hi I am wondering with a script ..
sc \\serverXXX stop serviceABC
timeout /t 2

I am running this from serverYYY .. how come this sc would login to serverXXX to stop service serviceABC??
Please help

A: SC gives you the option to perform a command on \\SERVERNAME if you want. If you also want to pass a username and a password use this:
SC \\SERVERNAME STOP myService obj= Username password= Password

If you want to perform it on your local system simplay skip the servername.
For more information on SC check http://ss64.com/nt/sc.html.
EDIT:
To answer your question from the comments, here is the code:
SC \\SERVERNAME START serviceAAA obj= username password= password
:WAITINGFORSERVICEAAA
PING -n 10 127.0.0.1 > NUL
FOR /f "tokens=2 delims= " %%a IN (
    'wmic /node:"\\SERVERNAME" service get name^,state /format:TABLE ^| findstr /i /r /c:"serviceAAA"'
) DO SET state=%%a
IF NOT %state%==Running (
    GOTO WAITINGFORSERVICEAAA
)
SC \\SERVERNAME START serviceBBB obj= username password= password

What this code does is start serviceAAA, then it waits 10 seconds and checks whether the state of serviceAAA is Running. If this is not the case it jumps back, waits another 10 seconds and so on. As soon as the state is Running it exits the loop and starts serviceBBB.


text:
Q: How to unshorten this js code I was trying to understand code of this Tic-Tac-Toe (30 lines of code) game and encountered with this strange for me notation of js.

*

*t[id] ? ai() : move(id, 'ai');

*!checkEnd() ? (role == 'player') ? ai() : null : reset()
I know that this is shortened version of if-statement, but don't know exactly how to convert it.
Thanks in advance.

A: This is the ternary operator in javascript.
t[id] ? ai() : move(id, 'ai');

Translates to:
if (t[id])
    ai();
else
    move(id, 'ai');

And !checkEnd() ? (role == 'player') ? ai() : null : reset() to:
if (!checkEnd())
    if (role == 'player')
        ai();
    else
        ;
else
    reset();

A: That is called a ternary operator.
Check this from MDN. They have good info if you're starting.
And this one from MSDN
Simply put,
condition ?  expression if true : expression if false


text:
Q: Bash Loop with outer and inner array How to add another array like the output below?
I am using while loop to read the file
while read i
do
  echo "outer $i"
done < ./aaaaa

First Array (Content inside my file aaaaa)
abc
def
ghi

Second Array
1
2
3

The Output I want
abc1
def2
ghi3

Is this called multi-dimension array?
Thank you very much

A: Use paste:
$ paste -d "" aaaaa bbbbb
abc1
def2
ghi3


text:
Q: Trapping "Trying to get property of non-object" in blade templats i'm debugging a laravel project, and there are many instances where the developer simply dropped double mustaches into the blade templates referencing object properties, without first checking if those relations exist.
example
{{$category->name}}

{{$category->parent->name}}

Is there a built in way in laravel to just silently fail if for example $category is not set, or $category->parent is not set, without resorting to something along these lines...
@if (isset($category))
   {{$category->name}}
@endif

@if (isset($main_category->parent))
    @if($main_category->parent != null)
        {{$main_category->parent->name}}
    @endif
@endif

A: There is better way to hide error you get,
{{ @$category }}

@ will suppress error for undefined or unset variables.

PHP supports one error control operator: the at sign (@). When
  prepended to an expression in PHP, any error messages that might be
  generated by that expression will be ignored.

Here is official php documentation for error control operator.

A: There is a better way.
{{ $category->name ?? '' }}
// or
{{ $category->name or '' }} // for older version of laravel


text:
Q: Can we take out a constant while differentiating?
In the solved example above, rather than taking $a^2x^4$ together and differentiating $a^2 = 0$, we differentiated $x^4$ and took out $a^2$. Why? Couldn't we have differentiated $a^2$ and gotten the answer zero?

A: We have $\dfrac{\mathrm{d}}{\mathrm{d}x} \left(a^2 x^4\right) = a^2 \cdot 4x^3$. You can see that this is true by using the product rule as follows:
$$\dfrac{\mathrm{d}}{\mathrm{d}x} \left(a^2 x^4\right) = x^4 \dfrac{\mathrm{d}}{\mathrm{d}x} \left(a^2\right) + a^2\dfrac{\mathrm{d}}{\mathrm{d}x} \left(x^4\right)$$
Like you said $\dfrac{\mathrm{d}}{\mathrm{d}x} \left(a^2\right) = 0$, so the above simplifies to $$\dfrac{\mathrm{d}}{\mathrm{d}x} \left(a^2 x^4\right) = a^2\dfrac{\mathrm{d}}{\mathrm{d}x} \left(x^4\right) = a^2 \cdot 4x^3$$

This is true in the general case, let $f(x) = a\cdot g(x)$ where $a$ is a constant and $f, g$ are differentiable functions. Then using the notation that $f'(x)$ is the derivative of $f$ with respect to x and the product rule, we have $$f'(x) = g(x)\dfrac{\mathrm{d}}{\mathrm{d}x}\left(a\right) + a \cdot g'(x)$$
Applying the rule that $\dfrac{\mathrm{d}}{\mathrm{d}x}\left(a\right) = 0$ simplifies the above to $$f'(x) = a\cdot g'(x)$$

As a side note, whilst it is true that $$\dfrac{\mathrm{d}}{\mathrm{d}x}\left(f(x) + g(x)\right) = \dfrac{\mathrm{d}}{\mathrm{d}x}\left(f(x)\right) + \dfrac{\mathrm{d}}{\mathrm{d}x}\left(g(x)\right) = f'(x) + g'(x)$$
which is called the linearity of the differential operator, we have $$\dfrac{\mathrm{d}}{\mathrm{d}x}\left(f(x) \cdot g(x)\right) \neq \dfrac{\mathrm{d}}{\mathrm{d}x}\left(f(x)\right) \cdot \dfrac{\mathrm{d}}{\mathrm{d}x}\left(g(x)\right) $$

A: Yes, you can always take the constant out. You are right in stating that
$$\frac{d}{dx}(a^{2})=0 $$ But be aware of the fact below.
$$
\frac{d}{dx}(a^{2}x^{4})\neq \frac{d}{dx}(a^{2}) \cdot \frac{d}{dx}x^{4}
$$
If you want to do $\frac{d}{dx}(a^{2}x^{4})$, apply chain rule and you will
obtain
$$
\frac{d}{dx}(a^{2}x^{4})=a^{2}\frac{d}{dx}x^{4}
$$ So whenever you have a constant, you can just take it out.

A: Derivative of a anything multiplied by a constant is the derivative of that thing times that constant. You can jolly well take out the constant in the multiplicative context.
$$ \dfrac {d (b^2)}{dx} = b^2 (0) $$
is nonsense. Derivative of a constant is directly zero.

A: One thing about the differentiation rules is that they always work in any circumstance.
Yes, you can always pull out the constant while differentiating, but at the same time, since $f(x)=a$ is certainly a function, taking the derivative of $ax^{2}$ using the product rule had better still work - it's a product of functions and so the product rule must work. It does and must work, it's just that it's quicker to use the rule that constants can be pulled out of the differentiation operation, but these two methods will always agree, they are equivalent.
Similarly, if I asked you to differentiate $x^{2}$, you would probably quickly use the power rule and return $2x$, but what if we wrote this as $x \cdot x$? Since it's the same as $x^{2}$, and it's a product of functions, the product rule had better work here, and it does: $\frac{d}{dx}(x \cdot x) = x \cdot \frac{d}{dx} x + \frac{d}{dx}x \cdot x = x + x = 2x$.
Pretty much any function can have multiple rules applied to it to take the derivative. The derivative rules are complete mathematical theorems, they will never fail to work.
If you want to pull the constant out of differentiation, do so, if you want to use the product rule, do so; both are valid moves. Note that using the product rule on a constant function and arbitrary function product proves that pulling the constant out is always valid.


text:
Q: How to add the content of a text file into a mySQL database,the file content is given ConnID        Source IP:Port          Dest IP:Port            PeerID Accel RR
114145       22.0.4.187:2011      192.168.37.3:445 00:0c:29:de:1e:6d TCDL  00.0%
491114       22.0.4.163:2013      192.168.37.3:445 00:0c:29:de:1e:6d TCDL  00.0%
323469       22.0.4.144:2127      192.168.37.3:445 00:0c:29:f1:07:41 TCDL  00.0%
321395        22.0.4.37:2087      192.168.37.3:445 00:0c:29:de:1e:6d TCDL  00.0%
303508        22.0.4.30:2073      192.168.37.3:445 00:0c:29:f1:07:41 TCDL  00.0%
127701        22.0.7.36:2066      192.168.37.3:445 00:0c:29:f1:07:41 TCDL  00.0%

A: You should try below code. It will helps you.
<?php
$handle = @fopen("text_file_name.txt", "r"); //read line one by one
$values='';

while (!feof($handle)) // Loop til end of file.
{
    $buffer = fgets($handle, 4096); // Read a line.
    list($a,$b,$c)=explode("|",$buffer);//Separate string by the means of |
    //values.=($a,$b,$c);// save values and use insert query at last or

    // use mysql insert query here
}
?>

A: Create a field in your table to store the text file with one of the following data types:
VARCHAR(1 to 255) - for up to max 255 characters
VARCHAR(MAX) - for the maximum charaters your machine can handle
TEXT can store 65,535 characters (approx 64KB)
MEDIUMTEXT = 16,777,215 characters (approx 16 MB)
LONGTEXT = 4,294,967,295 chars (approx 4GB)
Then read the data in the text file serially or randomly using an IO stream or its just the data above, just copy paste directly into the field.


text:
Q: uploading files to onedrive using delphi rest api Access token getting added to content of the text file while uploading file to onedrive using rest api in delphi. How to remove access token from Content of text file that i uploaded.
my observations.
1.If i see my request in fiddler access token is getting added to body of the content(even though i cleared body after authenticate method called)
2.If i put TRESTContentType as ct_None then i can see two content dispositions are going in reqest.one is file content and the other is Access token.
3.I even tried to remove extra content by overriding content length value which resulted in protocol violation exception.
4.If i remove access token from request i am getting unauthorized access(which is obvious)
Please help me.
//
_filename :=  'C:\filename.txt';
  RClient := TRESTClient.Create('https://api.onedrive.com/v1.0');
  RClient .Authenticator :=OAuth2_OneDrive ;

  RESTRequest.Params.Clear;
  RESTRequest.ClearBody;
  RESTRequest.Method := TRestRequestMethod.rmPUT;
  RESTRequest.Resource:='/drive/items/root:/newFile.txt:/content';

  RESTRequest.Client:= RClient ;

  RESTRequest.AddAuthParameter('Authorization', 'Bearer ' + OAuth2_OneDrive.AccessToken, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);

  upload_stream := TFileStream.Create(_filename ,fmOpenRead);
  upload_stream.Position := 0;

  Size := upload_stream.Size- upload_stream.Position;
  SetLength(Buffer, Size);
  upload_stream.ReadBuffer(Pointer(Buffer)^, Size);

  Size := TEncoding.GetBufferEncoding(Buffer, Encoding);
  TextDocText := Encoding.GetString(Buffer, Size, Length(Buffer) - Size);

  RESTClient.Authenticator.Authenticate(RESTRequest);

  RESTRequest.ClearBody;

   RESTRequest.AddBody(TextDocText,TRESTContentType.ctTEXT_PLAIN);
   RESTRequest.Params.AddItem('Cache-Control', 'no-store, no-cache', TRESTRequestParameterKind.pkHTTPHEADER );

  RESTRequest.Execute;


text:
Q: Memory-mapping huge files in Java Is it possible to memory-map huge files (multiple GBs) in Java?
This method of FileChannel looks promising:
MappedByteBuffer map(FileChannel.MapMode mode, long position, long size)

Both position and size allow for 64-bit values -- so far, so good.
MappedByteBuffer, however, only provides methods for 32-bit positions (get(int index), position(int newPosition), etc.), which seems to imply that I cannot map files larger than 2 GB.
How can I get around this limitation?

A: As mentioned, MappedByteBuffer has the 2GB limitation due to usage of integer index/position pointers.
To get around that you could use an alternative implementation like larray

A: Take a look at Using a memory mapped file for a huge matrix code which shows how to create a list of MappedByteBuffer, each smaller then 2 GB, to map the entire file:
private static final int MAPPING_SIZE = 1 << 30;
...
long size = 8L * width * height;
for (long offset = 0; offset < size; offset += MAPPING_SIZE) {
    long size2 = Math.min(size - offset, MAPPING_SIZE);
    mappings.add(raf.getChannel().map(FileChannel.MapMode.READ_WRITE, offset, size2));
}

As per JDK-6347833 (fs) Enhance MappedByteBuffer to support sizes >2GB on 64 bit platforms the reason for the 2 GB limit is:

A MappedByteBuffer is a ByteBuffer with additional operations to support memory-mapped file regions. To support mapping a region larger than Integer.MAX_VALUE would require a parallel hierarchy of classes. For now the only solution is create multiple MappedByteBuffers where each corresponds to a region that is no larger than 2GB.


text:
Q: Yolo Algorithm for custom object detection with Multiclasses I am building a project to detect waste such as plsticbottle, plastic bag, mouse, keyboard and clothes. I have created a dataset and annotated it using labelimg. From the labelled images I have created two folders of train and test.
Now I want to apply the YOLO object Detection algorithm to detect the waste. I am unable to find any resources for multiclass object detection with YOLO. Please help me understand the next step after creating the dataset.


text:
Q: filtering streams in c# What's the easiest way to filter a stream/reader line-by-line in c# (somewhat like putting sed in the middle of a pipeline)?
I want to feed an iCalendar file to DDay.iCal but DDay.iCal dies on "VERSION:5.1.1" because it wants a number or number SEMICOLON number (where number is digits (DOT digits)? so the last "." is unexpected).
What I want to do is filter the VERSION: line to something harmless like "VERSION:5.1" so the parser doesn't die.
Here's a sample:
BEGIN:VCALENDAR
PRODID:-//SunONE/Calendar Hosting Server//EN
METHOD:PUBLISH
VERSION:5.1.1
X-NSCP-CALPROPS-LAST-MODIFIED:20011208T005613Z
X-NSCP-CALPROPS-CREATED:20010913T223336Z
X-NSCP-CALPROPS-READ:999
X-NSCP-CALPROPS-WRITE:999

Now, the DDay.iCal parser doesn't like "VERSION:5.1.1", so I want to replace that with something harmless like "VERSION:5.1".
The parser interface takes a reader or a stream.
Anyway, I tried to use the code here and it works (reimplementing TextReader on top of  a filtered ReadLine).

A: System.IO.Stream uses the decorator pattern so it makes it pretty easy to create your own which wraps an underlying stream. This allows streams such as CryptoStream and GZipStream to wrap any other Stream instance and effectively "override" its Read/Write methods without deriving from the class you want to extend. Very flexible and popular design pattern described in the Gang of Four book.
Now I'm not sure if the API you're working with requires a Stream or StreamReader. There is a significant distinction between the two. A StreamReader works at the text level and operations on characters/lines. A Stream works at the binary level and operates on bytes. In other words, the StreamReader is expected to be able to decode the bytes into text so that the consumer doesn't need to be concerned about the encoding. Use a Stream when encoding doesn't matter (such as when compressing or encyrpting) and use a StreamReader when working with text data.
From what it sounds like, a StreamReader would make more sense here. If the API can accept a StreamReader, just derive your own from TextReader and override its ReadLine method so that the first call returns the line of text you need appended and subsequent calls just function as normal.
The other option is to just use a StringWriter/StringReader and stuff it all into an in-memory string buffer, manipulate it, then pass it.

A: The easiest way might be to wrap the stream as an IEnumerable and filter with LINQ:
static void Main(string[] args)
{
    System.IO.StreamReader sr = // ...
    var filtered = Enumerable.Where(
        StreamReaderToSeq(sr), input => { int temp; return int.TryParse(x, out temp); });
}

static IEnumerable<string> StreamReaderToSeq(System.IO.StreamReader sr)
{
    while(!sr.EndOfStream)
    {
        yield return sr.ReadLine();
    }
}

The sequence above filters only integers, but its easy enough to write a better filter to handle all of the inputs you want.


text:
Q: Extract the frame (in image format) at exactly every minute (or second) from a video (by ffmpeg) Motivation: I would like to seek the frame, then take high quality and exact time screenshots (images) from a video.
The video is length is 00:48:43.71 and 23.98 fps (we can think it is 24 fps, isn't it?).

With reference from this webpage: Create a thumbnail image every X seconds of the video
I wrote some commands that grab a frame every hour, every minute, and every second.
After exterminating the images, the screenshots are in fact taken from the half hour, half minute, and half second. You will understand shortly.
For example, the command to grab a frame every minute, it is in fact extracting the frame at the half minute, which means the 00:00:30 , 00:01:30 , 00:02:30 , and so on. That is why I name to filename as follow:
ffmpeg -i "video.mp4" -start_number 0 -vf fps=1/60 "B 00-%02d-30.000.png"

(adding the "B" prefix is to prevent overwriting by different commands.)
For example, to grab a frame every second from 00:03:00 to 00:04:00, the commend is:
ffmpeg -i "video.mp4" -start_number 0 -vf fps=1 -ss 00:03:00 -to 00:04:00 "C 00-03-%02d.500.png"

To verify them, we can extract all the frames from 00:03:29 to 00:03:31 :
ffmpeg -copyts -ss 00:03:29 -i "video.mp4" -start_number 0 -to 00:03:31 "D 00-03-29.%03d.png"

We may check the following image files are identical:
D 00:03:29.012.png is identical to C 00:03:29.500.png.
D 00:03:29.024.png is identical to B 00:03:30.000.png.
D 00:03:29.036.png is identical to C 00:03:30.500.png.

Those are my findings from trials and errors this morning. Here comes my question:
Let's take "extract a frame at exactly every minute" as an example, how can we get / what is the command to get the frames 00:00:00.000 , 00:00:01.000, 00:00:02.000 , and so on?
I have just heard of ffmpeg this morning. I still do not know what -copyts means (after reading the docs) and when I need to put -ss position before -i and when to put it at the output part. So please do correct me if I am using the wrong commands.

A: The fps filter is designed to smartly drop/duplicate frames to match the output fps based on the input fps. If you ask it to output one frame every minute, it's going to select one frame at the center of the 00:00-01:00 window and drop all the others, thus why you get frames at 00:30, 01:30, etc..
Have you considered making a bat/bash script that does this ?
for i in 0..50
   ffmpeg -ss %i:oo -i input.mp4 -vframes 1 out-%i.png

You can also do the following if you wish to get screenshots at 01:00, 02:00 [..] instead of 00:30, 01:30 [..] :
ffmpeg -ss 00:30 -i input.mp4 -start_number 0 -vf fps=1/60 "B 00-%02d-00.000.png"


text:
Q: SVG формы периодически не прорисовываются Есть svg-лого у сайта, состоящее из изображения и текста. На сайте есть 6 страниц. При переходе со страницы на страницу случается так, что текст не отображается либо частично (не прорисовываются 1-2 буквы), либо полностью. Картинка при этом отображается всегда.
SVG текст преобразован в кривые path, и объединён тегом <g></g>. Всё изображение вставлено на сайт инлайново и подключается к хедеру посредством тега use. Так же на сайте есть пару svg-иконок и стрелочек, но с ними такого не происходит. И это случается только на внешнем хостинге, на локальном серваке такого не замечено. Какие могут быть причины такого поведения svg-текста? Есть какие-то предположения?

A: Проблема решилась переносом SVG-спрайта в хедер, до использования его элементов тегом use. Всем спасибо за внимание!