Q: What is the name of this q/kdb+ feature? Does any flavor of LISP implement it? How? The q programming language has a feature (which this tutorial calls "function projection") where a function of two or more parameters can be called with fewer parameters than it requires, but the result is an intermediate object, and the function will not be executed until all remaining parameters are passed; one way to see it is that functions behave like multi-dimensional arrays, so that (f[x])[y] is equivalent to f[x;y]. For example ...
q)add:{x+y}
q)add[42;]
{x+y}[42;]
q)add[42;][3]
45
q)g:add[42;]
q)g[3]
45

Since q does not have lexical scoping, this features become very useful in obtaining lexical scoping behavior by passing the necessary variables to an inner function as a partial list of parameters; e.g. a print parameter decorator can be constructed using this feature:
q)printParameterDecorator:{[f] {[f;x] -1 "Input: ",string x; f x}f};
q)f: printParameterDecorator (2+);
q)f 3
Input: 3
5

My questions:

*

*Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature?

*Does any variety of LISP implement this feature? Which ones?

*Could you provide some example LISP code please?

A:
Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature?

No, you usually call it partial application.

Does any variety of LISP implement this feature? Which ones?

Practically all Lisp allow you to partially apply a function, but usually you need to write a closure explicitly. For example in Common Lisp:
(defun add (x y)
  (+ x y))

The utility function curry from alexandria can be used to create a closure:
USER> (alexandria:curry #'add 42)
#<CLOSURE (LAMBDA (&REST ALEXANDRIA.1.0.0::MORE) :IN CURRY) {1019FE178B}>

USER> (funcall * 3)  ;; asterisk (*) is the previous value, the closure
45

The resulting closure is equivalent to the following one:
(lambda (y) (add 42 y))

Some functional languages like OCaml only allow functions to have a single parameter, but syntactically you can define functions of multiple parameters:
(fun x y -> x + y)

The above is equivalent to:
(function x -> (function y -> x + y))

See also What is the difference between currying and partial application?

Nb. in fact the q documentation refers to it as partial application:

Notationally, projection is a partial application in which some arguments are supplied and the others are omitted

A: I think another way doing this :
q)f:2+
q)g:{"result: ",string x}
q)'[g;f]3
"result: 5"

It is composite function, passing 3 to f, then the result from f will be passed to g.
I'm not sure if it is LISP, but it could achieve the same result.


Q: Graphics and Graphics 2D in java I am having a problem changing the color of the diamond I had created when I am using methods in java. I don't know how to inherit or to correct it by using methods. I just want it to become object oriented I don't know how to properly do it. Please help me.
package Trial;

import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    public GradientPaint gradientPaint;
    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        GradientPaint black = new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK);
        blackDiamond(g2,black);
        GradientPaint yellowOrange = new GradientPaint(50,20,Color.YELLOW,50,50,Color.RED);
        redDiamond(g2,yellowOrange);

    }

    public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        setGradientPaint(gradientPaint);
        g2.setPaint(getGradientPaint());
        fillPolygon(a,b,5,g2);
    }
    public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        setGradientPaint(gradientPaint);
        g2.setPaint(getGradientPaint());
        fillPolygon(a2,b2,5,g2);
    }

    public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){

        getGraphics().fillPolygon(a,b,c);
    }

    public GradientPaint getGradientPaint() {
        return gradientPaint;
    }

    public void setGradientPaint(GradientPaint gradientPaint) {
        this.gradientPaint = gradientPaint;
    }
}

This is the code that I try to create object-oriented but it doesn't inherit the color of gradient paint.
enter image description here
That is the result of my code
This the code that not yet create multiple methods
import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    public GradientPaint gradientPaint;
    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        g.fillPolygon(a,b,5);
        GradientPaint red = new GradientPaint(50,10,Color.RED,10,70,Color.ORANGE);
        g2.setPaint(red);
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        g.fillPolygon(a2,b2,5);

    }
}

This is the result that I want:
enter image description here
I just want to correct it to organize so that I wont declare all the local variables in paint method I just want to seperate it in different methods the problem is that the Color doesn't change. Please help me thanks a lot. :)

A: Maybe organize it like this, so that the color is easily changed:
package Trial;

import javax.swing.*;
import java.awt.*;

public class ColorRed extends JApplet {
    private GradientPaint black;
    private GradientPaint yellowOrange;

    public void init() {
        setBlack(new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK));
        setYellowOrange(GradientPaint(50,20,Color.YELLOW,50,50,Color.RED));
    }

    public setBlack(GradientPaint black) {
        this.black = black;
    }

    public setYellowOrange(GradientPaint yellowOrange) {
        this.yellowOrange = yellowOrange;
    }

    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        blackDiamond(g2,black);
        redDiamond(g2,yellowOrange);
    }

    public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a [] = {100,50,100,150,100};
        int b [] = {10,60,110,60,10};
        g2.setPaint(gradientPaint);
        fillPolygon(a,b,5,g2);
    }
    public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){
        int a2 [] = {100,60,100,140,100};
        int b2 [] = {20,60,100,60,20};
        g2.setPaint(gradientPaint);
        fillPolygon(a2,b2,5,g2);
    }

    public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){

        g2.fillPolygon(a,b,c);
    }
}

Unfortunately I didn't locate an online swing runner to test it.

A: I modified Adder's answer (which worked as advertised) so it would work without using JApplet (which is also tagged as deprecated).  I added some comments where different.

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;

    public class ColorRed extends JPanel {
       private GradientPaint black;
       private GradientPaint yellowOrange;

       JFrame                frame = new JFrame();

       public static void main(String[] args) {
          SwingUtilities.invokeLater(() -> new ColorRed().init());
       }

       public void init() {

          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          // set the panel size
          setPreferredSize(new Dimension(500, 500));
          // add panel to frame.
          frame.add(this);
          // adjust frame and subcomponents
          frame.pack();
          // center on screen
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          setBlack(new GradientPaint(50, 20, Color.BLACK, 50, 50, Color.BLACK));
          setYellowOrange(new GradientPaint(50, 20, Color.YELLOW, 50, 50, Color.RED));
       }

       public void setBlack(GradientPaint black) {
          this.black = black;
       }

       public void setYellowOrange(GradientPaint yellowOrange) {
          this.yellowOrange = yellowOrange;
       }
       // use paintComponent(g) and not  paint(g)
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          blackDiamond(g2, black);
          redDiamond(g2, yellowOrange);
       }

       public void blackDiamond(Graphics2D g2, GradientPaint gradientPaint) {
          int a[] = { 100, 50, 100, 150, 100
          };
          int b[] = { 10, 60, 110, 60, 10
          };
          g2.setPaint(gradientPaint);
          fillPolygon(a, b, 5, g2);
       }
       public void redDiamond(Graphics2D g2, GradientPaint gradientPaint) {
          int a2[] = { 100, 60, 100, 140, 100
          };
          int b2[] = { 20, 60, 100, 60, 20
          };
          g2.setPaint(gradientPaint);
          fillPolygon(a2, b2, 5, g2);
       }

       public void fillPolygon(int a[], int b[], int c, Graphics2D g2) {

          g2.fillPolygon(a, b, c);
       }
    }


Q: Linux Software Raid Rebuild on machine failure I have a debian home server that has a 4 disk software RAID 5 array. My OS runs only on a normal nvme SSD. I know thats not secure, but it is a home server, so I didn't really care when I installed it and now it is too late to change it. I was wondering what would happen to my software RAID when the OS failed (or the SSD). How could I resync (I don't know what the correct term for it is) the array to use it after I bought a new ssd and installed a new OS?
I found something regarding the mdadm config, but mine is empty... Just for clarification: this is just something I thought about to be prepared when it happens (I don't want to loose all my data)
Thanks for your answers in advance

A: What makes you think the mdadm config is empty ?
You should try the mount command to know how your volumes are mounted : mdadm devices ? LVM volumes ? Depending of the technology, the way to rebuild your volumes after a crash will be different. (My previous link is for mdadm).
The behaviour of the OS if the unmirrored SSD is faulty will depends of which files won’t be available… I have a server which a single HDD : I rebuilt it with a backup.
Usually, RAID system use metadata to verify if the disks are paired when assembling them, then adding a SSD and mirroring the first one may need an OS reinstall. This typically create the volume (and wipe it), create initramfs file to be sure the mirroring modules are available at the boot stage, etc. I don’t think there is an easy and shorter way.


Q: jquery remove everything after and including certain character I have a location - Pearl River, NY (10965) that I want displayed as Pearl River, NY (so it must delete (10965) -- including the space before ( -- I'm not looking to make a big deal of this and do anything server side. jQuery would work fine. I know this is probably simple as hell, I just don't use JS much.
Thanks!

A: location_string = location_string.replace(/ \([^)]*\)/, '');

On a side note, please stop thinking that jQuery is necessary for anything at all, especially not a string manipulation task like this. It really isn't, and jQuery is overhyped.

A: I'm not sure how you're given "Peal River NY..." (variable? innerHTML?), but you need to use a regular expression to match the (numbers), and the replace method to substitute the match for nothing "".
"Peal River, NY (10965)".replace(/ \([0-9]+\)/, "");

This doesn't use jQuery!
See the String.replace method.
As mentioned by @James in the comments, this snippet will leave "Peal River, NY ()" as "Peal River, NY ()", rather than removing the brackets. If this is a case you need to consider, change the + to *:
"Peal River, NY (10965)".replace(/ \([0-9]*\)/, "");

A: Use a regex:
var s = "Pearl River, NY (10965)";
alert(s.replace(/ \([\d]*\)/,''));

See it at this JSFiddle
Of course, here I am assuming you'll be wanting to replace only numbers in the brackets. For letter and underscore, use \w in place of \d
You might also want to make it a requirement that the item occurs at the end. In which case, the following will suffice:
alert(s.replace(/ \([\d]*\)$/,''));

You'll note that none of the above references jQuery. This is something that can be achieved with pure JavaScript.


Q: Recognize file type by content In Ubuntu 12.10 there was a nice app called Assogiate. It has ability to add new mimetype, add recognition by content of file and new icon, all done by mouse clicking. Now assogiate disappears from repos. Other programs doesn't have that ability. How to do it by hand?
For example:
I have a file test.lzx. This is a packed test file with LZX packer used mostly on Amiga. Gnome doesn't recognize it. If I test file with file command I see:
$ file test.lzx
test.lzx: LZX compressed archive (Amiga)

Recognize that type of file by content is simple. At 0 offset (at the beginning of file) there is a LZX string:
$ hexdump -C test.lzx | head -n 1
00000000  4c 5a 58 00 0c 00 0a 04  00 00 07 00 00 c0 0d 00  |LZX.............|

In Assogiate I was able to add search string and offset where Gnome have to look for this string.
Now question: how to add manually new mime type and make Gnome recognize it by file content?
Answers at

*

*How do I change the MIME type for a file?

*How are file-extensions/mime-types/icons/default applications associated?
are not related to my question.


Q: How to style a dashboard with CSS in dash and python? I don’t know much about CSS and I need help aligning these 4 smaller graphs under this larger graph. This is the closest I’ve come to being aligned.
I need the 4 smaller graphs to be aligned under the larger graph, but covering the whole page, how to do that?

my code:
fig_pick = px.pie(map_pick, values='Total', names='Map', title='Mapas com mais Picks no Valorant Champions 2022')
fig_pick.update_layout(margin=dict(l=40, r=25, t=45, b=20), height=300,  width=340 , template='darkly')

fig_ban = px.pie(map_ban, values='Total', names='Map', title='Mapas com mais Bans no Valorant Champions 2022')
fig_ban.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=340 , template='darkly')

fig_atk = px.bar(map_side, x='Map', y='Atk Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de ataque pelo Valorant Champions em %:',
            labels={
    'Atk Wins': 'Vitórias no lado de Ataque em %',
    'Map': 'Mapa'        }, text='Atk Wins')

fig_atk.update_traces(textposition='inside',texttemplate='%{text:.3s}')
fig_atk.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=360 , template='darkly')

