text:
Q: I want to convert JSON stringify Data into an associative array? I retrieved the data from the database which was in [object Object].
I usually convert these data using JSON.parse but it did not working so, I tried JSON.stringify but the data now it's like
[{"station" : "NewYork"}, {"station" : "Toronto"}]
Now I don't know how to convert this data into an array object and access it. I need only object entries but I don't know how to access it.
If it is declared to var data I need it like data[0]['station'] to access but I couldn't do it.


text:
Q: enable main page scroll when angular material dialog open I have a requirement where I will have my material dialog and when I am opening it I will not have a vertical scrollbar on dialog, instead I will just use the main page (on which page dialog is opened) scroll, For now what happening is, its blocking any scroll movement on the main page.
check the stackblitz link
so if you see in above stackblitz dialog has lot of content which is not visible because I am not able to scroll down using main page scroll. Its blocking the main page scroll and note I don't want the scroll inside the dialog itself. that is not my requirement unfortunately

A: You should add a scroll strategy as an option when the dialog opens. I changed your openDialog() function as follows, to include a scroll strategy.
export class DialogContentExample {
  constructor( public dialog: MatDialog, private overlay: Overlay ) {}

  openDialog() {
    const dialogRef = this.dialog.open(DialogContentExampleDialog, {
      scrollStrategy: this.overlay.scrollStrategies.noop()
    }); //Added the strategy, after first constructing the variable containing it

    dialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog result: ${result}`);
    });
  }
}

You also need to import the library: import { Overlay } from "@angular/cdk/overlay";
Here is your refactored stackblitz example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How create a button by programmatically for a GridLayout I'm triying to create a GridLayout by programmatically in Kotlin. My code for the XML is this:
<androidx.constraintlayout.widget.ConstraintLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#46FF4433"
      tools:context=".MainActivity">

     <androidx.gridlayout.widget.GridLayout
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:rowCount="5">
        app:columnCount="3"
     </androidx.gridlayout.widget.GridLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

I want to set 15 buttons into my Grid. My mainActivity is this:
    val gridLayout: GridLayout = findViewById(R.id.grid)

    for (i in 1..10){
        val button = Button(this)
        button.text = "Boton: " + i
        button.setBackgroundColor(Color.parseColor("#ffffff"));

        gridLayout.addView(button)

    }

But I need each button be like this:
    <Button
        android:id="@+id/button1"

        app:layout_gravity="fill"
        app:layout_columnWeight="1"
        app:layout_rowWeight="1"

        android:text="Button 1"
        android:background="#ffffff"
    />

I think it has something to do with the layout param but I don't know how to set those atributes.

A: Take a look at GridLayout.LayoutParams and GridLayout.Spec. You can do something like the following:
val button = Button(this)
val lp = GridLayout.LayoutParams()
lp.setGravity(Gravity.FILL)

// GridLayout.spec is immutable, so one can be applied more than once.
// There are several other versions of GridLayout.spec which may be applicable.
lp.rowSpec = GridLayout.spec(row, 1.0f) // row start, weight
lp.columnSpec = GridLayout.spec(col, 1.0f) // column start, weight
button.layoutParams = lp

I haven't tested this, but it should get your started.


text:
Q: code was working properly (from keras.preprocessing.image import img_to_array) but same code is giving this error code was working properly from keras.preprocessing.image import img_to_array but same code is giving this error
Traceback (most recent call last):
  File "c:\Users\Acer\Desktop\miniprojectdiscussion\predict.py", line 1, in <module>
    import cv2
  File "C:\Users\Acer\AppData\Local\Programs\Python\Python39\lib\site-packages\cv2\__init__.py", line 9, in <module>
    from .cv2 import _registerMatType
ImportError: cannot import name '_registerMatType' from 'cv2.cv2' (C:\Users\Acer\AppData\Local\Programs\Python\Python39\lib\site-packages\cv2\cv2.cp39-win_amd64.pyd)


text:
Q: Pass multiple functions to purrr:map I would like to pass multiple functions at once to one purrr::map call, where the functions need some arguments. As pseudo code:
funs <- c(median, mean)

mtcars %>%
  purrr::map(funs, na.rm = TRUE)

This code does not run, but is intended to show what I am looking for: passing over multiple functions to map along with some arguments.
I looked at compose but that function does something different.

A: Here is my baby-steps solution (depends what you mean by "at once"):
mtcars %>%
  map_dbl(~{mean(.x, na.rm = TRUE)}) %>%
  enframe() %>%
  rename(mean = value) %>%
  as_tibble %>%
  left_join(mtcars %>%
              map_dbl(~{median(.x, na.rm = TRUE)}) %>%
              enframe() %>%
              as_tibble %>%
              rename(median = value))

A: You want to apply multiple functions to a dataframe with map(), but (apparently) there is no map() variation that does exactly this, only parts of it. For the multiple function part we have invoke_map() and for the multiple argument part over a dataframe we have pmap().
invoke_map() allows the use of multiple functions at once. For example, if we want to generate 5 random variates for a uniform and normal distributions, the code is:
func <- list(runif, rnorm)
invoke_map(func, n = 5)

pmap() is just like map, but it allows to pass multiple arguments to a single function. For example, if we want to generate 10 random variates from a normal distribution with mean = 0 and sd = 1, but also 100 random variates from a normal distribution with mean = 100 and sd = 20, the code looks like this:
args <- list(mean = c(0, 100), sd = c(1, 20), n = c(10, 100))
pmap(args, rnorm)

To solve your question, we have to combine both functions in the following way:
fun <- function(f) pmap(list(x = mtcars, na.rm = TRUE), f)
param <- list(list(mean), list(median))

invoke_map(.f = fun, .x = param)

How does this work?

*

*At the invoke_map() level, fun takes as arguments param, which are the functions we want to apply to mtcars.

*Next, at the fun level, these functions stored in param are applied by pmap(), one at a time, to each column in mtcars.
Note: For the solution to really make sense, keep in mind the arguments invoke_map() and pmap() take.
More info about how invoke_map() and pmap() work.

A: invoke() and its map variants have been retired in favour of rlang::exec().  From the documentation:

These functions are retired in favour of exec(). They are no longer
  under active development but we will maintain them in the package
  indefinitely.
invoke() is retired in favour of the simpler exec() function
  reexported from rlang. exec() evaluates a function call built from its
  inputs and supports tidy dots
invoke_map() is retired without replacement because it is more
  complex to understand than the corresponding code using map(), map2()
  and exec()

So the equivalent method now is:
library(dplyr)
library(purrr)

funs <- c(mean = mean, median = median)
args <- list(na.rm = TRUE, trim = .1) # trim argument non-matching and ignored for median

mtcars %>%
  map_df(~ funs %>%
           map(exec, .x, !!!args), .id = "var")

# A tibble: 11 x 3
   var      mean median
   <chr>   <dbl>  <dbl>
 1 mpg    19.7    19.2
 2 cyl     6.23    6
 3 disp  223.    196.
 4 hp    141.    123
 5 drat    3.58    3.70
 6 wt      3.15    3.32
 7 qsec   17.8    17.7
 8 vs      0.423   0
 9 am      0.385   0
10 gear    3.62    4
11 carb    2.65    2


text:
Q: EF Core - why ClientSetNull is default OnDelete behavior for optional relations (rather than SetNull) For optional relationships (when Foreign Key can accept Null), a new ClientSetNull behavior has been introduced since EF Core 2.0 as the default option for delete behavior DeleteBehavior.ClientSetNull.
This has SetNull semantics for tracked entities and Restrict (no action) behavior for database records not loaded into memory.

Microsoft docs say that:

If you want the database to also try to propagate null values to child
  foreign keys even when the child entity is not loaded, then use
  SetNull. However, note that the database must support this, and
  configuring the database like this can result in other restrictions,
  which in practice often makes this option impractical. This is why
  SetNull is not the default.

But I think it is usually normal to set FK of dependent entities to Null when the associated parent is deleted (every where in db). And also, what's those "other restrictions, which in practice often makes this option impractical.." as claimed above?

A: Those other restrictions the docs are referring to are, as far as I know, circular or multi path cascades.
MS Sql Server for example does not allow cascades (both delete and set null) if

*

*the change would cascade to the same table it originated from

*there are multiple cascade paths to the same table. Like table 'A' affects table 'B' and 'C', both 'B' and 'C' affect 'D'.

You can't even create the constraint.
EF core can circumvent this limitation with ClientSetNull. EF handles the set null operation, but it can only do so if all the affected entities are loaded into memory.


text:
Q: What was "it" referring to in the line "it was saying"? In sci-fi movie Existenz (1999), After both returning to home from video game world, Allegra found Ted's bio port is infected.

Allegra: It's Kiri Vinokur. That bastard.
Ted: Vinokur?
Allegra: He gave you a new bio-port. He gave you an infected one so
  that my pod and my game system would die!
Ted: I'm infected? Wait a minute.
Allegra: It was saying it was sick by introducing the theme of disease
  in the game.
Ted: "The theme of disease"? l'm fucking really infected!

A: Allegra is referring to the game system itself. It's infected and hence the game contains imagery about disease that wasn't originally programmed into it.
The conversation in the film's novelisation is worded slightly differently and makes it abundantly clear what the object in the sentence is.

"There was no reality bleed-through after all," Geller said. "We were thinking about it from the wrong direction. When we were in the game, the poor thing was trying to tell us that it was sick. It was the pod that introduced the theme of disease into the game."
"The theme of disease?"


text:
Q: SDE FeatureClass Granting and Revoking Privilege with ArcObjects How can I with ArcObjects GRANT or REVOKE Privileges like SELECT, UPDATE on SDE FeatureClasses to/from Roles?
The equivalent in normal Oracle would be something like this:
GRANT SELECT ON SCHEMA.TABLE TO SOME_ROLE;
REVOKE SELECT ON SCHEMA.TABLE FROM SOME_ROLE;

I can't seem to find the interface to perform this task, and it may not exists?
My dream would be to have an Interface like this:
public interface IPrivilegeManager
{
    void Grant(string privilegeName, string schemaOwnerName, string featureClassName, string roleName);
    void Revoke(string privilegeName, string schemaOwnerName, string featureClassName, string roleName);
}

Related Q: For a SDE FeatureClasses list all Roles that have been Granted any Privileges on it, and which Privileges each Role have on it

A: You can obtain the name object for the given feature class and cast it to ISQLPrivilege, which allows you to enumerate, grant and revoke permissions.
E.g.:
var name = ((IDataset) featureClass).FullName;
var sqlPrivilege = name as ISQLPrivilege;
if (sqlPrivilege != null)
{
    sqlPrivilege.Grant("USER_OR_ROLE_NAME", (int) esriSQLPrivilege.esriSelectPrivilege, false);
}


text:
Q: How to print 2D arrays in a table with key name(just one time) and all it's values php? Array
(

 [1JANATAMF] = Array
     (
         [0] = 4.10
         [1] = 5.10
         [2] = 6.10
         [3] = 7.10
         [4] = 8.10
         [5] = 5
         [6] = 0.02
         [7] = 5413
     )

 [1STPRIMFMF] = Array
     (
         [0] = 12.90
         [1] = 1.90
         [2] = 16.90
         [3] = 11.90
         [4] = 14.90
         [5] = 24
         [6] = 04
         [7] = 10
     )

I have this kind of arrays. Now I want to print then in a table with the key name of the main arrays (once) on the table row with its all values.
Table I Want is like:
1JANATAMF    4.10   5.10  6.10   7.10   8.10   5   0.02  5413
1STPRIMFMF   12.90  1.90  16.90  11.90  14.90  24  04    10

My Code is this which prints all keys together and some values at the end.
foreach ($c as $keys =>$values)
         echo $keys . " ";`enter code here`
     foreach ($values as $key=>$data)
         echo " " . $data . "
";

A: You have to use simple foreach():
foreach($array as $key=>$value){?>

    <?php echo $key;?>
    <?php foreach($value as $val){?>
        <?php echo $val;?>
    <?php } ?>

<?php }?>

Sample output: https://3v4l.org/gFhO7

A: One way is You can use array_values() and foreach() like this :
$arrVals = array_values($1JANATAMF)
foreach($arrVals as $value){
    // Use Html To Create Table and add $value to columns
}


text:
Q: Gack Id "-1079455898" in Lightning Experience Any reasons or steps to reproduce for Lightning Salesforce Internal error with gack id "-1079455898"?
Please note: this is not duplicate of Salesforce Internal Error in Lightning with Gack Id 1747963889 since gack id is different and reason is different.

A: Implement lightning app with apex controller with @auraEnabled method with Integer parameter.
Pass Integer to @auraEnabled method and perform Integer x = i + 1 inside of that method.


text:
Q: Questions on the proof of make change problem using greedy algorithm I recently learned the proof of the greedy algorithm solution to make change problem:

There's a set of coins $\{c_1 < c_2<...<c_{i-1}<c_i\}$. $c_i$ is an integer and $c_{i+1}=q\cdot c_i$ where $q$ is an integer. Given number $x$ what is the least amount of coins needed to pay $x$ of some currency?

The solution will use a greedy algorithm. In order to prove that greedy algorithm is correct we suppose that we have:
$$
\{c_1, c_2,...,c_{i-1},c_i\} \quad\text{coins set}\\
k_1, k_2,...,k_{i-1},k_i\quad\text{how many times}\quad c_i \quad\text{is repeated}\\
c_1=1
$$
We also suppose that there's another different algorithm that works and in it there're $p_i$
repetitions of $c_i$.
Then $p_i<k_i$. Then we have some "deficit" on $p_i$ part then the deficit must be resolved by some former combination of $p$ and $c$.
We'll prove that the deficit will never be resolved because:
$$
p_1\cdot c_1<c_2\qquad (1)
$$
then:
$$
p_1\cdot c_1 \le c_2-c_1 \implies\qquad (2)\\
p_2\cdot c_2 \le c_3-c_2 \implies\\
\vdots\\
p_i\cdot c_i \le c_i-c_{i-1} \implies
$$
Now if we sum up the LHS and RHS we get:
$$
\sum_{k=1}^{i-1}p_k\cdot c_k\le c_i-c_1<c_i
$$
which proves that the deficit is never made up for by $\sum p_k\cdot c_k$.

Two things I can't grasp:
why does $(1)$ and $(2)$ hold?

A: (1) is true because you could have used $c_2$'s instead if $p_1c_1 \geq c_2$.
(2) is true from (1) because $qc_1 = c_2$ for some integer $q$, so if $p_1c_1 < c_2$ then $(p_1 + 1)c_1 \leq c_2$


text:
Q: Unknown character at end of snippet titles in EmEditor 20.9 After upgrading from EmEditor 20.8.1 to 20.9, the titles of some of the handmade and preinstalled snippets end with a symbol normally used to represent unknown characters (black diamond with white question mark).
Is this a bug?
If so, can this be automatically repaired or will I have to do it manually?


text:
Q: Can't PUT customer in Rest Api Magento2 - fails to complete How do you PUT (update) a customer using the rest api?
I have a ticket open on github, but I was wondering if I'm just doing this wrong..
https://github.com/magento/magento2/issues/5115
I've created a customer in admin.  I've noted the entity id. It is 22.
I'm attempting to PUT using the rest api to myhost.com/rest/V1/customers/{{myEntityId}}
The actual URL is http://192.168.5.65/rest/V1/customers/22 just to avoid confusion.
I'm sending the following json:
{
    "customer": {
        "firstname": "NewMitchell",
        "lastname": "NewThompson"
    }
}

Magento documentation states you only need to send the properties you want to update.
I'm expecting the customer object to be updated, but its actually trying to create a new customer.  I'm seeing this message come back:
{
  "message": "Please enter a customer email.",
  "trace": "#0 /var/www/vendor/magento/module-eav/Model/Entity/VersionControl/AbstractEntity.php(90): Magento\\Customer\\Model\\ResourceModel\\Customer->_beforeSave(Object(Magento\\Customer\\Model\\Customer))\n#1 /var/www/vendor/magento/framework/Interception/Interceptor.php(74): Magento\\Eav\\Model\\Entity\\VersionControl\\AbstractEntity->save(Object(Magento\\Customer\\Model\\Customer))...blahblahblah

I'm afraid I may be doing it wrong, but at the same time, I think I may have identified a bug.
Can anyone test this and see if it works or not?  I'm using Magento CE RC3, but i've tested it on Magento CE 2.0.6 and it doesn't work there either.

A: if you look at the documentation you'll find that actually the email is not optional so is needed in order to update the customer
customer-data-customer-interface {
id (integer, optional): Customer id ,
groupId (integer, optional): Group id ,
defaultBilling (string, optional): Default billing address id ,
defaultShipping (string, optional): Default shipping address id ,
confirmation (string, optional): Confirmation ,
createdAt (string, optional): Created at time ,
updatedAt (string, optional): Updated at time ,
createdIn (string, optional): Created in area ,
dob (string, optional): Date of birth ,
email (string): Email address ,
firstname (string): First name ,
lastname (string): Last name ,
middlename (string, optional): Middle name ,
prefix (string, optional): Prefix ,
suffix (string, optional): Suffix ,
gender (integer, optional): Gender ,
storeId (integer, optional): Store id ,
taxvat (string, optional): Tax Vat ,
websiteId (integer, optional): Website id ,
addresses (Array[customer-data-address-interface], optional): Customer addresses. ,
disableAutoGroupChange (integer, optional): Disable auto group change flag. ,
extensionAttributes (customer-data-customer-extension-interface, optional),
customAttributes (Array[framework-attribute-interface], optional): Custom attributes values.
}

but if you try with the email at the current release you'll see there also  another param that is not optional (problably the documentation has to be updated). here is the very least needed to do the update:
{
  "customer": {
  "email": "email@here.me",
  "firstname": "firstname new",
  "lastname": "lastname new",
  "website_id": 1
  }
}


text:
Q: Flutter Scrollable Navigation bar Is it possible to make the NavigationBar scrollable?
My goal is to make a NavigationBar, so you can add up to 15 diffrent Items, if you want.
Thanks for your answers.

A: That is not possible, and you don't find navigation bars to be scrollable, good UI design features a few elements at the most in the nav bar.
For a scrollable solution, please check out Tabs: https://material.io/components/tabs/flutter


text:
Q: Problem with a sql statement string insertCommand =
    "INSERT INTO Users (UserID) VALUES" + "" + "(CONVERT(uniqueidentifier, '" +
    UsersIdentityToinsert + "'),'"+ userName+",0,null')";

it tells me:

There are fewer columns in the INSERT statement than values specified

in the VALUES clause. The number of
  values in the VALUES clause must match
  the number of columns specified in the
  INSERT statement.

But i have four columns?

A: you only have UserID in the insert list but in the value list, you have two values -  a uniqueidentifier and a username
this would work better: (assuming the name of your username column)
string insertCommand =
    "INSERT INTO Users (UserID, username) VALUES" + "" +
    "(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";

EDIT:
I feel i need to address this part a bit more clearly:

But i have four columns?

The error you received refers to the number of columns specified in the INSERT statement - not the actual table so if you start an INSERT with:
INSERT INTO AnyTable (ColumnA, ColumnB)

you need to match the number of columns here in your VALUES clause
VALUES ("Value1", "Value2")

A: You are missing "UserName" in column Names, that is, Column Name and values mismathch.
string insertCommand =
    "INSERT INTO Users (UserID,UserName) VALUES" + "" +
    "(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";


text:
Q: Loop infinito ao recuperar e gravar dados no Firebase sou iniciante em Android e tive um problema ao recuperar um dado do Firebase e gravar novamente, sei o motivo do loop infinito mas não sei como corrigir.
public static void setVoto (String candidato){
    votoFirebase = referenciaDatabase.child(candidato).child("votos");

    votoFirebase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            voto = dataSnapshot.getValue().toString();
                votoInt = Integer.parseInt(voto);
                votoFirebase.setValue(votoInt + 1);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

O problema acontece que sempre que é alterado o valor, ele volta para o método, então quando a pessoa vota, ele fica em um loop infinito..
Como eu posso corrigir, ou usar outra função para que eu possa recuperar a pontuação atual no firebase e possa gravar o dado somando +1 sem que ocorra o loop ?
Eu tentei criar uma flag, funcionou, porem quando o app é fechado e aberto, a flag volta como true e permite que o usuario vote novamente...

A: Isso acontece porque você está utilizando um ValueEventListener. Ele é chamado sempre que acontece uma alteração na Database. Isso significa que sempre que você incrementa o número de votos, ele é chamado novamente e incrementa mais uma vez.
Para resolver isso, utilize um ListenerForSingleValueEvent:
votoFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        voto = dataSnapshot.getValue().toString();
        votoInt = Integer.parseInt(voto);
        votoFirebase.setValue(votoInt + 1);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});


text:
Q: Is it possible to recover a deleted named.conf if named still running? If, for example, you spend some time working on a named.conf, and then by mistake clear it and save it (thanks to vi), is there a saved copy of the named.conf in the running instance that I could grab?

A: found it!
/var/named/1 contains the running config!

A: Since I'm not high-enough to make comments, I'll address my question in my answer, if that's ok.
First, is your instance of vi still running?  You can undo, or check if the .swp file exists, it might contain your buffer.
Also, you can definitely dump the processes memory and extract the data you're looking for that way, but this would be significantly more tedious.

A: You can use LSOF if your process is still running
IBM example, aimed at AIX but the process should be similar for most implementations. Then an example from Linux.com
Whilst you've already accepted an answer to this question, I'm submitting this response as it may be useful to others that can't rely on the /var/named/1 file existing or if they've removed a file not related to named


text:
Q: How do I compress files in-place? I have a machine with 90% hard-disk usage.  I want to compress its 500+ log files into a smaller new file. However, the hard disk is too small to keep both the original files and the compressed ones.
So what I need is to compress all log files into a single new file one by one, deleting each original once compressed.
How can I do that in Linux?

A: gzip or bzip2 will compress the file and remove the non-compressed one automatically (this is their default behaviour).
However, keep in mind that while the compressing process, both files will exists.
If you want to compress log files (ie: files containing text), you may prefer bzip2, since it has a better ratio for text files.
bzip2 -9 myfile       # will produce myfile.bz2

Comparison and examples:
$ ls -l myfile
-rw-rw-r-- 1 apaul apaul 585999 29 april 10:09 myfile

$ bzip2 -9 myfile

$ ls -l myfile*
-rw-rw-r-- 1 apaul apaul 115780 29 april 10:09 myfile.bz2

$ bunzip2 myfile.bz2

$ gzip -9 myfile

$ ls -l myfile*
-rw-rw-r-- 1 apaul apaul 146234 29 april 10:09 myfile.gz

UPDATE as @Jjoao told me in a comment, interestingly, xz seems to have a best ratio on plain files with its default options:
$ xz -9 myfile

$ ls -l myfile*
-rw-rw-r-- 1 apaul apaul 109384 29 april 10:09 myfile.xz

For more informations, here is an interesting benchmark for different tools: http://binfalse.de/2011/04/04/comparison-of-compression/
For the example above, I use -9 for a best compression ratio, but if the time needed to compress data is more important than the ratio, you'd better not use it (use a lower option, ie -1, or something between).

A: I figured out a tar solution by myself.
It deletes single file after compressed it into the target file.
The compressing speed is not quite fast, though. The command looks like:
tar -zcvf my_log.tar.gz *.log --remove-files

A: In complement to @apaul, I emphasize that compressing files individually
 bzip2 *.log.*

(replace bzip2 by gzip, xz, or what ever your favorite file zip is)
may be important:
This way you can still see (bzcat file.bz2), search (bzgrep file.bz2), edit (vi file.bz2) the compressed file
and remove the older ones when necessary.

A: I was trying to do this on the BSD-version of tar. In this case, the --remove-files option is not available. What I ended up doing (and worked) was:
find folder_to_tar -type f -exec tar --append --file=output_tar_file.tar {} \; -exec rm -v {} \;

A: when you use io redirection in bash with >, the original file will be empty before write new data.
there is a command dd that can overwrite some content of the file instead of empty the file before writing, so following command may work:
gzip -c some-file | dd conv=notrunc of=some-file

mostly, compressed data are smaller than original data.
when gzip read first N bytes, it only output M bytes where M < N,
so one can safely overwrites first M bytes
of original file with compressed data,
and leave data after first N bytes not changed.
but there will be data after the end of gzip.
however, if dd write faster than gzip, i do not know what will happen.

or you can map a file to a block device by losetup.
for block device, writing operation will not empty the original data.
loop_device=$(losetup -f--show some-file)
gzip -c $loop_device > $loop_device


text:
Q: SQL error on password resetting laravel 5.1 I am trying to implement a password reset on my Laravel 5.1 app using  the docs. When i click on send password reset button it gives me the following error.

QueryException in Connection.php line 651:
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause' (SQL: delete from password_resets where email = abc@abc.com).

A: Kindly check the password_resets table in your database. And see if email column exists.


text:
Q: ellipse polar co-ordinate conversion I have a somewhat trivial question out of interest. Given the equation of an ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ why is the substitution $x = \sqrt{a}\cos t$ and $y = \sqrt{b}\sin t$ valid?
For the unit circle $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ it is clear graphically why the polar co-ordinate conversion $x = r \cos t$ and $y = r \sin t$ is valid since the radius $r$ is fixed, but with an ellipse, this is not the case. Why is it taken trivially that this substitution is valid?
Thanks for any assistance.

A: You don't actually have these square roots there. The line of thought is like this: $$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1 \iff \left(\frac{x}{a}\right)^2 + \left(\frac{y}{b}\right)^2 = 1,$$so making a change of coordinates $\overline{x} = x/a$ and $\overline{y} = y/b$, we have that this equation reads $\overline{x}^2+\overline{y}^2 = 1$. That ellipse in the $xy$ plane is a circle in the $\overline{x}\overline{y}$ plane, with the axes stretched. We can parametrize it as ${\overline{x}} = \cos t$, $\overline{y}= \sin t$. Going back to the $xy$ coordinates we obtain $x = a \cos t$ and $y = b \sin t$.

A: Note that
$$ x = a \cos t , y = b \sin t $$
are not polar coordinates for ellipse:
$$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1.$$
The polar coordinate equation of central ellipse is
$$ \left(\frac{ \cos t }{a}\right)^2 + \left(\frac{\sin t }{b}\right)^2 = \frac{1}{r^2} $$
And for a circle radius r
$$\frac{x^2}{r^2}+\frac{y^2}{r^2}=1 $$
is valid.

A: For the ellipse $$\left( \frac{x}{a} \right)^2 + \left( \frac{y}{b} \right)^2 = 1 $$
the expression $[x,y] = [a \cos t,b \sin t]$ is a parametrization that solves the equation of the ellipse. If you plug in $x$ and $y$ you get
$$\left( \frac{a \cos t}{a} \right)^2 + \left( \frac{b \sin t}{b} \right)^2 = \cos^2 t + \sin^2 t = 1 $$
This parametrization does not represent the polar coordinates. To get the polar coordinates $r$ and $\theta$ you need $[x,y] = [r \cos \theta, r \sin \theta]$ which leads to the solution
$$\boxed{ r (\theta) = \frac{a b}{\sqrt{a^2 + (b^2-a^2) \cos^2 \theta}} }$$
If you plot the above for any constants $a$ and $b$ you will get an ellipse with semi-major and semi-minor radii of $a$ and $b$ respectively.


text:
Q: Rxjs increment loop counter after limit I have sample code of observable to print some values
 sample4Observable() {
    var observable = Observable.create(function (observer) {
      for (var i = 1; i <= 4; i++) {
        if (i <= 3) {
          observer.next(i);
        }
        if (i === 4) {
          setTimeout(() => {
            observer.next(i);
            observer.complete();
          }, 5000);
        }
      }
    });
    console.log('just before subscribe');
    observable.subscribe({
      next: x => console.log('got value ' + x),
      error: err => console.error('something wrong occurred: ' + err),
      complete: () => console.log('done'),
    });
    console.log('just after subscribe');
  }

the output is
just before subscribe
got value 1
got value 2
got value 3
just after subscribe
got value 5
done

My question is my loop is end when the value reached to 4. So the next value will be 4 instead of 5. why RxJS skip the value 4?
In order to get the value for 4 i can change my code like below. But in above scenario I am little bit confusing. Can anyone explain
 setTimeout((i) => {
            observer.next(i);
            observer.complete();
          }, 5000,i);

A: When you set a timeout, the inner function will be executed after the time has passed. When the loop reaches i === 4 it starts the timeout, the inner function is not yet executed. The loop goes one more round incrementing i to 5, then the loop terminates because the condition i <= 4 is not met anymore. After the 5 seconds have passed (which is after i has been incremented to 5), the timeout is fulfilled and the function is executed. Although when the timeout was started i === 4 was true, now when the timeout function is executed, it is i === 5.
This is not directly linked to RxJS. This simpler example should illustrate it. Just run it in your browser console:
let i = 0;
setTimeout(() => console.log(`the value of i is ${i}`), 500);
i++;

A: It isn't relate anything with RxJS anyway, this is the javascript execution happens. Since you're looping up until i<=4, count is reaching to 4 and once i==4 you're firing up a function with setTimeout. So as soon setTimeout gets registered, it doesn't get evaluate directly. setTimeout is async event, browser place it inside something called as Event Loop. And wait till all synchronous execution of javascript get over. Since you had i++ in for loop i value becomes 5. Afterwards all synchronous execution completion. Javascript visit Event Loop to evaluate asynchronous operation(they can be events as well). That time your setTimeout evaluate and it wait till 5000(5 sec), then it gets i value as 5 as expected.
The point is even if you set timeout 0 instead of 5000 you will get same result i.e. i = 5.
Since javascript is single threaded, it always evaluate synchronous code followed by asynchronous code.

There you could pass i value as parameter to setTimeout function while calling it. Provided i value will be available inside the scope of function directly, so that wouldn't checking the global value. Check MSDN Docs here
setTimeout((i) => {
   observer.next(i);
   observer.complete();
}, 5000,i);


text:
Q: Sign JWT with PrivateKey from android Fingerprint API I have some claims and I want to create JWT  and sign it with a PrivateKey created in Fingerprint API.
This is the JWT claim -
Header:

{
     "alg": "RS256",
     "kid": "ABCDEDFkjsdfjaldfkjg",
      "auth_type" : "fingerprint" / "pin"
}

Payload:
{
      "client_id":"XXXXX-YYYYYY-ZZZZZZ"
}

Creating KeyPair for fingerprint -
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.yourmobileid.mobileid.library.common.MIDCommons;

import org.jose4j.base64url.Base64;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.RSAKeyGenParameterSpec;

@RequiresApi(api = Build.VERSION_CODES.M)
public class BiometricHelper {

    public static final String KEY_NAME = "my_key";
    static KeyPairGenerator mKeyPairGenerator;
    private static String mKid;
    private static KeyStore keyStore;

    public static void init() {
        try {
            mKeyPairGenerator = KeyPairGenerator.getInstance(  KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException("Failed to get an instance of KeyPairGenerator", e);
        }
        mKid = MIDCommons.generateRandomString();

         keyStore = null;

        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
        } catch (KeyStoreException e) {
            throw new RuntimeException("Failed to get an instance of KeyStore", e);
        }

        createKeyPair();
    }

    /**
     * Generates an asymmetric key pair in the Android Keystore. Every use of the private key must
     * be authorized by the user authenticating with fingerprint. Public key use is unrestricted.
     */
    public static void createKeyPair() {
        try {

            mKeyPairGenerator.initialize(
                    new KeyGenParameterSpec.Builder(
                            KEY_NAME,
                            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                            .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
                            .build());
            mKeyPairGenerator.generateKeyPair();
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
    }

    public static PrivateKey getPrivateKey() {
        PrivateKey privateKey = null;
        try {
            keyStore.load(null);
            privateKey = (PrivateKey) keyStore.getKey(KEY_NAME, null);
        } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        return privateKey;
    }

    public static PublicKey getPublicKey() {
        PublicKey publicKey = null;
        try {
            keyStore.load(null);
            publicKey = keyStore.getCertificate(KEY_NAME).getPublicKey();
        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        return publicKey;
    }

    public static KeyStore getKeyStore(){
        return keyStore;
    }
    public static String getPublicKeyStr()  {
        StringBuilder publicKey = new StringBuilder("-----BEGIN PUBLIC KEY-----\n");
        publicKey.append(Base64.encode((getPublicKey().getEncoded())).replace("==",""));
        publicKey.append("\n-----END PUBLIC KEY-----");

        Log.d("Key==","\n"+publicKey);
        return publicKey.toString();
    }

    public static String getKid() {

        Log.d("mKid==","\n"+mKid);
        return mKid;
    }
 }

And creating JWT this way -
@RequiresApi(api = Build.VERSION_CODES.M)
private String createJWT(){

    JwtClaims claims = new JwtClaims();
    claims.setClaim("client_id",""XXXXX-YYYYYY-ZZZZZZ"");

    JsonWebSignature jws = new JsonWebSignature();

    jws.setPayload(claims.toJson());
    jws.setKey(BiometricHelper.getPrivateKey());
    jws.setKeyIdHeaderValue(BiometricHelper.getKid());
    jws.setHeader("auth_type","fingerprint");
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = null;
    try {
        jwt = jws.getCompactSerialization();

    } catch (JoseException e) {
        e.printStackTrace();
    }
    System.out.println("JWT: " + jwt);

    return jwt;
}

When i am doing this it am getting -
W/System.err: org.jose4j.lang.InvalidKeyException: The given key (algorithm=RSA) is not valid for SHA256withRSA
W/System.err:     at org.jose4j.jws.BaseSignatureAlgorithm.initForSign(BaseSignatureAlgorithm.java:97)
W/System.err:     at org.jose4j.jws.BaseSignatureAlgorithm.sign(BaseSignatureAlgorithm.java:68)
W/System.err:     at org.jose4j.jws.JsonWebSignature.sign(JsonWebSignature.java:101)

I tried many other way for signing JWT with PrivateKey so far i did not find solution.
Any help is appreciated

A: You have created a key for encryption only, not for signing. Change
mKeyPairGenerator.initialize(
        new KeyGenParameterSpec.Builder(
                    KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
                    .build());

With
mKeyPairGenerator.initialize(
      new KeyGenParameterSpec.Builder(
                  KEY_NAME,
                  KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                  .setDigests(KeyProperties.DIGEST_SHA256)
                  .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
                  .build());

A: Using gradle dependency
compile group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '4.41.1'

library I am able to fix the issue and sign JWT using AndroidKeyStoreRSAPrivateKey
Here RSASSASigner constructor which takes PrivateKey from Android KeyStore and this signer is used to sign JWSObject.
While looking for solution I did not find much information on this on Web so posting solution here for how to Sign JWT using PrivateKey from android Fingerprint API. Thanks pedrofb for you help :)
@RequiresApi(api = Build.VERSION_CODES.M)
private String createJWT(){
    RSASSASigner signer = new RSASSASigner(BiometricHelper.getPrivateKey());
    JSONObject message = new JSONObject();
    message.put("client_id",mConfiguration.getClientID());

    JWSObject jwsObject = new JWSObject(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(BiometricHelper.getKid())
           .customParam("auth_type","touchid").build(),new Payload(message ));
    try {
        jwsObject.sign(signer);
    } catch (JOSEException e) {
        e.printStackTrace();
    }

    String jwt = jwsObject.serialize();

    Log.d("JWT============","\n"+jwt);

    return jwt;
}

While working on this thing i came across some bug reported in  Nimbus-JOSE-JWT older version https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/169/android-m-support

A: For anyone reading finding this question and the answers, it's worth mentioning that this key is NOT finger print protected - (setUserAuthenticationRequired(true) is not set on the key, and BiometricPrompt is not being used to approve the signing operation.
To do this correctly with jose4j you need to use it's jws.prepareSigningPrimitive() method - https://bitbucket.org/b_c/jose4j/issues/176/signing-not-possible-with-an has a discussion and a link to a full example.


text:
Q: Python raw input with arrows How can I allow the arrows in raw_input()?
There is a better way?
When I write and I use the left arrow, ^[[D appears.
I am using Linux.

A: If you are Windows, the cursor keys work normally to allow editing of your input. On Linux, I find that I need to import readline to get the input editing module.
If you Google for "python readline" you will get many more hits and suggestions on enhanced editing, tab completion, etc.

A: Have you tried?
myinput = raw_input("Enter your input ->")
I am using windows , it works fine. Don't have a linux to simulate.
Also, why are you pressing arrow keys? Is it a need for program?
You can simply make arrow using a dash and greater than keys.


text:
Q: Property description panel missing from WPF project property window in Visual Studio For some reason I do not see the property description panel in my WPF project in Visual Studios.
Here is a screenshot take from the internet with the panel

Here is what is showing up on my machine

As you can see the description for my properties do not show up. This was a very useful feature when I was working with Windows Forms and I would love if it worked with WPF.
I'm using Visual Studios 2010 professional edition.

A: Just mouse over the property and it'll tool-tip the description.
Or see How do I show the description box of the properties window in Visual Studio 2010 if it is hidden? (now this is for Win Forms, not WPF - but could be the same solution for you)


text:
Q: iPhone UILabel Hidden weirdness between OS 3.0 and 4.0 When I initially load my view there is a spinner and "Loading..." label displayed. However, after my data is loaded, the spinner and label appear on screen for a good 2 seconds. I did some debugging and my method is getting called and completes before these elements hide. It's like there's a lag.
The method:
- (void)isLoadingData:(BOOL)flag {
    NSLog(@"here %d", flag);
    if (flag) {
        [spinner startAnimating];
    }
    else {
        [spinner stopAnimating];
    }
    [loadingData setHidden:!flag];
    NSLog(@"done");
}

The ivars:
IBOutlet UILabel *loadingData;
IBOutlet UIActivityIndicatorView *spinner;

I haven't changed anything with this code other than updating the app from 3.0 SDK to 4.1 SDK. The odd thing is on my test device, with 3.1.3, I don't have a problem. But 4.0+ Simulator and device have the lag.
Seems SDK related, but I don't want to jump the gun. Any help would be appreciated.


text:
Q: Powershell Script to sort files and put them into individual folders of different names New to PowerShell so here goes... I have a bunch of xml files that have a sequential set of digits at the end as below.
HSUS_IMP_EN_NOM_I_00138001004.xml
HSUS_IMP_EN_NOM_I_00138002004.xml
HSUS_IMP_EN_NOM_I_00138003004.xml
HSUS_IMP_EN_NOM_I_00138004004.xml
.....
I would like to sort these files and place each one of them into its own folder like 1, 2, 3... So the above files would be put into there own folder based on sequence, example:
HSUS_IMP_EN_NOM_I_00138001004.xml goes to folder 1
HSUS_IMP_EN_NOM_I_00138002004.xml goes to folder 2 and so on.
I just cant seem to figure it out. My script just puts them into a folder of the same name which is incorrect.
$Files = Get-ChildItem -Path 'C:\TEMP'
$Files | ForEach-Object {

$FileFullName = $_.FullName
$foldername = $_.BaseName
$destinationFolder = "C:\TEMP\$foldername\"
New-Item -Path C:\TEMP\$foldername -ItemType Directory
Move-Item $FileFullName $destinationFolder
}

Can anyone help with this dilemma

A: If the filenames are consistent then you can select a substring from the file name and use that to create the folder. In the example below, I've selected the 25th character in the filename but you can adjust this to whatever you need.
$Files = Get-ChildItem -Path 'C:\TEMP'
$Files | ForEach-Object {

$foldername = $_.Name.Substring(25,1)
$destinationFolder = "C:\TEMP\$foldername\"
New-Item -Path C:\TEMP\$foldername -ItemType Directory
Move-Item $_.FullName $destinationFolder
}

Edit: You will probably want to add the -File or -filter *.xml flag in the following line to avoid putting all your folders inside folders if you run the script twice.
$Files = Get-ChildItem -Path 'C:\TEMP'


text:
Q: Pass multiple mock objects to a method I have a method CreateAccount to test. I am using Moq for the same.
Under CreateAccount method, there are multiple table insertion methods which belongs to two classes AccountRepository and BillingRepository
I have setup the Moq but don't know how to use multiple moq objects.
Below is some code snippet
Mock<AccountRepository> moq = new Mock<AccountRepository>();
Mock<BillingRepository> moqBill = new Mock<BillingRepository>();
moq.Setup(x => x.AddTable_1(new AddTable_1 { }));
moq.Setup(x => x.AddTable_2(new AddTable_2 { }));
moqBill.Setup(x => x.Table_3());

CreateAccount method takes four parameters and its under ApplicationService class
public class ApplicationService
{
public CreateAccountServiceResponse CreateAccount(AuthenticateApp App, CustomerInfo Customer, ServiceInfo Service, Optional op)
    {
       // SOME VALIDATION CODE
       //.....................

       // SOME CODE TO SAVE DATA INTO TABLES
       obj_1.AddTable_1(objdata_1);
       obj_1.AddTable_2(objdata_2);
       obj_2.AddTable_3(objdata_3);
    }
}

Please suggest some solution. How can these three methods will be skipped ?
Thanks in advance.

A: You have to provide some means to inject obj_1 and obj_2, since they seem to represent your instances of AccountRepository and BillingRepository, resp.
Typically, you might want to do this by using constructor injection. Extending the snippet you provided, this might look like this:
public class ApplicationService
{
    private readonly AccountRepository _accountRepository;
    private readonly BillingRepository _billingRepository;

    public ApplicationService(AccountRepository accountRepository, BillingRepository billingRepository)
    {
        _accountRepository = accountRepository;
        _billingRepository = billingRepository;
    }

    public CreateAccountServiceResponse CreateAccount(AuthenticateApp App, CustomerInfo Customer, ServiceInfo Service, Optional op)
    {
       // SOME VALIDATION CODE
       //.....................

       // SOME CODE TO SAVE DATA INTO TABLES
       _accountRepository.AddTable_1(objdata_1);
       _accountRepository.AddTable_2(objdata_2);
       _billingRepository.AddTable_3(objdata_3);
    }
}

Now you can inject your mocks into the class under test:
public void CreateAccount_WhenCalledLikeThis_DoesSomeCoolStuff()
{
     var accountRepoMock = new Mock<AccountRepository>();
     // set it up
     var billingRepository = new Mock<BillingRepository>();
     // set it up
     var appService = new ApplicationService(accountRepoMock.Object, billingRepoMock.Objcet);

     // More setup

     // Act
     var response = appService.CreateAccount(...);

     // Assert on response and/or verify mocks
}


text:
Q: iOS in-app purchase free / paid persistence I am building a game that will be free to play, and will include 100 free consumable 'hints'.  I intend to offer more hints for purchase through in-app purchase.  My current method is to store a file locally with the number of hints the user still has left.  When the game is first downloaded the local file doesn't exist, so a new file is created with 100 hints.  When an in-app purchase happens, it simply adds to the number of hints. (In the game, each hint simply removes a choice from a multiple choice question - the file simply stores a counter.)
My problem: A user could simply delete the app when they have 0 hints remaining (which will delete my local file that has a count of 0), re-download the app from the app store and they will then start again with 100 hints.
My question: How do I prevent this?  Is there a different method I should use for storing hints?

A: use the Keychain to store your data, because the Keychain items are not deleted even if the app is Uninstalled or removed. This Api will help a lot link, have a look
or
You can refer to Apple's documentation on Keychain data

A: If you are going to offer some part of your hints as an in-app product, I suggest you to keep track of all your hints (both purchased and free) on a server. This way you can keep track of each user and even if they delete and re-download your app, you will still be able to keep track of your hints.
Edit: If you are implementing IAP you might find it healthy to keep track of your purchased goods anyway (ie. keeping track of your purchase statistics, watching out for fake in-app purchases, etc.)

A: usualy you use a server for such things, so not the device but the account is the interesting. Also a good possibility to save your progress and share to other devices ;)


text:
Q: Adding Bind to a prototyped object in vanilla Javascript in a for loop I have a Javascript class with a prototyped method that is using a for loop to add an event listener to a group of objects and calling another method in the class.
In order to be able to access the other method in the class I have to bind the function in the event listener that gives me access to the other class method.  However I always get the highest value in the for loop so I return a function in an anonymous function, but now I can't get the bind function to work and find the other class method.
    ToDoList.prototype = {
      addListener : function(){
        //inside for loop
        for(var i = 0; i < ToDoList.counter; i++){
          el.addEventListener("click", ((function(value){
            return function(){
              this.remove(value); //trying to call this method
            };
            })(i)).bind(this)
          );
        }

      }

      remove : function(index){
        //do some stuff if you can get to me
      }
    }

The code above only works on the last value of the for loop.  Is there any way that I can get the code to work on all the values in the for loop.

A: The bind function returns a new function with this set to the first argument of bind, and all subsequent arguments are passed as parameters.
You don't need a closure if using bind:
ToDoList.prototype = {
  addListener: function() {
    for (var i = 0; i < ToDoList.counter; i++) {
      el.addEventListener("click", function(value) {
        // `this` is the same as outer `this`
        // `value` is `i`
        this.remove(value);
      }.bind(this, i));
    }
  },
  remove: function(index) {
  }
}

A: With ES2015 features:
ToDoList.prototype = {
  addListener() {
    for (let i = 0; i < ToDoList.counter; i++) {
      el.addEventListener("click", () => this.remove(i));
    }
  }
}

Neat huh?
The let will make it so that each iteration of the loop has its own i, rather than a shared one for the entire function. That solves the problem of i being equal to ToDoList.counter.
The arrow function => is automatically bound, so you don't need to worry about this, it'll automatically be bound to the external this correctly.


text:
Q: Get javascript array object from its name In javascript I have an array of strings in which each string is name of another array.
How can I get each array object from its name?
In my example I need to get cavaSel array from its name which is contained in array CaveTipo
for (var i = 0; i < CaveTipo.length; i++) {
    var cavaSel = $(CaveTipo[i]);
    for (var t = 0; t < cavaSel.length; t++) {
        ///
    }
}

A: By 'name' I'll assume you mean 'identifier'.
For example: say you have 'identifier' CaveTipo to reference the following example array:
var CaveTipo=[ 'my_array_a'
             , 'my_array_b'
             , 'my_array_c'
             ]
; //end var

Above example array, contains strings which are the identifiers of other array's, for example:
var my_array_a=[ /* data */ ]
,   my_array_b=[ /* data */ ]
,   my_array_c=[ /* data */ ]
; //end var

Now in order to use the identifier (strings) in CaveTipo one should use bracket-notation on the object that holds the target-arrays: namespace[/*identifier*/] (instead of dot-notation).
If that namespace was global, then you'd use window (or self): window[/*identifier*/].
var cavaSel, i, t;
for (i = 0; i < CaveTipo.length; i++) {
    cavaSel = window[ CaveTipo[i] ];
    for (t = 0; t < cavaSel.length; t++) {
        ///
    }
}

Now let's assume the array's are inside an object you created (in global):
var caveData={ my_array_a: [ /* data */ ]
             , my_array_b: [ /* data */ ]
             , my_array_c: [ /* data */ ]
             }
;

var cavaSel, i, t;
for (i = 0; i < CaveTipo.length; i++) {
    cavaSel = caveData[ CaveTipo[i] ];
    for (t = 0; t < cavaSel.length; t++) {
        ///
    }
}

This last approach is better in most cases since it either frees up namespace usage in global (for my_array_X) OR provides an identifier to the object within 'private' closures.


text:
Q: Assignment in python class argument I don't have much experience with python and probably this is duplicated question.. sorry for that
Let assume I have the following code:
class myclassI:
    def __init__(self, key=None, data=None):
        self.key = key
        self.data= data

class myclassII:
    def addInfo(self, key, data)
        NewInfo = myclassI(key=key, data=data)

I see this type of call and I was wondering what do we mean by performing "key=key" when we are calling "myclassI"?
Many thanks for any suggestions!


text:
Q: In Python, identify parts of an e-mail address Given a list of e-mail addresses:
list = ('First Last <first@example.com>' , 'name@example.org')

some of which contain first and last name, others which just contain an e-mail address, how can I loop through the list and extract a first and last name (if they exist), and the email address?
Thanks.

A: import email.utils
map(email.utils.parseaddr, email_list)


text:
Q: How to change card_view:cardCornerRadius programmatically In my project, I am using RecyclerView in my listing using CardView. In my listing I have to set the corner radius  of CardView dynamically based on device.
Is there any way to set cardview corner radius value dynamically?
Thanks.

A: Use CardView.setRadius(float), see androidx.cardview.
(It is worth noting that this will have no effect if you also invoke setBackgroundColor, make sure to use setCardBackgroundColor instead).
You must specify a pixel size, rather than dp value, e.g. for corner radius of 4dp you can invoke, in Kotlin:
radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, context.resources.displayMetrics)


text:
Q: Express OAuth Authorization for Different Access Methods I am looking to figure out best practices for the following scenario.  I am a relatively new/hobby programmer.  I am developing a chat bot that is using Dialogflow. I want users to be able to use different messaging apps to be able to access the data and information in a backed database, but that I want the users to be authenticated (I need to know who they are in order to query relevant data).  I also have a website where users can create an account and login.
I have created the website and all of the OAuth connection is working fine.  I am storing the information on account creation to keep track of users.
Where I am stuck, is that I want to be able to authenticate users on the messaging platforms to link to their accounts on my database (token/some sort of simple profile identifier).
I am looking for advice on the OAuth flow and routing.  I am using Express.  Let's use Google Account Linking as an example:
One way to create/access account:
Website -> SignUp/Login -> Send Out to Google -> Confirm Identity -> Return to Callback (within protected area of website).
Another way to access account:
DialogFlow Chat -> Send to webhook (I want to have this route protected) -> Authenticate/Recognize User -> Query Data -> Return Information to user's device.  This process requires access to the same flow as the website process.  As I have it now, my callback always refers back to the internal page within my website.  But I would imagine I do not want that if a user is trying to access information via Google Assistant.
Is it best/better practices to:

*

*Handle the different flows via route conditional statements?

*Set up different route endpoints using the same account logic (I am using passport.js) but specify different callback urls?

*Register different API credentials with different urls to handle the different methods of access?

*How do you handle callbacks coming from within a messaging app?

In my newbie self, am I over complicating this an is there a simpler and more elegant solution?  Thank you!

A: I ended up solving the problem myself.
I looked at this SO answer here (Nodejs Passport - Using Multiple Google Strategies).
For those that need/want code.
My routes are:
// GOOGLE ROUTER

  //process route to verification
    router.get('/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

  //callback after verification
    router.get('/google/callback', passport.authenticate('google', {
        successRedirect : '/profile',
        failureRedirect : '/'
    }));

// DIALOGFLOW ROUTER
   router.get('/auth', passport.authenticate('google-dialogflow', { scope : [ 'email'] }));

I added the separate name parameter in the authenticate method.
Then in a passport.js file I have two passport strategies.  One starts with:
passport.use('google',new GoogleStrategy({
   clientID        : configAuth.googleAuth.clientID,
   clientSecret    : configAuth.googleAuth.clientSecret,
   callbackURL     : configAuth.googleAuth.callbackURL,
   passReqToCallback : true
},
function(req, token, refreshToken, profile, done) {...

and the other starts with:
passport.use('google-dialogflow',new GoogleStrategy({
   clientID        : configAuth.dialogAuth.clientID,
   clientSecret    : configAuth.dialogAuth.clientSecret,
   callbackURL     : configAuth.dialogAuth.callbackURL,
   passReqToCallback : true
},
function(req, token, refreshToken, profile, done) {...

I also created a different credential in the Google API console, so that I could use different credentials (clientID, clientSecret, callbackURl) for the different means of accessing the data/site.
Again, I don't know if this is best or even good practice but it solved my problem.


text:
Q: Thevenin equivalent and RC circuit Here is the schematic:
I got a little problem in electronics: it involves simple things but I can't figure it out (and found no other circuit that was the same configuration).
At t < 0 ms, both switches are open.
The problem is the following : when t = 0 ms, the switch I is closed and the switch II is open. Then I need to make an equivalent circuit when one DC source is in series with A and B (from UAB = UTH), to find the value V0 and calculate the exponential equation for the voltage of the capacitor.
Do we remove the branch that is open to calculate UTH or do we keep it? In short, is Uth (when t = 0ms) equal to 0V or 10V?
The question is here: if we close the switch I, and if V1 is equal to 10V, the equation for the capacitor being equal to \$V_1 + (V_0 - V_1) \times e^{(-t/TAU)}\$ will be equal to 10V constant, which doesn't seem logical since we added one resistance in the circuit!
But if V1 is equal to 0V, it would not be logical since the capacitor is in series with the 10V DC...
Can you please guide me in the right direction or tell me what I did wrong?

A: For t < 0 ms, the circuit can be re-drawn as shown.

simulate this circuit – Schematic created using CircuitLab
at t = 0 ms the \$30\Omega\$ resistance comes in parallel with the old resistance. Now the circuit becomes.

simulate this circuit
You can directly write \$R_{th}\$ and \$U_{th}\$ from this circuit.
The only thing happened here is that you made the capacitor's charging fast. But it won't have any effect on voltage across C if it has reached V1 volts before t = 0 ms.


text:
Q: How to select the forst item of w2ui list field I have a w2ui form with this list field:
...
{ field: 'field_module', type: 'list', required: true,
  html: { caption: 'Program', attr: 'size="14"', span: 3 }},
...

Once I have loaded the items via ajax (that works fine) I would like to preselect the first item of that list.
How to achieve this?

A: I've found the answer.
Quite easy, even if I couldn't find out how to select the first item numerically
form.record.field_module = {id: '--ALL--', text: '--ALL--'};


text:
Q: Tools to manage upgrade of heavily modified framework I realize this question is a bit subjective and won't have a definitive answer but hopefully it's a question that can help others in the same situation.
I am running an extremely modified CMS (in this case xCart v4.1.8) and I am looking for the best tools/means to upgrade in an organized fashion.
We have added a boat load of functions, modules, new db tables, modified db tables, modules, etc.
We already use an SVN but with how heavily modified this CMS is I fear an SVN is far from enough.
I figure some sort of tool/script that will not only analyze code for differences but actually run through all of the functions, see what's passed and how it's manipulated then compare that with the other code in order to determine the differences.  If there's a way to integrate databases into the comparison that would be great too.
Any help pointing me in the right direction would be greatly appreciated.  I imagine there would be tools that manage this and would prefer to not have to reinvent the wheel if at all possible.
Thanks in advance for your help and suggestions.
Also for what it's worth the site we are upgrading consists of mainly PHP/MySQL and runs off Apache.

A: You can obviously use your source code tool for the code mods that you have done.  If I understand you correctly, it is the database scripts that are causing the greatest issue.
I would either purchase some db comparison tools (thinking Redgate here), write your own db scripts that allow you to compare an 'as is' (your current modified database) with the 'to be' database (problem with this is this is time consuming and doesnt offer any ROI!).
Performing comparisons on database is always 'fun'!  Good luck!

A: I don't believe there are any tools that would analyse and merge code difference automatically.
It's been a long time ago when I used SVN last time but it should have a diff/merge tools. Git handles merging amazingly easy, resolves conflicts automatically and forces you to remove unnecessary code by yourself.
But anyway you have to compare code line by line and modify as expected.
Good luck.


text:
Q: Are there any limitations to the iPhone simulator? Is there anything that a device can do that the simulator can't? There are obvious things like using the accelerometer in a certain way, but are there others? Such as DSP, for example? My app runs fine on the device, but crashes on the simulator and I just want to make sure that it is not due to any of the simulators possible inherent limitations.
Thanks!

A: Here's a nice list from a previous question:
iPhone device vs. iPhone simulator
And another one current to iOS 4: IPhone Application Development For Dummies

A: For example Apple Push Notification Service will not work in Simulator, as far as I can remember.

A: The Simulator is less limited than any actual device in such things as CPU performance, memory, storage, etc.  But there may be differences in Open GL and GPU performance, etc.
Your app should be checking for the existence of any hardware features before using them, and checking for nil objects and pointers as well.  So anything missing, such as an accelerometer or the camera, should not cause an app to crash.
If your app is crashing on the Simulator, that is a very strong indication that it might crash on some future iOS device or OS release.  So you should hunt the cause down.
The instruction sets are different between the device and the Simulator (ARM vs. x86, NEON vs. SSE), so there's an extremely tiny possibility that it could be a compiler or compiler optimization bug.

A: Within iOS Simulator, there are some limitations,

including:
    Apple Push Services
    Privacy alerts for access to Photos, Contacts, Calendar, and Reminders
    The UIBackgroundModes key
    iCloud document syncing and key-value storage support
Unsupported frameworks include:
External Accessory
Media Player
Message UI
Event Kit
In UIKit, the UIVideoEditorController class
Store Kit

A: Camera does not work. They could make a default mac camera simulated.


text:
Q: How to apply pipe to dictionary in python I am wondering if there is any way to apply pipe operator to the dictionary object like pandas dataframe.
With pandas dataframe we can do below steps:
import pandas as pd
dat1 = pd.DataFrame({'A' : [0], 'B' : [1]})
dat2 = pd.DataFrame({'C' : [0], 'D' : [1]})
chose = 'something'

((dat1 if chose == 'something' else dat2)
   .pipe(lambda x : x.assign(col_new = lambda z : 'some_value'))
)

Similarly now let's say we have a dictionary:
dat1 = {'A' : [0], 'B' : [1]}
dat2 = {'C' : [0], 'D' : [1]}
chose = 'something'

((dat1 if chose == 'something' else dat2)
   .pipe(lambda x : x['A'])
)

But now I get below error
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'dict' object has no attribute 'pipe'

Is there any way to apply pipe like pandas to dictionary object?

A: To emulate the "R-like" behaviour (a function from any class to any other class), you can create a thin wrapper around any value:
from dataclasses import dataclass
from typing import Generic, TypeVar, Callable

A = TypeVar("A")
B = TypeVar("B")

@dataclass(frozen=True)
class Box(Generic[A]):
    value: A

    def pipe(self, fn: Callable[[A], B]) -> "Box[B]":
        return Box(fn(self.value))

Test-drive:
if __name__ == "__main__":
    b = (
        Box({"a": 2, "b": 1})
        .pipe(lambda d: d["a"])
        .pipe(lambda a: a * 10)
        .pipe(str)
        .pipe(lambda s: f"Value={s}")
    )
    print(b, b.value, type(b))

The output:
Box(value='Value=20') Value=20 <class '__main__.Box'>

In general, it is nothing more than a classical map function from the functional programming.

A: Given your example, you can directly access the dictionary key without lambda:
dat1 = {'A' : [0], 'B' : [1]}
dat2 = {'C' : [2], 'D' : [3]}
chose = 'something'

(dat1 if chose == 'something' else dat2).get('A')

Output: [0]


text:
Q: constexpr вызов функции size() у ссылки #include <iostream>
#include <array>

template<typename array_type>
auto array_size(const array_type& arr) {
    constexpr auto size = arr.size(); // действительно ли size будет constexpr?
    return size;
}

int main() {
    constexpr std::array arr = {1, 2, 3, 4, 5};
    std::cout << array_size(arr);
}

Правда ли что в этой программе size является constexpr, ведь мы вызываем функцию-член size() у ссылки? Интересно, что программа компилируется gcc, но не компилируется clang последних версий. Кто прав?

A: Откровенно говоря, мне эта идея - в не-constexpr функции иметь constexpr-переменную - не очень нравится. Вот такой вариант мне представляется более корректным и согласованным.
template<typename array_type>
constexpr auto array_size(const array_type& arr) {
    auto size = arr.size();
    return size;
}

int main() {
    constexpr std::array arr = {1, 2, 3, 4, 5};
    constexpr auto as = array_size(arr);
    std::cout << as;
}

Так что мне кажется, что в вашем случае формально прав clang, но, как обычно, о том, насколько я неправ и как это соответствует стандарту, пусть расскажут гуру :)

A: Эта программа не должна компилироваться в соответствии со стандартом, так что clang прав. Однако в C++23 это станет возможно благодаря принятому P2280, в котором уберут указанный ниже пункт стандарта.

Чтобы объявить переменную size со спецификатором constexpr, надо инициализировать её с помощью constant expression.
[dcl.constexpr]/10:

... In any constexpr variable declaration, the full-expression of the
initialization shall be a constant expression. ...

Однако выражение arr.size() не является core constant expression.
[expr.const]/5.12:

An expression E is a core constant expression unless the evaluation of
E, following the rules of the abstract machine, would evaluate one of the following :

*

*...

*an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either

*

*...

*...

Здесь E это arr.size(), а arr является  an id-expression that refers to a variable of reference type, не имеющим preceding initialization.
Т.к. выражение не является core constant expression, то оно не является и constant expression.
[expr.const]/11:

A constant expression is either a glvalue core constant expression
that refers to an entity that is a permitted result of a constant
expression (as defined below), or a prvalue core constant expression
whose value satisfies the following constraints:

*

*...

A: Передача в функцию аргумента с constexpr классификатором теряет свою константность в процессе компиляции. И остаётся только обычная константность const.
Причина такая, что функция не сможет использовать константность компиляции так как фактический аргумент ему не известен.
Допустим вы сделали шаблонную функцию в заголовочном файле и два constexpr массива в двух файлах. Как компилятор может сделать вам код функции с constexpr size если размеры этих массивов разные?
h.hpp
template<typename array_type>
auto array_size(const array_type& arr) {

// здесь size не может быть одновременно 4 и 5
    constexpr auto size = arr.size();

    return size;
}

1.cpp
constexpr std::array arr1 = {1, 2, 3, 4, 5};
std::cout << array_size(arr1);

2.cpp
constexpr std::array arr2 = {1, 2, 3, 4};
std::cout << array_size(arr2);

Ни один компилятор ваш код у меня не смог скомпилировать.


text:
Q: can I be keylogged at pc lock-in? I was opening my pc with a password and noticed that the letters of the keystrokes did not appear in the password-field. It made me suspicious if a key-logger 'snatched' my password.
Opening the pc with a password is a spine reaction, so I went back to check how much would be needed to miss a proper lock-in .. I'm sure enough to proceed to question you here.
Would I in the first place notice, if someone used a keylogger on me? Is letters not appearing in the text-field symptomatic for the use of a key-logger against me? If yes, do I have any chance of finding the key-logger to delete it from my pc?
I've written plenty of appropriate code (opengl + glfw) to suggest, that the keylogger would have to work as a service (added with administrator-credintials?) and be turned on at pc-start to do it's job, but I don't have a clue more than that.

A:
letters of the keystrokes did not appear in the password-field

It could be a scenario; maybe the textbox was out of focus while you were trying to login. Because I beleive that keylogger won't hinder the keypress of a textbox.

A: According to my experience of getting hardware-input it would seem to be a slim case not to reveal it in a stelthy situation - you must be right.


text:
Q: run multiple time a neural network and save only the best weight i'm making a convolutional neural network using keras for images classification.
i'm making a script which will allow user to train again the model with new data.
As you know, model weight initialisation influence model performance, so I want to run automaticaly the same model (same architecture and same data) with different random value for weight initilisation and save the weight of the best model
What is a bit tricky is that i'm creating a .exe file and I can't

*

*run all model and save their weight in different .h5 files

*delet all h5 files which are useless (worst performances)

What I need is to create only one h5 file, correspoding to model with best performance
But I have no idea how i could do that
edit: about the code, even if my curent process is totaly normal, I add it for more visualisation
model = Sequential()
model.add(Conv2D(24,kernel_size=3,padding='same',activation='relu',
        input_shape=(n,n,1)))
model.add(MaxPool2D())
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(X, activation='softmax'))
model.compile(optimizer="adam", loss="categorical_crossentropy",metrics=["accuracy"])

atch_size=256
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=30) # Stop trainning si pas d'améliorationaprès n = patience
mc = ModelCheckpoint(ROOT+"\\model_weight_"+name+'_'+str(n)+".h5", monitor='val_loss', mode='min', verbose=1, save_best_only=True) #Sauvegarder meilleur modèle
train = model.fit_generator(image_gen.flow(train_X, train_label, batch_size=batch_size),epochs=400,verbose=1,validation_data=(valid_X, valid_label),class_weight=class_weights,callbacks=[es,mc],steps_per_epoch=len(train_X)/batch_size)

A: I want to speak many things here but first, this should be what you ask for.
mc = ModelCheckpoint(ROOT+"\\model_weight_"+name+"_{epoch:02d}-{val_loss:.2f}.h5", monitor='val_loss', mode='min', verbose=1, save_best_only=True)

Where val_loss is metrics name Keras prints in training process(like val_acc if you put metric=['accuracy']).
More information https://keras.io/callbacks/.
And for deleting files. I didn't check the best weights in training part mainly because the save_best_only=True, a loop still needed to check every epoch in train.history.
import os
min_val_loss = float('inf')
best_file = ''
# Find the best weights from file name
for weightsfile in os.listdir(ROOT):
    if int(weightsfile[-7:-3]) < min_val_loss:  # Since I use .2f above, I use -7:-3 here
        min_val_loss = int(weightsfile[-7:-3])
        best_file = weightsfile

# delete everything in ROOT except the best.
for weightsfile in os.listdir(ROOT):
    if weightsfile == best_file
        continue  # do nothing in this loop
    os.remove(os.path.join(ROOT, weightsfile))  # I recommend you to use `os.path.join` instead of `SOMTHING+"\\"+ANOTHER`. It might fuck you up later when you move to Linux machine(like Colab).

Now, for what I want to speak. Actually the weights initialization doesn't much matter in Deep CNN(where there're 10 or 100 layers). In fact, I trained the same network like ResNet50 with same setting several times on the same data and it usually only differ for 2% or 3% for the accuracy(around 0.69 to 0.72). And the weights that perform the best on another validation set wasn't the 0.72 one.
So, it's better to use the already fine-tuned weights of some good models like ResNet, DenseNet, NasNet or the most recent state-of-the-art EfficientNet and waste time on trying different setting like optimizer or learning rate schedule. And most importantly train on free GPU machine like Colab.


text:
Q: How can I make an updatable function-map with an updatable condp inside of it? I have two primary goals:
1.) {:foo (fn ...)} should be defined outside of the function-map in a way that allows you to update :foo's (fn ...) (perhaps a ref, but maybe? an atom)
2.) The cases for condp: "fred", "ethel" should live in a structure that can be updated as well.  For instance, if I want to add "lucy" (handle-lucy a b c d) to the condp I'd like to be able to do that by using a separate structure to hold all of the cases for the condp.  The trouble is that placing them in a map or a vector, for instance, means the variables a b message and d are not available within the context of that structure.
Summary: Help me refactor this to make :foo and :bar their own functions which live in #'function-map that can be updated while the program is running.  In addition, help me find a way to take the cases for the condp and put them into their own updatable container.
Summary 2: If you think what I'm asking for is crazy, take a whack at refactoring this however you see fit.  I'm mainly interested in generally increasing readability and accessibility.
This is a shortened version of the function-map that I am struggling to refactor
(def function-map
  {:foo (fn [{:keys [a b message d]}]
          (let [[command & args] (.split message " ")]
            (condp = command
                "fred" (handle-fred a b @d)
                "ethel" (handle-ethel a b (first args) @d)
                nil)))
   :bar (fn [{:keys [a b c]}]
          (do-something a b c))})

A: 1) Your obvious choices here are to make function-map a ref/atom containing a map OR to make the value for each key a ref/atom containing the function.  I can't judge from your description which makes more sense.  1 ref/atom is simpler but any change to the function-map will potentially create a transaction conflict for every other change.  I'm guessing this map isn't changing constantly but only occasionally, in which case 1 ref/atom would probably be sufficient.  Atoms are for uncoordinated synchronous change.  Refs are for coordinated (transactional) synchronous change.  If you need to change multiple functions together as part of a transaction or do compare-and-set type behavior, use a ref. Otherwise, use an atom.
2) For the condp part, it sounds to me like you want dynamic (polymorphic) behavior based on value.  To get that, don't use condp; use a multimethod with a dispatch function that utilizes the mutable state.  That will let you dynamically add cases (defmethods) without modifying the dispatch code.  If you want to "update" the set of commands after the fact, add a new defmethod whenever you want. If you want access to state at the time of handling, just pass it into the handler definition.
(defmulti handle-command (fn [command a b message d & args] command))
(defmethod handle-command "fred" [_ a b _ d] (handle-fred a b d))
(defmethod handle-command "ethel" [_ a b _ d [f & _]] (handle-ethel a b f d))

(def function-map
  {:foo (fn [{:keys [a b message d]}]
          (let [[command & args] (.split message " ")]
            (handle-command command a b message @d args)))})

Apologies on typos...not actually trying any of this at a repl.


text:
Q: Usage of String.format in Java What I wanted to print:
Coca-Cola      $ 11.00
Pepsi           $ 9.45
Sprite          $ 8.50

What end up printing:
Coca-Cola       $ 11
Pepsi       $ 9.45
Sprite       $ 8.5

My code:
public void test(){
    for (int i = 0; i<20; i++){
        System.out.print(product[i]);
        System.out.println(String.format("%20s%n", "$ "+price[i]));;

    }

I am looking for this for like 2 hours, perhaps I'm not that good specifying my search terms, but I'll try to avoid some more hours of searching and suffering by simply asking... Sorry for not knowing enough to properly find this on the forums or specify my title and thank you very much.

A: The problem of your code is that it first prints the product then it try to print a formatted string.
The battle is already lost when it print those things separately. Because the second print needs to know the length of the product to determine how many spaces it needs to align the prices. That number is definitely not going to be the same.
Try this instead:
System.out.printf("%-20s$ %5.2f\n", product[i], price[i]);

Output:
Coca-Cola           $ 11.00
Pepsi               $  9.45
Sprite              $  8.50

The %-20s will left justify the product name, fill required number of spaces after the product name.
To align the decimal point, we need to specify the total length of the formatted number as well. With %5.2, we ask for a total length of 5, which 11.00 fits well, you can tune up this number if price is greater than 99.
Good luck.

A: Syntax for string.format
public static String format(String format, Object... args)
Parameters
format-This is a format string.
args- This is the argument referenced by the format specifiers in the format string.If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.


text:
Q: Which control should be use I am using Telerik to make report. I want create a report has area like image below

Which control I should use?

A: You should clarify in which context you are working with Telerik Reporting. However, does not make sense to add a progress-bar in the report itself and moreover there are no controls available for such function in the Reporting controls that you can add. You could eventually work on the Report-viewer progress message but looking at your pic this does not sound that will meet what you have in mind.
Would it be much more convenient to add the progress bar on the form or page outside the Report viewer and then use any progress bar control. Eventually hide the Report-viewer until the data and are fully loaded. I have no samples for Telerik reporting/Telerik Report Viewer but here you can see a simple made on another controls suits.

A: If you're using the latest version of Telerik controls for ASP.NET Web Forms, you can use the new RadProgressBar control.
"The Telerik ASP.NET Progress Bar is a lightweight customizable control that allows you to visualize the progress of an operation such as a download, file transfer, level of completion of a form or any other measurable process."
Link: http://demos.telerik.com/aspnet-ajax/progress-bar/overview/defaultcs.aspx


text:
Q: When " flutter upgrade", I get "Permission denied" error I would like to build a web application with Flutter. I followed this instruction. https://flutter.dev/docs/get-started/web
I use Windows 10, Windows Subsystems for Linux, Debian 10.
I installed Flutter SDK in ~/development/ directory and have already set the path.
I input this.
flutter channel beta

And get this result.
Switching to flutter channel 'beta'...
git: From https://github.com/flutter/flutter
git:    5f21edf8b..b041144f8  stable         -> origin/stable
git:  * [new branch]          CareF-macrobenchmark-typo-fix -> origin/CareF-macrobenchmark-typo-fix
git:    c0d537ad3..311ad4bde  dart_development_service -> origin/dart_development_service
git:    456d80b9d..2f7a59a8d  dev            -> origin/dev
git:    5f21edf8b..b041144f8  flutter-1.17-candidate.3 -> origin/flutter-1.17-candidate.3
git:  * [new branch]          flutter-1.19-candidate.2 -> origin/flutter-1.19-candidate.2
git:  * [new branch]          flutter-1.19-candidate.3 -> origin/flutter-1.19-candidate.3
git:  * [new branch]          flutter-1.19-candidate.4 -> origin/flutter-1.19-candidate.4
git:    eacd1c8de..746749244  master         -> origin/master
git:  * [new tag]             1.17.3         -> 1.17.3
git:  * [new tag]             1.19.0-2.0.pre -> 1.19.0-2.0.pre
git:  * [new tag]             1.19.0-3.0.pre -> 1.19.0-3.0.pre
git:  * [new tag]             1.19.0-4.0.pre -> 1.19.0-4.0.pre
git: Switched to a new branch 'beta'
git: Branch 'beta' set up to track remote branch 'beta' from 'origin'.
Successfully switched to flutter channel 'beta'.
To ensure that you're on the latest build from this channel, run 'flutter
upgrade'

Next, I input this.
flutter upgrade

Then, I get this.
Downloading Dart SDK from Flutter engine ef9215ceb2884ddf520d321bcd822d1461330876...
mv: cannot move '/home/kazu/development/flutter/bin/cache/dart-sdk' to
'/home/kazu/development/flutter/bin/cache/dart-sdk.old': Permission denied

So, I read this NOTE. https://flutter.dev/docs/get-started/web#set-up
The flutter upgrade command silently fails when origin points to a personal fork.
To validate that origin points to https://github.com/flutter/flutter.git,
run the following commands in the root directory of your local copy of the
https://github.com/flutter/flutter repository:

Then, I input this.
cd ~/development/flutter/
git remote get-url origin

Then my terminal returned this.
https://github.com/flutter/flutter.git

So, I tried again.
flutter upgrade

I got the same result.
Downloading Dart SDK from Flutter engine ef9215ceb2884ddf520d321bcd822d1461330876...
mv: cannot move '/home/kazu/development/flutter/bin/cache/dart-sdk' to
'/home/kazu/development/flutter/bin/cache/dart-sdk.old': Permission denied

Next, I tried sudo
sudo flutter upgrade

Then I got this.
sudo: flutter: command not found

Could you give me any advice please?

A: For me, The problem you got is the current user not have permission in dart-sdk folder. You need to re-check the permission or dart-sdk folder.
Example
run ls -la to see the details
drwxr-xr-x  10 user-xxx  staff       320  6 Jun 10:18 dart-sdk
If not current user, using sudo chown to change owner of dart-sdk folder.
try flutter upgrade again.
Update
Solution: (ref: github.com/flutter/flutter/issues/17898)

*

*Manually rename dart-sdk to something else  resolved the problem.

*or run this command git clean -xffd git pull flutter doctor before flutter upgrade

A: When you are trying to call some flutter command and have such output:
Downloading Dart SDK from Flutter engine 40441def692f444660a11e20fac37af9050245ab...
mv: rename /Library/Flutter/bin/cache/dart-sdk
to /Library/Flutter/bin/cache/dart-sdk.old: Permission denied

it means you do not have sufficient permissions or the file belongs to another user.
What to do?
1) Go to provided directory with this to the file.
cd /Library/Flutter/bin/cache/

2) Check who is the owner
By listing all of the files:
ls -l

with output:

3) Change owner of this file to you
sudo chown -R $USER dart-sdk

provide password (needed by sudo) and click Enter
4) Check again who is the owner
file owner should be set for your current user
5) Repeat your flutter command


text:
Q: how to add all string type numbers in list in python 3 I am trying to solve one problem in which I extracted data form text file and added it in list in python
now I want to add all those string numbers in list.
miles = ['47498.85', '70659.35', '31547.41', '106170.69', '84370.07', '46772.57', '3307.2', '65022.25', '85115.3', '17306.08', '39973.38', '53738.33', '19604.96']

This list is generated, now how do I add all the elements in this list as all elements are string type numbers ?

A: This is very simple. All you need to do is iterate through the list and typecast each of the elements and add them to a variable.
sum = 0
for mile in miles:
    sum += float(mile)
print(sum)

you can convert the elements to any type you want. (int, double etc.)

A: One way:
for i in range(len(miles)):
    miles[i] = float(miles[i])

result = sum(miles)

Second :
result = sum(list(map(float,miles)))

A: Use map with sum
result = sum(map(float, miles))

print(result)

Output:
671086.44


text:
Q: How to access the manifest.json file of a Firefox extension? I am making a short research about Chrome and Firefox extensions. I can access the manifest.json file of a Chrome extension installed on my Chrome browser with this URL chrome-extension://<extension_id>/manifest.json. Is there a Firefox equivalent URL to see the manifest.json of a Firefox extension?
N.B: I have already tried moz-extension:// prefix. But it does not work.

A: There is an easier way, go to about:debugging, and press button This Firefox, and look up for your extension in Extensions tab, then just find below extension - Manifest URL and open link that will be around it.

A: The URLs used for files inside WebExtensions add-ons are in the format:
moz-extension://<extension UUID>/<pathToFileInExtension>

If you are in code within the extension, you can obtain the URL to any file in your extension with chrome.extension.getURL(). This will effectively give you the UUID for your extension.
If you are wanting to access a file through typing it into the URL bar of the Firefox Browser UI, then you will need to obtain the UUID for the extension you desire.  For WebExtensions, the mapping from extension ID to UUID is available from about:config in extensions.webextensions.uuids.  The value for that key is a JSON formatted Object with keys that are the WebExtension IDs and the value for each key is that WebExtensions' UUID.
If you are wanting to generally access files within a particular extension, you may be better off finding the extensions packed archive (usually [extensionID].xpi) which will, normally, be located in your [profileDirectory]/extensions. You will then need to unpack the archive (a normal .zip archive with the file extension changed) to access the files. Doing this may be easier than trying to crawl through the files by entering their URLs one-by-one in the URL bar.


text:
Q: Two variables with the same value in Python In neural network, I have come across a line like this one:
W_grad,b_grad = grad_fn(X_train,y_train,W,b)

I don't understand what the above means. Is it a shorthand for
W_grad = grad_fn(X_train,y_train,W,b)
b_grad = grad_fn(X_train,y_train,W,b)  ?

A: No, it's called unpacking (look it up, it's common in python)
It's shorthand for
W_grad = grad_fn(X_train,y_train,W,b)[0]
b_grad = grad_fn(X_train,y_train,W,b)[1]

It will only work if grad_fn(...) returns an iterable with two elements, otherwise it will fail.

A: No, it means grad_fn(X_train,y_train,W,b) have 2 values that distributed to W_grad and b_grad.
For the example, if I declare these variables:
a, b = 1, 2

it means a has value of 1 and b has value of 2

A: As I understand it,
W_grad,b_grad = grad_fn(X_train,y_train,W,b)

is shorthand for
W_grad = grad_fn(X_train,y_train)
b_grad = grad_fn(W,b)


text:
Q: Iterate through string I am having difficulties in Ruby for an assignment(we just started to see it). I think I am close to the answer but something is not right with how I stor emy string elements.
So the assignment is to have a method HID_Num(String) that takes a string.
To be a valid string it needs to have:  4 uppercase letters, followed by 8 digits number (e.g.: "ABCD18347692").The method should return the individual number as an integer value, or nil if no individual valid card number is found.
Ex: HID_num ("ADBC12345678 abcD12345678") should return 12345678
my code so far:
def HID_num(str)
  str.gsub(/\s+/m, ' ').strip.split(" ")
  str.each { |element|
    if(element.count == 12)
      count = str.count("A-Z")
      if(count == 4)
        count2 = str.count("1-9")
        if(count == 8)
          puts str[3...11]
        else{
            puts "nil"
        }   }
    end end

What'S wrong with it: does not store the element of str.gsub.
I was thinking to used pointers but not sure how to used them OR to store each element in an array but I have no idea how... Maybe I am thinking too much like Java coding?
Thanks!

A: This is pretty easy to do with regular expressions.  Here's an example:
def hid_num(str)
  exp   = /\A[a-z]{4}(\d{8})\z/i
  match = str.match(exp)
  match && match[1]&.to_i
end

In this case, the expression exp matches strings beginning with 4 alphabet characters, followed by 8 digits, to the end of the string.  Next, we grab a match on the exp against the provided str.  If there is not a match, return nil; otherwise, return the digit portion of the string, cast to an integer value.
Hope that helps!

A: You could use:
def HID_num(string)
  entries = string.split(" ")
  entries.map do |entry|
    matches = entry.match(/\A[A-Z]{4}(\d{8})\z/)
    next unless matches
    matches[1]
  end.compact
end

It's a fairly simple regex matcher - this will return an array of all the valid strings' numbers. If you want to tweak it to return just the first valid number, you can change map for each and add break ahead of the line matches[1], and finally remove the compact.
Hope that helps!


text:
Q: Apache Camel XPath with nodelist I would like to concatenate all values from the Apache Camel XPath result and add it to the message context. The header should look like: "|value1|value2|valueN|"
My route looks like:
from("direct:test")
.setHeader("key").xpath("//Identifier", List.class)
.to("mock:result")

What is the best way for doing that? Is there a way to implement an own result type?

A: As Willem said, you have to write your own processor.
For such a little thing, my favourite way is to declare a function in the class containing the route definition returning an anonymous Processor like this:
private Processor setHeaderWithIdentifiers() {
    return exchange -> {
        List<String> identifiers = new ArrayList<>();
        NodeList nodes = XPathBuilder.xpath("//Identifier").evaluate(exchange,  NodeList.class);

        for (int i = 0; i < nodes.getLength(); i++) {
            identifiers.add(nodes.item(i).getNodeValue());
        }

        // StringUtils from Apache Commons 3
        String idAsString = StringUtils.join(identifiers, "|");
        exchange.getIn().setHeader("key", idAsString);
    };
}

With that, you do not need to find any complex XPath functions and the code remains clear to understand as long the Processor code remains short.


text:
Q: How to work localhost correctly? (Magento 2) Edited:
My problem is:
Sometimes I need to run:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
find ./var -type d -exec chmod 777 {} \;
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc;
chmod 644 ./app/etc/*.xml;
chmod 777 -R var/*;

because sometimes I have problems with permissions on my localhost, I am using developer mode, and I would like to know if there is any permanent way to resolve this

A: Based on your command you are place your project in wrong location.
Change:
sudo chown myuser:www-data /var/www/magento -R

Into:
sudo chown myuser:www-data /var/www/html/magento -R

Or Else you do like this also:
sudo chown www-data:www-data -R /var/www/html/magento

I hope this will help you some extend.
Thanks!
Note: for better practice follow this document: http://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html

A: My problem is:
Sometimes I need to run:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
find ./var -type d -exec chmod 777 {} \;
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
chmod 777 ./app/etc;
chmod 644 ./app/etc/*.xml;
chmod 777 -R var/*;

becouse sometimes I have problems with permissions with my localhost, I am using develp mode, and I would like to know if there is any permanent way to resolve this