text:
Q: Group nested lists of tuples by two repeating elements I have a nested list of tuples:
[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)],
[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
[(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)],
[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
[(1237.45, -697.53), ([1237.17, -697.82), (1237.19, -697.34)]]

How to group them by two repeating tuples in the lower list:
[[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]],
[[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
[(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]],
[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
[(1237.45, -697.53), ([1237.17, -697.82), (1237.19, -697.34)]]

i.e. It's like grouping triangles having the common edge.
I tried solution from this question, but it returns me wrong result:
    [[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]]
    [[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)], [(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]]
    [[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)], [(1237.45, -697.53), (1237.17, -697.82), (1237.19, -697.34)]]
    [[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)]]

It correctly groups lists in the middle, but lists on the edge are not grouped.

A: Use itertools.groupby to group the items  and a function to check the repeating elements which can be used in groupby as key with functools.cmp_to_key same as mentioned in answers of question you shared.
from itertools import groupby as gby
import functools
def check_common(a, b):
    return 0 if any(key in a for key in b) else -1

Result:
>>> key_common = functools.cmp_to_key(check_common)
>>> groups = [list(group) for key, group in gby(input_list, key=key_common)]
>>> groups
>>> [[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
      [(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]],
     [[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
      [(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]],
     [[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
      [(1237.45, -697.53), (1237.17, -697.82), (1237.19, -697.34)]]
    ]


text:
Q: Changes in the ng-model value doesn't get propagated to element value in angular js Below is the issue that I was facing and while going through the code I realized that the ng-model get's updated but the element for the same input field doesn't.
what is the reason and solution for the same.
below are the details of the issue faced due to this.
Currently I have an input field where the user enters a phone number. I'm formatting the number and updating the scope simultaneously.The formatting starts when the user enters 7 digits. The model value gets updated, however the cursor remains at the same point where it was before formatting (the 7th pos. in this case).
Below is the function I am calling on ng-change:
 $scope.FormatNumber =function(){
        var userID=$scope.phoneNumber.replace(/[^\w\@\.]/g, '');
        userID=  userID.replace(/\s/g,'');
        $log.info(userID);
        if(isNaN(userID)){
            $scope.phoneNumber=userID;
            return;
        }
        else if(userID.length < 7 || userID.length>10){
            $scope.phoneNumber=userID;
        }
        else if((userID.length > 6 && userID.length<11))  {
            ascii=[];
            //alert("length :"+$scope.phoneNumber.length);
            for (var i = 0, len = userID.length; i < len; i += 1) {
               if(ascii.length == 0){
                    ascii[0]="(";
                }
                else if(ascii.length ==4){
                    ascii[4]=")";
                    ascii[5]=" ";
                }
                else if(ascii.length ==9){
                    ascii[9]="-";
                }
                    ascii.push(+userID.charAt(i));

                var formattedNumber=ascii.join().replace(/[,]/g, '');
                $scope.phoneNumber=formattedNumber ;

            }}

    };

This issue is only occurring in Chrome; it's working fine in Mozilla.
Moreover it's only there when formatting takes place for the first time.
Even if you enter the next value at the wrong place, the cursor gets updated to end of text.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Continuity of an operator in a Hilbert space Working in the $\textit{Hilbert space}$ of sequences
$$
X=\ell^2=\Big\{\{x_n\}_{n\in\mathbb{N}}:\sum_{n=1}^{\infty}|x_n|^2<\infty, x_n\in\mathbb{R}\quad\forall n\in\mathbb{N}\Big\},
$$ with the dot product $\langle x,y\rangle =\sum_{n=1}^{\infty}x_n y_n$, I have to prove that the operator $$T:\overline{B_X}(0,1)\to\overline{B_X}(0,1)$$ defined as $$T(x)=(\sqrt{1-||x||^2},x_1,x_2,x_3,...), \quad x=(x_1,x_2,x_3,...)$$
is continuous. Since it is non-linear I have tried to prove it with the classic definition of $\epsilon$ and $\delta$. I got this:
$$||T(x)-T(y)||=\sqrt{2-||x||^2-||y||^2-2\sqrt{1-||x||^2-||y||^2+||x||^2||y||^2}+\sum_{n=1}^{\infty}|x_n-y_n|^2}.$$
Any hint?

A: Let $\gamma:\mathbb R\to\mathbb R$ be the function $\gamma(t)=\sqrt{1-t^2}$. You have
$$
\|Tx-Ty\|^2=|\gamma(\|x\|)-\gamma(\|y\|)|^2+\|x-y\|^2.
$$
Fix $\varepsilon>0$. As $\gamma$ is uniformly continuous on $[0,1]$, there exists $\delta'>0$ such that $|\gamma(t)-\gamma(s)|<{\varepsilon/{\sqrt2}}$ if $|t-s|<\delta'$. Put $\delta=\min\{\delta',{\varepsilon}\}$. Then, if $\|x-y\|<\delta$,
$$
|\,\|x\|-\|y\|\,|\leq\|x-y\|<\delta\leq\delta',
$$
and so
$$
\|Tx-Ty\|^2=|\gamma(\|x\|)-\gamma(\|y\|)|^2+\|x-y\|^2\leq\frac{\varepsilon^2}2+\frac{\varepsilon^2}2=\varepsilon^2.
$$

A: $f(x)=\|x\|$ is continuous. Therefore $g(x)=(\sqrt {1-\|x\|^2},0,0,0,...)$ is continuous on $\overline {B_X}(0,1)$. Now $h(x)=(0,x_1,x_2,x_3,...)$ is also continuous. Therefore $T(x)=g(x)+h(x)$ is continuous on $\overline {B_X}(0,1)$.


text:
Q: MariaDB docker images build failed I try to build MariaDB docker image which contains database, table and simple values. But it failed and furthermore, I can't find any log. This is my Dockerfile:
FROM centos:centos7

RUN yum install -y mariadb-server mariadb
RUN mysql_install_db --user=mysql --ldata=/var/lib/mysql/
ADD my.cnf /etc/
RUN sed -i '/[mysqld]/aport=3306' /etc/my.cnf

RUN \
 echo "/usr/bin/mysqld_safe --basedir=/usr &" > /tmp/config && \
 echo "cat /var/log/mariadb/mariadb.log" >> /tmp/config && \
 echo "mysqladmin -u mysql password 11111" >> /tmp/config && \
 echo "mysql -u mysql -p -h localhost test" >> /tmp/config && \
 bash /tmp/config && \
 rm -f /tmp/config

RUN \
 echo "use test" > /tmp/config1 && \
 echo "mysql -e 'GRANT ALL PRIVILEGES ON . TO mysql@localhost IDENTIFIED BY 1111' " >> /tmp/config1 && \
 echo "FLUSH PRIVILEGES;" >> /tmp/config1 && \
 bash /tmp/config1 && \
 rm -f /tmp/config1

VOLUME ["/var/lib/mysql"]
WORKDIR /data
EXPOSE 3306
CMD ["/usr/bin/mysqld_safe"]

But docker throws the exception
Step 0 : FROM centos:centos7
 ---> bb3d629a7cbc
Step 1 : RUN yum install -y mariadb-server mariadb
 ---> Using cache
 ---> ca601a1b4536
Step 2 : RUN mysql_install_db --user=mysql --ldata=/var/lib/mysql/
 ---> Using cache
 ---> f2ad799ac3ae
Step 3 : ADD my.cnf /etc/
 ---> Using cache
 ---> 44849c37620d
Step 4 : RUN sed -i '/[mysqld]/aport=3306' /etc/my.cnf
 ---> Using cache
 ---> e787b9d14542
Step 5 : RUN echo "/usr/bin/mysqld_safe --basedir=/usr &" > /tmp/config && echo "cat /var/log/mariadb/mariadb.log" >> /tmp/config && echo "mysqladmin -u mysql password hsj7749" >> /tmp/config && echo "mysql -u mysql -p -h localhost **test" >> /tmp/config && bash /tmp/config && rm -f /tmp/config
 ---> Running in 9ecbc5d0fe53
 mysqladmin: connect to server at 'localhost' failed
> error: 'Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)'**
> Check that mysqld is running and that the socket: '/var/lib/mysql/mysql.sock' exists!
> Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
The command '/bin/sh -c echo "/usr/bin/mysqld_safe --basedir=/usr &" > /tmp/config && echo "cat /var/log/mariadb/mariadb.log" >> /tmp/config && echo "mysqladmin -u mysql password hsj7749" >> /tmp/config && echo "mysql -u mysql -p -h localhost test" >> /tmp/config && bash /tmp/config && rm -f /tmp/config' returned a non-zero code: 1

How can I fix this?


text:
Q: Create multiple students and check if any are repeated java In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
    public class Registrar
    {

    public static void main(String[] args)
    {

  Scanner input = new Scanner(System.in);

  String string1 = " ";

  while(string1 != "1")
  {

     System.out.println("Please input full name name of student: ");
     string1 = input.next(); // user input of name
     if (string1 != "0"){
        break;
     }
     System.out.println("Please input Student ID (if done enter 0): ");
     String string2 = input.next(); // user input of ID
     System.out.println("Please input Students Credits: ");
     int inputCredits = input.nextInt(); // User input of Credits
     System.out.println("Please input Student's Total Grade Points Earned: ");
     double getPoints = input.nextDouble();
     double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA

     Student first = new Student(string1, string2, inputCredits, GPA);

     System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints()  );

     }

  }
}

This is my Student Class
public class Student {
   private String name;
   private String idnum;
   private int credits;
   private double gradePoints;

   public Student(String n, String id, int c, double gp){
      name = n;
      idnum = id;
      credits = c;
      gradePoints = gp;
      }

   public String getName(){
      return name;
      }
   public String getId(){
      return idnum;
      }
   public int getCredits(){
      return credits;
      }
   public double getGradePoints(){
      return gradePoints;
      }
}

A: You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
 //Code for take details of user
 }
//Then you can print the details of student in similar way.

A: Try this code. better implementation with collection.
      Scanner input = new Scanner(System.in);
      String string1 = " ";
      System.out.println("Number of students to be entered");
      int s = input.nextInt();
      List<Student> studentList = new ArrayList<Student>();

      for(int i = 0; i<s; i++) {
             System.out.println("Please input full name of student: ");
             string1 = input.next(); // user input of name
             System.out.println("Please input Student ID (if done enter 0): ");
             String string2 = input.next(); // user input of ID
             System.out.println("Please input Students Credits: ");
             int inputCredits = input.nextInt(); // User input of Credits
             System.out.println("Please input Student's Total Grade Points Earned: ");
             double getPoints = input.nextDouble();
             double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA

             Student student = new Student(string1, string2, inputCredits, GPA);
             System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints()  );
             studentList.add(student);
       }


text:
Q: Are separate SSH public keys required for remote terminal and git pushing? I'm remotely logging into my Raspberry Pi via SSH. I'm starting to use it for web development testing and would like to push to git repositories from the Raspberry Pi. Do I reuse the public key or do I need to make a new pair of keys? Do I need to use ssh-agent to manage the keys?
The public key used for SSH login is written in ~/.ssh/authorized_keys
I already tried making new key pairs with ssh-keygen and adding the new public key as a Bitbucket Deployment key.
Thanks!

A: A pair of key is supposed to represent an identity, i.e. your own machine. Unless you have different machines with different levels of trust (for example, a work machine and a personal machine), you don't need to generate different pair of keys on the same machine for different services.
Concerning key pairs, note that they are pairs, i.e. two keys (a public and a private one). id_rsa is the usual name of your private key on that machine. authorized_keys is the usual name of a list of public keys, for other machines, authorized to log in on that machine. The name of your public key is most certainly id_rsa.pub. That's why copying your authorized_keys to id_rsa elsewhere doesn't make much sense.


text:
Q: PHP OOP: Creating database class I am making my first steps in the OOP world - please bear with me.
I know that having many ongoing mySQL connections open at the same time can be fatal for performance, so it should be a good idea to make a database class that takes this into account.
Is $this->session->write(...); going to result in a new mySQL connection being opened each time?
Or is that up to the "persistent connection" feature in mySQL?
Here's the code:
abstract class database {
    function __construct() {
       //mysql_connect()
    }
}

class session extends database {
    function write () {
       // mysql_query(--.)
    }
}

A: mysql_query will create a new connection only if no previous mysql connection has been made. Otherwise, it will either use the connection you specify or the last connection opened with mysql_connect. http://php.net/manual/en/function.mysql-query.php

A: Is session handler some kind of specialized type of database? It is not, so don't use inheritance (a is a relationship). Session handler uses database so you should use composition (a has a relationship):
class Session {
    protected $db;

    public function __construct(DB $db) {
        $this->db = $db;
    }

    public function write() {
        $this->db->query(...);
    }
}

$db = new DB(...);
$session = new Session($db);

Also, don't use mysql_*() functions. Use much more powerful PDO.

Returning to your question... mysql_connect() will be executed every time you create a new Database object. However in this case Session is an object of type Database so every time you write new Database() or new Session() the constructor is invoked, therefore mysql_connect() is invoked as well.
PS. mysql_connect() function won't create a new connection if specified connection already exists. Check 4th argument of this function to learn more.

A: Why not
class database {
    function __construct() {
       //mysql_connect()
    }
    function write() {
       //query the DB
    }
}

I'm not sure of the syntax, I don't do OOP PHP.  Anyway, in your structure above a new connection would be opened for each "session" instance so assuming you only create one instance of "session" you won't be openeing loads of database connections.


text:
Q: Reset all graphs in tensorflow Is there a way to reset all tensorflow graphs?
I am running a hyperparamter search for a convolutional neural network in tensorflow. For each set of hyperparameters I want to build and train the graph similar to how they do it in this mnist tensorboard tutorilal.
The issue is that the tf.reset_default_graph() is not sufficient since I have more than one graph.


text:
Q: Programmatically submitting web-to-case form with preventDefault() Does anyone know if there's a way to programmatically submit a web to case form while also preventing the page redirect?  I've embedded a web to case form in the html of a LWC.  This LWC is added to a screen element of a flow.  I'm using the renderedCallback() method within in the js file to auto-submit the form after the screen renders, but I'm having trouble with the page redirect after the submit event.  Ideally, after the form is auto-submitted the flow finishes (this is the last element within the flow) and the user remains on the record they were viewing.  However, currently the form is submitting, the flow is finishing, and then the entire page reloads and redirects the user back to our homepage.
Here's one of my attempts where I'm querying the form tag and then submitting it.  I'm unable to use e.preventDefault() within this submit() event because while it does submit the form, the event instance is never actually triggered:
import { LightningElement } from "lwc";

export default class App extends LightningElement {
  renderedCallback() {

  const form = this.template.querySelector('form').submit(function (e) {
    e.preventDefault()
  })
}
}

Here's another attempt where I've created/dispatched a custom event.  Again no luck with preventing the page redirect on submit():
import { LightningElement } from "lwc";

export default class App extends LightningElement {
  renderedCallback() {

  const form = this.template.querySelector('form');

  form.addEventListener('submit', function (e) {
    form.submit(function(evt) {
      evt.preventDefault()
    })
  })

  form.dispatchEvent(new CustomEvent('submit', {cancelable: true}));
  }
}

Does anyone know of anything else I could try?  Or is there an alternative way to disable the redirect after submit()?  I've seen some potential jQuery options but I'm trying to stick with vanilla js.  Thanks.

A: You can override the submit action and then preventDefault from there : https://developer.salesforce.com/docs/component-library/bundle/lightning-record-edit-form/documentation, check this topic Overriding Default Behaviors


text:
Q: Serviços WCF com quantidade de métodos (endpoints) diferentes Peguei um projeto que usa WCF e não estou conseguindo desvendar esse mistério.
Tenho duas solutions: Projeto A e Projeto B. Quando ele tenta instanciar o OAuthServiceClient dentro do Projeto B, ele gera o seguinte erro:

Could not find default endpoint element that references contract 'SSOWebService.IOAuthService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

Código do Ambiente.ServiceModelClients.config
<client>
  <endpoint address="http://sso.fundacao.interno/SSO/WebServices/OAuthService.svc"
            binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IOAuthService"
            contract="OAuthService.IOAuthService" name="BasicHttpBinding_IOAuthService" />
</client>

Isso acontece, acredito eu, por diferença de quantidade de métodos do WCF do Projeto B (30 endpoints) e Projeto A (15 endpoints).
P.S. Ao analisar novamente o código percebo que há dentro do arquivo Reference.cs 5 construtores que não estão definidos dentro da interface
public interface IOAuthService {

    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IOAuthService/IsValidToken", ReplyAction="http://tempuri.org/IOAuthService/IsValidTokenResponse")]
    LoginResult IsValidToken(string token, string appClientID);

    // mais 29 outros métodos
        ....
    }

e ai na implementação existem 5 construtores, que consigo definir de onde estão sendo herdados
public partial class OAuthServiceClient : System.ServiceModel.ClientBase<IOAuthService>, IOAuthService {

public OAuthServiceClient() {

}

public OAuthServiceClient(string endpointConfigurationName) :
        base(endpointConfigurationName) {
}

//... outros construtores

public LoginResult IsValidToken(string token, string appClientID) {
        return base.Channel.IsValidToken(token, appClientID);
}

//outros 29 métodos
....

A:
Olá Acabei resolvendo o problema, simplesmente apagando e adicionando novamente as referências do serviço.


text:
Q: How to execute failed test cases using Maven TestNG We are using Maven for script execution. For reporting we have used TestNG.
In case test failed for first time we want to re execute those failed tests again.
Is there any option available?

A: Implement IRetryAnalyzer interface to rerun failed test cases with a count to re execute. Add @Test(retryAnalyzer=<classname>) to test case.


text:
Q: How to soap api authenticate with certification using Spyne in Python I am new to the soap api with python, And I am using the spyne. That I need to access the soap api with certification (.crt file). Is there any way to access soap api with ".crt" file or any other libraries available for python to access the shop with secure server.
Thanks


text:
Q: FileProvider - IllegalArgumentException: Failed to find configured root I'm trying to take a picture with camera, but I'm getting the following error:
FATAL EXCEPTION: main
Process: com.example.marek.myapplication, PID: 6747
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.marek.myapplication/files/Pictures/JPEG_20170228_175633_470124220.jpg
    at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
    at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
    at com.example.marek.myapplication.MainActivity.dispatchTakePictureIntent(MainActivity.java:56)
    at com.example.marek.myapplication.MainActivity.access$100(MainActivity.java:22)
    at com.example.marek.myapplication.MainActivity$1.onClick(MainActivity.java:35)

AndroidManifest.xml:
<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.marek.myapplication.fileprovider"
        android:enabled="true"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>

Java:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            Toast.makeText(getApplicationContext(), "Error while saving picture.", Toast.LENGTH_LONG).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.marek.myapplication.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }

file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_images" path="images/"/>
</paths>

I was searching whole day about this error and trying to understand FileProvider, but I have no idea what this error message tries to tell me. If you want more info/code, write me in the comment.

A: Got similar problem after enabled flavors (dev, stage).
Before flavors my path resource looked like this:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
    name="my_images"
    path="Android/data/pl.myapp/files/Pictures" />
</paths>

After added android:authorities="${applicationId}.fileprovider"
in Manifest appId was pl.myapp.dev or pl.myapp.stage depends on flavor and app started crashing.
I removed full path and replaced it with dot and everything started working.
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="my_images"
        path="." />
</paths>

A: None of this worked for me. The only approach that works is not to declare an explicit path in xml. So do this and be happy:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="." />
</paths>

Here too has a excelent tutorial about this question:
https://www.youtube.com/watch?v=9ZxRTKvtfnY&t=613s

A: My issue was that I had overlapping names in the file paths for different types, like this:
<cache-path
    name="cached_files"
    path="." />
<external-cache-path
    name="cached_files"
    path="." />

After I changed the names ("cached_files") to be unique, I got rid of the error. My guess is that those paths are stored in some HashMap or something which does not allow duplicates.

A: I am sure I am late to the party but below worked for me.
<paths>
    <root-path name="root" path="." />
</paths>

A: Your file is stored under getExternalFilesDir(). That maps to <external-files-path>, not <files-path>. Also, your file path does not contain images/ in it, so the path attribute in your XML is invalid.
Replace res/xml/file_paths.xml with:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="my_images" path="/" />
</paths>

UPDATE 2020 MAR 13
Provider path for a specific path as followings:

*

*<files-path/> --> Context.getFilesDir()

*<cache-path/> --> Context.getCacheDir()

*<external-path/> --> Environment.getExternalStorageDirectory()

*<external-files-path/> --> Context.getExternalFilesDir(String)

*<external-cache-path/> --> Context.getExternalCacheDir()

*<external-media-path/> --> Context.getExternalMediaDirs()
Ref: https://developer.android.com/reference/androidx/core/content/FileProvider

A: If you are using internal cache then use.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
</paths>

A: Lost 2 weeks trying to find some solution... If you arrive here after try everthing above:
1 - Verify if your tag provider are inside tag application
<application>

    <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.Pocidadao.fileprovider" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
    </provider>

</application>

2 - If you try a lot paths way without success, then test with this:
<?xml version="1.0" encoding="utf-8"?>
<paths>
  <cache-path name="cache" path="." />
  <external-path name="external" path="." />

  <root-path name="root" path="." />
  <files-path name="my_images" path="/" />
  <files-path name="my_images" path="myfile/"/>
  <files-path name="files" path="." />

  <external-path name="external_files" path="." />
  <external-path name="images" path="Pictures" />
  <external-path name="my_images" path="." />
  <external-path name="my_images" path="Android/data/com.companyname.yourproject/files/Pictures" />
  <external-path name="my_images" path="Android/data/com.companyname.yourproject/files/Pictures/" />

  <external-files-path name="images" path="Pictures"/>
  <external-files-path name="camera_image" path="Pictures/"/>
  <external-files-path name="external_files" path="." />
  <external-files-path name="my_images" path="my_images" />

  <external-cache-path name="external_cache" path="." />

</paths>

Test this, if camera works, then start eliminate some lines and continue testing...
3 - No forget verify if camera are actived in your emulator.

A: This Worked for me as well.Instead of giving full path i gave path="Pictures" and it worked fine.
<?xml version="1.0" encoding="utf-8"?>
 <paths>
  <external-files-path
    name="images"
    path="Pictures">
  </external-files-path>
 </paths>

A: This may resolve everyones problem:
All tags are added so you don't need to worry about folders path.
Replace res/xml/file_paths.xml with:
<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path
    name="external"
    path="." />
  <external-files-path
    name="external_files"
    path="." />
  <cache-path
    name="cache"
    path="." />
  <external-cache-path
    name="external_cache"
    path="." />
<files-path
    name="files"
    path="." />
</paths>

EDIT: 1st June 2021
We should use only specific path which we need.
Try alternate path on your own and use which you needed.
See Accepted answer for more information: https://stackoverflow.com/a/42516202/4498813

A: What I did to solve this -
AndroidManifest.xml
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.mydomain.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"/>
        </provider>

filepaths.xml (Allowing the FileProvider to share all the files that are inside the app's external files directory)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="files"
        path="/" />
</paths>

and in java class -
Uri fileProvider = FileProvider.getUriForFile(getContext(),"com.mydomain.fileprovider",newFile);

A: It depends what  kind of storage you want to do, INTERNAL or EXTERNAL
for EXTERNAL STORAGE
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="my_images" path="my_images" />
</paths>

but for INTERNAL STORAGE, be careful with the path, because it uses getFilesDir() method
which mean that your file will be located in the root directory for the app ("/")
  File storeDir = getFilesDir(); // path "/"

So your provider file must be like this:
<paths>
    <files-path name="my_images" path="/" />
</paths>

A: Change your main/res/xml/provider_paths.xml

From

<paths>
    <files-path path="images/" name="myimages" />
    <external-path name="download" path="download/"/>
</paths>

To

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

A: Be aware that external-path is not pointing to your secondary storage, aka "removable storage" (despite the name "external"). If you're getting "Failed to find configured root" you may add this line to your XML file.
<root-path name="root" path="." />

See more details here FileProvider and secondary external storage

A: This confusing me a bit too.
The problem is on "path" attribute in your xml file.
From this document FileProvider
'path' is a subdirectory,
but in another document (camera/photobasics) shown
'path' is full path.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

I just change this 'path' to full path and it just work.

A:
I had the same problem, I tried the below code for its working.

1.Create Xmlfile : provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_images" path="myfile/"/>
</paths>

2. Mainfest file
 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.ril.learnet.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
 </provider>

3.In your Java file.
      File file =  new File(getActivity().getFilesDir(), "myfile");
        if (!file.exists()) {
            file.mkdirs();
        }
        String  destPath = file.getPath() + File.separator + attachmentsListBean.getFileName();

               file mfile = new File(destPath);
                Uri path;
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                {
                    path = FileProvider.getUriForFile(AppController.getInstance().getApplicationContext(), AppController.getInstance().getApplicationContext().getPackageName() + ".provider", mfile );
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    path = Uri.fromFile(mfile);
                }
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(path, "image/*");
                    getActivity().startActivity(intent);

A: none of the above worked for me,
after a few hours debugging I found out that the problem is in createImageFile(), specifically absolute path vs relative path
I assume that you guys are using the official Android guide for taking photo. https://developer.android.com/training/camera/photobasics
    private static File createImageFile(Context context) throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

Take note of the storageDir, this is the location where the file will be created. So in order to get the absolute path of this file, I simply use image.getAbsolutePath(), this path will be used in onActivityResult if you need the Bitmap image after taking photo
below is the file_path.xml, simply use . so that it uses the absolute path
<paths>
    <external-path
        name="my_images"
        path="." />
</paths>

and if you need the bitmap after taking photo
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bmp = null;
        try {
            bmp = BitmapFactory.decodeFile(mCurrentPhotoPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

A: If nothing helps and you are getting the error
failed to find configured root that contains /data/data/...

then try changing some line like:
File directory = thisActivity.getDir("images", Context.MODE_PRIVATE);

to:
File directory = new File(thisActivity.getFilesDir(), "images");

and in the xml file:
<files-path name="files" path="." />

which is weird, since the folder I access is /images.

A: The problem might not just be the path xml.
Following is my fix:
Looking into the root course in android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile():
    public File getFileForUri(Uri uri) {
        String path = uri.getEncodedPath();

        final int splitIndex = path.indexOf('/', 1);
        final String tag = Uri.decode(path.substring(1, splitIndex));
        path = Uri.decode(path.substring(splitIndex + 1));

        final File root = mRoots.get(tag); // mRoots is parsed from path xml
        if (root == null) {
            throw new IllegalArgumentException("Unable to find configured root for " + uri);
        }

        // ...
    }

This means mRoots should contains the tag of requested uri. So I write some code to print mRoots and tag of uri, and then easily find the tags do not match.
It comes out that setting provider authority as ${applicationID}.provider is a stupid idea! This authority is so common that might be used by other providers, which will mess up the path config!

A: I was getting this error Failed to find configured root that contains...
The following work around resolves my issue
res/xml/file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="media" path="." />
</paths>

AndroidManifest.xml
<provider
      android:name="android.support.v4.content.FileProvider"
      android:authorities="[PACKAGE_NAME]"
      android:exported="false"
      android:grantUriPermissions="true">
         <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths">
         </meta-data>
</provider>

ActivityClass.java
void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,"com.slappstudio.pencilsketchphotomaker", selectedFilePath));
        startActivity(Intent.createChooser(intent,getString(R.string.string_share_with)));
    }

A: I would be late but I found a solution for it.Working fine for me, I just changed the paths XML file to:
 <?xml version="1.0" encoding="utf-8"?>
<paths>
    <root-path name="root" path="." />
</paths>

A: Check how many storages your device offers - sharing files from secondary storage is not supported. Look at FileProvider.java source (from support-core-utils 25.3.1):
            } else if (TAG_EXTERNAL_FILES.equals(tag)) {
                File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
                if (externalFilesDirs.length > 0) {
                    target = externalFilesDirs[0];
                }
            } else if (TAG_EXTERNAL_CACHE.equals(tag)) {
                File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
                if (externalCacheDirs.length > 0) {
                    target = externalCacheDirs[0];
                }
            }

So, they take only the first storage.
Also, you can see that getExternalCacheDirs() is used to obtain list of storages through the ContextCompat interface. See documentation for its limits (it's told to not recognize USB Flashes for example). Best is to make some debug output of list of storages from this API on your own, so that you can check that path to storage matches the path passed to getUriForFile().
There's already a ticket assigned (as for 06-2017) in Google's issue tracker, asking to support more than one storage. Eventually, I found SO question on this as well.

A: I have spent 5 hours for this..
I have tried all the methods above but it depends on the what storeage your app currently using.
https://developer.android.com/reference/android/support/v4/content/FileProvider#GetUri
Check the documentation before trying the codes.
In my case
since files-path sub directory will be Context.getFilesDir().
The funky thing is it Context.getFilesDir() notes one another subdirectory.
what I am looking for is
data/user/0/com.psh.mTest/app_imageDir/20181202101432629.png
Context.getFilesDir()

returns
/data/user/0/com.psh.mTest/files
so the tag should be
....files-path name="app_imageDir" path="../app_imageDir/" ......
Then it works!!

A: Android official document says file_paths.xml should have:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.example.package.name/files/Pictures" />
</paths>

But to make it work in the latest android there should be a "/" at the end of the path, like this:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.example.package.name/files/Pictures/" />
</paths>

A: The following change in xml file_paths file worked for me.
 <external-files-path name="my_images" path="Pictures"/>
 <external-files-path name="my_movies" path="Movies"/>

A: My Problem Was Wrong File Name:
I Create file_paths.xml under res/xml while resource was set to provider_paths.xml in Manifest:
<provider
        android:authorities="ir.aghigh.radio.fileprovider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

I changed provider_paths to file_paths and problem Solved.

A: If your file path is like /storage/emulated/0/"yourfile"
you just need modify your FileProvider xml
<paths>
    <external-path name="external" path="." />
</paths>

then call this function when you need share file
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                    Uri fileUri = FileProvider.getUriForFile(getContext(),
                            "com.example.myapp.fileprovider",
                            file);
                    sharingIntent.setType("*/*"); // any flie type
                    sharingIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
                    startActivity(Intent.createChooser(sharingIntent, "Share file"));

it works on android M ~ Pie

A: The Answer from @CommonsWare is great.
But in my case, I had to add multiple paths.
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="." />
    <files-path name="external_files" path="." />
</paths>

A: I see that at least you're not providing the same path as others in file_paths.xml.
So please make sure you provide the exact the same package name or path in 3 places including:

*

*android:authorities attribute in manifest

*path attribute in file_paths.xml

*authority argument when calling FileProvider.getUriForFile().

A: *

*For Xamarin.Android users

This could also be the result of not updating your support packages when targeting Android 7.1, 8.0+. Update them to v25.4.0.2+ and this particular error might go away(giving you´ve configured your file_path file correctly as others stated).

Giving context: I switched to targeting Oreo from Nougat in a
  Xamarin.Forms app and taking a picture with the Xam.Plugin.Media
  started failing with the above error message, so updating the packages
  did the trick for me ok.

A: I noticed that the policy or behaviour regarding the path.xml file changed between Support Library 26 and 27. For capturing a picture from the camera, I saw the following changes:

*

*With 26, I had to use <external-path> and the full path given in the path argument.

*With 27, I had to use <external-files-path> and only the subfolder in the path argument.
So what specifically worked for me with Support Library 27 as the path.xml file was
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="camera_image" path="Pictures/"/>
</paths>

A: Hello Friends Try This

In this Code

1) How to Declare 2 File Provider in Manifest.
2) First Provider for file Download
3) second Provider used for camera and gallary
STEP 1
     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

Provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="apks" path="." />
</paths>

Second Provider
     <provider
        android:name=".Utils.MyFileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities"
        tools:ignore="InnerclassSeparator">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_path" />
    </provider>

file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="storage/emulated/0" path="."/>
</paths>

.Utils.MyFileProvider
Create Class MyFileProvider (only Create class no any method declare)
When you used File Provider used (.fileprovider) this name and you used for image (.provider) used this.
IF any one Problem to understand this code You can Contact on rp1741995@gmail.com i will help you.

A: try this
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="" />
</paths>

A: You need to change the xml file file_paths.xml from
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_images" path="images/"/>
</paths>

to
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <exeternal-path name="my_images" path="Android/data/com.example.marek.myapplication/files/Pictures"/>
</paths>

A: You need to ensure that the contents of your file_paths.xml file contains this string => "/Android/data/com.example.marek.myapplication/files/Pictures/"
From the error message, that is path where your pictures are stored. See sample of expected
files_path.xml below:

<external-path name="qit_images" path="Android/data/com.example.marek.myapplication/files/Pictures/" />


text:
Q: adding validation to my contact form php I've eventually got my contact form working, my next task is to add in some server side validation to the fields. Here is my php code for the form:
<?php
    require_once('../_inc/config/db.php');

    $postArray = $_POST;

    foreach($postArray['name'] as $row=>$Name) {
      $name=mysql_real_escape_string($Name);
      $company=mysql_real_escape_string($postArray['company'][$row]);
      $email=mysql_real_escape_string($postArray['email'][$row]);
      $contact=mysql_real_escape_string($postArray['contact'][$row]);

      $sql = "INSERT INTO registered_blue (`name`, `company`, `email`, `contact`, `day`, `event-time`, `event`) VALUES ('".$name."','".$company."','".$email."','".$contact."', '" . $postArray['event-day'] . "', '" . $postArray['event-time'] . "', '" . $postArray['event'] . "')";

      $result = mysql_query($sql);

    }

    if ($result) {
        header('Location: /blue-event/confirmed.php');
        exit();
    } else {
        die('Invalid query: ' . mysql_error());
    }

?>

Can someone point me in the right direction as  the simplest/most effective way of implementing validation on this form?

A: Well define the validation you want
values are required?
I personaly use strlen, others use == '' (use trim if wished for)
Values need to be a specific type?
You should look at preg_match or ctype_* (see these function)
Numbers need to me in a specific range, use the < <= >= > operators.
File validation, look at extension and then mime type (always look at the mime to be sure!)
So there are tons of ways to validate and tons of things to validate so you should be make a more specific question.
I also recommend, look at this answer. It gives you a nice start I think


text:
Q: Custom Service Account for ASP.NET app pools As documented in the deprecated Patterns and Practices article below, it used to be best practice to create a custom service account to run ASP.NET applications. This avoided the problem of having to give the generic Network Service account permissions to resources  or having credentials in config files.
http://msdn.microsoft.com/en-us/library/ff649309.aspx
You would simply create a new Windows account, add it as the Custom identity of an app pool and then run  aspnet_regiis –ga to grant the necessary permissions.
Is this still a valid way of doing things? Or has it been supplanted by a better way? I realise that there are AppPoolIdentities now, but they use the machine account for granting permission to databases which strikes me as a bit rubbish.
If I'm still doing it the right way, is there a newer article that isn't marked as outdated?

A: you can set custom service account in IIS as below.

*

*Open IIS Manager. For information about opening IIS Manager, see Open IIS Manager (IIS 7).

*In the Connections pane, expand the server node and click Application Pools.

*On the Application Pools page, select the application pool for which you want to specify an identity, and then click Advanced Settings in the Actions pane.

*For the Identity property, click the ... button to open the Application Pool Identity dialog box.

*If you want to use a built-in account, select the Built-in account option and select an account from the list.

*If you want to use a custom identity, select the Custom account option and click Set to open the Set Credentials dialog box. Then type the custom account name in the User name text box, type a password in the Password text box, retype the password in the Confirm password text box, and then click OK.

*Click OK to dismiss the Application Pool Identity dialog box.

A: Here's the newer article (3/20/2020) that you seek, written by a Microsoft employee:
https://techcommunity.microsoft.com/t5/premier-field-engineering/iis-best-practices/ba-p/1241577
For what it's worth, he lists Application Pool Identities as a best practice for app pool identity configuration.


text:
Q: Disproving onto functions I'm so confused with inverse function with their proofing and disproving which is giving me a big headache.
For instance the question is,

Consider the function $F$ on the interval
$[-1, 1]  = \{ x \in \mathbb{R} : -1 \leq x \leq 1\}$, given by $F = \{(x, y): y = \sqrt{1 - x^2}\}$
Since $F$ is a relation, there is an inverse relation $F^{-1}$ on $[-1, 1]$ given by $F^{-1} = \{(x, y): y = \pm\sqrt{1 - x^2}\}$

Then it immediately jumps to the next line and says $F^{-1}$ is not a function since F is neither one-to-one nor onto.
I do understand one-to-one is definitely not possible because $x$ is a square which means that the outcome of a negative $x$ or a positive $x$ will definitely be positive.
However as for onto, it's disproving method is that find $y \in B$ which is not an image of another $x \in A$.
The question is how do I identify the $A$ and the $B$ for this function? I'm so confused with how to proof or disproof any onto functions.

A: $A$ is the domain and $B$ is the codomain of the function under discussion. In this case it would be the domain and codomain of $F$. You need to show that there exists an element of $B$ that is not equal to $F(x)$ where $x$ is some element of $A$. If $F: [-1,1]\rightarrow \mathbb{R}$, then clearly the negative real numbers are not in the image of $F$.

A: The domain ($A$) and codomain ($B$) of the function should always be specified by the person who defines the function.
In this case, the text says : "Consider the function $F$ on the interval $[-1, 1]$", that means that the domain $A$ is $[-1,1]$.
The text does not say anything about the codomain $B$, so it can be any set containing the image of A (and in this precise case, the image of $A$ by $F$ is $[0,1]$).
As it is often the case, you have to infer $B$ from the context. Here it could be for example $[-1,1]$, or $\mathbb{R}$...


text:
Q: Could not find a required file I'm trying to run docker container with create-react-app App. App works fine and here's how my dockerfile looks like.
# base image
FROM node:12.2.0-alpine

# set working directory
WORKDIR ./

# add `//node_modules/.bin` to $PATH
ENV PATH ./node_modules/.bin:$PATH

# install and cache  dependencies
COPY package.json ./package.json
COPY ./build/* ./public/
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g

# start
CMD ["npm", "start"]

When I run docker im getting error
> my-app@0.1.0 start /
> react-scripts start

Could not find a required file.
  Name: index.js
  Searched in: /src
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-app@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-app@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2019-07-14T08_29_30_761Z-debug.log

has anybody have any idea?

A: npm start is for webpack - which serves you as the dev server. you are still using directly the src files, not the minified build (dist), which will only be used on production.
#Dockerfile.dev:

# base image
FROM node:12.2.0-alpine

# set working directory
WORKDIR ./

# add `//node_modules/.bin` to $PATH
ENV PATH ./node_modules/.bin:$PATH

COPY package.json ./package.json

#use the minified build file for production, not now - npm start is for development.
#COPY ./build/* ./public/

#install dependencies:
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g

#copy your project files: (also bad for development, use volume(https://docs.docker.com/storage/volumes/) instead)
COPY . .

# start
CMD ["npm", "start"]

A: (This builds on @EfratLevitan's answer, but is a little more production-oriented.  Their answer will be better if you want to use Docker as a core part of your development flow.)
If you have a working Webpack setup already, its output is static files that can be served up by any Web server.  Once you've successfully run npm run build, you can use anything to serve the resulting build directory – serve it as static content from something like a Flask application, put it in a cloud service like Amazon S3 that can serve it for you, directly host it yourself.  Any of the techniques described on the CRA Deployment page will work just fine in conjunction with a Docker-based backend.
If you'd like to serve this yourself via Docker, you don't need Node to serve the build directory, so a plain Web server like nginx will work fine.  The two examples from the image description work for you here:
# Just use the image and inject the content as data
docker run -v $PWD/build:/usr/share/nginx/html -p 80:80 nginx

# Build an image with the content "baked in"
cat >Dockerfile <<EOF
FROM nginx
COPY ./build /usr/share/nginx/html
EOF

# Run it
docker build -t me/nginx .
docker run -p 80:80 me/nginx

The all-Docker equivalent to this is to use a multi-stage build to run the Webpack build inside Docker, then copy it out to a production Web server image.
FROM node:12.2.0-alpine AS build
WORKDIR /app
COPY package.json yarn.lock .
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g
COPY . .
RUN npm run build

FROM nginx
COPY --from=build /app/build /usr/share/nginx/html

In this model you'd develop your front-end code locally.  (The Webpack/CRA stack has pretty minimal host dependencies, and since the application runs in the user's browser, it can't depend on Docker-specific networking features.)  You'd only build this Dockerfile once you wanted to run an end-to-end test with all of the parts running together before you actually pushed out to production.


text:
Q: Função circle, como mandar o parametro centro? Estou mandando o parametro centro dado por (2953,1999) como mostro a seguir:
circle(imgOr,(2953,1999),224,Scalar(255,0,0));

Mas da o erro:

could not convert (0,1999) from 'int' to 'cv::Point'

A: Tente usar isto:
circle(imgOr,Point(2953,1999),224,Scalar(255,0,0));

só tem que tomar cuidado para que esse circulo não ultrapasse as bordas da imagem


text:
Q: List of empty variables in Python Is there any possibility of creating a list of variables/names* that have not been defined yet, and then loop through the list at a later stage to define them?
Like this:
varList = [varA, varB, varC]
for var in varList:
    var = 0
print(varList)

>>>[0, 0, 0]

The reason I'm asking is because I have a project where I could hypothetically batch fill 40+ variables/names* this way by looping through a Pandas series*. Unfortunately Python doesn't seem to allow undefined variables in a list.
Does anyone have a creative workaround?
EDIT: Since you asked for the specific problem, here goes:
I have a Pandas series that looks like this (excuse the Swedish):
print(Elanv)

>>>
Förb. KVV PTP                 5653,021978
Förb. KVV Skogsflis                     0
Förb. KVV Återvinningsflis    337,1416119
Förb. KVV Eo1                         6,1
Förb. HVC Återvinningsflis           1848
Name: Elanv, dtype: object

I want to store each value in this array to a set of new variables/names*, the names of which I want to control. For example, I want the new variable/name* containing the first value to be called "förbKVVptp", the second one "förbKVVsflis", and so forth.
The "normal" option is to assign each variable manually, like this:
förbKVVptp, förbKVVsflis, förbKVVåflis = Elanv.iloc[0], Elanv.iloc[1], Elanv.iloc[2] ....

But that creates a not so nice looking long bunch of code just to name variables/names*. Instead I thought I could do something like this (obviously with all the variables/names*, not just the first three) which looks and feels cleaner:
varList = [förbKVVptp, förbKVVsflis, förbKVVåflis]
for i, var in enumerate(varList): var = Elanv.iloc[i]

print(varList)

>>>[5653,021978, 0, 337,1416119]

Obviously this becomes pointless if I have to write the name of my new variables/names* twice (first to define them, then to put them inside the varList) so that was why I asked.

A: You cannot create uninitialized variables in python. Python doesn't really have variables, it has names referring to values. An uninitialized variable would be a name that doesn't refer to a value - so basically just a string:
varList = ['förbKVVptp', 'förbKVVsflis', 'förbKVVåflis']

You can turn these strings into variables by associating them with a value. One of the ways to do that is via globals:
for i, varname in enumerate(varList):
    globals()[varname] = Elanv.iloc[i]

However, dynamically creating variables like this is often a code smell. Consider storing the values in a dictionary or list instead:
my_vars_dict = {
    'förbKVVptp': Elanv.iloc[0],
    'förbKVVsflis': Elanv.iloc[1],
    'förbKVVåflis': Elanv.iloc[2]
}

my_vars_list = [Elanv.iloc[0], Elanv.iloc[1], Elanv.iloc[2]]

See also How do I create a variable number of variables?.

A: *

*The answer to your question is that you can not have undefined variables in a list.

*My solution is specific to solving this part of your problem  The reason I'm asking is that I have a project where I could hypothetically batch fill over 100 arrays this way by looping through a Pandas array.

*Below solution prefills the list with None and then you can change the values in the list.

Code:
varList = [None]*3
for i in range(len(varList)):
    varList[i] = 0
print(varList)

Output:
[0, 0, 0]

A: So something you are trying to do in your example that won't do what you expect, is how you are trying to modify the list:
for var in varList:
    var = 0

When you do var = 0, it won't change the list, nor the values of varA, varB, varC (if they were defined.)
Similarly, the following won't change the value of the list. It will just change the value of var.
var = mylist[0]
var = 1

To change the value of the list, you need to do an assignment expression on an indexed item on the list:
mylist = [None, None, None]
for i in range(len(mylist)):
    mylist[i] = 0

print(mylist)

Note that by creating a list with empty slots before assigning the value is inefficient and not pythonic. A better way would be to just iterate through the source values, and append them to a list, or even better, use a list comprehension.


text:
Q: Force user change password after first login in ASP.NET Core In my ASP.Net Core application, I want, after I create an account with a default password,  the next time that user logs in I would like to force them to change their password If InforceChangePassword field in database be true.
Note: I want, If the user does not change his password, he will never be able to sign in.
In my code is:
 public async Task<IActionResult> Login(LoginInputModel model)
    {

    if (ModelState.IsValid)
    {
        var user = await _userResolver.GetUserAsync(model.Username);
        if (!user.IsActive)
        {
            return View("Error");
        }

        if (user != default(TUser)) {
            var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberLogin, lockoutOnFailure: true);
            if (result.Succeeded)
            {
                await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));
                if (user.InforceChangePassword)
                {
                    return RedirectToAction("ChangePassword", "Manage");
                }

                 if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return Redirect("~/");
                }

                // user might have clicked on a malicious link - should be logged
                throw new Exception("invalid return URL");
            }

    }

    // something went wrong, show form with error

    return View("Error");
}

Can anyone help me?


text:
Q: Reducing .XAP file size? I created a customized version of the Silverlight Player. After building/compiling, the .XAP which gets pushed out, it ends up being over 700KB.
I'm not too sure why it's doing this because I'm not adding any new resources. All my changes have all been in the code.
Is there any way to reduce the file size?

A: You are probably including DLLs you did not intend to. The Copy Local option for DLL references you add is True by default.
A XAP file is just a ZIP file with a different extension so the first thing to do is unzip it and take a look at what is included.
You can use a better Zip program to recompress the XAP file, but that will only gain you another 10%-20% at best.
If it turns out you are really just concerned about initial load time vs. total load time you can load an initial (small) bootstrapper to update the display while loading subsequent modules dynamically (look at PRISM and MEF).

A: You can check the "Reduce XAP size by using application library caching" option.
By default any system dlls that your application uses will be included in the XAP file. By checking this option they are downloaded as separate zip files.
This won't reduce the total size of the files that your application downloads, but will mean that when you publish an update your users won't have to download all the system dlls again - they'll already have these in their local cache.
This option is primarily used in applications that are split across several XAP files to ensure that only one copy of the system dlls are downloaded for the whole application.


text:
Q: Inserting data into two different tables with SQL Server 2008? I have three tables in my database: Contacts (master table), Users and Staff. The Contacts table has a primary key that is referenced as a foreign key from the Users and Staff tables.
Contacts
ContactID (Primary Key)
First Name
Last Name
Email

Users:
ContactID (Foreign Key)
Username
Password

Staff:
ContactID (Foreign Key)
Position
Comments

Pulling data from these tables is fairly simple with INNER JOIN and depends what data you need from the Users or Staff table. Updating and inserting new records is something that I'm not sure which way to approach.
Since the Contacts table is my master table and holds unique ID's but at the same time is shared between Users and Staff, I'm not sure about this situation.
Let's say I want to enter new user record. I need to enter First, Last name and email into the Contacts table, and User Name and Password into the Users table. At the same time I have to check if First, Last name and email already exist in the Contacts table, since maybe this Contact record has been previously entered for a Staff record.
I'm not sure how to prevent duplicates but at the same time there might be user or staff with the same name. Should I limit/filter by email and not let them enter the records if the email already exist in contacts table? Or is there a better way to handle this?
The whole point of having three tables is to prevent redundant data since User might be a Staff, but Staff might not be a User if that make sense. If anyone can help me pick the best approach please let me know. Thanks

A: You have to start by using a SELECT query and whatever business rules you want to test to decide if you will perform the INSERT at all, or UPDATE an existing record instead.
Then if you are going to INSERT, you have to INSERT into Contacts first, get the newly inserted ID, and then INSERT into the other two tables.


text:
Q: How to rewrite url in htaccess in IMPRESSPAGES cms? I'm trying to add rewrite rule for url in .htaccess in IMPERSSPAGES CMS.
I have example.com/obj?id=123 and I want it to look like example.com/obj/123
Is it even possible because there is already a rewire rule in htaccess pointing to index.php:
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L]

A: You have to add the Redirect flag at the end and a directory slash at the beginning for this to work. Otherwise the last rule will still be called and IP routing will throw a 404 error.
Before
RewriteRule ^obj/(\d+)/?$ your-script.php?id=$1 [L]

After:
RewriteRule ^obj/(\d+)/?$ /your-script.php?id=$1 [R,L]

A: You can use:
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^obj/([0-9]+)/?$ obj?id=$1 [L]
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L]


text:
Q: How can I get the longitude and latitude in my android app? I've been trying to get the location for the particular  phone for a while now. I have used the following code but instead of showing the location it will just crash when I try and run the app in my emulator.
Once I've got the longitude and latitude I am going to use it to map the current location on a google map!
public class Homescreen extends ActionBarActivity implements LocationListener {
    final TextView t = (TextView)findViewById(R.id.textView1);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homescreen);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.homescreen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        int latitude = (int) (location.getLatitude());
        int longitude = (int) (location.getLongitude());
        t.setText(latitude);

//      Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);

    }

A: Use This Activity. I hope it will help you.
   package yourPackage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingDefaultValue;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingKey;
import com.infologitech.spotways.custom.TransactionSupport;

public class GetCurrentLocationActivity extends Activity implements
        LocationListener, ConnectionCallbacks, OnConnectionFailedListener {

    private Context context = this;
    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    private Location mLocation;
    private float minAccuracy = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (checkPlayServices()) {
        mLocationClient = new LocationClient(this, this, this);
        mLocationClient.connect();
        //waitForLocation();
}else finish();
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle arg0) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(5 * 1000);
        mLocationRequest.setFastestInterval(2 * 1000);
        mLocationRequest.setSmallestDisplacement(5f);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onLocationChanged(Location loc) {
        if (loc != null) {
            int latitude = (int) (loc.getLatitude());
        int longitude = (int) (loc.getLongitude());
        Toast.makeText(this,"Lat "+latitude+", Lng "+longitude);
        }
    }

    @Override
    protected void onDestroy() {
        stopUpdate();
        super.onDestroy();
    }

    private void stopUpdate() {
        try {
            mLocationClient.removeLocationUpdates(this);
            mLocationClient.disconnect();
        } catch (Exception e) {
        }
    }

    public  boolean checkPlayServices() {
        final int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
                        resultCode, context, 3434);
                if (dialog != null) {
                    dialog.show();
                    dialog.setOnDismissListener(new OnDismissListener() {
                        public void onDismiss(DialogInterface dialog) {
                            if (ConnectionResult.SERVICE_INVALID == resultCode) {
                            }
                        }
                    });
                    return false;
                }
            }

            return false;
        }
        return true;
    }
}


text:
Q: Output shows all 0's. The gross and OT is not calculating Output shows all 0's. The gross and OT is not calculating..
#include <stdio.h>

#define STD_HOURS 40.0
#define OT_RATE 1.5
#define SIZE 5

void read_hours(float worked_hours[], long int clockNumber[]);
void calculate_gross(float wage[], float worked_hours[], float gross);
void calculate_gross_ot(float wage[], float worked_hours[]);
void printFunction(long int clockNumber[], float wage[], float worked_hours[], float OT[],              float gross);

int i;

int main()
{

    long int clockNumber [SIZE] = {98401, 526488, 765349, 34645, 127615};/* employee ID */
    float gross = 0.0; /* gross */
    float OT [SIZE] = {}; /* overtime */
    float wage [SIZE] = {10.6, 9.75, 10.5, 12.25, 8.35};      /* hourly wage */
    float worked_hours [SIZE] = {};    //  Hours  worked

    read_hours(worked_hours, clockNumber);

    if (worked_hours[i]>STD_HOURS)
    {

    calculate_gross_ot(wage, worked_hours);

    }

    else

    {
       calculate_gross(wage,worked_hours, gross);

    }
    printFunction(clockNumber, wage, worked_hours, OT, gross);

    return(0);
}

void read_hours(float worked_hours[], long int clockNumber[])
{

    for (i=0; i<SIZE; i++)
    {

        printf("\n Enter Hours for Emlployee ID: %ld\n", clockNumber[i]);
        scanf ("%f", &worked_hours[i]);

    }

}

void calculate_gross(float wage[], float worked_hours[], float gross)
{

    for(i=0; i<SIZE; i++)

        gross=(wage[i]*worked_hours[i]);
}

void calculate_gross_ot(float wage[], float worked_hours[])
{

    float gross;
    float OT[SIZE];

    for (i=0; i<SIZE; i++)
    {

        /* calculating overtime hours */
           OT[i]=worked_hours[i]-STD_HOURS;

            /* calculating gross pay with overtime */
            gross = (STD_HOURS*wage[i]) + (OT[i]*OT_RATE*wage[i]);
        //}

    }

}

void printFunction(long int clockNumber[], float wage[], float worked_hours[], float OT[], float gross)
    {

        /* creating a table for the output */
        printf("------------------------------------------------\n");
        printf("%7s","Clock#");
        printf("%7s","Wages");
        printf("%7s","Hours");
        printf("%7s","OT");
        printf("%7s\n","Gross");
        printf("------------------------------------------------\n");
for (i=0; i<SIZE; i++)

{
        /* printing the results */
        printf("%6ld", clockNumber[i]);
        printf("%10.2f",wage[i]);
        printf("%6.1f", worked_hours[i]);
        printf("%6.1f", OT[i]);
        printf("%10.2f",gross);
        printf("\n");

 }

    }

The program is used to calculate gross with and without OT hours. The output is showing      all 0's for the gross and OT. Please help to figure out where is the mistake.

A: In the first case, you are passing gross by value.
In the second case, you are not passing it at all (the function has a local function called gross).
In both cases, whenever the respective function changes gross, this change does not propagate to the caller.
You need to either pass gross by pointer, or return the value from the function using the return statement (and changing the return type appropriately).

A: Pass OT to your calculate_gross_ot() function from main().
 ...
 calculate_gross_ot(wage, worked_hours, OT);
 ...

 void calculate_gross_ot(float wage[], float worked_hours[], float OT[])


text:
Q: Error Received while importing data using Flat File into SQL server I am trying to import a flat file into SQL Server table and I received an error below. I verified the mappings looks good and around 5million data gets loaded into the table and then it fails. Any help would be greatly appreciated.

*

*Copying to [dbo].[TABLE1] (Error)

Messages
Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80004005  Description: "Communication link failure".
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80004005  Description: "TCP Provider: The semaphore timeout period has expired.
".
 (SQL Server Import and Export Wizard)

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Destination - TABLE1.Inputs[Destination Input]" failed because error code 0xC020907B occurred, and the error row disposition on "Destination - TABLE1.Inputs[Destination Input]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Destination - TABLE1" (370) failed with error code 0xC0209029 while processing input "Destination Input" (383). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

Error 0xc02020c4: Data Flow Task 1: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.
 (SQL Server Import and Export Wizard)

Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on Source - TABLE1_txt returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

A: TCP Provider: The semaphore timeout period has expired
Try to use Chunks  and take a look here for Example.
Please also specify how big FlatFile (the bigger one) you are trying to put into SQL Server ?


text:
Q: Doing git pull in Engine Yard I am deploying my rails app to Engine Yard.
What i had so far:
1. created SSH hey
2. Install public key to Engine Yard app.
3. ssh deploy@my.server.ip.address
I was put at home/deploy, which is not a right place to perform git pull.
The reason I need to deploy in this way, is because my app is using nmatrix gem, which need to be installed manually using c++ compiler. The automatic bundler got an error while fetching that gem, and stopped.
Update:
I guess my question should be, how to install nmatrix to EngineYard. This is the error message I got from calling gem install nmatrix:
Building native extensions.  This could take a while...
ERROR:  Error installing nmatrix:
    ERROR: Failed to build gem native extension.

    /usr/bin/ruby21 extconf.rb
checking for main() in -llapack... no
checking for main() in -lcblas... yes
checking for main() in -latlas... no
checking for clapack.h... no
checking for cblas.h... yes
checking for cblas.h... yes
checking for clapack_dgetrf() in cblas.h,clapack.h... no
checking for clapack_dgetri() in cblas.h,clapack.h... no
checking for dgesvd_() in clapack.h... no
checking for cblas_dgemm() in cblas.h... yes
using C++ standard... c++0x
g++ reports version... Hardened
creating nmatrix_config.h
creating Makefile

make "DESTDIR="
compiling nmatrix.cpp
In file included from nmatrix.cpp:331:0:
ruby_nmatrix.c: In function 'VALUE nm_mset(int, VALUE*, VALUE)':
ruby_nmatrix.c:1378:108: warning: format '%u' expects type 'unsigned int', but argument 4 has type 'size_t'
ruby_nmatrix.c: In function 'VALUE nm_xslice(int, VALUE*, void* (*)(const STORAGE*, SLICE*), void (*)(NMATRIX*), VALUE)':
ruby_nmatrix.c:1556:91: warning: format '%u' expects type 'unsigned int', but argument 4 has type 'size_t'
ruby_nmatrix.c: In function 'SLICE* get_slice(size_t, int, VALUE*, size_t*)':
ruby_nmatrix.c:1903:104: warning: format '%u' expects type 'unsigned int', but argument 3 has type 'size_t'
ruby_nmatrix.c:1903:104: warning: format '%u' expects type 'unsigned int', but argument 4 has type 'size_t'
compiling ruby_constants.cpp
compiling data/data.cpp
compiling util/io.cpp
compiling math.cpp
In file included from math.cpp:140:0:
math/rot.h: In function 'void nm::math::rot(int, DType*, int, DType*, int, CSDType, CSDType) [with DType = nm::Complex<float>, CSDType = float]':
math/rot.h:123:40: error: 'cblas_csrot' was not declared in this scope
math/rot.h: In function 'void nm::math::rot(int, DType*, int, DType*, int, CSDType, CSDType) [with DType = nm::Complex<double>, CSDType = double]':
math/rot.h:128:40: error: 'cblas_zdrot' was not declared in this scope
In file included from math.cpp:141:0:
math/rotg.h: In function 'void nm::math::rotg(DType*, DType*, DType*, DType*) [with DType = nm::Complex<float>]':
math/rotg.h:99:125: error: 'cblas_crotg' was not declared in this scope
math/rotg.h: In function 'void nm::math::rotg(DType*, DType*, DType*, DType*) [with DType = nm::Complex<double>]':
math/rotg.h:104:125: error: 'cblas_zrotg' was not declared in this scope
make: *** [math.o] Error 1

Gem files will remain installed in /home/deploy/.gem/ruby/2.1.0/gems/nmatrix-0.0.9 for inspection.
Results logged to /home/deploy/.gem/ruby/2.1.0/gems/nmatrix-0.0.9/ext/nmatrix/gem_make.out

One of the prerequisite to install nmatrix is to have gcc > v4.7, but EngineYard is having v4.5.4 only. Anyone know how to upgrade gcc? I think I am running Gentoo.

A: The question actually should include what you want to git pull.
When you ssh in, you are put into /home/deploy which is your home directory.
The Git copy of your app is located in /data/APPNAME/shared/cache-copy/ on the App Master
You can have multiple apps on one instance and each one can have a different deploy key so you use a GIT_SSH wrapper
GIT_SSH=/data/APPNAME/shared/config/pulse-ssh-wrapper git pull

(in all the above commands remember to replace APPNAME with the name used for the app)
If you want to find the actual location for a bundled gem, you can look in
/data/APPNAME/shared/bundled_gems/ruby/2.0.0/gems (version will depend on Ruby ABI)
if your Gemfile uses a :git remember that only a single deploy key can be used for both the app clone and bundle phase, you cannot select different keys per gem.
Most likely the issue with installing the nmatrix gem is that the ATLAS libraries are not installed yet and those would be installed with the system's package manager (Portage for Gentoo and Apt-get for Ubuntu).  You can add them via "Edit Unix Packages" on the UI, just select sci-libs/blas-atlas and sci-libs/lapack-atlas.  Currently this will fail because the EC2 instances are Xeon processors and the libraries do not build on these yet.

*

*http://sourceforge.net/p/math-atlas/support-requests/614/

*https://bugzilla.kernel.org/show_bug.cgi?id=13794
You can see the CPU type on your Linux instance with "cat /proc/cpuinfo" and will see something like
model name  :Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz


text:
Q: How to make Terminator terminal emulator transparent in dwm? How to make window transparency for Terminator terminal emulator work with dwm?
I've set background transparency inside Terminator settings. It works with ordinary Ubuntu 20.04 windows manager, but with dwm it doesn't work.
How to make Terminator terminal emulator transparent in dwm?

A: Dwm has a patch on suckless.org/dwm go to patches and default transparency. Download the patch to dwm source directory. patch -p1 < path/to/patch.diff. Remake dwm and start again see if it works. If it doesn't you need a compositor. I prefer xcompmgr in .xinitrc, Cheers. https://www.youtube.com/watch?v=zaRzOEoyR4s


text:
Q: Updating JQuery dataTable table outside itself I managed to get jquery datatables plugin to work with asp.net mvc 3 so it posts back json, and with a search function.
Problem now I that I need to move the search box and add a "language" filter outside it's "normal" position next to a custom made menu.
Is there a way that I can integrate:
Language: <select name="languageid">
<option value="SV">Swedish</option>
<option value="EN">English</option>
</select>
Keywords: <input type="text" name="keywords">

To refresh datatables when languageid or keywords change? and still have sorting, paging working?

A: My brain is only firing at half power today, but the short answer is that this can be done; it's just my suggestions that are kind of vague...sorry!

*

*There are a whole set of language options in oLanguage; it was a bit "Too Long, Didn't Read" for me to sort through, but perhaps something there will help you identify where to set up a language switcher

*You can remove the search box from the main table and set up your own, using the fnFilter method to trigger the search

*Depending on how your other options are configured (server-side, for example), there are methods to trigger a refresh of the table. You would bind a listener for the languageid or keyword change action (.on('change', '#languageid', function(e) { /* ... */ })) which would fire the appropriate refresh action (in my instance which uses server-side, I use fnDraw())
I'm sorry about the directionless advice, but I wanted you to know at least that this is possible. Posting the question on the datatables.net forums directly might get you the best possible answer.


text:
Q: react native TouchableOpacity, different functions by first and second click I'm creating a simple text-to-speech function for my react native app.
I have a button, when you click it for the first time, it will read the text and play the sound.
But I want to make it dynamic. For example: If you click again it should stop, if click again, should play again, etc.....
But now, it is only available for playing the sound with any click.
Where/how should I execute the stopReadText()?
I still don't have any idea about this. Thanks a lot.
Here is the code:
const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

  return (
    <View>
      <TouchableOpacity onPress=(readText)>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )

(I am using expo-speech)

A: You can do it by taking on a boolean state variable:
import { useState } from 'react';

const [isPlay,setIsPlay]=useState(false)

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

const handlePlay =() =>{
  if(!setIsPlay){
      readText()
      setIsPlay(true)
  }
  else {
      stopReadText()
      setIsPlay(false)
  }

 }

  return (
    <View>
      <TouchableOpacity onPress={handlePlay}>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )


text:
Q: Cannot create scratch orgs in visual studio I am trying to create a scratch orgs from visual studio, I authorise the dev hub  successfully but when I try to create a scratch org it throw this error :
ERROR:  Error authenticating with the refresh token due to: expired access/refresh token.
I tried with 3-4 dev hub orgs, all the dev hub org authorised successfully, but cant able to create scratch orgs. Please advise

A: Run command %USERPROFILE%\.sfdx in windows. This will open folder which is host of .json files. All connected orgs .json files will be here.
Inside the file, has the hashes for current access token, refresh token, and all the other OAuth goodness that allows DX to access your org. So simply deleted that file using command:

rm dhanik.sahni@lwc.com.json

That appears to have cleaned it all up, and I'm no longer bothered by the "invalid grant" message and the shadow org.
After this done try to create scratch org.


text:
Q: Using a recursive method to publish a Java SwingWorker process I have a recursive method that takes a list of file paths from the user and iterate through them recursively to find all files. This may take a while, so I needed a progress dialog. I've coded a SwingWorker thread in an attempt to publish each file to the progress dialog. However, because my method is of a recursive nature, it needs to be in its own method, not the doInBackground() method provided by the SwingWorker library.
Here is a simplified version of my SwingWorker code:
SwingWorker<Boolean, String> worker = (new SwingWorker<Boolean, String>() {
    protected Boolean doInBackground() throws Exception {
        for (int i = 0; i < model.size(); i++) {
            File currentDir = new File(model.get(i));
            searchFiles(currentDir); // The recursive method
        }
        return true;
    }

    protected void process(List<String> chunks) {
        jpanel.someLabel.addFile(chunks.toString());
    }
});
worker.execute();

Here is a simplified version of my Recursive code:
private void searchFiles(File fn) {
    if (fn.isDirectory()) {
        String[] subDir = fn.list();
        if (subDir != null) {
            for (String fn2 : subDir) {
                searchFiles(new File(fn, fn2));
            }
        }
    } else { // If fn isn't a directory, then it must be a file
        String absoluteFile = fn.getAbsoluteFile().toString();
        publish(absoluteFile); // This isn't working... How can I get this method to publish to process()?
    }
}

Is there a way for me to call publish() from another method?

A: To clarify something in the accepted answer:
Your posted code and this sentence:

So the answer to your question,You CANNOT call publish() from another method.

nullify each other since you actually use publish() inside another method :) (well actually it is in the doInBackground() since you call the other method there :))
The reason why your publish() method did not work is written here:
https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#publish(V...)