fig_def = px.bar(map_side, x='Map', y='Def Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de defesa pelo Valorant Champions em %:',
            labels={
    'Def Wins': 'Vitórias no lado de Defesa em %',
    'Map': 'Mapa'        }, text='Def Wins')

fig_def.update_traces(textposition='inside',texttemplate='%{text:.3s}')
fig_def.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300,  width=360 , template='darkly')

app.layout = html.Div(children=[

        dbc.Row([

                dbc.Col([

                        dbc.Card([

                                 html.H5('Opcões'),
                                 dcc.Dropdown(opcoes, value = 'ACS' , id='check_opcao', style={'width': '100%'}),

                        ],style={'height': '94vh', 'margin': '20px', 'padding': '20px', 'width': '300px'})

                ], sm=2),

                dbc.Col([

                        dbc.Row([dcc.Graph( id='grafico_gc_players', style={ 'width': '1100px'})], style={ 'margin': '20px', 'margin-right': '70px'}),
                        dbc.Row([
                                dbc.Col([dcc.Graph(id='map_pick', figure=fig_pick)], sm=3),
                                dbc.Col([dcc.Graph(id='map_ban', figure=fig_ban)], sm=3),
                                dbc.Col([dcc.Graph(id='map_side_atk', figure=fig_atk )], sm=3),
                                dbc.Col([dcc.Graph(id='map_side_def', figure=fig_def )], sm=3)
                        ])

                ],sm=10)
        ])


Q: how to convert webp image to jpeg or png by using intervention image laravel I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket.

A: Firstly we can use Intervention Image library. We must have php 7 and gd library installed. I am writing the commands to install gd library and webp library below (for ubuntu) :
sudo apt-get update
sudo apt-get install webp
sudo apt-get install php7.0-gd (check php version and then install accordingly)

now check file extension and if extension is webp, select your output file extension
$extension = $this->file->extension();

if($this->file->getMimeType() == 'image/webp'){
    $extension = 'png';
}
// Generate a random filename
$fileName = time() . '_' . strtolower(uniqid()) . '.' . $extension;

Now encode the image to desired format
if($this->file->getMimeType() == 'image/webp'){
    $image = $image->encode($extension);
}
$image = $image->stream();

Now upload the image to s3 bucket
Storage::disk('s3')->put($folderName . '/' . $fileName, $imageNormal->__toString());


Q: Intellij SBT project: How to change the content roots? This is the current content root configuration in my project:

However, I want the "scala" directory to be the actual test content root, and not the directory named "test". If I modify it, I get the warning that "Module is imported from Sbt. Any changes in its configuration will may be lost after re-importing." (and, indeed, they are).

Unfortunately, I couldn't find where in my Build.scala file (or any other file) this configuration is declared. What I can do to once and for all convince IntelliJ that "scala" is the correct test content root?
This is my Build.scala file (this is a Play 2.5.4 project if it matters):
import play.routes.compiler.StaticRoutesGenerator
import play.sbt.PlayScala
import play.sbt.routes.RoutesKeys._
import sbt.Keys._
import sbt._

object Build extends Build {
  val main = Project("Mp3Streamer", file(".")).enablePlugins(PlayScala).settings(
    scalaVersion := "2.11.8",
    version := "1.0-SNAPSHOT",
    addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full),
    libraryDependencies ++= Seq(
      // a bunch of dependencies
    ),

    resolvers += Resolver.mavenLocal,
    javaOptions ++= Seq("-Xmx4000M", "-Xms2024M", "-XX:MaxPermSize=2000M"),
    routesGenerator := StaticRoutesGenerator
  )
}

A: By adding scalaSource in Test := baseDirectory.value / "test" "/scala", to my Build.scala file, I've been able to make the "scala" folder a test source, but the parent "test" folder was still also a test source:

As far as I could tell, this is a setting inherited from Play, since if I removed the .enablePlugins(PlayScala) code, the "test" folder stops being a test source. Following the instructions in https://www.playframework.com/documentation/2.5.x/Anatomy#Default-SBT-layout, I disabled the play layout, and then manually added the source and resource directories, which I copied from https://github.com/playframework/playframework/blob/master/framework/src/sbt-plugin/src/main/scala/play/sbt/PlayLayoutPlugin.scala#L9, only modifying the test source, and adding my own resource folders. My modified Build.scala file is now:
val main = Project("Mp3Streamer", file("."))
      .enablePlugins(PlayScala)
      .disablePlugins(PlayLayoutPlugin)
      .settings(
           target := baseDirectory.value / "target",

           sourceDirectory in Compile := baseDirectory.value / "app",
           // My change
           sourceDirectory in Test := baseDirectory.value / "test" / "scala",

           resourceDirectory in Compile := baseDirectory.value / "conf",

           scalaSource in Compile := baseDirectory.value / "app",
           // My change
           scalaSource in Test := baseDirectory.value / "test" / "scala",
           // I've added this resource
           resourceDirectory in Test := baseDirectory.value / "test" / "resources",

           javaSource in Compile := baseDirectory.value / "app",

           sourceDirectories in(Compile, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Compile).value),
           sourceDirectories in(Test, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Test).value),

           // sbt-web
           sourceDirectory in Assets := (sourceDirectory in Compile).value / "assets",
           sourceDirectory in TestAssets := (sourceDirectory in Test).value / "assets",

           resourceDirectory in Assets := baseDirectory.value / "public",

           // Native packager
           sourceDirectory in Universal := baseDirectory.value / "dist",

           // Everything else is the same as the original Build.scala file

Honestly, this feels so hacky that I'll probably end up modifying my directory structure to match Play's default... But it's the principle that counts!


