text:
Q: How to check field from database with jquery and show check or cross? I have a page and I ask them zipcode. While they are filling the form right after they finish writing 5 numbers of zipcode, It will check if it is covered from my database and will show a check or cross sign near it and will disable submit.
To summarize.

*

*Will wait for visitor to type 5 digits zip code( If we can check if customer only enters number it will be a plus and great)

*It will check if it is covered in database ( I don't ask for php part. Probably we will send it as POST to a php file)

*If it exists in database it will show check else it will show cross and will not allow the form to be submitted.

I checked some websites but couldn't find an exact solution.
Thank you

A: Probably you need have an image tag besides the zip code text box with the src attribute set to an invisible image. Then perform an ajax upon the blur event.
HTML:
<input type="text" id="zip" name="zip"> <img id="imgconf" src="images/blank.png">

Javascript:
$('#zip').blur(function() {
   $.ajax({
     url: "script.php",
     type: "POST",
     data: "zip=" + $('#zip').val(),
     dataType: "text",
     success: function (data){
         if (data=="1"){
            $('#imgconf').attr("src", "images/correct.png");
         } else {
            $('#imgconf').attr("src", "images/wrong.png");
         }
       }
     });
});

For the numeric validation, you may use the same PHP script to return another flag besides "1" and display it in another span element that the data entered is not numeric. Just add another key-value pair in the data part, maybe.

A: You will need to use AJAX. JQuery has a built in AJAX function. On each keyup event, you can have it run this AJAX function. The PHP should return a value of either 1 or 0 to make it easy. 1 obviously is match, and 0 is no-match.
$('#YourObjectID').keyup(function (event) {
    searchZips();
})

function searchZips()
{

    var myJSON = $.ajax({
        url: options.script + '?Q=' + curValue,
        type: 'POST',
        contentType: 'application/json',
        success: function (msg) {
            if(msg==="1"){
                // CODE TO SHOW YOUR X DIV
            }
        }

}

You will want to also add functionality on clearing the search, checking if null or empty string, etc., etc., but this is the basics that should get you going. I use this all the time. Once you get the hang of it, it's VERY useful. Then look into building a jQuery plugin. Once you can do the above functionality, you can build it into a plugin (with tons of cool options!) GOOD LUCK and happy programming.


text:
Q: Angular: Structuring code into many small files I am fairly new to AngularJS. Things were going well, but my controller.js was huge, so I thought to split it into smaller files.
Now, my index.html header has these lines
  <script src="js/services/date_picker_service.js"></script>
  <script src="js/controllers/common.js"></script>
  <script src="js/controllers/overview_map_controller.js"></script>
  <script src="js/controllers/overview_locations_controller,%20.js"></script>
  <script src="js/controllers/other_controllers.js"></script>

and loading my app gives
Error: [$injector:unpr] Unknown provider: dateServiceProvider <- dateService
http://errors.angularjs.org/1.2.9/$injector/unpr?p0=dateServiceProvider%20%3C-%20dateService
    at https://code.angularjs.org/1.2.9/angular.js:78:12
    at https://code.angularjs.org/1.2.9/angular.js:3546:19
    at Object.getService [as get] (https://code.angularjs.org/1.2.9/angular.js:3673:39)
    at https://code.angularjs.org/1.2.9/angular.js:3551:45
    at getService (https://code.angularjs.org/1.2.9/angular.js:3673:39)
    at invoke (https://code.angularjs.org/1.2.9/angular.js:3700:13)
    at Object.instantiate (https://code.angularjs.org/1.2.9/angular.js:3721:23)
    at https://code.angularjs.org/1.2.9/angular.js:6772:28
    at https://code.angularjs.org/1.2.9/angular.js:6185:34

I am guessing that the problem is that the script files in the <header> load asynchronously?
QUestion: how do I fix this, so that I don't need to go back to one humungeous controller.js?

[Update] I made a stupid error when splitting the big file into small ones & forgot the date service. So sorry. I awarded the answer to the oen who's post made me think D'oh! Sorry to waste your time.

A: Probably you can refactor your controller, and have it have its data come from multiple services, so your controller would appear smaller.
Another thing you can do is split the controller into multiple controllers for subcomponents of your view.
A controller is basically responsible for a view. I can't imagine a controller requiring more than 4-5 things to be loaded at the same time. Refactoring is the way to go for you, I recon.
Apart from that, here is a way to define a controller that depends on a service:
angular.module('someModule', ['depends.on.otherModule'])

.controller('MyController',['Service', function(Service){

...codez
}]);

So in your  case your controllers should be a part of a module that depends on the module which date_picker_service.js brings to the table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sum pairs of columns by group I wish to sum pairs of columns by group.  In the example below I wish to sum pairs (v1 and v2), (v3 and v4), and (v5 and v6), each by r1, r2 and r3.
I can do this using the sapply statement below and I get the correct answer.  However, the required code is complex.  Could someone show me how to do the same operation perhaps in package data.table or with rollapply and/or other options?  I have not yet explored those options.
Sorry if this is a duplicate.
my.data <- read.table(text= "
   r1  r2  r3    t1    t2    t3    v1   v2   v3   v4   v5   v6
    1   0   0    10    20    30     1    0    0    0    0    0
    1   0   0    10    20    30     1    1    0    0    0    0
    1   0   0    10    20    30     1    0    1    0    0    0
    1   0   0    10    20    30     1    0    1    1    0    0
    1   0   0    10    20    30     0    0    0    0    0    0

    0   1   0    10    20    30     0    1    1    1    1    1
    0   1   0    10    20    30     0    0    1    1    1    1
    0   1   0    10    20    30     0    0    0    1    1    1
    0   1   0    10    20    30     0    0    0    0    1    1
    0   1   0    10    20    30     0    0    0    0    0    1

    0   0   1    10    20    30     1    1    1    1    1    1
    0   0   1    10    20    30     1    0    1    1    1    1
    0   0   1    10    20    30     1    0    0    1    1    1
    0   0   1    10    20    30     1    0    0    0    1    1
    0   0   1    10    20    30     1    0    0    0    0    1
", header=TRUE, na.strings=NA)

my.data$my.group <- which(my.data[,1:3]==1, arr.ind=TRUE)[,2]
my.data

my.sums <- t(sapply(split(my.data[,7:(ncol(my.data)-1)], my.data$my.group), function(i) sapply(seq(2, ncol(i), 2), function(j) sum(i[,c((j-1),j)], na.rm=TRUE))))
my.sums

#   [,1] [,2] [,3]
# 1    5    3    0
# 2    1    5    9
# 3    6    5    9

A: Here's a pretty general expression that you can probably simplify if you want it to match your specific data dimensions/column names/etc:
library(data.table)
dt = data.table(my.data)

dt[, lapply(1:(ncol(.SD)/2), function(x) sum(.SD[[2*x-1]], .SD[[2*x]])),
     by = eval(grep('^r', names(dt), value = TRUE)),
     .SDcols = grep('^v', names(dt), value = TRUE)]
#   r1 r2 r3 V1 V2 V3
#1:  1  0  0  5  3  0
#2:  0  1  0  1  5  9
#3:  0  0  1  6  5  9

A: Also, using aggregate and mapply:
DF <- my.data

#function to sum 2 columns
fun <- function(col1, col2)
{
 rowSums(aggregate(DF[c(col1, col2)], by = list(DF$r1, DF$r2, DF$r3), sum)[c(4, 5)])
}

#all pairs of columns, to be summed, in a matrix
#(7 is the column of v1)
args_mat <- matrix(7:ncol(DF), ncol = 2, byrow = T)

#apply `fun` to all pairs
mapply(fun, args_mat[,1], args_mat[,2])
#     [,1] [,2] [,3]
#[1,]    5    3    0
#[2,]    1    5    9
#[3,]    6    5    9


text:
Q: If row exists then delete else Insert into a table using SQL Server stored procedures in SQL Server 2014 I have two tables Table1 and Table2.
Now I want to write a stored procedure where if the record exists it will delete that record and if the record doesn't exists then it will insert the record.
NOTE: I don't have any primary key in the table. I may need to make a key based on multiple columns.
USE lan_db;
GO

CREATE PROCEDURE dbo.udm_to_app_invoice
AS
    SET NOCOUNT ON;

    INSERT INTO dbo.dummy3
        SELECT
            poc_name,
            poc_code,
            salesrep_code,
            invoice_date,
            product_name
        FROM
            [dbo].[src_nota_fiscal]
        WHERE
            LAST_UPDT = (SELECT MAX(last_updt) FROM DBO.SRC_NOTA_FISCAL);
GO

A: Look into T-SQL IF...ELSE, that will probably be easiest.

IF Boolean_expression
      { sql_statement | statement_block }
  [ ELSE
      { sql_statement | statement_block } ]

The boolean expression can be a subquery where you can use the EXISTS operator.

Specifies a subquery to test for the existence of rows.

To your question, the answer in pseudo SQL:
IF EXISTS(<SELECT statement that selects the record>)
    <DELETE statement>
ELSE
    <INSERT statement>

An alternative would be to use the MERGE statement. However it is a cumbersome statement and IMO not that intuitive.


text:
Q: how to show text while object is loading I'm trying to show some text while my html object (a video) is loading. There used to be a standby attribute, but now that is deprecated. I'm having trouble making this simple word show up while the object is loading. What happens is that onclick, the word Loading becomes visible, then disappears while the object is loading. Does anyone know please of a quick solution?
HTML:

LOADING ...

css:
.half-embed
    {
    display:inline;
    float:right;
    position:relative;
    margin-right:-260px;
    margin-left:15px;
    padding:15px 0px;

    }

jquery:
$('#vidcontainer').click(function() {
        $('#vidcontainer img').fadeOut('slow');
        $('#vidcontainer').html("<object id='openingVideo' class='BrightcoveExperience'><param name='bgcolor' value='#FFFFFF' /><param name='width' value='480' /><param name='height' value='300' /><param name='playerID' value='xxx' /><param name='playerKey' value='xxx' /><param name='isVid' value='true' /><param name='isUI' value='true' /><param name='dynamicStreaming' value='true' /><param name='autoStart' value='true' /><param name='@videoPlayer' value='xxx' /></object>");
        brightcove.createExperiences();
});

A: You could start loading the object in a hidden / zero opacity container and once your video is ready to play transition to your video.
Actually, maybe your problem is that you're overwriting the contents of your #vidcontainer div so your image and loading label is immediately destroyed?

A: what about create object in fadeOut callback:
$('#vidcontainer').click(function() {
    $('#vidcontainer img').fadeOut('slow', function() {
        $('#vidcontainer').html("<object id='openingVideo' class='BrightcoveExperience'><param name='bgcolor' value='#FFFFFF' /><param name='width' value='480' /><param name='height' value='300' /><param name='playerID' value='xxx' /><param name='playerKey' value='xxx' /><param name='isVid' value='true' /><param name='isUI' value='true' /><param name='dynamicStreaming' value='true' /><param name='autoStart' value='true' /><param name='@videoPlayer' value='xxx' /></object>");
        brightcove.createExperiences();
    });
});

But im not sure if this is what you want, question is not clear enough for me


text:
Q: Why are there dashes in a .NET GUID? Why are there dashes in a .NET GUID? Are there dashes in most implementations of a GUID, or is it just a Microsoft thing?
Signed,
741ecf77-9c92-4435-8e6b-85975bd13452

A: It's just a convenience.
http://en.wikipedia.org/wiki/GUID

A: Technically, there are no "dashes" in a GUID.  A GUID is a 128-bit value which is usually stored in the following manner (using C# here to represent the structure):
public struct Guid
{
  public ulong Data1;
  public ushort Data2;
  public ushort Data3;
  public fixed byte Data4[8];
}

The dashes are in the string representation of a GUID.
The dashes are optional and are not required in a string representation of a GUID.
That said, there are historical reasons as to where the placement of the dashes are, related to how the GUIDs were generated, but that historical semantic no longer applies.

A: This is an example of chunking, just like phone numbers, credit card numbers, etc.
Here is a good Wikipedia article about it.

A: In the initial version of the UUID (Universally Unique Identifier) specification, each of the data elements had a semantic meaning:
{ time_low } – { time_mid } – { time_high_and_version } – { clock_seq_and_reserved clock_seq_low } – { node_id }
These elements were designed to provide temporal (time bits), and spatial (host bits) uniqueness.
Version History
As the the mathematical probability of collisions in a keyspace of 2^1024 random bits was found to be astronomically improbable, subsequent versions of the UUID spec have phased out the time and host data for security and privacy reasons.
The only elements that retain any meaning are the version bits and the reserved bits.
Version 3 UUIDs are derived from an MD5 hash of a URI or other Distinguished Name.
Version 4 is generated with random data and is, currently, the most common implementation you'll see in the wild.
Version 5 is derived from a SHA1 hash.
Storage formats
Since the hyphens are specified for the ASCII formatting of UUIDs in the RFC, even though the individual sections no longer retain their original meaning, they are still required if you need interoperability.
UUIDs are also sometimes stored as a base64 or ascii85 encoded string to save space for transmission over transports that are not binary-safe, and adherence to the RFC is not required.

Ascii:   3F2504E0-4F89-11D3-9A0C-0305E82C3301
Base64:  7QDBkvCA1+B9K/U0vrQx1A
Ascii85: 5:$Hj:Pf\4RLB9%kU\Lj

References:
RFC4122 (see page 3 specifically for the ABNF description of the UUID format)
Wikipedia GUID UUID

A: Just about every visual represenation of a guid that I've seen uses the dashed format.  It's much easier on the eyes.

A: The Guid class of .NET recognizes a bunch of different formats: dashes as separators, no separators, brackets as delimiters, parenthesis as delimiters, no delimiters, etc

A: The hyphens are used to separate each  number
E93416C5-9377-4A1D-8390-7E57D439C9E7
Hex digits  Description
8           Data1
4           Data2
4           Data3
4           Initial two bytes from Data4
12          Remaining six bytes from Data4

A: You can get your guid in various formats.
Assuming you're using c#:
Guid guid = Guid.NewGuid();

Console.WriteLine(guid.ToString("N"))

63be6f7e4e564f0580229f958f492077
Console.WriteLine(guid.ToString("D"))

63be6f7e-4e56-4f05-8022-9f958f492077
Console.WriteLine(guid.ToString("B"))

{63be6f7e-4e56-4f05-8022-9f958f492077}
Console.WriteLine(guid.ToString("P"))

(63be6f7e-4e56-4f05-8022-9f958f492077)

A: Hyphens denote the byte structure of a Guid.
typedef struct _GUID
{
   DWORD Data1;
   WORD Data2;
   WORD Data3;
   BYTE Data4[8];
} GUID;

For:
(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX)

You can probably strip them before saving. At least in .NET the constructor of the Guid type will initialize a Guid variable from its string representation regardless of whether the hyphens are still there or removed.

A: That's just for convenience. GUID consists of 16 bytes which makes up 32 characters in hex text representation. Without hyphens GUIDs are harder to perceive by humans and harder to be recognized as GUIDs and not some random nature 16-byte numbers.

A: If you want to store a guid somewhere, then store it as an array of 16 bytes, not as its textual representation. You will save a lot of space, and the question of hyphens will not arise.

A: The GUID is really just a number.  The hyphens show you how the various components are broken down but aren't really part of the number.  It's like an IP address - you can store a 32-bit number, or you can store a string with dots in it, they are equivalent.

A: The hypens have avsolutely no effect on the uniqueness or randomness of the value. They are merely a holdover from the definition of a GUID and visually separate the four distinct parts of data that make up the GUID.


text:
Q: Does bayesian neural network good for text/document classification? I've tried to do my research online, but I find most of them are image classification. I guess that is because nature(downside) of Bayesian DL: it's significantly slower than traditional DL, then few people use it for text/doc classification. Am I right? Or is there a more specific reason for that.
Please correct me if I'm wrong/ missing some text/document implement on code during my research, thanks guys!


text:
Q: git push throws an error "bash: line 0: echo: write error: No such file or directory". How can I resolve this error? I have been using git without any errors for past few months.
However, now, when I do git push, I get the following error:
"bash: line 0: echo: write error: No such file or directory"
How can this error be resolved ?


text:
Q: Function looks like a distribution curve I was playing around with Desmos and noticed that the graph of $y=(x^2+1)^{-1}$ looks like a distribution. I know that distributions like the normal distribution follow the form of $a^{-x^2}$. Are these functions related at all? Does the function I've mentioned have any use? Thanks.

A: The density function
$$f(x)=\frac1{\pi(1+x^2)}$$
defines the Cauchy distribution. It's a great example
in probability theory. It has no mean, no variance, and does not
satisfy the central limit theorem!


text:
Q: Can't start pyspark shell [
C:\Users\Asus>pyspark
1]: https://i.stack.imgur.com/aJBdg.png
how to resolve this issue want to run it on my terminal,
tried running bin\pyspark no luck.

After days of tweaking the environment variable reached to this solution still no luck, any form of suggestions would be appreciated


text:
Q: randomly generate 100 unique numbers using Math.random I want to print out an array of those 100 numbers.  However, my program stops after generating certain amount of numbers. Here's my code.
class A4
    public static void main(String[] args)
    {
        int[] array1 = new int[101];
        int num, i = 0;
        boolean repeat = false;
        while(i < 100)
        {
            num = (int) (Math.random() * 100) + 1;
            array1[(i)] = num;
            for (int e = 0; e < i; e++)
            {
                if (num == array1[e])
                    repeat = true;
            }

            if (repeat == true)
            {
                continue;
            }

            array1[i] = num;
            System.out.println(array1[i]);
            i++;
        }
    }
}


text:
Q: Jenkins: Dynamic List Subversion Tags I have a Jenkins task for deploy SVN tags.
I have a List Subversion Tag parameter (TAGS) with my SVN repository to select the tag to deploy with a url like this  http://svnserver/tags/productA
I need add a previous parameter to select the product
Parameter: PRODUCTS
Values: productA, productB,....
and use the value selected in List Suversion tag parameter.
If PRODUCTS=productA then TAGS= http://svnserver/tags/productA
If PRODUCTS=productB then TAGS= http://svnserver/tags/productB
I tried with several plugin like "uno choice" or "active choices",.. but nothing.
Any idea.
Thanks

A: In my company, we are using Git and Linux.
For some jobs, I need to display the Git branches and I've used the Extended Choice Parameter plugin (with a Groovy script).
Here is my configuration:

I think you can use the same template with a svn command like that:
svn ls -v ^/tags


text:
Q: How to add classes to Symfony 4 "ChoiceType" item labels? I have here four radio buttons, and I want to add a css class to each label of the radio button. How can I do that? I have tried two ways but neither are working:
Try 1:

        ->add('background', ChoiceType::class, ['label'=>'2. Dein Hintergrund: ',
        //this adds class to the parent div
        'attr' => ['class' => 'label'],
        'choices'  => [
            1 => 1,
            2 => 2,
            3 => 3,
            4 => 4
        ], 'choice_value' => null,
        'expanded' => true,
        'multiple' => false,
        // this adds class to all radios/input elements
        'choice_attr' => function($choice, $key, $value){
            return ['class' => 'radio radio_'.($key)];
         },
         //this does NOT work, no error but it will not render a class to the label! Why?
         'label_attr' => function($choice, $key, $value){
            return ['class' => 'label'.($key)];
         },
        ])

Try 2:

   {{ form_label(form.background, {'attr': {'class': 'label'}}) }}
            {{ form_widget(form.background) }}
            <button class="button_main">Übernehmen</button>

With number 2 I get the following error:

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").

I have looked at this documentation many times but can't figure it out!

A: You need to make your own implementation of the template:

    {{ form_label(form.expandedField) }}
    {% for child in form.expandedField.children %}

                {{ form_widget(child, {'attr': {'class': 'custom-control-input'}}) }}
                {{ child.vars.label }}

    {% endfor %}

Is not possible to add your own class to labels in FormTypes.

A: You need to create your own form template like in this documentation

A: Apparently you can't modify the attributes of a choice label of ChoiceType. This feature does not exist in Symfony core for the moment. Please have a look to this.


text:
Q: No imprimir un objeto <?php
$curl = curl_init($url);

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Accept: */*",
   "User-Agent: PostmanRuntime/7.29.0"
);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);

curl_close($curl);

$resp2 = json_decode($resp);

$paraGuardar = '';

    foreach($resp2->orders as $orden){
        foreach($orden as $key=> $item){
           $paraGuardar .= print_r($item, true);
           echo($item);
           echo '*';
        }
        echo '
'.'
';
    }
?>


text:
Q: Insert sql rows instead of deleted rows will make database size increase or still the same I have a large database its MDF file nearly 190 GB. When I delete a large number of old rows the MDF size doesn't get reduced. What will happen when insert new records into my database? Will the size of the data-files increase or does the new records fill the available / free space created by the deleted rows. I can't shrink the database or copy it into a new empty one. This is a production database and doing any of these operations would require me to stop the website which is not feasible for me. Should I acquire more disk space from my hosting provider???

A:
What will happen when insert new records into my database? Will the size of the data-files increase or does the new records fill the available / free space created by the deleted rows

It will fill the free space.

I can't shrink the database

You shouldn't, either. At most, you should ONLY use SHRINKFILE. However, this shouldn't be something you do often either. It should only be done when (by accident) your data-files have grown abnormally large. Most databases continue to grow as time passes since most aren't purged of any data. Thus, it's common to require more space (see below)

Should I acquire more disk space from my hosting provider?

As you insert more data, and are unable to delete any "old" data, then yes, you would need more disk space. Note that though your datafiles are a certain size, that doesn't mean they are full. You can check the disk free space via a report. This blog and others explain the difference between Unallocated, Unused, and Free Space


text:
Q: Unable to install or use pipreqs to create requirements.txt file for dependencies I have a Python project that I would like to send to someone else. I am trying to create a requirements.txt file containing the required dependencies for this script so that my partner can run the script.
I tried installing pipreqs like this: pip install pipreqs.
This outputs the following:
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
Requirement already satisfied: pipreqs in c:\python310\lib\site-packages (0.4.11)
Requirement already satisfied: yarg in c:\python310\lib\site-packages (from pipreqs) (0.1.9)
Requirement already satisfied: docopt in c:\python310\lib\site-packages (from pipreqs) (0.6.2)
Requirement already satisfied: requests in c:\users\nroll97\appdata\roaming\python\python310\site-packages (from yarg->pipreqs) (2.26.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\nroll97\appdata\roaming\python\python310\site-packages (from requests->yarg->pipreqs) (1.26.8)
Requirement already satisfied: idna<4,>=2.5 in c:\users\nroll97\appdata\roaming\python\python310\site-packages (from requests->yarg->pipreqs) (3.3)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\nroll97\appdata\roaming\python\python310\site-packages (from requests->yarg->pipreqs) (2021.10.8)
Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\nroll97\appdata\roaming\python\python310\site-packages (from requests->yarg->pipreqs) (2.0.11)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: You are using pip version 21.2.4; however, version 22.0.4 is available.
You should consider upgrading via the 'C:\Python310\python.exe -m pip install --upgrade pip' command.

I then tried to create the requirements.txt file by running the command:
pipreqs ./my_calc.py

from the folder that contains the Python script and I get the following error:
bash: pipreqs: command not found

Why can't I use pipreqs? I use pip install all the time for other libraries.
Also, I am on a Windows computer. Is there an easier way to create the requirements.txt file even if its manually?
These are the only imports:
import pandas as pd
import os
import openpyxl
import os.path
import math
from tkinter import filedialog

A: I still wasn't able to get the pipreqs to work so I just made the requirements.txt file manually by first finding out which versions of the Python modules are being used.
I found that out like this:
import pandas as pd
import os
import openpyxl
import os.path
import math
from tkinter import filedialog
# VERSIONS OF LIBRARIES AS OF DEVELOPMENT - 04/28/2022
print("Version of pd: " + str(pd.__version__)) # 1.4.2
print("Version of openpyxl: " + str(openpyxl.__version__)) # 3.0.9
print("Version of tkinter: " + str(tkinter.TkVersion)) # 8.6

And then created the requirements.txt from those values like this (but only for the imports that are not already included in the standard Python library):
pandas==1.4.2
openpyxl==3.0.9


text:
Q: Wordpress - Update function if users deleted their account I'm stuck with this, How can i update this function if one of our users deleted their account?
It should update it self and i don't know what can i do to update automatically.
Any help please.
/**
 * Retrieve following count
 *
 * Gets the total number of users that the specified user is following
 *
 * @access      private
 * @since       1.0
 * @param   int $user_id - the ID of the user to retrieve a count for
 * @return      int
 */

function pwuf_get_following_count( $user_id = 0 ) {

    if ( empty( $user_id ) ) {
        $user_id = get_current_user_id();
    }

    $following = pwuf_get_following( $user_id );

    $count = 0;

    if ( $following ) {
        $count = count( $following );
    }

    return (int) apply_filters( 'pwuf_get_following_count', $count, $user_id );
}

here is the function to get the following users
/**
 * Retrieves all users that the specified user follows
 *
 * Gets all users that $user_id followers
 *
 * @access      private
 * @since       1.0
 * @param   int $user_id - the ID of the user to retrieve following for
 * @return      array
 */

function pwuf_get_following( $user_id = 0 ) {

    if ( empty( $user_id ) ) {
        $user_id = get_current_user_id();
    }

    $following = get_user_meta( $user_id, '_pwuf_following', true );

    if ( empty( $following ) ) {

    return;

    }
    return (array) apply_filters( 'pwuf_get_following', $following, $user_id );
}

And this one for Increase or Decrease the users number.
/**
 * Increase follower count
 *
 * Increments the total count for how many users a specified user is followed by
 *
 * @access      private
 * @since       1.0
 * @param   int $user_id - the ID of the user to increease the count for
 * @return      int
 */

function pwuf_increase_followed_by_count( $user_id = 0 ) {

    do_action( 'pwuf_pre_increase_followed_count', $user_id );

    $followed_count = pwuf_get_follower_count( $user_id );

    if ( $followed_count !== false ) {

        $new_followed_count = update_user_meta( $user_id, '_pwuf_followed_by_count', $followed_count + 1 );

    } else {

        $new_followed_count = update_user_meta( $user_id, '_pwuf_followed_by_count', 1 );

    }

    do_action( 'pwuf_post_increase_followed_count', $user_id );

    return $new_followed_count;
}

/**
 * Decrease follower count
 *
 * Decrements the total count for how many users a specified user is followed by
 *
 * @access      private
 * @since       1.0
 * @param   int $user_id - the ID of the user to decrease the count for
 * @return      int
 */

function pwuf_decrease_followed_by_count( $user_id ) {

    do_action( 'pwuf_pre_decrease_followed_count', $user_id );

    $followed_count = pwuf_get_follower_count( $user_id );

    if ( $followed_count ) {

        $count = update_user_meta( $user_id, '_pwuf_followed_by_count', ( $followed_count - 1 ) );

        do_action( 'pwuf_post_increase_followed_count', $user_id );

    }
    return $count;
}

Now i don't know why the count not changed when some users deleted their accounts.

A: Have a backup of your database before trying this, or try using in a staging site before implementing in live. Add this to your theme's 'functions.php'.
function follow_delete_user( $user_id ) {
    $userslist = get_users();

    foreach ( $userslist as $user ) {
        pwuf_unfollow_user( $user->ID, $user_id );
        pwuf_unfollow_user( $user_id, $user->ID );
    }
}
add_action( 'delete_user', 'follow_delete_user' );


text:
Q: Sort map based on object property while keeping key I have created a map that contains a list of products, and the shop closest by that is selling that product, like so:
var products = new Map()
products.set('product_key', {
  shop: 'shop_key',
  distance: 1.2
})

Now what I would like to do is sort the entire map on the distance property, so that I can list the products by proximity to my location.
I use a map because I also need to go in and be able to find the distance to one specific product using the key.

A: Map loops through its entries in insertion order; you can't sort a map, you can only create one in the sorted order you want.
For what you're doing, I'd probably use an array of entries, and then a map mapping strings to the entries that are in the array:

const productList = [
    {distance: 1.8, product_key: "one", shop: "shop_key1"},
    {distance: 1.2, product_key: "two", shop: "shop_key2"},
    {distance: 1.4, product_key: "three", shop: "shop_key3"}
];
productList.sort((a, b) => a.distance - b.distance);
const map = new Map();
productList.forEach(entry => {
    map.set(entry.product_key, entry);
});

console.log("List:");
productList.forEach(entry => {
    console.log(JSON.stringify(entry));
});
console.log("Product 'two':", map.get("two"));

That allows you to re-sort as necessary.
But again, Map iterates in insertion order, so you can do it with just a Map as the endpoint, by inserting the entries in order:

const productList = [
    {distance: 1.8, product_key: "one", shop: "shop_key1"},
    {distance: 1.2, product_key: "two", shop: "shop_key2"},
    {distance: 1.4, product_key: "three", shop: "shop_key3"}
];
productList.sort((a, b) => a.distance - b.distance);
const map = new Map();
productList.forEach(entry => {
    map.set(entry.product_key, entry);
});
productList = null; // don't need it anymore

console.log("List:");
for (let entry of map) {
    console.log(JSON.stringify(entry));
}
console.log("Product 'two':", map.get("two"));

A: One way is to have an array of keys sorted by distance:
"use strict";

var products = new Map()
products.set('product_key', {
    shop: 'shop_key',
    distance: 1.2
})
products.set('product2_key', {
    shop: 'shop2_key',
    distance: 0.1
})
console.log(products);

var keysByDistance = Array.from(products.keys()).sort((a, b) => products.get(a).distance - products.get(b).distance);
console.log(keysByDistance.map(key => products.get(key)));

Outputs:
Map {
  'product_key' => { shop: 'shop_key', distance: 1.2 },
  'product2_key' => { shop: 'shop2_key', distance: 0.1 } }
[ { shop: 'shop2_key', distance: 0.1 },
  { shop: 'shop_key', distance: 1.2 } ]

A: Move some pieces to an array, the product key and distance, then sort that array. Do the lookup after you sort.
var products = {
   p1:300, p2:60, p3:200, p4:1000,
   p5:400, p6:600
}
var sortable = [];
for (var x in products)
  sortable.push([x, product[x]])
sortable.sort(
   function(a, b) {
      return a[1] - b[1]
   }
)

//Do lookup on the map based on first elements in sorted array


text:
Q: Cannot compile ARToolkit on 64-bit Mac I was trying to compile ARToolkit on my 64-bit MacMini but when I run make, it give errors as follows
   ./videoInternal.h:38:50: error: unknown type name 'SeqGrabComponent'
   ./video.c:255:10: error: use of undeclared identifier 'seqGrab'
   ...

I realized that these errors are related to Quicktime Framework on Mac but I have no idea how to fix it. My Mac version is 10.7.5, 64-bit.
Thanks.

A: QuickTime is not and won't ever be 64-bit, it has been superseded by QTKit and AVFoundation. ARToolKit Professional v4.x includes a QTKit video input module (http://www.artoolworks.com). ARToolworks has stated that it is their intention to release parts of ARToolKit v4.x under the GPL soon.


text:
Q: Support for Windows-Left and Windows-Right in undecorated JFrames I use an undecorated JFrame with a custom title bar and custom resizer. All works fine but when I make a JFrame undecorated I lose the support for Windows-Left/Right key bindings (seems that it's native implemented by Windows). I want to reimplement this feature for my application. My problem: I can detect in a key listener whether the Windows key pressed, but I cannot detect whether another key (left/right in my case) is pressed together with Windows key (no modifier WINDOWS_MASK_DOWN in InputEvent). Probably somebody knows a workaround?
Here is my code:
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class HeadlessFrameTest {

    public static void main(String[] args) {
        final JFrame frm = new JFrame("Test");
        final JTextField field = new JTextField();
        frm.add(field, BorderLayout.NORTH);
        field.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println(e);
            }
        });
        frm.setUndecorated(true);
        frm.setSize(500, 550);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setVisible(true);
    }

}

A: Well, I couldn't test it properly as on my system, Windows+Left or Right were intercepted and processed by Windows even for undecorated frames, however adding another case for the unused combination Windows+A proved that the following code works if the host system does not consume the key shortcut:
(Update: since it seems to be the key pressed event which Windows consumes, a key release of Windows+Left or Right can be catched)
final JFrame frm = new JFrame("Test");
final JTextField field = new JTextField();
frm.add(field, BorderLayout.NORTH);
frm.getToolkit().addAWTEventListener(new AWTEventListener() {
    boolean winDown;
    public void eventDispatched(AWTEvent event) {
        KeyEvent ev=(KeyEvent)event;
        final boolean pressed = ev.getID()==KeyEvent.KEY_PRESSED;
        if(ev.getKeyCode()==KeyEvent.VK_WINDOWS) winDown=pressed;
        else if(winDown) switch(ev.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                System.out.println("windows + LEFT "+(pressed?"pressed":"released"));
                break;
            case KeyEvent.VK_RIGHT:
                System.out.println("windows + RIGHT "+(pressed?"pressed":"released"));
                break;
            case KeyEvent.VK_A:
                System.out.println("windows + A "+(pressed?"pressed":"released"));
                break;
        }
    }
}, KeyEvent.KEY_EVENT_MASK);
frm.setUndecorated(true);
frm.setSize(500, 550);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);

It seems that an ordinary key listener on a component does not work because the component loses the focus when Windows is pressed.


text:
Q: "You should only initialize MvxBindingSingletonCache once" error when have several test classes I run into a strange exception. In my test project, I use Moq, xUnit, and MvvmCross.Tests.
When I run my tests from one class - everything works just fine. When I run tests from 2 classes I get MvvmCross.Exceptions.MvxException.
I have 2 identical (initialization is identical) classes VitalsDataTests and GetReimbursedTests:
    public class VitalsDataTests : MvxIoCSupportingTest
    {
        public VitalsDataTests()
        {
            base.Setup();
        }
        protected MockDispatcher MockDispatcher
        {
            get;
            private set;
        }
        protected override void AdditionalSetup()
        {
            MockDispatcher = new MockDispatcher();

            Ioc.RegisterSingleton<IMvxViewDispatcher>(MockDispatcher);
            Ioc.RegisterSingleton<IMvxMainThreadDispatcher>(MockDispatcher);
            Ioc.RegisterSingleton<IMvxMainThreadAsyncDispatcher>(MockDispatcher);
        }
       ...
     }

Here is my MockDispatcher:
    public class MockDispatcher
        : MvxMainThreadDispatcher
        , IMvxViewDispatcher
    {
        public readonly List<MvxViewModelRequest> Requests;
        public readonly List<MvxPresentationHint> Hints;
        public MockDispatcher()
        {
            if (Hints == null) Hints = new List<MvxPresentationHint>();
            if (Requests == null) Requests = new List<MvxViewModelRequest>();
        }
        public override bool IsOnMainThread { get; }

        public Task<bool> ChangePresentation(MvxPresentationHint hint)
        {
            Hints.Add(hint);
            return Task.FromResult(true);
        }

        public async Task ExecuteOnMainThreadAsync(Action action, bool maskExceptions = true)
        {
            await Task.Run(action);
        }

        public async Task ExecuteOnMainThreadAsync(Func<Task> action, bool maskExceptions = true)
        {
            await Task.Run(action);
        }

        public override bool RequestMainThreadAction(Action action, bool maskExceptions = true)
        {
            action();
            return true;
        }

        public Task<bool> ShowViewModel(MvxViewModelRequest request)
        {
            Requests.Add(request);
            return Task.FromResult(true);
        }
    }

What I tried:
Clearing MvxSingleton and MvxBindingSingletonCache singletons in the constructor of each class before I call base.Setup():
MvxSingleton.ClearAllSingletons();
MvxBindingSingletonCache.ClearAllSingletons();
Not sure what I'm doing wrong.
thank you for your help.

A: I was able to solve this error by adding XUnit Collection Attribute for each test class, like this:
[Collection("ViewModels")]
public class GetReimbursedTests : BaseTest
{
     ...
}


text:
Q: Can I get an error when closing a file? When programming I often open and close files. I understand that when opening a file, it's important to check for errors to see if it did in fact open. I don't know of an instance though when closing a file would be an issue (except for maybe if opening the file did give an error and it went unchecked).
I'm currently programming in go, and under the os package the .Close() function can return an error if it needs to. I know in C++ this is possible as well.
So finally, my question is what circumstances would cause an error when trying to close a file?

A: Yes. Closing a file can cause an error/fail. See for example the errors that close(3) can return -  http://linux.die.net/man/3/close - stuff like filesystem corruption is one probable cause.
Often you can't really do much about it though other than log an error and know that your data is probably screwed (depending on the error) - you can rarely "fix it" except for maybe re-writing the data somewhere else if you still have it etc.
The language you are using (Go, C++, whatever) is irrelevant. If the filesystem is full, corrupt or someone has physically ripped out the harddrive, then your programming language just can't save you and close will fail and it is anybodys guess whether your data are safely stored somewhere or not.

A: At OS level, things can also go wrong when closing files, especially if you have written to them (i.e. buffering issues, out of disk space, media removed, etc...).
The C++ fstream has a void close() function which doesn't return anything. The principle is that once you called close you can no longer use the stream whether there was an error or not.  However when a closing error occurs, the fail bit is set, so that it can be detected, and the error code can be retrieved the usual way.
The C fclose() returns an int which shows if there was an error or not.  If you want to know why it failed you have to get and analyze the errno error code.  It's not as self-explaining as a void function, but here also, you can't use the FILE* anymore after the closing call, whether there was an error or not.


text:
Q: Set counter for tcolorbox environment in beamer Please help me to put a simple counter in the tcolorbox environment in beamer. It only needs to go from 1,2,3,...
\begin{tcolorbox}[colback=green!5,colframe=green!40!black, center,title=    ]

\end{tcolorbox}

A: There is the key auto counter for that purpose. As it turns out, it does not yet automatically harmonize with beamer \pauses. This can be fixed by redefining \tcb@proc@counter@auto to become
\def\tcb@proc@counter@auto#1{%
  \newcounter{tcb@cnt@#1}%
  \csxdef{tcb@cnt@#1}{tcb@cnt@#1}%
  \tcb@proc@counter@autoanduse{#1}%
  \ifcsname resetcounteronoverlays\endcsname%<-added
  \resetcounteronoverlays{tcb@cnt@#1}%<-added
  \fi%<-added
}

So the MWE becomes
\documentclass{beamer}
\usepackage{tcolorbox}
\makeatletter
\def\tcb@proc@counter@auto#1{%
  \newcounter{tcb@cnt@#1}%
  \csxdef{tcb@cnt@#1}{tcb@cnt@#1}%
  \tcb@proc@counter@autoanduse{#1}%
  \ifcsname resetcounteronoverlays\endcsname%<-added
  \resetcounteronoverlays{tcb@cnt@#1}%<-added
  \fi%<-added
}
\makeatother
\newtcolorbox[auto counter]{numberedbox}[2][]{%
colback=green!5,colframe=green!40!black,center,title=Numbered
box~\thetcbcounter: #2,#1}

\begin{document}
\begin{frame}[t]
\frametitle{tcolorboxes}
\begin{numberedbox}[label={boxA}]{title A}
I am random box and have number~\ref{boxA}
\end{numberedbox}
\pause
\begin{numberedbox}[label={catinbox}]{A cat in a box}
\dots wrote this, see numbered box~\ref{boxA}
\end{numberedbox}
\pause
\begin{numberedbox}[label={yetanotherbox}]{title B}
I'm boring, see numbered box~\ref{catinbox} for something exciting
\end{numberedbox}
\end{frame}
\end{document}


text:
Q: ZFS on Linux send/receive resume on poor/bad ssh connection I am using ZFS on Linux, and trying to setup remote replication. But I have bad ssh connection, and zfs send/receive over ssh restarts again.
I know there is a issue on ZoL, but I don't know when it will be implemented, or a new stable release come.
I've hear about mbuffer, but seems it can't do restart. Maybe it is possible to use it somehow like zfs send | mbuffer | while true; do ssh ...; done, but not sure.
Right now I am doing zfs send to a file, rsync it with --append --partial to remote and restore. but it consumes space, need manual assistance, and is a dirty solution.
I want to have some automated solution, like sanoid/syncoid, to keep a mirror of my pool with all snapshots.
Maybe some bash script that doing the same, but keeps all snapshots on remote, deletes files on host when they are successfully rsynced, etc.
Please help
P.S. I know there is a duplicate question, but there is no any solution. In my question I use some dirty solution, and want to replace or improve it

A: You can use the -s option of zfs receive which will save a resumable token on the receiving side if the transfer fails. It depends if you are using netcat (nc) or SSH.
On the recv machine (netcat only):
nc -l <port> | zfs receive -s -v tank/dataset
On the send machine:
Start with the usually send:
zfs send -v snapshot | nc <host> <port>
zfs send -v snapshot | ssh ... zfs receive -s -v tank/dataset
If the transfer fails, go on the recv machine and type:
zfs get all tank/dataset
Get the receive_resume_token and go on the send machine:
zfs send -v -t <token> | nc <host> <port>
zfs send -v -t <token> | ssh ... zfs receive -s -v tank/dataset
Here you go :)


text:
Q: append to an active record relations object I have a Post model. Having a scope which finds the enabled posts.A post can belong to a category. I also have a Category model, with categories ranked. Category has many posts. I want to display first distinct 20 posts which belong to distinct categories(which are the top 20 categories) and then display the rest of the post in descending order of their published_time.
This is what I have
Post model:
class Post < ActiveRecord::Base
belongs_to :categories
scope :by_category, ->(category) { joins(categories).where(categories: { id: category.id }) }
scope :enabled, where(disabled: false)
scope :recent, order('published_at DESC')

Category model
class Category < ActiveRecord::Base
has_many :feeds
scope :most_popular, order('rank ASC')

Home Controller
def index
  Category.most_popular.limit(20).each do |cat|
    @posts= Post.enabled.recent.by_category(cat).page(1).per(30)
  end

in view file I am rendering the attributes of the post that i receive using @posts. But as obvious, it returns only the post of the last category found in the loop. Basically it doesn't append. I tried using << to append.. as in -
@posts <<  Post.enabled.recent.by_category(cat).page(1).per(30)

But it gives no method << for nil:nil class
I tried making @posts as an array, but then it does not take page and per of kaminari into play.
I tried making @posts as ActiveRecord::Relation object using new, it gave argument error.
I tried making @posts as object of Post but then it says undefined method << for Post, since ofcourse, << is not a method for my model class. I also followed some SO posts but it didn't seem to fit in my step.
Basically, my insight into achieving this was appending records into the model object and then displaying the object. I even doubt, if my approach is good enough. There could be more efficient way of doing this, which I may be missing out in RoR.

A: You could do something like this:
def index
  posts_ids = []
  Category.most_popular.limit(20).each do |cat|
    post_ids << Post.enabled.recent.by_category(cat).map(&:id)
  end
  @posts = Post.find( post_ids ).page(1).per(30)
end

A: Let me define your problem to ensure that I understand it correctly. In your view, you want the latest post of each category first. And then you want all posts ordered by their recentness.
I would create two instance variables in the controller to be later used in the view.
def index
  enabled_posts = Post.enabled.recent

  @category_posts = enabled_posts.joins(:categories).group("categories.id")

  exclude_post_ids = @category_posts.pluck("posts.id")

  @posts = enabled_posts.where("id NOT IN (?)", exclude_post_ids)
end

The above should be convenient if you're using two different sections to display @category_posts and the remaining posts. But if you're using a single section and you want all the posts ordered in a single variable, then simply change your controller code to the following:
def index
  enabled_posts = Post.enabled.recent

  category_posts = enabled_posts.joins(:categories).group("categories.id")

  exclude_post_ids = @category_posts.pluck("posts.id")

  remaining_posts = enabled_posts.where("id NOT IN (?)", exclude_post_ids)

  @posts = category_posts + remaining_posts
end


text:
Q: Sort by first column, after by second if first contains duplicates etc I have a simple .txt file, which contains table, where columns are divided by tabulation. So, I need to read data from the file and write to another in a sorted way. I need firstly sort by first column. If it contains duplicates values, values from second column should be sort (only ones which are against duplicates in the first column) and so on.
Numbers are higher than letters, numbers are in increasing order, letters are in alphabetical order.
So, if I have file like this

after sorting I need to have this one

I've found this one How do I sort records in a text file using Java?, but is there effective way to implement remaining sorting logic, not only by first column?

A: You can try the following algorithm.

*

*Create class TableLine with 4 String fields: rowOne, rowTwo, rowThree, rowFour (I suppose maximum row number is 4?).

*Read lines from file and put every line in TableLine object. You should have List<TableLine> as result.

*Create a comparator:
Comparator<TableLine> comparator
= Comparator.comparing(TableLine::getRowOne)
            .thenComparing(TableLine::getRowTwo)...

etc for all rows you need to consider.

*Sort your List using above comparator.

*Write back to file

A: So, actually you try to compare rows by their contents, that is, each row can be represented as an array of strings, where some strings should be compared as numbers.
So, custom comparator needs to be implemented like this according to the mentioned requirements:

*

*numbers should be compared as numbers

*strings should be compared alphabetically

*numbers go before strings (therefore less than strings)

private static int customCompare(String[] s1, String[] s2) {
    int res = 0;
    for (int i = 0, n = Math.min(s1.length, s2.length); res == 0 && i < n; i++) {
        Comparable e1 = convert(s1[i]);
        Comparable e2 = convert(s2[i]);

        if (e1 instanceof Double && e2 instanceof Double) {
            res = Double.compare((Double)e1, (Double)e2);
        } else if (e1 instanceof String && e2 instanceof String) {
            res = e1.compareTo(e2);
        } else {
            res = e1 instanceof Double ? -1 : 1;
        }
    }
    return res != 0 ? res : Integer.compare(s1.length, s2.length);
}

// utility method to check for numeric format and convert to Double if needed
private static Comparable convert(String s) {
    if (null == s || !s.matches("[-+]?(\\d+|\\d*\\.\\d+)")) {
        return s;
    }
    return Double.valueOf(s);
}

Test:
String[] data = {
    "-2.2\t2\t3\t4",
    "2.2\t12345q\t69\t-afq",
    "2.2\t12345q\t69\t-asdf",
    "-22\t1234234\tasdfasf\tasdgas",
    "-22\t-3\t4",
    "",
    "-1.1",
    " ",
    "qqqq\tq1.1",
    "qqqq\t0.1",
    "qqqq\t-1.1",
    "-22\t11\tabc"
};

Arrays.stream(data)
      .map(s -> s.split("\t")) // Stream<String[]> rows
      .sorted(MyClass::customCompare) // reference to customCompare method
      .map(arr -> String.join("\t", arr))
      .forEach(System.out::println);

Output:
-22 -3  4
-22 11  abc
-22 1234234 asdfasf asdgas
-2.2    2   3   4
-1.1
2.2 12345q  69  -afq
2.2 12345q  69  -asdf

qqqq    -1.1
qqqq    0.1
qqqq    q1.1


text:
Q: How do I write a multi-line string in Rust? Is it possible to write something like:
fn main() {
    let my_string: &str = "Testing for new lines \
                           might work like this?";
}

A: If I'm reading the language reference correctly, then it looks like that should work.  The language ref states that \n etc. are supported (as common escapes, for inserting line breaks into your string), along with "additional escapes" including LF, CR, and HT.

A: Every string is a multiline string in Rust.
But if you have indents in your text like:
fn my_func() {
    const MY_CONST: &str = "\
    Hi!
    This is a multiline text!
    ";
}

you will get unnecessary spaces. To remove them you can use indoc! macros from indoc crate to remove all indents: https://github.com/dtolnay/indoc

A: Another way to do this is to use a raw string literal:

Raw string literals do not process any escapes. They start with the
  character U+0072 (r), followed by zero or more of the character U+0023
  (#) and a U+0022 (double-quote) character. The raw string body can
  contain any sequence of Unicode characters and is terminated only by
  another U+0022 (double-quote) character, followed by the same number
  of U+0023 (#) characters that preceded the opening U+0022
  (double-quote) character.
All Unicode characters contained in the raw string body represent
  themselves, the characters U+0022 (double-quote) (except when followed
  by at least as many U+0023 (#) characters as were used to start the
  raw string literal) or U+005C (\) do not have any special meaning.
Examples for string literals:
"foo"; r"foo";                     // foo
"\"foo\""; r#""foo""#;             // "foo"

"foo #\"# bar";
r##"foo #"# bar"##;                // foo #"# bar

"\x52"; "R"; r"R";                 // R
"\\x52"; r"\x52";                  // \x52

A: If you'd like to avoid having newline characters and extra spaces, you can use the concat! macro. It concatenates string literals at compile time.
let my_string = concat!(
    "Testing for new lines ",
    "might work like this?",
);

assert_eq!(my_string, "Testing for new lines might work like this?");

The accepted answer with the backslash also removes the extra spaces.

A: There are two ways of writing multi-line strings in Rust that have different results. You should choose between them with care depending on what you are trying to accomplish.
Method 1: Dangling whitespace
If a string starting with " contains a literal line break, the Rust compiler will "gobble up" all whitespace between the last non-whitespace character of the line and the first non-whitespace character of the next line, and replace them with a single .
Example:
fn test() {
    println!("{}", "hello
    world");
}

No matter how many literal  (blank space) characters (zero or a hundred) appear after hello, the output of the above will always be hello world.
Method 2: Backslash line break
This is the exact opposite. In this mode, all the whitespace before a literal \ on the first line is preserved, and all the subsequent whitespace on the next line is also preserved.
Example:
fn test() {
    println!("{}", "hello  \
    world");
}

In this example, the output is hello     world.
Additionally, as mentioned in another answer, Rust has "raw literal" strings, but they do not enter into this discussion as in Rust (unlike some other languages that need to resort to raw strings for this) supports literal line breaks in quoted content without restrictions, as we can see above.


text:
Q: HBase wal getting bigger and bigger HBase wal getting bigger and bigger. The details are as follows:
3.2 K    9.6 K    /hbase/.hbase-snapshot
0        0        /hbase/.hbck
0        0        /hbase/.tmp
0        0        /hbase/MasterProcWALs
534.2 G  1.6 T    /hbase/WALs
400.3 M  1.2 G    /hbase/archive
0        0        /hbase/corrupt
267.0 G  796.5 G  /hbase/data
42       126      /hbase/hbase.id
7        21       /hbase/hbase.version
0        0        /hbase/mobdir
1.7 M    5.1 M    /hbase/oldWALs
0        0        /hbase/staging

HBase version 2.1.0. I set the following parameters:
hbase.master.logcleaner.ttl 60s
hbase.wal.regiongrouping.numgroups 2
hbase.regionserver.maxlogs 32

I calculated that my actual data size is equal to the size of the /hbase/data file directory. I tested to delete the log data which is relatively long, but the program will report an exception.
My data is mainly written by Phoenix. Is there any reason for this?

A: In RegionServer logs, I found the following:
2020-11-07 00:36:45,750 INFO org.apache.hadoop.hbase.regionserver.wal.AbstractFSWAL: Too many WALs; count=385, max=32; forcing flush of 10 regions(s): 12bcc8a5c4d5087f7c8607cc943250fc, 94fa37159fb219dd510d20eba243e5a3, b4c2ad111677e61758ada3af4c1e9dbb, d6c6928e0a400ce53c9d8ee614dc552c, d224956d3d3f6f7657d0e9c9c4c544cc, 02bda653c9a66d85b064c4070f3f9e9e, 9297d8fbbd3b535ac0807e3665517752, 5ffdd4261cb294a1922fdac8fbfeef2f, 27c13a71b1d90dc7640f7df2dfd2093b, 159931a1de7fab4a04cdc3bd967d77bc
ah....
https://issues.apache.org/jira/browse/PHOENIX-5250


text:
Q: Gesture Detector with onDraw() called multiple times I am using GestureDetector to identify the touch.I have two Relative layoutsof same layout  size.I am trying to draw an image A on one layout and move an image B(created using onDraw) on another layout.While I move my image B I am using GestureDetector to identify the touch.When I move my image B, image A(view) onDraw() method  is called multiple times. Please help me to avoid calling onDraw() multiple times.Here is my code
public class TouchExampleActivity extends Activity {

RelativeLayout r1;
RelativeLayout r2;
Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    context = TouchExampleActivity.this;
    r1 = (RelativeLayout) findViewById(R.id.r1);
    r2 = (RelativeLayout) findViewById(R.id.r2);

    TouchExampleView view = new TouchExampleView(this);

    DrawCircle drawCircle = new DrawCircle(context);

    r1.addView(view);
    r2.addView(drawCircle);

}

class DrawCircle extends View {

    Paint p;

    public DrawCircle(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        p = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);

        Log.v("Touch", "Called Draw Circle");
        p.setColor(Color.BLUE);
        canvas.drawCircle(60, 50, 50, p);

    }
}

}

TouchExampleView.java
public class TouchExampleView extends View {
private Drawable mIcon;
private float mPosX;
private float mPosY;
static boolean fStartDrag = false;
static boolean fDrag = false;
private float ypos = 40;
private float xpos = 30;
public static float sx, sy;

private VersionedGestureDetector mDetector;
private float mScaleFactor = 1.f;

public TouchExampleView(Context context) {
    this(context, null, 0);
}

public TouchExampleView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public TouchExampleView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mIcon = context.getResources().getDrawable(R.drawable.icon);
    mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());

    mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback());
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    mDetector.onTouchEvent(ev);
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStrokeWidth(5);

    canvas.save();
    canvas.translate(mPosX, 0);
    canvas.scale(mScaleFactor, mScaleFactor);

    canvas.drawRect(0, 0, 30, 30, paint);
    canvas.restore();
}

private class GestureCallback implements VersionedGestureDetector.OnGestureListener {
    public void onDrag(float dx, float dy) {

        if ((dx == -1) && (dy == -1)) {

            fStartDrag = true;
            fDrag = false;
        }

        else if (fStartDrag) {

            if (dy >= mPosY && dy <= ypos + mPosY && dx >= mPosX && dx <= mPosX + xpos) {

                fDrag = true;
                fStartDrag = false;
            }
        } else if (fDrag) {
            System.out.println("fDrag");
            if (mPosX < 3)
                mPosX = 3;
            else if (mPosX > 400)
                mPosX = 400;
            else

                mPosX = dx;

            // mPosY = dy;

            postInvalidate();
        }
    }

    public void onScale(float scaleFactor) {
        mScaleFactor *= scaleFactor;

        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

        postInvalidate();
    }
}

}

My sample xml
<RelativeLayout
    android1:id="@+id/r1"
    android1:layout_width="620dip"
    android1:layout_height="320dip"
    android1:layout_alignParentBottom="true"
    android1:layout_alignParentLeft="true"
    android1:layout_marginBottom="94dp" >
</RelativeLayout>

<RelativeLayout
    android1:id="@+id/r2"
    android1:layout_width="620dip"
    android1:layout_height="320dip"
    android1:layout_alignParentBottom="true"
    android1:layout_alignParentLeft="true"
    android1:layout_marginBottom="94dp" >
</RelativeLayout>

If I use two relative layouts of different size and position then it works fine, onDraw() is not called multiple times

A: After trying so much I found this answer to my question.setDrawingCacheEnabled(true) prevents calling onDraw() multiple times.Its working for me.I hope I am going right.
   View circleView;
   r2 = (RelativeLayout) findViewById(R.id.r2);
   circleView= r2;
   circleView.setDrawingCacheEnabled(true);


text:
Q: Unsure of the understanding of in list2=i[:4] Python 3++ I've stumbled upon this for loop. In the for loop, I can't understand i[:4] operation. The i variable will receive all the values from the 'cast' while the j variable will receive the corresponding index value. However, when I move down to the list2=i[:4], I can't get it. Does it mean to transfer the first four values in i? So i can contain ['A','B','C','D','E'], but it will only pass on the values from A to D to list2? Am I right?
for i,j in zip(movies['cast'],movies.index):
     list2=[]
     list2=i[:4]
     movies.loc[j,'cast']=str(list2)


text:
Q: How to synchronize with the remote if local is ahead of the remote? I've recently started to use Git. I've pulled a project from GitHub server and started to work on it in the develop branch (on my local develop branch that is tracking origin/develop remote). I've just added a new file and did not track it with Git yet.
Meanwhile another person reverted the origin/develop branch and removed the latest 6 commits.
How can I force-synchronize my branch with the remote? I want to revert back my local branch so that it will be consistent with the remote. I've tried forced-pull but it didn't work:
$ git pull origin +develop
From https://***ADDRESS***
 * branch            develop    -> FETCH_HEAD
Already up to date.

$ git status
On branch develop
Your branch is ahead of 'origin/develop' by 6 commits.
  (use "git push" to publish your local commits)

A: You can
$ git checkout origin/develop

to get their copy of the code in your working directory. Then, perhaps, cherry-pick your change on top (this command cherry-picks only the last commit from the specified branch). This should be clean if you're only adding a new file:
$ git cherry-pick develop

Then, maybe point your local branch to reflect the remote one (this does not change any files, but moves your local develop branch pointer to your current state):
$ git checkout -B develop

Read about each of these commands in the Git docs if you're unsure of what they do.

A: I find that the best solution sometimes is to just delete you local branch and check it out again:
git branch -D <local_branch_name>

And then checkout you remote branch:
git checkout -b <branch_name> origin/<branch_name>

And if you don't want to lose your current changes you can save them with 'git stash'


text:
Q: Ubuntu 12.04 - Ctrl+T does not work in browsers I have just installed Ubuntu 12.04.
At the beginning I used Unity, I downloaded and installed Chrome, Ubuntu tweak (where I configured my favorite shortcuts) and decided to switch to Gnome-classic (Unity was so slow on my machine). Unfortunately in both Firefox and Chrome shortcut Ctrl+T does not work (But others shortcuts work well). Maybe I misassigned it by mistake or there is another magic.
How can I check list of all shortcuts on my system.?
I tried in keyboard settings, gnome advanced settings, dconf editor - no trafe after Ctrl+T.
Is there a way to assigne/force it again?


text:
Q: InstallReferrerReceiver not working in live app I am developing an app in android studio and tracking referrer using referral link but my app not working in live condition
My app work fine when I send referrer using below command
adb shell
am broadcast -a com.android.vending.INSTALL_REFERRER -n com.example.app/.InstallReferrerReceiver --es "referrer" "123456"

but when I install my app using play store link https://play.google.com/store/apps/details?com.example.app&referrer=123456 then my app is not receiveing referrer
I already added receiver in my manifest file under application tag.
<receiver
    android:name=".InstallReferrerReceiver"
    android:exported="true"
    android:permission="android.permission.INSTALL_PACKAGES">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

My InstallReferrerReciver
public class InstallReferrerReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String referrer = intent.getStringExtra("referrer");
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        if (referrer != null) {
            preferences.edit().putString("referral_code", referrer).apply();
        }
    }
}

A: INSTALL_REFERRER is no longer broadcast to the receiver since March 2020. Now if you want to use referral program in android app then you need to use Google Play Install Referrer API


text:
Q: Avoid duplicates in nested for loop I have the following nested for loop in Rust:
#[derive(Debug)]
struct Tes2 {
    a: Vec<String>,
    b: Vec<Vec<String>>,
}

fn vectes() {
    let mut ff: Vec<Tes2> = Vec::new();

    let one = vec![
        vec!["a".to_string(), "b".to_string()],
        vec!["x".to_string(), "y".to_string()],
    ];

    let two = vec![
        vec![
            vec!["d".to_string(), "e".to_string()],
            vec!["g".to_string(), "h".to_string()],
            vec!["j".to_string(), "k".to_string()],
        ],
        vec![
            vec!["mm".to_string(), "nn".to_string()],
            vec!["oo".to_string(), "pq".to_string()],
            vec!["rr".to_string(), "ss".to_string()],
        ],
    ];

    for i in one {
        for (mut k, j) in two.clone().into_iter().enumerate() {
            if k != 1 {
                ff.push(Tes2 { a: i.clone(), b: j });
            }
            k += 1;
        }
    }
    println!("{:?}", ff);
}

The output of which is:
[Tes2 { a: ["a", "b"], b: [["d", "e"], ["g", "h"], ["j", "k"]] }, Tes2 { a: ["x", "y"], b: [["d", "e"], ["g", "h"], ["j", "k"]] }]

This is what I want and is correct. Essentially, in each new struct I am trying to pair one[0] with two[0] and then one[1] with two[1] etc.
I am sure there is a much more real and efficient "Rust way" to do this, maybe with the map method, and avoiding for loops altogether, but I have tried in different ways and it never worked.

A: The method you're looking for is Iterator::zip() (or since Rust 1.59.0, std::iter::zip()).
for (a, b) in std::iter::zip(one, two) {
    ff.push(Tes2 { a, b })
}

Playground.
At that time, you can avoid using a loop altogether and just use collect():
let ff: Vec<_> = std::iter::zip(one, two)
    .map(|(a, b)| Tes2 { a, b })
    .collect();

Playground.
Of course, a simple loop will always work:
for i in 0..one.len() {
    ff.push(Tes2 {
        a: one[i].clone(),
        b: two[i].clone(),
    });
}

Playground.
As a side note, it's better to use .iter().clone() than .clone().into_iter(). See How to determine whether to use .clone() and .cloned() with iterators.


text:
Q: Pagedown and Angle Brackets not Cooperating I'm trying to use Pagedown to parse markdown (containing code sections) into html.
It mostly works, but I've noticed one strange behavior. If I have this in my markdown:
`ArrayList<String> names = new ArrayList<>();`

The text that displays ends up being this:
ArrayList<string> names = new ArrayList<>();

Notice that the first String is lower-cased, and the second <> is converted into html entities, which are not correctly displayed since they end up inside a code block.
If I look at the markdown that Pagedown "thinks" it's supposed to process, it gets stranger:
`ArrayList<string> names = new ArrayList<>();`</string>

Obviously, it's treating the <String> section of the code text as an html tag, and adding a closing </string> tag. Parsing that markdown produces this html:
ArrayList<string> names = new ArrayList&lt;&gt;();

If I encode the angle brackets ahead of time:
`ArrayList<String> names = new ArrayList<>();`

Then Pagedown simply encodes the html entities as part of the code, which is exactly what I want it to do with the angle brackets:
 ArrayList&lt;String&gt; names = new ArrayList&lt;&gt;();

I just want to be able to throw markdown (containing code sections) into the Pagedown parser and have it output sanitized html. Here is what I'm currently doing:
<!DOCTYPE html>

`ArrayList<String> names = new ArrayList<>();`

In real life the markdown is either coming from a database (which was written using the Pagedown editor) or from markdown files (which were written in a basic text editor). Is there an extra step I'm missing? Is the above approach a risk of bad JavaScript being run before Markdown parses it?

A: The problem has nothing to do with Markdown or Pagedown.
When you put content inside an HTML document, the HTML parser (the browser...) "corrects" invalid HTML fragments. In your case, it automatically adds a closing tag to make the HTML well formed. It apparently also converted "String" to lowercase "string" as part of its parsing process.
As you described yourself, Markdown code should probably come from a different source (JSON, external resources wrapped in a script element, etc...) where you will not have this problem at all.


text:
Q: nodeValue, data, textContent, wholeText, innerHTML don't work I have the following text node:
                    <content ID="med1">
                    Medication: Albuterol inhalant

                    Instructions: 2 puffs QID PRN wheezing

                    Status: Active
                    </content>

I get the content node like this:
var content = items[i].getElementsByTagName("content")[0];

and then try:
    var item = content.childNodes[0].textContent;  //returns "Medication: Albuterol inhalant"

instead of textContent I have tried data, nodeValue, and wholeText.  They all return the same thing.
I have also tried innerHTML and innerText which both return "undefined"
I want the entire text.  How to prevent the
 from truncating the result?

A: Try This.
var item = document.getElementById('med1').textContent;
alert(item)

A: Remove childNodes[0]:
var item = content.textContent;

A: try innerText
var c = document.getElementById('med1');
alert(c.innerText)

Fiddle

A: Why don't you just use jQuery?
var text = $( "content[ID='med1']" ).text();


text:
Q: Batch Script shows no output With reference to my previous question and responses received (which can be found here), I am seeking a help regarding a Batch Script. Based on the responses received to above mentioned question, I have created a Batch script which is as follows:
@echo off

setlocal enabledelayedexpansion

ping -n 1 %1 | find "TTL=" > NUL
IF NOT ERRORLEVEL 1 (

FOR /F %%i IN ('wmic /node:%1 computersystem get Name') DO (SET A=%%i)

FOR /F %%i IN ('wmic /node:%1 computersystem get Domain') DO (SET B=%%i)

FOR /F %%i IN ('wmic /node:%1 computersystem get UserName') DO (SET C=%%i)

FOR /F %%i IN ('wmic /node:%1 computersystem get Manufacturer') DO (SET D=%%i)

FOR /F "delims=" %%i IN ('wmic /node:%1 computersystem get Model') DO (SET E=%%i)
FOR %%a in (%E%) DO (SET E=%%a)

FOR /F %%i IN ('wmic /node:%1 computersystem get SystemType') DO (SET F=%%i)

FOR /F %%i IN ('wmic /node:%1 bios get SerialNumber') DO (SET G=%%i)

FOR /F "delims=|" %%i IN ('wmic /node:%1 os get Name') DO (SET H=%%i)
FOR %%a in (%H%) DO (SET H=%%a)

FOR /F %%i IN ('wmic /node:%1 os get TotalVisibleMemorySize') DO (SET J=%%i)

FOR /F "delims=" %%i IN ('wmic /node:%1 cpu get Name') DO (SET K=%%i)
FOR %%a in (%K%) DO (SET K=%%a)

echo !A!,!B!,!C!,!D!,!E!,!F!,!G!,!H!,!J!,!K! >> output.csv

)

The problem is that, when above script is executed with a valid argument, it neither displays any error message not displays any data in the generated CSV file. I am not able to understand what is wrong with the script.

A: 1 - Retrieve as much information you can from each call to wmic
2 - Filter the output of wmic. In this case, i'm using find to search the line containing the indicated node.
3 - If possible, to avoid having to remove the aditional CR at the end of the line, retrieve an aditional field that you will not read.
4 - Output from wmic is prefixed with the node name and fields ordered alphabetically. Define tokens accounting for this.
@echo off

    setlocal enableextensions disabledelayedexpansion

    set "node=%~1"

    ping -n 1 %node% | find "TTL=" > NUL
    if errorlevel 1 goto endProcess

    for /f "tokens=2-7 delims=," %%a in (
        'wmic /node:"%node%" computersystem get domain^,manufacturer^,model^,name^,systemtype^,username^,wakeuptype /format:csv ^| find /i "%node%"'
    ) do (
        set "_domain=%%a"
        set "_manufacturer=%%b"
        set "_model=%%c"
        set "_name=%%d"
        set "_systemType=%%e"
        set "_userName=%%f"
    )

    for /f "tokens=2 delims=," %%a in (
        'wmic /node:"%node%" bios get serialNumber^,version /format:csv ^| find /i "%node%"'
    ) do (
        set "_serialNumber=%%a"
    )

    for /f "tokens=2-3 delims=," %%a in (
        'wmic /node:"%node%" os get description^,totalvisiblememorysize^,version /format:csv ^| find /i "%node%"'
    ) do (
        set "_osName=%%a"
        set "_memory=%%b"
    )

    for /f "tokens=2 delims=," %%a in (
        'wmic /node:"%node%" cpu get name^,version /format:csv ^| find /i "%node%"'
    ) do (
        set "_cpu=%%a"
    )

    echo %_name%,%_domain%,%_userName%,%_manufacturer%,%_model%,%_systemType%,%_serialNumber%,%_osName%,%_memory%,%_cpu%

:endProcess
    endlocal

A: Here is a debugging build.  You can see that the variables are ending up nul.
@echo off

setlocal enabledelayedexpansion

ping -n 1 %1 | find "TTL=" > NUL
IF NOT ERRORLEVEL 1 (
echo running loop
FOR /F %%i IN ('wmic /node:%1 computersystem get Name') DO echo (set A=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get Domain') DO echo (set B=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get UserName') DO echo (set C=%%i)
FOR /F %%i IN ('wmic /node:%1 computersystem get Manufacturer') DO echo (set D=%%i)

FOR /F "delims=" %%i IN ('wmic /node:%1 computersystem get Model') DO echo (set E=%%i)
FOR %%a in (!E!) DO echo (set E=%%a)

FOR /F %%i IN ('wmic /node:%1 computersystem get SystemType') DO echo (set F=%%i)
FOR /F %%i IN ('wmic /node:%1 bios get SerialNumber') DO echo (set G=%%i)

FOR /F "delims=|" %%i IN ('wmic /node:%1 os get Name') DO echo (set H=%%i)
FOR %%a in (!H!) DO echo (set H=%%a)

FOR /F %%i IN ('wmic /node:%1 os get TotalVisibleMemorySize') DO echo (set J=%%i)
FOR /F "delims=" %%i IN ('wmic /node:%1 cpu get Name') DO echo (set K=%%i)
FOR %%a in (!K!) DO echo (set K=%%a)

echo !A!,!B!,!C!,!D!,!E!,!F!,!G!,!H!,!J!,!K! >> output.csv

)
pause

A: Rebuild your FOR lines to the following syntax:
FOR /F "tokens=2 delims==" %%i IN ('wmic /node:%1 computersystem get Name /value') DO echo (set A=%%i)

(and obviously remove the echo when the output satisfys you)

A: @echo off

setlocal enableextensions enabledelayedexpansion

for %%y in (73,74) do (
for /L %%z in (1,1,254) do (

set "node=172.22.%%y.%%z"

ping -n 1 %node% | find "TTL=" > NUL
if not errorlevel 1 (

for /f "tokens=2-7 delims=," %%a in (
    'wmic /node:"%node%" computersystem get domain^,manufacturer^,model^,name^,systemtype^,username^,wakeuptype /format:csv ^| find /i "%node%"'
) do (
    set "_domain=%%a"
    set "_manufacturer=%%b"
    set "_model=%%c"
    set "_name=%%d"
    set "_systemType=%%e"
    set "_userName=%%f"
)

for /f "tokens=2 delims=," %%a in (
    'wmic /node:"%node%" bios get serialNumber^,version /format:csv ^| find /i "%node%"'
) do (
    set "_serialNumber=%%a"
)

for /f "tokens=2-3 delims=," %%a in (
    'wmic /node:"%node%" os get description^,totalvisiblememorysize^,version /format:csv ^| find /i "%node%"'
) do (
    set "_osName=%%a"
    set "_memory=%%b"
)

for /f "tokens=2 delims=," %%a in (
    'wmic /node:"%node%" cpu get name^,version /format:csv ^| find /i "%node%"'
) do (
    set "_cpu=%%a"
)

echo !_name!,!_domain!,!_userName!,!_manufacturer!,!_model!,!_systemType!,!_serialNumber!,!_osName!,!_memory!,!_cpu! >> output.csv
)))


text:
Q: PHP autoload and static variable in function === Base.php ===
<?php
class Base
{
    public static function e()
    {
        static $number = 0;
        $number++;
        var_dump($number);
    }
}

=== A.php ===
<?php
class A extends Base {}

=== B.php ===
<?php
class B extends Base {}

=== test.php ===

function __autoload($classname)
{
    require_once("{$classname}.php");
}

Base::e();
A::e();
B::e();

php test.php, result is:
int(1)
int(2)
int(2)

Why not result is 1,1,1?

A: Try
require "Base.php";
Base::e();
require "A.php";
A::e();

vs.
require "Base.php";
require "A.php";
Base::e();
A::e();

The former will yield int(1) int(2), while the latter yields int(1) int(1).
Why?
When a class is bound, the static variable content is copied at exactly that moment how it currently is. There is no backing up of the original value of the static variable.
That implies, when the static variable is 0 when class A is bound, A::e() will have 0 as static value; in case it's 1, A::e() will also have 1 as value.
Similar for B::e() then, as Base::e() and A::e() are independent as the values are copied (no references). It will also have the same static variable Base::e() has at the binding time of B.

A: I did some research on this problem and it is really weird.
Static properties inside methods remain their state between instances of object. Which may be confusing. Also there are two statics one is the static function and the other one is static variable inside method.
It may be connected with autoloader. I did similar example with your but without using static methods but using static variable inside method. The result is 1:1:1 using both autoloader and same file.
<?php
class Base
{
    public function t()
    {
        static $number = 0;
        $number++;
        var_dump($number);
    }

    public static function e()
    {
        static $number = 0;
        $number++;
        var_dump($number);
    }
}

$base = new Base();
$base->t();

$a = new A();
$a->t();

$b = new B();
$b->t();

Also if you won't execute Base::e() the result is correct.
I've did require_once without autoloading and it still works. So it is definitly because of autoloader.
If you put
require_once "Base.php";
require_once "A.php";
require_once "B.php";

instead of autoloader function it works. Why is that I have no idea I've tried to find anything considering static variables with autoloader but without success. However, this answer may give you some clue.


text:
Q: How to include the vDSP-Framework (iOS)? I have problems to include the vDSP-Framework.
I thought it is just that steps todo:
#include <Accelerate/Accelerate.h>

void test()
{
  float a[1024], b[1024], c[1024];
  vDSP_vmul( a, 1, b, 1, c, 1, 1024 );
}

but if i try to build,I get an error:
 "_vmul", referenced from:

I think i didnt link the framework. but how can I do that?

A: The vDSP functions are in the Accelerate framework, if I remember correctly.
From your target's settings on the Build Phases tab, expand the area titled "Link Binary With Libraries".
From there you can press the plus button to add a new framework. Locate Accelerate in the list and add it.
You should then be able to use the functions in your app.


text:
Q: How to make code stop running after resolve or reject from EventEmiter I was trying to make a downloader, but now I struggle with download-remove.
My concept is pretty simple. Delete the files, and stop the download process if there's one.
My current problem is that code is still proceeding after the download-removed event received although I returned rejected.
This is for Node.js, and I don't use such external modules like bluebird or so, thus please provide plain javascript code if possible.
function download(id) {
    return new Promise(async (resolve, reject) => {
      // some logics to define both *links* and *size*
      process.on("download-removed", ($id) => {
        console.log("removed")
        if (id === $id) {
          console.log("matched")
          return reject("download-removed");
        }
        console.log("unmatched")
      });
      // from here, when event received, code should be stop as reject returned
      for (let index in links) {
        console.log("start", (index, size - links.length + Number(index) + 1));
        this._current = path.join(this._directory, String(id), `${(index, size - links.length + Number(index) + 1)}.${/\.([a-zA-Z]+)(\.webp)*$/.exec(links[index])[1]}`);
        await global.toolkits.download(links[index], this._current, false, `https://my_website/${String(id)}.html`).then((response) => {
          this._current = null;
          switch (response) {
            case "downloaded":
            case "file-exist": {
              console.log("end");
              let copy = [...links];
              copy.splice(0, index);
              process.emit("download-progress", id, (index, size - links.length + Number(index) + 1), size);
            }
          }
        });
      }
      this._current = null;

      if (this._process.length) {
        this.download(this._process[0]);
        this._process.splice(0, 1);
      }
      console.log("return", id);
      return resolve("downloaded");
      // to here!
    });

  remove(id) {
    process.emit("download-removed", id);
    // eslint-disable-next-line no-unused-vars
    this._process = this._process.filter((value, index, array) => { return value !== id; });
    fs.rmdirSync(path.join(this._directory, String(id)), { recursive: true });
  }

A: In your case, there is a few possible solutions:

1. Run download process in separate thread or process and kill the process on event
2. Create some global variable like let DOWNLOAD_ALLOWED = true and verify it's status before each load step (while you iterate through links). On system event, change DOWNLOAD_ALLOWED to false and exit your load script.


text:
Q: Displaying text in Android Status Bar I am trying to display text in the Status Bar of Android Nougat just as time is displayed. I can display icons using NotificationCompat.Builder but not text. How to proceed?

A: If you're using NotificationCompat.Builder you can set text there
NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")

You can also address this

A: Solved the problem by converting String to Bitmap. Got the idea from here


text:
Q: Error 403 Forbidden - when a site collection is locked as readonly I got an an error 403 Forbidden when I browse a site collection that I set to readonly (locked).
MOSS 2007 without SP2.
Is it related to SP2 installation ?

A: Check in Central Administration > Application Management > Site Quotas and Locks if that site collection is set to lock itself when the quota is reached.


text:
Q: ImageView slideshow animation I have a couple buttons under an ImageView within a LinearLayout.  I also have a series of images that I want to play through like a flip book to create an animation.  I do not know anything really about animation and I have no clue how I would accomplish this task. Any ideas and suggestions are greatly appreciated.
I did try to search but my lack of teminology makes it a little difficult..
Thanks!

A: You could make an array of the images and create a thread to change the image associated to the ImageView every so often. If you need help with that just ask.
~Aedon

A: This code snippet would (fade in/out) animate images in a ImageView showing them one after the other. You need to sligthly change the code though, if want to back and forth move the images with the buttons instead of playing a slideshow.


text:
Q: Julia. Specifying tolerance for fzero (in Roots package) I can't seem to find an option for specifying convergence tolerance levels when using fzero over a given range e.g. something along the lines of
wageresult= fzero(fbargsolve, wageguess0, [wagemin,wagemax], ftol=1e-5,xtol=1e-5)

Any ideas?
When I use this in the way specified below, I get a convergence failure which I think is because the default tolerance is overly strict for my purposes:
wageresult= fzero(fbargsolve, wageguess0, [wagemin,wagemax])

The error message is "Convergence failed("More than 15 iterations before convergence")"

A: When using fzero with an initial guess within a bracket, the only options to control convergence are maxeval and xtol, maxeval controls maximum number of iterations and it's default value is 15, you can set it to higher values. xtol is acceptable error and it's default is zero(float(a)) that means machine precision so it's already as low as possible.
an other way is to use fzeros function, it attempts to find all simple zeroes of f within an interval [a,b] available options for fzeros are no_pts=251 subintervals count, ftol=10*eps() and reltol=0.0
Roots v0.1.18


text:
Q: Rudin's PMA, Theorem 11.20 This is the definition which we need for the theorem: (source)

11.19 $\; \;$ Definition $\; \;$Let $s$ be a real-valued function defined on $X$. If the range of $s$ is finite, we say that $s$ is a simple function.
$\quad \quad$ Let $E \subset X$, and put
$$
K_{E}(x)= \begin{cases}1 & (x \in E), \\ 0 & (x \notin E).\end{cases}
$$
$K_{E}$ is called the characteristic function of $E$.
$\quad \quad$ Suppose the range of $s$ consists of the distinct numbers $c_{1}, \ldots, c_{n}$. Let
$$
E_{i}=\left\{x \mid s(x)=c_{i}\right\} \quad(i=1, \ldots, n) .
$$
$\quad \quad$ Then
$$
s=\sum_{n=1}^{n} c_{l} K_{E_{1}},
$$
that is, every simple function is a finite linear combination of characteristic functions. It is clear that $s$ is measurable if and only if the sets $E_{1}, \ldots, E_{n}$ are measurable.
$ \quad \quad$ It is of interest that every function can be approximated by simple functions:

Here is the theorem: (source)

11.20 $\; \;$ Theorem $\; \;$ Let $f$ be a real function on $X$. There exists a sequence $\left\{s_{n}\right\}$ of simple functions such that $s_{n}(x) \rightarrow f(x)$ as $n \rightarrow \infty$, for every $x \in X$. If $f$ is measurable, $\left\{s_{n}\right\}$ may be chosen to be a sequence of measurable functions. If $f \geq 0,\left\{s_{n}\right\}$ may be chosen to be a monotonically increasing sequence.
$\quad$Proof $\; \;$ If $f \geq 0$, define
$$
E_{n i}=\left\{x \mid \frac{i-1}{2^{n}} \leq f(x)<\frac{i}{2^{n}}\right\}, \quad F_{n}=\{x \mid f(x) \geq n\}
$$
for $n=1,2,3, \ldots, i=1,2, \ldots, n 2^{n}$. Put
$$
s_{n}=\sum_{i=1}^{n 2^{n}} \frac{i-1}{2^{n}} K_{E_{n l}}+n K_{F_{n}} .
 \quad \quad (50)$$
In the general case, let $f=f^{+}-f^{-}$, and apply the preceding construction to $f^{+}$and to $f^{-}$.
$\quad$ It may be noted that the sequence $\left\{s_{n}\right\}$ given by $(50)$ converges uniformly to $f$ if $f$ is bounded.

I couldn't understand that why does the sequence {$s_n$}, given by $(50)$ converge to $f$ .
Any help would be appreciated.

A: $\lim_{n \to \infty} s_n(x)=f(x)$:
Suppose $f$ is $\mathbb{R}_{\geq 0}$-valued.
Let $x \in X$. Since $f(x) \in \mathbb{R}_{\geq 0}$, there is a positive integer $M$ so that $0 \leq f(x) <M$. This means we will have
\begin{aligned}s_{M}(x)=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}(x)+M K_{F_{M}}(x)&=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}(x)+M \cdot0\\&=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}(x).
\end{aligned}
Now we may repeat the proceeding corresponding argument for uniform convergence in the case that $f$ is bounded to similarly conclude that $\lim_{n \to \infty} |s_n(x)-f(x)|=\lim_{n \to \infty} \frac{1}{2^n}=0$.

$f$ bounded $\implies$ $s_n \to f$ uniformly:
Suppose $f$ is bounded. This means there is a positive integer $M$ so that $0 \leq f(x) <M$ (assuming $f$ nonnegative to spare some headache).
Notice we have
\begin{aligned}s_{M}=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}+M K_{F_{M}}=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}+M \cdot0=\sum_{i=1}^{M 2^{M}} \frac{i-1}{2^{M}} K_{E_{M i}}.
\end{aligned}
So if $n \geq M$ and $x \in X$, then we have
\begin{aligned}|s_{n}(x)-f(x)|&=\left|\sum_{i=1}^{n 2^{n}} \frac{i-1}{2^{n}} K_{E_{n i}}(x)-f(x)\right|
\\&=\left|\sum_{i=1}^{n 2^{n}} \frac{i-1}{2^{n}} K_{E_{n i}}(x)-\sum_{i=1}^{n 2^{n}}f(x)K_{E_{n i}}(x)\right|
\\&=\left|\sum_{i=1}^{n 2^{n}} \left(\frac{i-1}{2^{n}}-f(x)\right) K_{E_{n i}}(x)\right|
\\&=\sum_{i=1}^{n2^{n}}\left( f(x) -\frac{i-1}{2^{n}}\right)K_{E_{n i}}(x) \quad \quad \left(f(x) -\frac{i-1}{n} < 0 \implies  K_{E_{n i}}(x)=0 \right)
\\&< \sum_{i=1}^{n 2^{n}} \frac{1}{2^n}K_{E_{n i}}(x)
\\&=\frac{1}{2^n}\sum_{i=1}^{n 2^{n}} K_{E_{n i}}(x)
\\&=\frac{1}{2^n}.
\end{aligned}
Let $\varepsilon > 0$ be given.
By the Archimedean Principle, there is a positive integer $L$ so that $L\varepsilon>1$. Consider $N=\max\{M,L\}$. So if $n \geq N$, then we have
$$\sup_{x \in X} \left|s_n(x)-f(x) \right|< \varepsilon.$$

A: Suppose $f : X \to [0, \infty]$ is measurable. Realize that for $x \in X$, $$s_n(x) = \min(\lfloor\frac{f(x)}{2^{-n}}\rfloor 2^{-n}, n).$$
In words, if $f(x) \leq n$, we let $s_n(x)$ be the largest multiple of $2^{-n}$ that is $\leq f(x)$, and if $f(x) \geq n$, we let $s_n(x) = n$. Now it is clear that for $x \in X$, if $f(x) < \infty$, then for $n \geq f(x)$ we have $s_n(x) \leq f(x) < s_n(x) + 2^{-n}$. So for $n \geq f(x)$, $|s_n(x) - f(x)| \leq 2^{-n} \to 0$ as $n \to \infty$. This proves that $s_n \to f$ pointwise.
Now suppose $f$ is bounded. Then there is $M > 0$ such that $f(x) \leq M$ for all $x \in X$. So for $n \geq M$, for all $x \in X$, $|s_n(x) - f(x)| \leq 2^{-n}$. So for $n \geq M$, $\sup_{x \in X}|s_n(x) - f(x)| \leq 2^{-n} \to 0$. This shows that $s_n \to f$ uniformly.


text:
Q: finding examples for a non negative and continuous function for which the infinite integral is finite but the limit at infinity doesn't exist Question:
a. Find an example for a non-negative and continuous function s.t. $\int _0^\infty f(x)dx$ is finite but the following limit doesn't exist: $\lim_{x\to \infty} f(x)$.
b. Is it possible that $\int _0^\infty f(x)dx$ is bounded but $f(x)$ is not bounded?
What we did with A:
We suggested the function $|sin(x^2)|$ which has periods that get smaller and smaller until they no longer imply on the sum. But since it's a trig function it doesn't have a determinate limit. Wolfram didn't have the integral value for that func, and we were wondering if it really converges and if it is really a good example.
What we did with B:
We thought about the function: $f(x)=  { x\in \Bbb N },{e^{-x} \notin \Bbb N }$ and we had a disagreement whether f(x) is integrable. I said no because similarly to Dirichlet function, one sum's limit will be 0 while the other one's will be infinite. My partner said that if I find a $\delta<1$ then the definition of Riemann's integral does hold and so this integral is equal to that of $f(x)=e^{-x}$ She was trying to say this functions integral will be 0, but still it won't be bounded. I disagreed. Who's right?

A: For (b), and therefore (a), let $f(x)=0$ with the following exceptions. For  every positive integer $n$, $f(x)$ climbs linearly from $f(x)=0$ at $x=n-2^{-2n}$ to $f(x)=2^n$ at $x=n$, then falls linearly to $0$ at $x=n+2^{-2n}$.
The area of the triangle "at" $n$ is $(2^{-2n})(2^n)$, that is, $2^{-n}$, and the sum of the areas of these triangles is $1$.

A: For A: The function $x \mapsto |\sin x^2|$ is not integrable. See Fresnel integrals are not Lebesgue integrable for example.
For B: Assuming that you meant $f(x) = \begin{cases} x, & x \in \mathbb{N} \\
e^{-x}, & x \notin \mathbb{N} \end{cases}$, then $f$ is not continuous, but it is integrable and unbounded. (And yes, the integral of $f$ is the same as the integral of $x \mapsto e^{-x}$.)
Here is a simple example that satisfies all requirements at the same time:
Let $\phi(x) = \max(0, 1-|x|)$. Let $f_n(x) = n\phi(n^3(x-n))$. Note that $\int f_n = \frac{1}{n^2}$.
Let $f=\sum_{n=2}^\infty f_n$. Note that $f(n) = n$ for all $n \ge 2$, $\int f = \sum_{n=2}^\infty \frac{1}{n^2}$, and $f(n+\frac{1}{2}) = 0$ for $n \ge 2$.
Hence $f$ is continuous, unbounded, integrable and has no limit as $x \to \infty$.


text:
Q: What exactly is PyOpenGL-accelerate? The title is the main question here. I had some PyOpenGL code I was running on my computer, which was running somewhat slow. I realized I hadn't installed PyOpenGL-accelerate. This didn't change the speed at all, but most tutorials with the Python OpenGL bindings suggest that PyOpenGL-accelerate should be installed.
What exactly does this module do?

A: First of all note that PyOpenGL-accelerate isn't a silver bullet. Thereby if you're already poorly optimizing your application, then PyOpenGL-accelerate wouldn't gain you that much if any additional performance.
That being said. PyOpenGL-accelerate consist of Cython accelerator modules which attempt to speed up various aspects of PyOpenGL 3.x. Thus if you're using glBegin() and glEnd() to draw with, then you won't gain any performance from this.
So what is Cython accelerator modules?

These modules are completely self-contained, and are created solely to run faster than the equivalent pure Python code runs in CPython. Ideally, accelerator modules will always have a pure Python equivalent to use as a fallback if the accelerated version isn't available on a given system. The CPython standard library makes extensive use of accelerator modules.
– Python – Binary Extensions

In more layman's terms. Cython is a bit of a mix between Python and C so to speak. With a goal being optimization and execution speed.
In relation to PyOpenGL-accelerate this means that the various helper classes PyOpenGL offers. Is instead implemented in a manner that offers more performance.

A: From the documentation:

This set of C (Cython) extensions provides acceleration of common operations for slow points in PyOpenGL 3.x. For code which uses large arrays extensively speed-up is around 10% compared to unaccelerated code.

You could dig through the code if you want to know precisely which optimizations are defined, but OpenGL is usually built around surprisingly coarse optimizations to account for different hardware - i suppose that extends to running off of an interpreter as well.


text:
Q: Is it possible to detect the class that called super() in base class? Is it possible to detect which class called super() in the base class?
I have a base class which will be extended by several classes. In the base class constructor, i need to make an initialization based on the class which called super().
Currently I'm passing an argument while calling super(), and initializing accordingly in the base class.

class BaseClass {
  constructor(child) {
    if (child === "ChildClass") {
      // ......
    }
    else {
      // .......
    }
  }
}

class ChildClass extends BaseClass {
  constructor() {
    super("ChildClass")
  }
}

What is the proper way of achieving this?
Thanks.


text:
Q: Sencha Touch Cross Origin Error I am trying to make ajax request using Sencha Touch 2 but I am getting the cross origin error.
I am using Ext.Ajax.Request for sending the ajax request with POST method.
I have no idea how to fix that.

A: There are so many question regarding this issue
Origin is not allowed by Access-Control-Allow-Origin
Access-Control-Allow-Origin issue with mobile web app
Sencha touch 2 json + twitter = Access-Control-Allow-Origin


text:
Q: Attach Backbone.Marionette Layout to the "body" I have a marionette layout, which I want to attach directly to the  element of the page.
App.Views.Layouts.Unauthenticated = Backbone.Marionette.Layout.extend
  template: "layouts/unauthenticated"
  regions:
   content: "#content"
   header: "#header"
   footer: "#footer"
  views: {}

 initialize:->
  @el = $("body")
  @delegateEvents()

then later in the app, I do this
App.layouts.unauthenticated = new App.Views.Layouts.Unauthenticated()
App.layouts.unauthenticated.render()

The layout is not attached to the page.
How do I attach it to the body, while I already used body as an "el", since I don't need extra wrappers.

A: You need to set the el in the definition of the view, not in the initializer.

App.Views.Layouts.Unauthenticated = Backbone.Marionette.Layout.extend
  el: "body"
  template: "layouts/unauthenticated"
  regions: ...