protected final void publish(V... chunks)

That means that publish() is NOT visible outside the Swing-package.
And finally you can call publish() from other methods like for example SwingWorker's own done() method or even its constructor

A: As the SwingWorker documentation for the publish() method says link

Sends data chunks to the process(java.util.List) method. This method is to be used from inside the doInBackground method to deliver intermediate results for processing on the Event Dispatch Thread inside the process method.

So the answer to your question,You CANNOT call publish() from another method.
However, you can move your recursive method into your SwingWorker class if you really want to call publish() inside the recursive method. Like this:
SwingWorker<Boolean, String> worker = (new SwingWorker<Boolean, String>() {
    protected Boolean doInBackground() throws Exception {
        for (int i = 0; i < model.size(); i++) {
            File currentDir = new File(model.get(i));
            searchFiles(currentDir); // The recursive method
        }
        return true;
    }

    protected void process(List<String> chunks) {
        jpanel.someLabel.addFile(chunks.toString());
    }

    private void searchFiles(File fn) {
        if (fn.isDirectory()) {
            String[] subDir = fn.list();
            if (subDir != null) {
                for (String fn2 : subDir) {
                searchFiles(new File(fn, fn2));
            }
        }
        } else { // If fn isn't a directory, then it must be a file
            String absoluteFile = fn.getAbsoluteFile().toString();
            publish(absoluteFile);
        }
    }

});
worker.execute();