Q: Why did I lose data when I change the orientation of camera doing crop image? I'm doing an app that takes an image from camera and crop it after, but some how i'm losing the objects of my activity and when it comes back i get NullPointerExeception, on OnCreate method of it. But when i choose an image from gallery it works fine, because it does not close the activity.
public void onClick(DialogInterface dialog, int item) {
    if (items[item].equals("Camera")) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PICK_FROM_CAMERA);
    } else if (items[item].equals("Galeria")) {

        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        // ******** code for crop image
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("max-height", 800);
        intent.putExtra("max-width", 800);
        intent.putExtra("return-data", true);
        intent.putExtra("scaleType", "centerCrop");
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        try {
             startActivityForResult(Intent.createChooser(intent,
             "Complete action using"), Constants.PICK_FROM_GALLERY);
        } catch (ActivityNotFoundException e) {
        }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Bitmap tempImage;
    OutputStream fOut = null;

    File root = new File(Environment.getExternalStorageDirectory()
            + File.separator);

    try {
        File sdImageMainDirectory = new File(root, "foto.jpg");
        fOut = new FileOutputStream(sdImageMainDirectory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (requestCode == Constants.PICK_FROM_CAMERA) {
        root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        saveBitmap(photo, Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        try{
            cropCapturedImage(Uri.fromFile(root));
        }catch(ActivityNotFoundException aNFE){
            //display an error message if user device doesn't support
            String errorMessage = "Desculpe, seu dispositivo não suporta Crop!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    if (requestCode == Constants.PICK_FROM_GALLERY && data != null) {
        Bundle extras2 = data.getExtras();
        if (extras2 != null) {
            Bitmap photo = extras2.getParcelable("data");
            this.photo.setImageBitmap(photo);

            this.photo.buildDrawingCache();
            tempImage = this.photo.getDrawingCache();

            try {
                tempImage.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                BasicUserPerson.getInstance().setPhotoPath(
                        Environment.getExternalStorageDirectory()
                        + File.separator + "foto.jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //user is returning from cropping the image
    else if(requestCode == Constants.PIC_CROP && data != null){
        //get the returned data
        Bundle extras = data.getExtras();
        if (extras != null){

            Bitmap thePic = (Bitmap) data.getExtras().get("data");
            saveBitmap(thePic, Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");

            photo.setImageBitmap(thePic);
            BasicUserPerson.getInstance().setPhotoPath(
                    Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");
        }
    }
}

public void saveBitmap(Bitmap photo, String path) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File f = new File(path);
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void cropCapturedImage(Uri picUri){
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(picUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    cropIntent.putExtra("outputX", 256);
    cropIntent.putExtra("outputY", 256);
    cropIntent.putExtra("return-data", true);
    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(cropIntent, Constants.PIC_CROP);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dados_pessoais);

    fullName = (EditText) findViewById(R.id.edtFullName);
    cpf = (EditText) findViewById(R.id.edtCpf);
    email = (EditText) findViewById(R.id.edtDadEmail);
    ddd = (EditText) findViewById(R.id.edtDadDDD);
    telefone = (EditText) findViewById(R.id.edtDadTele);
    ddd2 = (EditText) findViewById(R.id.edtDadDDD2);
    celular = (EditText) findViewById(R.id.edtDadTel);
    btSalvar = (ImageView) findViewById(R.id.imgSalvar);
    head = (ImageView) findViewById(R.id.imgDadosHead);
    sexo = (Spinner) findViewById(R.id.spnSex);
    birthday = (EditText) findViewById(R.id.edtBrithday);
    civil = (Spinner) findViewById(R.id.spnCivil);
    loadingCity = (ImageView) findViewById(R.id.imgLoadingCity);
    escolaridade = (Spinner) findViewById(R.id.spnEscolaridade);
    cep = (EditText) findViewById(R.id.edtCep);
    state = (Spinner) findViewById(R.id.spnState);
    city = (Spinner) findViewById(R.id.spnCity);
    endereco = (EditText) findViewById(R.id.edtEndereco);
    bairro = (EditText) findViewById(R.id.edtBairro);
    num = (EditText) findViewById(R.id.edtNum);
    comp = (EditText) findViewById(R.id.edtComp);
    photo = (ImageView) findViewById(R.id.imgPhoto);

    btSalvar.setOnClickListener(this);
    photo.setOnClickListener(this);

    //Line of error
    if (!User.getInstance().getFullName().equals("null") && !User.getInstance().getFullName().equals("")){
        fullName.setText(User.getInstance().getFullName());
    }
    if (!BasicUserPerson.getInstance().getPersonRegistration().equals("null") && !BasicUserPerson.getInstance().getPersonRegistration().equals("")){
        cpf.setText(BasicUserPerson.getInstance().getPersonRegistration());
    }
    if (!User.getInstance().getEmail().equals("null") && !User.getInstance().getEmail().equals("null")){
        email.setText(User.getInstance().getEmail());
    }
    email.setKeyListener(null);
    if (!BasicUserPerson.getInstance().getMobilePhone().equals("null") && !BasicUserPerson.getInstance().getMobilePhone().equals("")){
        String tel = BasicUserPerson.getInstance().getMobilePhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd.setText(tel.subSequence(0, 2));
        celular.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getPhone().equals("null") && !BasicUserPerson.getInstance().getPhone().equals("")){
        String tel = BasicUserPerson.getInstance().getPhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd2.setText(tel.subSequence(0, 2));
        telefone.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getBirthday().equals("null") && !BasicUserPerson.getInstance().getBirthday().equals("")){
        birthday.setText(BasicUserPerson.getInstance().getBirthday());
    }
    if (!BasicUser.getInstance().locationObj.getZipCode().equals("null") && !BasicUser.getInstance().locationObj.getZipCode().equals("")){
        cep.setText(BasicUser.getInstance().locationObj.getZipCode());
    }
    if (!BasicUser.getInstance().locationObj.getAddress().equals("null") && !BasicUser.getInstance().locationObj.getAddress().equals("")){
        endereco.setText(BasicUser.getInstance().locationObj.getAddress());
    }
    if (!BasicUser.getInstance().locationObj.getNeighborhood().equals("null") && !BasicUser.getInstance().locationObj.getNeighborhood().equals("")){
        bairro.setText(BasicUser.getInstance().locationObj.getNeighborhood());
    }

}

And it outputs:
  12-15 21:22:55.002: E/AndroidRuntime(2263): FATAL EXCEPTION: main
    12-15 21:22:55.002: E/AndroidRuntime(2263): Process: br.com.inradar, PID: 2263
    12-15 21:22:55.002: E/AndroidRuntime(2263): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.inradar/br.com.inradar.activities.DadosPessoais}: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Handler.dispatchMessage(Handler.java:102)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Looper.loop(Looper.java:136)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invoke(Method.java:515)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at dalvik.system.NativeStart.main(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263): Caused by: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at br.com.inradar.activities.DadosPessoais.onCreate(DadosPessoais.java:176)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Activity.performCreate(Activity.java:5275)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     ... 11 more

A: Are you using in this way
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    if(resultCode == RESULT_OK) {
          // stub here
          }
        }
       }


Q: geofacet package in R adding labels to bar graphs in geofacets I recently discovered the geofacet package in R. Amazing.  I have 5 years worth of data for each state.  I have horizontal bars in each facet.  I am trying to figure out how to add a simple label that shows the value of each bar in each graph such that it sits off to the right of the bar or right side of the facet. I have tried geom_text and a number of code lines but nothing seems to add the labels for each bar in each facet.
Below is my code to make the geofacet of the US.  Not sure where to add the label code either.
Any help is greatly appreciated.  This is my last step to complete this awesome map.
ggplot(Alabamatest, aes(YEAR, SALES, fill = YEAR)) +
  geom_bar(alpha=1, width = .75,
    aes(color =TYPE, fill=TYPE),
    stat = "identity", position = position_stack(reverse = TRUE)
  ) +
  scale_color_manual(values = c("firebrick1", "cornflowerblue"))+
  scale_fill_manual(values = c("firebrick1", "cornflowerblue"))+
  ylim(0,9
  )+
  coord_flip() +
  theme_bw()+
  facet_geo(~ state, grid= "us_state_grid4", label ="SALES")+
  scale_y_continuous(expand = c(0, 0)) +
  labs(title = "2019 State Average Sales",
       caption = "Data Source: Year End Data",
       x = NULL,
       y = "Percentage of Voters") +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.text.x = element_text(size = 6))

I am adding some test data to run with the code.  I am not sure how to add a simple data frame so I have typed it out here.  I am brand new to Stackoverflow.   Apologies if this is not the correct way to present data
state    name    YEAR    SALES    TYPE
AL     ALABAMA    2019     2       POS
AL     ALABAMA    2018     1.5     POS
AL     ALABAMA    2017     1.4     NEG
AL     ALABAMA    2016     1.7     NEG
AZ     ARIZONA    2019     3       POS
AZ     ARIZONA    2018     3       POS
AZ     ARIZONA    2017     2       POS
AZ     ARIZONA    2016     3.4     POS
AZ     ARIZONA    2015     5       POS

The two states create bar graphs.   I want to be able to add the sales label to the right side of the bar graph for each year.


Q: Question about Pauli Matrices I found the following identities about Pauli matrices from the lecture notes of Supersymmetry.
$$((\sigma^{\mu})^{\alpha\dot{\alpha}})^{\ast}=(\bar{\sigma}^{\mu})^{\dot{\alpha}\alpha}$$
$$((\sigma_{\mu\nu})^{\alpha}_{\,\,\,\beta})^{\ast}=-(\bar{\sigma}_{\mu\nu})_{\dot{\beta}}^{\,\,\,\dot{\alpha}}$$
$$((\sigma_{\mu\nu})^{\alpha\beta})^{\ast}=(\bar{\sigma}_{\mu\nu})^{\dot{\alpha}\dot{\beta}}$$
Please give me some hints on how to derive the above identities.

For the first identity, if we take $\mu=0$, then $\sigma^{0}\equiv 1$, which is real. Then, the identity says
$$(1^{\alpha\dot{\alpha}})^{\ast}=-1^{\dot{\alpha}\alpha}.$$
Why does the complex conjugation acting on this identity matrix $1_{2\times 2}$ exchange the two spinorial indices? Where does the minus sign come from?

A: Remember that $\bar{\sigma}^{\mu \dot{a}b}=(1,-\vec{\sigma})^{\dot{a}b}$
And
$(\sigma^{\mu b \dot{a}})^*=\bar{\sigma}^{\mu \dot{a}b}$
Taking $\mu=0$, would simply yield
$1=1$
from the definition.


Q: How to set up these ratios? Here's a question while reading my textbook:

For about 10 years after the French Revolution, the French government
  attempted to base measures of time on multiples of ten: One week
  consisted of 10 days, one day consisted of 10 hours, one hour
  consisted of 100 minutes, and one minute consisted of 100 seconds.
  What are the ratios of (a) the French decimal week to the standard
  week and (b) the French decimal second to the standard second? Assume
  that the definition of a "day" remains the same.

The problem is, I have a very shaky foundation in Algebra and this is a Physics class.  From Cal+ I'm fine, but setting up basic stuff using Algebra is hard for me.  Any idea how I would set this up?  I'm not looking for an answer I'm looking for some help understanding how this should done.  Thank you.

A: One standard week is 7 days.  One French revolutionary week is 10 days.  Thus
$$\frac 1 {10}\text{ French weeks} = 1\text{ day} = \frac 1 7\text{ standard weeks}.$$
Multiply both sides by 10 to get
$$1\text{ French week} = \frac {10} 7\text{ standard weeks}$$
or
$$\frac{1 \text{ French week}}{1 \text{ standard week}} = \frac {10} 7.$$
One day is $60 \times 60 \times 24 = 86400$ standard seconds, or $100 \times 100 \times 10 = 100000$ French revolutionary seconds.  Can you find the rest of the answer yourself from here?

A: the french decimal weak & the standard weak.
ratio of french decimal weak & standard weak=10:7
                                             =(10)(10)(100)(100)/(7)(24)(60)(60)
                                             =1.6534answer
ratio of french decimal second to the standard sec.
                                              100:60
                                              50:30
                                              25:15
                                              5:3answer
MuhAmmAD AhsAn MInhAs [0314-3875700]

A: Here our constant for the calculation is a "DAY". so we ahave to be able to change our measurments in a "DAY".

*

*Ratio of a French decimal week(W') to standard week(W)\
     1W'= 10 DAYS,        1W= 7 DAYS

Ratio= 1W'/1W = 10DAYS/7DAYS ~ 1.43-------------------------------ANSWER

*Ratio of a French decimal second(S') to standard second(S)
    1 DAY = 10 * 100 * 100 S',      1DAY = 24 * 60 * 60 S
       1DAY= 100000 S'                1DAY =86400 S

Now lets calculate the value of S' and S interms of a "DAY".
       1 DAY =100000 S'               1DAY = 86400 S
         ?   =   1 S'                  ?   =   1 S
      1 S' = 1/100000 DAY            1 S = 1/86400 DAY

Ratio = 1S'/1S  =  1/100000 DAY ÷  1/86400 DAY = 0.864--------------ANSWER.
ANY KIND OF COMMENT IS WELCOME.

A: There are slightly less than 16% more "ticks" on a French Revolutionary clock, (during one complete revolution of our planet ), than on the Standard Time clocks. Therefore; the actual "duration" of time between ticks, must be shorter on the French clock.(0,864), as compared to (1.000, on the Standard clock. Observation of both clocks together, will bear the above as truthful. Keep in mind. 16% is quite subtle when watching side by side ticking clocks. That tests, ones ingenuity & patients. Have fun.


Q: How much does minifying reduce file size? In a React app, is it possible to find out how much Webpack's minification reduces the project's size excluding all the dependencies and packages not written by the project's developer?
My build/static/ directory is currently bigger than my src directory and I believe it is because code from the dependencies is also minified with the files of interest. Where could I find something to approximately compare my src directory size to?

A: I built the project with npm run build to find out how large the output is with minimization enabled.
Then I edited node_modules/react-scripts/config/webpack.config.js and changed line 189 (the line with the minimize property) from:
...
    optimization: {
      minimize: isEnvProduction,
      minimizer: [
...

to:
...
    optimization: {
      minimize: false,
      minimizer: [
...

to disable minimization.
Then built the project again to find out its size without minimization.
You can compare the built file sizes manually to find out their difference, but you will also get a nice output to the terminal when building the second time:
File sizes after gzip:

  613.36 KB (+504.48 KB)  build\static\js\2.0ddf8239.chunk.js
  60.24 KB (+20.01 KB)    build\static\js\main.8e9dd59c.chunk.js
  4.73 KB (+457 B)        build\static\css\main.aaaa4d7d.chunk.css
  1.66 KB (+933 B)        build\static\js\runtime~main.7f8cc4df.js

Notice the differences stated in parantheses.


Q: Memory issue when create a diagonal numpy array I have created a diagonal numpy array:
a = numpy.float32(numpy.random.rand(10))
a = numpy.diagonal(a)

However, I face MemoryError since my matrix is extremely large. Is there anyway to save the memory?

A: The best way to handle this case is to create a sparse matrix using scipy.sparse.diags as follows:
a = numpy.float32(numpy.random.rand(10))
a = sparse.diags(a)

If the shape of your diagonal numpy array is n*n, utilizing sparse.diags would result in a matrix n times smaller. Almost all matrix operations are supported for sparse matrices.


Q: auditctl - logging the CPU or identifier of pthread that invoked the system call auditctl is a great utility for monitoring many things, such as executed system calls.
I would ideally like to know either the CPU or the POSIX thread that instantiated each recorded system call. In the log, I see:
type=SYSCALL msg=audit(1561851079.335:286): arch=c000003e syscall=9 success=yes exit=140507297914880 a0=0 a1=1000 a2=3 a3=22 items=0 ppid=22818 pid=24283 auid=1005 uid=1005 gid=1005 euid=1005 suid=1005 fsuid=1005 egid=1005 sgid=1005 fsgid=1005 tty=pts0 ses=89 comm="my_benchmark" exe="my_benchmark" key=(null)

I don't think any of these do the trick, unless I'm missing something. Does anyone know if what I want is possible? Thanks.

A: Piping your audit line through ausearch -i at least gets the most information out of it:
» echo "type=SYSCALL msg=audit(1561851079.335:286): arch=c000003e syscall=9 success=yes exit=140507297914880 a0=0 a1=1000 a2=3 a3=22 items=0 ppid=22818 pid=24283 auid=1005 uid=1005 gid=1005 euid=1005 suid=1005 fsuid=1005 egid=1005 sgid=1005 fsgid=1005 tty=pts0 ses=89 comm="my_benchmark" exe="my_benchmark" key=(null)" | ausearch -i
----
type=SYSCALL msg=audit(06/30/2019 01:31:19.335:286) : arch=x86_64 syscall=mmap success=yes exit=140507297914880 a0=0x0 a1=0x1000 a2=PROT_READ|PROT_WRITE a3=MAP_PRIVATE|MAP_ANONYMOUS items=0 ppid=22818 pid=24283 auid=unknown(1005) uid=unknown(1005) gid=dovenull euid=unknown(1005) suid=unknown(1005) fsuid=unknown(1005) egid=dovenull sgid=dovenull fsgid=dovenull tty=pts0 ses=89 comm=my_benchmark exe=my_benchmark key=(null)

AFAIK, the thread ID is only recorded for kernel-generated syscalls and is then placed in the pid field. Reference: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security_guide/app-audit_reference under pid:

The pid field semantics depend on the origin of the value in this field.
  In fields generated from user-space, this field holds a process ID.
  In fields generated by the kernel, this field holds a thread ID. The thread ID is equal to process ID for single-threaded processes. Note that the value of this thread ID is different from the values of pthread_t IDs used in user-space. For more information, see the gettid(2) man page.

I know no way of auditing thread ID's for user generated syscalls.


Q: Check Printing With EC13B Font in PDFLaTeX I have made a template for printing checks from blank check stock but I am stuck on printing the MICR E-13B font at the bottom. I have found the true type font here. I am using PDFLaTeX but can't seem to find any information on specifying a font with anything other than XeLaTeX. Is this possible with PDFLaTeX?
The numbers at the base of the check are mostly static (account and routing number) but the check number is dynamic so that rules out a work around of simply positioning a pre-made EPS.

A: I have fond memories of those font conversion times... I have downloaded and unzipped the ZIP file into my working directory and I ran (I'm sorry, I haven't polished the 8r.enc file from the TeX distribution in any way, so there are some warning messages about missing letters):

afm2tfm GnuMICR.afm GnuMICR.tfm
  pdflatex mal-ec13B.tex

The main TeX file looks like this:
%! pdflatex mal-ec13B.tex
\pdfmapline{+GnuMICR GnuMICR <8r.enc <GnuMICR.ttf}
\documentclass[a4paper]{article}
\pagestyle{empty}
\begin{document}
\font\malfont=GnuMICR % setting the font
Text before {\malfont % loading the font
A B 12345 67890 C D} text after. % using the font
\end{document}


Q: Efficient computation of matrix exponential of trace zero matrix I am looking for identities that may help with numerical computation of the matrix exponential ${\rm exp}(A)$ where ${\rm tr}(A)=0$. I am already aware of general-purpose algorithms for computing the matrix exponential.
I am particularly interested in the case where $A \in \mathbb{R}^{3 \times 3}$.

A: From the trace condition and Cayley-Hamilton it follows that the powers of $A$  satisfy a recurrence of the form
$$A^{n+3}= cA^{n+1}+(\det A) A^n$$,
for some explicit  constant $c$. You actually need to compute  the matrices $B_n=\frac{1}{n!} A^n$. From the above recurrence you deduce
$$(n+3)! B_{n+3}= c(n+1)! B_{n+1} + n! B_n, $$ from which you get the recurrence
$$B_{n+3}=\frac{c}{(n+2)(n+3)}B_{n+1}+ \frac{\det A}{(n+1)(n+2)(n+3)} B_n. $$
Once you've computed $A^2$ and thus, $B_2$, you're in bussiness.


Q: When is the appropriate moment in rotation to change the Layout parameters of a UICollectionView Hopefully a simple question for a relatively new UIKit control
I have a UICollectionView that has a viewLayout with a single row of cells that are the exact height of the UICollectionView bounds in Portrait mode
Therefore, when the iPad is flipped to Landscape mode, that row becomes taller than the screen itself, at which point the layout (almost) silently fails and complains that the row is taller than the bounds.
What is the ideal way to manipulate the characteristics of the viewLayout, particularly as it relates to responding to rotation in a ViewController?

A: I'm working on a similar problem.
Currently, my UICollectionViewController has two instance variables of UICollectionViewFlowLayout, each with the appropriate insets for portait or landscape.
On rotation, I do this:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration{

    if (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) {
        [_itemCollection setCollectionViewLayout:_portraitLayout];
        [_itemCollection reloadData];
    } else {
        [_itemCollection setCollectionViewLayout:_landscapeLayout];
        [_itemCollection reloadData];
    }
}

The only problem that I'm having is that it randomly crashes with exc_bad_access on setCollectionViewLayout randomly.
Something like the above might work for you. I'm not sure if this is the right way to do things. I have only recently started using UICollectionViews.


Q: Python PyAutoGUI (automatic mouse macro) I want to display the (x.y) coordinates of the mouse found using "pyautogui.position()" on the window. What command should I use in this case?

A: If you want to print out the x,y mouse positions, you can use .position() like so:
print(pyautogui.position())

It will output something like (346, 653) (the numbers will be different, and this is just an example) where the first value is the x coordinate of the cursor, and the second value being the y coordinate.


Q: React Router v4 - How to dynamically use layouts To start, I'm both new to React and React-Router. I know the basics of each. Here is my scenario...
I want to have a separate login page with NO layouts at route (/login). When the user logs in, I want to route them to /home. This home page and every other page (beside login) will reuse a layout that contains a navbar and a sidebar.
How do I hide the reusable layout when the user visits the /login route? Do I use a conditional or is there a specific React-Router 'WAY'? I couldn't find examples in the documentation that fit my scenario.
Thanks a bunches!

A: If you are asking how could I render navbar and sidebar to all components except login, then you can check the browser url.
There are many ways of doing this, but one of which is like following:
<Route path="*" render={props => <Layout {...props} />} />

This will appear for all your routes now. Then inside Layout, you can check the route, and only render something if the route does not equal to login.
render(){
  if(this.props.location === "login"){return null}
  ...
}

While typing this, you can do it directly in React Router, maybe excluding certain route.


Q: wakeonlan and etherwake don't work My goal is to wake up my PC.
I have connected my Raspberry Pi directly through LAN to my PC. I have installed etherwake and wakeonlan, and both commands failed.
Well, actually it didn't really fail, on the contrary: it said it succeeded but my PC was still off and sleepy!
How I have found the mac address of my PC:

Also rechecked with:

I tried those two commands:
 sudo wakeonlan <my mac address>

Outputs:
 Sending magic packet to 255.255.255.255:9 with 00:25:xx:xx:xx:xx

and I get my console back (without anything happening),
and
 sudo etherwake <my mac address>

didn't work. I got my console back without any warnings/succeed or something else.
Then I tried this command
sudo etherwake <my mac address> -D

Output:
 The target station address is 0:25:xx:xx:xx:xx.
 Packet is ff ff ff ff ff ff 00 25 xx xx xx xx 08 etc. etc.
 Sendto worked ! 116

Can someone help me?
This is my motherboard:
asrock-z68-extreme4-gen3
Oh, and yes! Boot from onboard LAN is enabled!! I checked this like 10 times for now.

A: Once you've got WOL enabled in the target system's BIOS, check that wake on LAN is enabled in its OS. In Linux, this can be done with following the command (on the target system):
sudo ethtool <NIC> | grep "Wake"

Where <NIC> is an interface name like eth0. The output should look something like the following:
Supports Wake-on: g
Wake-on: g

If the output for Supports Wake-on doesn't contain the letter g either your hardware or driver is incompatible. If it does contain g and if the output for Wake-on contains d but not g, you should be able to enable WOL with the following command:
sudo ethtool -s <NIC> wol g

Note that this setting doesn't survive reboots, so you'll have to stash the command (minus the sudo) someplace where it will be executed on boot such as /etc/network/interfaces (which will also persist through ifdown/ifup cycles) or /etc/rc.local.
Now you should be able to wake the system from elsewhere with the wakeonlan command.
Reference:
Ubuntu Help: Wake on LAN


Q: Google Maps API-Key in gmaps4rails Why don't I have to supply my own gmaps-api-key in gmaps4rails?

A: Actually, you don't need the API key because, Google Maps Javascript API V3 is used there.
Only Google maps Javascript V2 requires an api-key, and it's deprecated now.


Q: Java regex for word with dot I need to a regex to validate a string like "foo.com". A word which contains a dot. I have tried several but could not get it work.
The patterns I have tried:

*

*(\\w+\\.)

*(\\w+.)

*(\\w.)

*(\\W+\\.)
Can some one please help me one this.
Thanks,

A: Use regex with character class
([\\w.]+)

If you just want to contain single . then use
(\\w+\\.\\w+)

In case you want multiple . which is not adjacent then use
(\\w+(?:\\.\\w+)+)

A: To validate a string that contains exactly one dot and at least two letters around use match for
\w+\.\w+

which in Java is denoted as
\\w+\\.\\w+

A: This regex works:
[\w\[.\]\\]+
Tested for following combinations:
foo.com
foo.co.in
foo...
..foo

A: I understand your question like, you need a regex to match a word which has a single dot in-between the word (not first or last).
Then below regex will satisfy your need.
^\\w+\\.\\w+$


Q: Restricting one view on Flask-Admin? I have a single file for a Flask application, views.py.
Inside views.py, I have the setup for Flask-Admin and the corresponding sqlalchemy database here:
db = SQLAlchemy(flaskapp)

def build_db():

import random
import datetime

db.drop_all()
db.create_all()

# Create sample Users
testuser = []
testgroup = []
testlevel = []

user_list = []
for i in range(len(testuser)):
    user = User()
    user.testuser = testuser[i]
    user.testlevel = testlevel[i]
    user.testgroup = testgroup[i]

    user_list.append(user)
    db.session.add(user)

for user in user_list:
    entry = random.choice(sample_text)  # select text at random
    post = Post()
    post.user = user
    post.title = entry['title']
    post.text = entry['content']
    tmp = int(1000*random.random())  # random number between 0 and 1000:
    post.date = datetime.datetime.now() - datetime.timedelta(days=tmp)
    post.tags = random.sample(tag_list, 2)  # select a couple of tags at random
    db.session.add(post)

db.session.commit()
return

# Create models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    testuser = db.Column(db.String(100))
    testgroup = db.Column(db.String(100))
    testlevel = db.Column(db.String(100))

# Required for administrative interface. For python 3 please use __str__ instead.
def __repr__(self):
    return self.testuser

class UserInfo(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    key = db.Column(db.String(64), nullable=False)
    value = db.Column(db.String(64))

    user_id = db.Column(db.Integer(), db.ForeignKey(User.id))
    user = db.relationship(User, backref='info')

def __repr__(self):
    return '%s - %s' % (self.key, self.value)

### Attempt at doing something...
class MyView(ModelView):
    @expose('/admin/userview', methods=('GET', 'POST'))
    def adminview():
        return "yes"
##ADMIN
admin = Admin(flaskapp, name="Test Aptly")
admin.add_view(MyView(User, db.session))

The Question.
How do I block access to the "/admin/userview" page depending on what level the user is (defined with the database "testlevel")? Users have 3 qualities, An example for two users would be:
testuser          testgroup        testlevel

joe               it               admin

john              dev              basic

How would I restrict the admin page to only let people with testlevel="admin"?
Do I use Flask-Security? Flask-Principal? If so, how? I've been tinkering with both for a little bit and I haven't gotten anything working so far.
Here's an example "/admin/userview" looks like: example Flask-Admin

First of all, you can use various class-level properties to configure
  what should be displayed and how. For example, column_list can be used
  to show some of the column or include extra columns from related
  models.
For example:

class UserView(ModelView):
    # Show only name and email columns in list view
    column_list = ('name', 'email')

    # Enable search functionality - it will search for terms in
    # name and email fields
    column_searchable_list = ('name', 'email')

    # Add filters for name and email columns
    column_filters = ('name', 'email')

Alternatively, you can override some of the ModelView methods and
  implement your custom logic.
For example, if you need to contribute additional field to the
  generated form, you can do something like this:

class UserView(ModelView):
    def scaffold_form(self):
        form_class = super(UserView, self).scaffold_form()
        form_class.extra = wtf.TextField('Extra')
        return form_class

Check flask.ext.admin.contrib.sqlamodel documentation for list of
  configuration properties and methods. Thanks!

A: I'll assume that you subclassed BaseView to create your admin view and that you are using Flask-login.
Then override the is_accessible method in your view class, to check the current user's quality:
from flask.ext.admin.base import BaseView
from flask.ext.login import current_user

class MyView(BaseView):
    def is_accessible(self):
        return current_user.testlevel == 'admin'

Hope this helps!


Q: The method in the type is not applicable for the arguments (even though they are?!) I'm trying to call a method using parameters that definitely match my args, yet I get this error...

The method getAdministratablePaging(Long, ContentFilter, int, int, Integer, Integer) in the type ContentService is not applicable for the arguments (Long, ContentFilter, int, int, Integer, Integer)

The code is...
ResultPage knowledgeCenters = _kcs.getAdministratablePaging(ContentConstants.KNOWLEDGE_ROOT, filter, 0, Constants.COUNT_ALL, ContentConstants.COLUMN_SIZE, Constants.SORT_ORDER_ASCENDING);

I'm working in Eclipse and have tried Clean and rebooting the IDE. Suggestions much appreciated!

A: Just putting my comment as an answer in case it can help somebody seeing this question in the future.
When you see a message like this, then the only possibility is that there are multiple types of one of the parameter objects. In this case, @nscoppin had two different definitions for ContentFilter. Either import the correct one, or use the fully qualified name in the method call, ie
someMethod(com.packageA.subPackage.ContentFilter);


Q: what is the dpdk0's effect in ovs-dpdk? today i get other guy's confiuration about ovs-dpdk,the config file is below:
dpdk-devbind –s
dpdk-devbind --force --bind=ixgbe 0000:81:00.0
dpdk-devbind --force --bind=ixgbe 0000:81:00.1
dpdk-devbind --force --bind=igb_uio 0000:81:00.0
dpdk-devbind --force --bind=igb_uio 0000:81:00.1
ovs-vsctl del-port br-eth6 eth6
ovs-vsctl del-port br-eth9 eth9
ovs-vsctl  -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1

the config file describe about take eth6 and eth9 ethernet interface to ovs bridge br-eth6 and br-eth9 but i wonder to know why set interface dpdk0's type to dpdk ? Does the port dpdk0 is a specific port or something else?
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

A: Based on the comments discussion, the problem turned out to be the configuration file sequence. Recommend approach of removing the Kernel Ports, then binding with dpdk compatible driver works
ovs-vsctl del-port br-eth6 eth6
ovs-vsctl del-port br-eth9 eth9
dpdk-devbind –s
dpdk-devbind --force --bind=ixgbe 0000:81:00.0
dpdk-devbind --force --bind=ixgbe 0000:81:00.1
dpdk-devbind --force --bind=igb_uio 0000:81:00.0
dpdk-devbind --force --bind=igb_uio 0000:81:00.1
ovs-vsctl  -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1
ovs-vsctl  -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1


Q: GreG nested templates We need to nest templates in the main template. The nested template should be able to display fields that the customer can fill. For example, there are two attachments to this message. The file 1.jpg: In this picture you can see how it displays a button with the plus sign. It has a red arrow. When I press the button it shows a nested template. In this template I can fill the event type and a path field, and nothing else. In our case we need to display fields that the user can fill, and the option of add more templates nested within the nested template. In the picture 2.jpg you can see the result that we need. This image 2 shows a red arrow that point to a green button. If you press the green button it displays another nested template. In this template you can fill in more fields. In addition you have another green button to nest another template.
Summarizing we need to create complex templates, that is, templates included in a main template.

A: If you mean RXT nesting by nested templates, WSO2 Governance Registry does not support nested RXTs as of now.


Q: QGIS boundaries of many collected polygons QGIS 3.4 LTR
I have a layer with many polygons.
I want 2 symbols for them in this layer :

*

*The first is one color for all (ok...).

*the second is the boundary of the polygons grouped by an attribute, using the generator of geometry
So, Here's the start :

I would like

I tried
exterior_ring(collect($geometry, group_by:='nom_dept')) and    boundary(collect($geometry, group_by:='nom_dept'))
But it does not work. Any idea ?

A: I recommend that you do not do it that way.
If the data of the source layer does not change frequently, it would be best to dissolve the features of the original layer by creating a new layer; style that layer and move on. This is the best solution in terms of rendering speed.
If the shapes of the polygons or the value of the grouping field usually change, then a little performance can be sacrificed in order to have a virtual layer, wich is updated immediately every time a modification in some of the original features is produced. Again, apply the style to the virtual layer. After that, be careful not to change the name of the original layer or grouping field.
But let's go into detail about the idea of styling a layer aggregating geometries with the geometry generator:

*

*The collect function aggregates, in this case, the geometries of all the features of the layer, grouping them by the value of the feature attribute in a field. This grouping does not mean that it dissolves the geometries, but that it generates a multi-part geometry for each group, in which each part is one of the original geometries.

*Assigning this expression in the geometry generator, the expression is evaluated once for each feature that must be rendered on the canvas, each time the canvas is refreshed. This means that if the original layer has 100 features, and you fully zoom the layer, 100 aggregates of 100 features each must be computed on the fly, rendered one on top of the other.

*Both exterior_ring and boundary functions need a single-part geometry as input. Since collect is returning a multi-part geometry, both functions return always NULL.

*Also, exterior_ring and boundary functions return a LineString type geometry, so you need indicate it to the geometry generator, assigning the appropriate value in the Geometry type menu.

*You don't need that functions anyway. If you had the dissolved polygon, you can assign a fill style with the Fill style: No Brush, and only the polygon rings would be displayed.

*The trick of causing the parts of each group to dissolve, is usually to apply a buffer of radius 0 to the group, with the following expression: buffer( collect( $geometry, group_by:= 'nom_dept'), 0). This adds considerable time to rendering processing.

*In the case of non-topological geometries (spaghetti geometries in the GRASS terminology), if all vertices are not shared by all adjacent polygons, coordinate rounding can cause two parts not to dissolve using a radius 0 in the buffer. The trick to force dissolution is to add two buffers instead of one: a small buffer out and one inwards. This can be achieved with the following expression: buffer( collect( buffer( $geometry, 0.1), group_by:= 'nom_dept'), -0.1). In addition to doubling the rendering time (with 100 original features you should sit back and wait for the canvas to refresh every time you make pan or zoom), invalid geometries (by overlapping parts) are being produced in the intermediate step. It is likely that QGIS will crash before finishing rendering.
The Geometry Generator seems to me a powerful tool. The aggregate functions included in the Expression Builder as well. But it doesn't seem advisable to aggregate geometries in the geometry generator of the layer style.


Q: PHP preg_match: exclude whitespaces I'm working on some code block that validates a config file containing PHP variable. I want to detect variables left empty using preg_match.
If the file contains the following lines:
$db_host = "blablah";
  $db_host   ='blablah';
$db_host='';
    $db_host=" ";
  $db_host="";

I'd like to match only lines 3-4-5, lines 1 and 2 being valid (no empty value). The following preg_match works well but matches all lines, not handling the whitespaces or empty values; how could I match only empty/whitespaced values?
preg_match( '#\$db_host(\ +)?\=(\ +)?(\'|\")(.*?)(\'|\");#i', $string );

Note: I'd rather not included the files to validate to check their validity. There might be a lot of them and I can't assume I'll always have control on their content. I'd rather not include unknown, third party code into my own.

A: How should your regex check something like this?:
$a = '';
$b = $a;
$c = preg_replace('/.*/', $a);

You should use PHP to check the variables and not a regex:
include 'config.php';

foreach(array(
    'db_host', 'db_pass', ...
) as $varname) {
    $value = trim($$varname);
    if(empty($value)) {
        die($varname . ' must not be empty');
    }
}

Also you should use trim() to avoid variables containing just whitespace content. (thanks @SamuelCook)

A: Why use preg_match when you can use trim() & empty() to check if it's empty or not.
Take the following examples:
<?php
$str[0] = ' ';
$str[1] = "\t";
$str[2] = "\r\n";

foreach($str as $k=>$val){
    $val = trim($val);
    if(empty($val)){
        echo $k.' is empty<br>';
    }
}

They will all return empty.

A: You can use this pattern:
$pattern = '~\$db_host\s*=\s*(["\'])\s*\1\s*;~';

\s* means "any white character zero or more times". White characters are spaces, tabs, carriage returns and newlines, but if you want, you can replace \s by \h that matches only horizontal white characters (i.e. tabs and spaces).
I put the type of quote in a capturing group with (["\']) and then I use a backreference to this group with \1 (1 because it is the first capturing group of the pattern).


Q: PHP 7.1 on hosted server not recognizing session.save_path I am pulling my hair out over this issue.  It seems simple enough, but the following simple script is not working for me.  I want to keep my session files in the directory as indicated.  I have the 'musanizer_session_tmp' folder in the same root with this php script:
if (!isset($_REQUEST['testit'])) {
    ini_set ('session.auto_start' , '1' );
    ini_set('session.save_path', '../musanizer_session_tmp');
    $_SESSION['tester'] = 'Testing Session Save Path! ';
    echo '<script language="Javascript">';
    echo 'window.location.href="sesstest.php?testit=YES"';
    echo '</script>';
}
else
{
    echo "===>>> ". $_SESSION['tester'].date('H:i:s');
}

Isn't that fairly straightforward and correct?


Q: Is "undefined" in Javascript an error or just a notice? Is the undefined message in the pop up or console log (e.g. when calling a variable that doesn't exist) an ERROR message or just a NOTICE message?
In PHP there is a difference, so, looking for your explanation on this subject.

A: Neither, it is a value (or a stringification of a value in the case of an alert)
Whether or not you can ignore the fact that a variable/property/whatever is undefined depends on the needs of the program you are writing. If a message displays "undefined" when it should display "sweet cuppin' cakes", then that would be a logic error; conversely, if a message displays undefined when it is merely intended to reflect an internal state that can legitimately be undefined, it would not be an error.

A: It sounds to me like an incomplete error message; like when a developer prints "This should never appear!11" Undefined is nothing more than a value, so seeing it on its own does not assign any meaning or importance to the message.

A: 'undefined' means exactly what it says - you have referenced a variable name that is not defined.
Some languages, like Python, are stricter about this kind of thing, and will throw an error if you try to do this.
Javascript assumes you know what you are doing, and so doesn't complain.

A: undefined is a special data type. For example, a common case is a missing parameter in a function call:
var foobar = function(val)
{
    alert(typeof val); // alerts 'undefined'
    alert(foobar.length); // throws an error
}

foobar();

The author of this example function should have checked for the type of val before trying to access the length property.

A: Undefined is, what its name says, a sign for something beeing not defined, like
var a=new Array(10);

It is an array: Array.isArray(a)is true, a.length is 10; but all it contains are undefined values: e.g. a[5] is undefined. So it is no error.

ERROR message or just a NOTICE message?

Neither nor.


Q: How do i remove or merge duplicated values in my JSON List? My Json looks like this,
[
    {
        "MatchNumber": 1,
        "RoundNumber": 1,
        "HomeTeam": "Crystal Palace",
        "AwayTeam": "Liverpool",
        "Group": null,
        "HomeTeamScore": 0,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 16,
        "RoundNumber": 2,
        "HomeTeam": "Fulham",
        "AwayTeam": "Liverpool",
        "Group": null,
        "HomeTeamScore": 2,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 11,
        "RoundNumber": 2,
        "HomeTeam": "Arsenal",
        "AwayTeam": "Leicester",
        "Group": null,
        "HomeTeamScore": 4,
        "AwayTeamScore": 2
    },
    {
        "MatchNumber": 191,
        "RoundNumber": 20,
        "HomeTeam": "Arsenal",
        "AwayTeam": "Leeds",
        "Group": null,
        "HomeTeamScore": null,
        "AwayTeamScore": null
    }
]

for this Json example, using this list will produce 2 Arsenal in the HomeTeam and 2 Liverpool AwayTeam in the dropdown list.
here's my controller code so far, i tried set but it only reordered the list, didn't remove duplicated teams.
@Controller
public class CCController {
private static final String MAIN_PAGE = "main";
private static final String JSON_URL = "https://randomfootball.com/json/epl-2022";
  @GetMapping("/")
    public String main(Model model, @ModelAttribute Team team){
       List<Team> teams = (List<Team>) parsingService.parse(JSON_URL);
       Set<Team> targetSet = new HashSet<>(teams);
       model.addAttribute("teamList", targetSet);
        return MAIN_PAGE;
    }
}

here is my Team model, added as per request.
thanks for any guidance
public class Team{

    public Team() {
    }

    Set<String> HomeTeam;

    public Set<String> getHomeTeam() {
        return HomeTeam;
    }

    public void setHomeTeam(Set<String> homeTeam) {
        HomeTeam = homeTeam;
    }

    public static Set<String> keySet() {
        return null;
    }
}

I finally got a list that doesn't duplicate.
I did it by getting the object from the array of Json. Build that into JsonArray, then use set. That requires a dependency, jakarta.json.


Q: Do I have to do a dispatch again or why is my code not running? I am trying to make it so when I do an ajax request my preload shows up when a request finishes(success or not) it goes away.
I am using Axios and they have interceptors for request and response. I am trying to do request right now.
import axios from "axios";
import {setPreLoader}  from './PreLoaderActions.js';

export const axiosInstant = axios.create({
    baseURL: 'http://localhost:54690/api',
    timeout: 2000,
});

export const config = axiosInstant.interceptors.request.use( config => {
    // Do something before request is sent
    console.log('afaf');
    setPreLoader(true);
    return config;
  }, function (error) {
    // Do something with request error
   // this.setPreLoader(false);
    return Promise.reject(error);
  });

import {actions}  from './Actions.js';

export function setPreLoader(show) {
     return function (dispatch) {
        dispatch({ type: actions.SHOW_PRE_LOADER, payload: { showPreLoader: show }  });
    };
}

when my setPreloader(true) gets hit nothing happens. Nothing is dispatched. Not sure if I need to do something else as I only ever done this in a react component so redux/reactjs might be doing something for me behind the scenes.

A: The setPreLoader function doesn't do anything itself beside returning another anonymous function. Therefore, just calling setPreLoader(true) does nothing because the anonymous function is not called.
You have to call the result of setPreLoader(true) with appropriate function:
setPreLoader(true)(someFunction)


Q: Write the content of an object into a file in C++ I'm using OpenCV, and I am computing the histogram of some images, which is contained inside a class named CvHist. I have a CvHist object, but I want to store it to use it later on in another file. How can I do that?
Thank you

A: Actually, in OpenCV there is a specific way to do that. You can write an object in an XML file as follow:
 CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_WRITE);
 cvWrite(storage, "histogram", global_histogram);

and read is as such:
  CvHistogram* global_histogram;
  CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_READ);
  global_histogram = (CvHistogram *)cvReadByName(storage, 0, "histogram" ,0);

A: The Boost Serialization library is pretty nice.  It may do what you want. http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html

A: 1) Decide on a file format, plan it at the byte level (If an existing format is suitable, prefer it).
2) Write out the data in the file format you decided on.

A: You can add a method to the class called Serialise, something along the lines of the following:
CvHist::Serialise( std::string fName, bool read )
{
    if ( read )
    {
        std::ifstream fStream( fName );
        // Read in values from file, eg:
        fStream >> this->param1;
        fStream >> this->param2;
        // ...etc
    }
    else
    {
        std::ofstream fStream( fName, ios::trunc ); // (ios::trunc clears file)
        // Read out values into file, eg:
        fStream << this->param1;
        fStream << this->param2;
        // ...etc
    }
}

Note, the order is important - the order that you read the various parameters from the file must match the order you write parameters to the file. Also remember to #include <fstream>
Now, to create a CvHist object populated with data from a file data.txt you can simply write this:
CvHist object;
object.Serialise( "data.txt", true );

If you've populated an object and want to store it in a file, this time, say, bob.dat, write this:
// (object has been populated with data previously)
object.Serialise( "bob.dat", false );


Q: I need to install Inkscape on an Ubuntu Server. Do I need to install x11? The PHP charting solution we use for a web application has a means of allowing user to download HTML5 charts/graphs as PDF or PNG etc... but uses Inkscape and ImageMagik to render. Normally Inkscape is GUI program, however our solution would use it from CLI only. Does anyone know whether X11 libraries are required by Inkscape?

A: According to the wiki Inkscape depends on GTK, which could depend on X11, but I am not sure. You could try running the following command to simulate installing it:
sudo apt-get install -s inkscape

See if it would pull down some X11 packages.

A: Both Inkscape, and ImageMagick from the repositories depend on X11. You therefore won't be able to install them from there without also installing X11 as a dependency.
ImageMagick can amongst other options also be compiled without X11 dependency for manual installation.


Q: Opendiff and online file I'd like to make a diff between to file, one is local and the other is online using for example
opendiff http://www.tex.ac.uk/ctan/web/lua2dox/Doxyfile Doxyfile

But it throw the following error :

2014-02-12 15:23:43.579 opendiff[72650:1007] /Users/Dev/Joker/http:/www.tex.ac.uk/ctan/web/lua2dox/Doxyfile does not exist

So how can I use a online file the same way as a local one ?

A: Since this is a programming Q&A site, we may as well write a program to do this for us :-)
You can create a script called (for example) odw for OpenDiffWeb which will detect whether you're trying to access web-based files and first download them to a temporary location.
Examine the following script, it's pretty rudimentary but it shows the approach that can be taken.
#!/bin/bash

# Ensure two parameters.

if [[ $# -ne 2 ]] ; then
    echo Usage: $0 '<file/url-1> <file/url-2>'
    exit 1
fi

# Download first file if web-based.

fspec1=$1
if [[ $fspec1 =~ http:// ]] ; then
    wget --output-document=/tmp/odw.$$.1 $fspec1
    fspec1=/tmp/odw.$$.1
fi

# Download second file if web-based.

fspec2=$2
if [[ $fspec2 =~ http:// ]] ; then
    wget --output-document=/tmp/odw.$$.2 $fspec2
    fspec2=/tmp/odw.$$.2
fi

# Show difference of two files.

diff $fspec1 $fspec2

# Delete them if they were web-based.

if [[ $fspec1 =~ /tmp/odw. ]] ; then
    rm -f $fspec1
fi

if [[ $fspec2 =~ /tmp/odw. ]] ; then
    rm -f $fspec2
fi

In this case, we detect a web-based file as one starting with http://. If it is, we simply use wget to bring it down to a temporary location. Both files are checked this way.
Once both files are on the local disk (either because they were brought down or because thet were already there), you can run the diff - I've used the standard diff but you can substitute your own.
Then, the temporary files are cleaned up.
As a test, I downloaded the page http://www.example.com and made a very minor change to it then compared the page to my modified local copy:
pax> odw http://www.example.com example.txt
--2014-09-25 16:40:02--  http://www.example.com/
Resolving www.example.com (www.example.com)... 93.184.216.119,
    2606:2800:220:6d:26bf:1447:1097:aa7
Connecting to www.example.com (www.example.com)|93.184.216.119|:80...
    connected.
HTTP request sent, awaiting response... 200 OK
Length: 1270 (1.2K) [text/html]
Saving to: `/tmp/odw.6569.1'

100%[=================================>] 1,270       --.-K/s   in 0s

2014-09-25 16:40:02 (165 MB/s) - `/tmp/odw.6569.1' saved [1270/1270]

4c4
<     <title>Example Domain</title>
---
>     <title>Example Domain (slightly modified)</title>

Now there's all sorts of added stuff that could go into that script, the ability to pass flags to the diff and wget programs, the ability to handle other URL types, deletion of temporary files on signals and so on.
But it should hopefully be enough to get you started.


Q: Use of Semicolon in this Sentence In the following sentence can the first comma be replaced with a semicolon for smoother reading?

"An hour drifted by, and the lady, whose name was Arcey Pierre, called it a day."

A: Yes, you can. And there is no inherent reason you must, or have to, delete the and (coordinating conjunction) right after the semicolon any more than there is a rational rule that says you can't start a sentence with and.
So yes,

"An hour drifted by; and the lady, whose name was Arcey Pierre, called it a day.

is fine. See this highly upvoted answer (+14 and climbing) regarding the usage of the coordinating conjunction but right after a semicolon.
As for Grammar Monster's statement that the use of conjunctions immediately after a semicolon is "outdated", one asks "so what?" What was once "in style" becomes out-of-style; and what was out-of-style becomes in style again... the author should choose her/his own punctuation usage based on her/his own sense of style.
Having reread the question, I think it is off-topic'; for what is "smoother reading" is opinion-based.

A: I'm going another way on this one: put a period after "by" and drop the "and".

"An hour drifted by. The lady, whose name was Arcey Pierre, called it a day."

In fairness, whether you go with a period or a semicolon here will depend on the surrounding text. See AleksandrH's input for the way to use the semicolon.

A: AleksandrH said in the comments

If you want to replace ", and" with a semicolon, yes ("An hour drifted by; the lady, whose name...). Otherwise, no ("An hour drifted by; and the lady, whose name...).

As to the acceptability of the semicolon, GrammarMonster (often better than the name warrants) has:

When a conjunction (words like and, but and or) is used to merge
  two independent clauses into one sentence, it is possible to use a
  semicolon before the conjunction to outrank any commas in the clause.
  (This practice is acceptable, but it is considered outdated these
  days. However, if you think a semicolon makes your sentence clearer,
  you can use one.)

[emphasis partly EA]
The article also adds examples from respected sources, but not recent ones. The Rebecca West quotation is possibly the most recent, dating from 1937.


Q: How to force Calculator Price Rules to fire after changing something in Configurator? This is my scenario:
I have configuration attribute on Configurator.
There are two options:

*

*A

*B

When option A is selected, the Price on the QuoteLine should be editable.
When option B is selected, the Price on the QuoteLine should not be editable.
The problem:
SBQQ__PriceEditable__c can be editable only on QuoteLine level, which is available only for Calculator evaluation event of Price Rule.
When Price Rule has evaluation event : Configurator we can affect only

*

*Product

*Product Option

So the real question is:

How to force Calculator Price Rules to fire after changing something in Configurator?

A: We can't do this, but the Quote Line is firing Calculate so in QCP we can use
export function onAfterCalculate(quote, quoteLines) {
  line.record["SBQQ__PriceEditable__c"] = true;
}

and put our logic there.

A: You can't adjust most pricing values from the configurator anyway, because it is not dependent on the existence of a quote line at the time of configuration. Move all of your pricing rules (minus quantity edits/etc.) to calculator scope and then you can control this in the way you seek.


Q: Hand-create images in javascript and draw with respect to the alpha channel? I'm currently trying to create a page with dynamically generated images, which are not shapes, drawn into a canvas to create an animation.
The first thing I tried was the following:
//create plenty of those:
var imageArray = ctx.createImageData(0,0,16,8);
//fill them with RGBA values...
//then draw them
ctx.putImageData(imageArray,x,y);

The problem is that the images are overlapping and that putImageData simply... puts the data in the context, with no respect to the alpha channel as specified in the w3c:

pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

So I thought, well how can I use Images and not ImageDatas?
I tried to find a way to actually put the ImageData object back into an image but it appears it can only be put in a canvas context. So, as a last resort, I tried to use the toDataURL() method of a 16x8 canvas(the size of my images) and to stick the result as src of my ~600 images.
The result was beautiful, but was eating up 100% of my CPU...(which it did not with putImageData, ~5% cpu) My guess is that for some unknown reason the  image is re-loaded from the image/png data URI each time it is drawn... but that would be plain weird... no? It also seems to take a lot more RAM than my previous technique.
So, as a result, I have no idea how to achieve my goal.
How can I dynamically create alpha-channelled images in javascript and then draw them at an appreciable speed on a canvas?
Is the only real alternative using a Java applet?
Thanks for your time.

A: Not knowing, what you really want to accomplish:
Did you have a look at the drawImage-method of the rendering-context?
Basically, it does the composition (as specified by the globalCompositeOperation-property) for you -- and it allows you to pass in a canvas element as the source.
So could probably do something along the lines of:
var offScreenContext = document.getCSSCanvasContext( "2d", "synthImage", width, height);
var pixelBuffer = offScreenContext.createImageData( tileWidth, tileHeight );
// do your image synthesis and put the updated buffer back into the context:
offScreenContext.putImageData( pixelBuffer, 0, 0, tileOriginX, tileOriginY, tileWidth, tileHeight );
// assuming 'ctx' is the context of the canvas that actually gets drawn on screen
ctx.drawImage(
  offScreenContext.canvas,                          // => the synthesized image
  tileOriginX, tileOriginY, tileWidth, tileHeight,  // => frame of offScreenContext that get's drawn
  originX, originY, tileWidth, tileHeight           // => frame of ctx to draw in
);

Assuming that you have an animation you want to loop over, this has the added benefit of only having to generate the frames once into some kind of sprite-map so that in subsequent iterations you'll only ever need to call ctx.drawImage() -- at the expense of an increased memory footprint of course...

A: Why don't you use SVG?
If you have to use canvas, maybe you could implement drawing an image on a canvas yourself?
var red = oldred*(1-alpha)+imagered*alpha

...and so on...

A: getCSSCanvasContext seems to be WebKit only, but you could also create an offscreen canvas like this:
var canvas = document.createElement('canvas')
canvas.setAttribute('width',300);//use whatever you like for width and height
canvas.setAttribute('height',200);

Which you can then draw to and draw onto another canvas with the drawImage method.


Q: Proof of existence of the Laplace distribution's first moment Given the Laplace distribution's PDF:
$$f_X(x|\mu,\sigma) = \dfrac{1}{2 \sigma}\,e^{-\frac{|x-\mu |}\sigma}$$
I'm trying to compute $\mathbb{E}[\lvert X \vert]$, or at the very least to show that it's finite.
$$\mathbb{E}[\lvert X \vert] = \frac{1}{2 \sigma} \int_{\mathbb{R}} \lvert x \rvert e^{-\frac{|x-\mu |}\sigma} dx = \ ?$$
What integration tactics should I use?

A: WLOG, assume $\mu>0$. Then we see that
\begin{align}
\int^\infty_{-\infty}|x|e^{-\frac{|x-\mu|}{\sigma}}\ dx =&\ \int^\infty_\mu xe^{-\frac{x-\mu}{\sigma}}\ dx+\int^\mu_0 xe^{-\frac{\mu-x}{\sigma}}\ dx-\int^0_{-\infty}x e^{-\frac{\mu-x}{\sigma}}\ dx \\
=&\ I_1 + I_2 +I_3.
\end{align}
Observe
\begin{align}
I_1 = \sigma \int^\infty_0 (\sigma y+\mu)e^{-y}\ dy = \sigma(\sigma+\mu)
\end{align}
and
\begin{align}
I_2 = \sigma\int^{\mu/\sigma}_0 (\mu-\sigma y)e^{-y}\ dy = \sigma^2\left(e^{-\mu/\sigma}-1 \right)+\mu\sigma
\end{align}
and lastly
\begin{align}
I_3 = \sigma^2e^{-\mu/\sigma}.
\end{align}
Thus, we have
\begin{align}
\mathbb{E}[|X|] = \frac{2\mu\sigma +2\sigma^2e^{-\mu/\sigma}}{2\sigma} = \mu + \sigma e^{-\mu/\sigma}.
\end{align}


Q: Write down all the topologies on $\{a,b\}$ consisting of two points Perhaps it's only the language here...what is meant by "two points"?
I mean, if it means "two elements only" then, well, isn't that just the indiscrete topology?

$\tau=\{\{a,b\},\phi\}$

I mean, otherwise, say $\{\{a,b\},\phi.\{a\}\}$ or anything else possible would have more than two. And this is a $4$ mark question in the pat papers so I'm guessing it shouldn't be as easy as I think that it's only the indiscrete topology.
Anyone know what is meant?

A: Can you list all subsets of $\{\{a,b\},\{a\},\{b\},\varnothing\}$?
If so, then you just can just go through and pick the ones that form a topology (many will be disqualified immediately for not containing $\{a,b\}$ or $\varnothing$).


Q: implement array.prototype.reduce() on string I have some confusion regarding how reduce operation takes place on a string .First a new Str instance is created and sends desired string as a parameter.
Then using split method it  splits into an array of string.A reduceIt method takes the array and execute a reduce operation which returns the array element which has height length.
It works fine with a two element array.But if there is more than two elements it returns NAN.
Why it returns NAN for array having more than two elements??
function Str(text){
   this.text=text.split('\n');
}
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {
          return Math.max(first.length,last.length);

  });
};

var t=new Str('i am a boy\n she loves cats\n a goat ate my flower garden ');
console.log(t.reduceIt());

A: The first time the callback is called first is a string (the first element in the array), and your function makes sense when first and last are both strings, so it works when the callback is only called once (the array has at most 2 elements).
The second time it is called it is the result of the previous call, a number. When you call first.length on a number you get undefined and when you call Math.max on that you get NaN.
If you want to find the length of the longest string in your array, you could use:
Math.max.apply(Math, this.text.map(function (str) { return str.length; }));

A: Some good answers already. :-)
The simple way to fix your problem is to supply an initial value of 0, then compare the returned value with the length of the new string, so:
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {

          // Compare current value (first) with length of string
          return Math.max(first,last.length);

  }, 0); // supply 0 as the initial value
};

It might make things clearer to rename first to maxSoFar and last to currentString.

A:
Why it returns NAN for array having more than two elements??

Because number.length is undefined, let's name your function foo and follow how it's invoked

*

*foo(0, "i am a boy") gives NaN

*foo(NaN, " she loves cats") gives NaN

*foo(NaN, " a goat ate my flower garden ") gives NaN
Giving a final result of NaN.
This happens because number.length is undefined and Math.max(undefined, x) is NaN
It looks like you wanted to write a function which only takes the length of the second arg
function foo(a, b) {
    return Math.max(a, b.length);
}

In this case, you'll get

*

*foo(0, "i am a boy") gives 10

*foo(10, " she loves cats") gives 15

*foo(15, " a goat ate my flower garden ") gives 29
Giving a final result of 29.


Q: How to add partition in presto? In hive I can do it by:

ALTER TABLE xxx ADD PARTITION
  (datehour='yy')  LOCATION
  'zz';

How can I do it in presto?

A: Currently, Presto Hive connector does not provide means for creating new partitions at arbitrary locations. If your partition location is under table location, you can use Presto Hive connector procedures:

*

*system.create_empty_partition -- creates a new empty partition with specified values for partition keys

*system.sync_partition_metadata -- synchronizes partition list in Metastore with the partitions on the storage

If you want to create/declare partitions somewhere else than under table's location, please file an issue.


Q: Error when retrieving office 2007 files from sql server 2005 blob I have a simple document storage database that allows people to upload various types of documents and then do a full-text search on them.
It works just fine for all documents except office 2007 documents. My retrevial code uses content type "application/octet-stream", the server has the MIMETypes registered as does my computer. I can open the file just fine on my system, but uploading it and then redownloading it gives an error:
"This error can be caused by some of the following conditions:

*

*Your hard drive or floppy drive has a
corrupt section (damaged track or
sector).

*A temporary operating system
or network failure has occurred.

*Your
network is unavailable, slow, or is
corrupting data packets (failure of a
router, network card, or noise on the
network transmission line).

If the network is experiencing problems, it is usually a temporary condition and if you wait a short period of time and try again, you can usually save the file. If the problem persists, consult your network administrator"

A: It would be tough for others to have debugged this, but when I created a byteStream, I used length, instead of length - 1. For some reason in almost all documents this is no problem, but office 2007 threw a fit.