text:
Q: Summary shown in R is short, many terms shown as "Other" How can I display the complete output summary, without classifying any values as "Other"?
summary(d)
     Date.of.Sale   City               Department      Product
 1/18/2015 :  149   A:5290   Footwear Mens  : 538   13245  :  255
 1/25/2015 :  149   B:2078   Home Furnishing:1937   15350  :  255
 11/23/2014:  149   C:5088   Infant W-Wear  : 992   15352  :  255
 11/30/2014:  149            Ladies Lower   :1735   15353  :  255
 12/14/2014:  149            Ladies Upper   :1805   15355  :  255
 12/21/2014:  149            Mens Lower     :2039   15356  :  255
 (Other)   :11562            Mens Upper     :3410   (Other):10926
            Sale      Predicted.Sale       Flag
 0            :3963   0      :3279   Forecast: 1341
 Not Available:1341   1      :1951   History :11115
 1            :1145   2      : 946
 2            : 797   3      : 700
 3            : 557   4      : 572
 4            : 498   5      : 438
 (Other)      :4155   (Other):4570

A: Aside: It looks like your data has factor columns where they should be numeric.  You may want to have a look at that as it may cause issues for you in later analysis.

As far as your call to summary() goes, you can adjust the maxsum argument.  We find in help(summary) that this can be used to change the amount of information shown in the summary

maxsum - integer, indicating how many levels should be shown for factors.

So let's have a look at this at work with a two-column data frame example -
set.seed(12)
df <- data.frame(
    a = sample(letters[1:8], 1e3, TRUE),
    b = sample(letters[1:10], 1e3, TRUE)
)

Calling summary() with no other arguments, we get "Other" listed at the bottom of each column summary.
summary(df)
#       a             b
# d      :132   g      :118
# c      :131   b      :108
# f      :131   e      :106
# a      :123   f      :104
# g      :123   d      :103
# e      :122   j      :103
# (Other):238   (Other):358

Now if we adjust maxsum to the length of the maximum number of unique values of all columns, we get all the values listed.
summary(df, maxsum = max(lengths(lapply(df, unique))))
#  a       b
#  a:123   a: 94
#  b:120   b:108
#  c:131   c: 99
#  d:132   d:103
#  e:122   e:106
#  f:131   f:104
#  g:123   g:118
#  h:118   h: 92
#          i: 73
#          j:103

Note that maxsum could also be maxsum = length(Reduce(union, df)), and that this assumes that you are working with a data frame.


text:
Q: imported stylesheets not working after adding react-native-navigation I've recently added react-native-navigation to my project, and now I can't get imported stylesheet to work. What I'm trying to do is this:
import screenstyles from './screenstyles';

class Screen extends Component {

 render() {
   return (
     <View style={screenstyles.container}>
       <Text style={screenstyles.basictext}>Text I want to display</Text>
     </View>
  );
 }

screenstyles.js:
import EStyleSheet from 'react-native-extended-stylesheet';

export default EStyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '$primaryBlue'
  },
  basictext: {
    color: "#fff",
    fontSize: 34
  }
});

But I simply get a default white screen with unstyled text.
The only way I get any sort of imported styling to work at the moment is by doing this
import {Container, styles} from '../components/Container';

  class Screen extends Component {

    render() {
       return (
         <Container backgroundColor={"red"}>
         </Container>
     );
  }
}

Container.js:
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'blue'
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: '500'
  }

});

const Container = ({onPress, backgroundColor, texttest}) => (
  <View style={[styles.container, {backgroundColor}]}>
    <Text style={styles.text}></Text>
  </View>
);

export default Container;

This approach isn't the best because it makes it much more difficult to use the same stylesheet for each screen but still being able to customize the screen.

A: Try rewriting the screenstyles.js file as follows:
const React = require('react-native-extended-stylesheet');
const { EStyleSheet } = React;

var styles =  EStyleSheet.create({
   container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: '$primaryBlue'
   },
   basictext: {
      color: "#fff",
      fontSize: 34
   }
});

module.exports = styles;


text:
Q: Error: "Traceback (most recent call last):" I'm trying to install pip to my pycharm, I'm using Mac OS X version 10.11.1
I tried: pip install --upgrade pip
Then I get:
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2793, in <module>
working_set.require(__requires__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 673, in require
needed = self.resolve(parse_requirements(requirements))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 576, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==7.1.0

I'm stuck a few days.

A: Don't modify your system python. Instead, install a new version of python with pyenv. And then create a new env for each project use virtualenv or venv if you are using py3k.


text:
Q: hexadecimal 0X19 is an invalid character SO,
I am building XML string based on the values from the dataset using XMLWriter.
It is properly building the xml string as per the settings and the conditions I specified.
If there are more than 1000 records in the dataset and when I try to build the xml string I am getting the above error. hexadecimal 0X19 is an invalid character
How do I get pass this. I have spent around 6 hrs trying to figure out.
Please help

A: Hex 0x19 is a control code in the ASCII sequence - it is End of Medium (EM). I'm not sure how it is getting into your data stream. If you are encoding something requiring more than one byte into UTF-8 and then treating it as a single byte character set or some other similar encode/decode sequence, you could be seeing the second byte of a UTF-8 sequence.
Are you transcoding from one character set to another? and What are the input and output encodings?

A: Quite simply, you're not allowed that character in an XML document, no matter how you mark it up.  To quote the spec:

Char     ::=      #x9 | #xA | #xD |
  [#x20-#xD7FF] | [#xE000-#xFFFD] |
  [#x10000-#x10FFFF]

Roughly translated, that means that before 0x20, you're only allowed tab (0x09), newline (0x0a) and carriage return (0x0d).
The normal way to overcome this sort of issue to use another, embedded, encoding like base64.

A: try 0x19 instead :)
hexadecimal (base 16) uses 16 symbols which are 0 to 9 and A B C D E F (or a to f, which represents 10 to 15)
0x is just a prefix for numeric constants in programming languages (like C) and shells

A: I've seen similar errors occur with invalid characters in XML tag and/or attribute names.  For example, if you don't include a space when manually building up the xml,
 <tagNameattributeName="attributeValue">

would throw an error vs the intended
 <tagName attributeName="attributeValue">

Might be worth a look.