problemas de layout em Android Studio

Question: Estou com um pequeno problema com meu layout olha como esta no Android Studio e como fica na avd:

código XMl:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/Linha1"
    android:id="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="0dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/A1"
    android:layout_alignBaseline="@+id/textView"
    android:layout_alignBottom="@+id/textView"
    android:layout_toRightOf="@+id/textView"
    android:layout_toEndOf="@+id/textView" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/B1"
    android:layout_above="@+id/textView2"
    android:layout_toRightOf="@+id/textView4"
    android:layout_toEndOf="@+id/textView4" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/C1"
    android:layout_above="@+id/textView2"
    android:layout_toRightOf="@+id/textView7"
    android:layout_toEndOf="@+id/textView7" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/K1"
    android:accessibilityLiveRegion="polite"
    android:layout_above="@+id/textView2"
    android:layout_toRightOf="@+id/textView10"
    android:layout_toEndOf="@+id/textView10" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/Linha2"
    android:id="@+id/textView2"
    android:layout_marginTop="41dp"
    android:layout_below="@+id/A1"
    android:layout_toLeftOf="@+id/A1"
    android:layout_toStartOf="@+id/A1" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/A2"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_toRightOf="@+id/textView2"
    android:layout_toEndOf="@+id/textView2" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/B2"
    android:accessibilityLiveRegion="polite"
    android:layout_alignTop="@+id/A2"
    android:layout_toRightOf="@+id/textView5"
    android:layout_toEndOf="@+id/textView5" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/C2"
    android:layout_above="@+id/textView3"
    android:layout_toRightOf="@+id/textView8"
    android:layout_toEndOf="@+id/textView8" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/K2"
    android:layout_alignTop="@+id/A2"
    android:layout_alignLeft="@+id/K1"
    android:layout_alignStart="@+id/K1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/Linha3"
    android:id="@+id/textView3"
    android:layout_marginTop="37dp"
    android:layout_below="@+id/A2"
    android:layout_toLeftOf="@+id/A1"
    android:layout_toStartOf="@+id/A1" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/A3"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_toRightOf="@+id/textView3"
    android:layout_toEndOf="@+id/textView3" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/B3"
    android:layout_alignTop="@+id/A3"
    android:layout_alignLeft="@+id/B2"
    android:layout_alignStart="@+id/B2" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/C3"
    android:layout_alignTop="@+id/B3"
    android:layout_toRightOf="@+id/textView9"
    android:layout_toEndOf="@+id/textView9" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/K3"
    android:layout_alignBottom="@+id/C3"
    android:layout_alignLeft="@+id/K2"
    android:layout_alignStart="@+id/K2" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calcular"
    android:id="@+id/button"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:singleLine="false"
    android:textColor="#54b2c7" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Limpar"
    android:id="@+id/Limpar"
    android:layout_below="@+id/button"
    android:layout_centerHorizontal="true"
    android:onClick="LimparCampos" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/x1"
    android:id="@+id/textView4"
    android:layout_alignTop="@+id/textView"
    android:layout_toRightOf="@+id/A1"
    android:layout_toEndOf="@+id/A1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/x2"
    android:id="@+id/textView5"
    android:layout_alignTop="@+id/textView2"
    android:layout_toRightOf="@+id/A2"
    android:layout_toEndOf="@+id/A2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/x3"
    android:id="@+id/textView6"
    android:layout_alignTop="@+id/textView3"
    android:layout_toRightOf="@+id/A3"
    android:layout_toEndOf="@+id/A3" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/y1"
    android:id="@+id/textView7"
    android:layout_alignTop="@+id/textView4"
    android:layout_toRightOf="@+id/B1"
    android:layout_toEndOf="@+id/B1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/y2"
    android:id="@+id/textView8"
    android:layout_alignTop="@+id/textView5"
    android:layout_toRightOf="@+id/B2"
    android:layout_toEndOf="@+id/B2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/y3"
    android:id="@+id/textView9"
    android:layout_alignTop="@+id/textView6"
    android:layout_toRightOf="@+id/B3"
    android:layout_toEndOf="@+id/B3" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/z1"
    android:id="@+id/textView10"
    android:layout_alignBottom="@+id/textView7"
    android:layout_toRightOf="@+id/C1"
    android:layout_toEndOf="@+id/C1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/z2"
    android:id="@+id/textView11"
    android:layout_alignTop="@+id/textView8"
    android:layout_toLeftOf="@+id/K2"
    android:layout_toStartOf="@+id/K2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/z3"
    android:id="@+id/textView12"
    android:layout_alignTop="@+id/textView9"
    android:layout_toRightOf="@+id/C3"
    android:layout_toEndOf="@+id/C3" />

Gostaria da saber também como e que eu faço para quando eu clicar em enter ele ir para a editText do lado e não para a que ta em baixo e quando ele chegar na última ele volte para a primeira de baixo.
Comment: O design mostrado no Android Studio é só uma referência de como vai ficar. Tens de ter em atenção o XML e as sua definições.
Answer: Tente adicionar nextFocusDown em cada EditText

android:nextFocusDown="@+id/.."

Por exemplo
<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/A1"
    android:nextFocusDown="@+id/B1"
    android:layout_alignBaseline="@+id/textView"
    android:layout_alignBottom="@+id/textView"
    android:layout_toRightOf="@+id/textView"
    android:layout_toEndOf="@+id/textView" />

<EditText
    android:layout_width="46dp"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned|numberDecimal"
    android:ems="10"
    android:id="@+id/B1"
    android:layout_above="@+id/textView2"
    android:layout_toRightOf="@+id/textView4"
    android:layout_toEndOf="@+id/textView4" />

Dessa forma quando clicar em Enter do EditText A1, o EditText B1 ganha o focus. Espero ter ajudado.
Answer: No xml dentro da tag dessa activity set sua screenOrientation para portrait, exemplo:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".activity.HomeActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"
        **android:screenOrientation="portrait"**
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

problemas de layout em Android Studio


Dynamic web page scraping in php

Question: I am trying chrome-php/chrome library to read the dynamicaly rendered web pages, but it's returning nothing. I am using php version 8.0.
This is what I have implemented [I have followed the documentation] -

use HeadlessChromium\BrowserFactory;

$browserFactory = new BrowserFactory();

// starts headless chrome
$browser = $browserFactory->createBrowser('/opt/google/chrome/chrome');

try {
    // creates a new page and navigate to an URL
    $page = $browser->createPage();
    $page->navigate('http://example.com')->waitForNavigation();

    // get page title
    $pageTitle = $page->evaluate('document.title')->getReturnValue();

    echo $pageTitle;

} finally {
    // bye
    $browser->close();
}

It's not returning the title of the url I am trying to read. can you help me to debug this issue?
Comment: What errors do you get? Either on CLI or, if this is executed inside a web server then in your http server's error log file ...
Comment: i am not getting any error.
Comment: Did you _really_ check in your http server's error log file? What does it contain?
Comment: I think you need to have chrome installed on the server for this to work. Iv used puppeteer before and it required chrom browser installed for it to work
Comment: @arkascha There is no error logged for today's date.. all are the old logs.
Answer: Before doing the modifications, put this on your script to make it show errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Probably the error is on this line:
This method doesn't accept a string.
$browser = $browserFactory->createBrowser('/opt/google/chrome/chrome');

You must pass the google chrome executable to:
$browserFactory = new BrowserFactory('/opt/google/chrome/chrome');

or just leave it blank and the system will use the default location:
$browserFactory = new BrowserFactory();

Comment: Got it working?

just remove the path from createbrowser and put on the browser factory method.

$browserFactory = new BrowserFactory('/opt/google/chrome/chrome');
$browser = $browserFactory->createBrowser();
Comment: The default location is throwing error, that's why i have passed the location as argument.
Comment: It really is questionable to advise to enable the `display_errors` feature. That is not how error reporting and debugging should be done now. It breaks the UI, creates chaos, it makes much more sense to monitor the error log file. That's what log files are for.
Comment: @arkascha, yes, you're right. But the suggestion was only to debug the code, as the OP was not finding the log file. The code as posted is throwing errors because the createBrowser() doesn't accept strings.

Dynamic web page scraping in php


hover case when move ( on video )

Question: index.html

Portfolio Page of Burak Aydin

Home

About

Portfolio

Contact

styles.css
nav.navbar {background-color:transparent;}
ul.nav {padding-top:1em;}
ul.nav li {text-transform: uppercase;font-weight:bold;}
ul.nav li a {-webkit-transition: color .3s ease-in-out; transition: color .3s ease-in-out;}
ul.nav li a:hover,ul.nav li a:active,
ul.nav li a:after{background-color:transparent;color:#ff6760;}

First of all I had used twitter bootstrap 3.

These problems happen on mozilla and IE's any version. When I hover over the menu and then if I move bottom right, you'll see a gray background behind the menu link.
When you click photo of portfolio section, you will see a pop-up. There is text decoration. I don't want text decoration.

This issue to mention is tough. So I uploaded a video. Here it is:
issue that I mention on this site:LINK
Answer: In the scaffolding.less there is a:hover and a:focus that underlines and turns into to the primary color set in the LESS variables.
a:hover,
a:focus {
  color: #2a6496;
  text-decoration: underline;
}

So if you want to remove it, do the following:
.my-container-with-content a:hover, .my-container-with-content a:focus {
text-decoration:none;
}

If the entire contents are in a wrapper such as ( a > div ):
So if you want to remove it, do the following:
a:hover .my-container-with-content,  a:focus .my-container-with-content {
text-decoration:none;
}

Make sure this CSS is after the Bootstrap CSS. Name "my-container-with-content" the class of the container that has the hover/focus that you want to remove.
Comment: thanks friend. it helped to me that you mentioned first.

hover case when move ( on video )


What does "Trad. G" as a chord mean?

Question: Perhaps a beginner question, but I couldn't manage to find the answer online. In the following informal instructions on playing the chords to a guitar song, the author mentions "trad. G":

Chords Used:
  Dmaj7, Bm7, Asus6, D/F#, trad. G, F#m7
Finger Pick bass note and B string/ G string
(for the Asus6, play the same notes on the G/B string as Dmaj7)
Chords Played on the A string:
  Dmaj7, Bm7, F#m7
Chords Played on the E string:
  G, D/F#, Asus 6

What does he mean by this?
Answer: There are several common fingerings of the G chord:

The author is likely referring to the fingering he considers "traditional" (trad.), but without context it's unclear which specific fingering that means. I suspect it refers to what Justin Guitar calls "Big G" (all strings fretted) although it might refer to "Folk G" instead (A string muted and B string open).
Comment: @Feryll  I agree with Bradd and there are several common ways to play a G chord in first or open position (using some open strings).  Click the link below for a chart showing 5 options in first position.  Try them all and see which one works best for the song you want to play. (http://music.stackexchange.com/a/31061/16897)
Comment: Cool, happy to help. Out of curiosity, is there something in your source that indicates which specific fingering is correct?
Comment: Not that I can quite tell; it comes from this song, and the playing instructions linked in the description is little more than what I already copied and pasted: https://www.youtube.com/watch?v=JMQdkL-cfGM

What does "Trad. G" as a chord mean?


How to keep track of the coordinates of the turtles after they hit the boundaries of the world in NetLogo?

Question: I am simulating a random walk within bounded angels, and I want to calculate the mean squared displacement of the turtles in 2D in my model. The turtles all start from the center. I am not sure how to update the xy coordinates for the turtles after they hit the boundaries. I am asking the turtles to bounce back when they hit the wall and save their new xcor and ycor. Here's my code:
<code>to go
  ask turtles
  [; head in a random direction in range (-theta, +theta)
   ifelse theta = 0
     [set heading heading + 0 ]
   ; choose a normally distributed random angel in range (-theta, +theta)
     [set heading heading +  random-normal 0 (theta)]

    fd step-size
    set xc xc + (step-size * dx)
    set yc yc + (step-size * dy)

   ; if your next patch is blocked:
    ifelse not can-move? 1
    [ set heading heading + 180
      fd 1 ]

   ;otherwise:
    [rt random-float random-normal 0 (theta)]
   set xcor xc
   set ycor yc
   set dist sqrt (xc * xc + yc * yc)]
  ]
</code>
I am getting the error which says:
"Cannot move turtle beyond the worlds edge.
error while turtle 423 running SET
  called by procedure GO
  called by Button 'go'". Any ideas why?
Answer: You have the grid-wrap disabled and your xcor/ycor of your agents are going past the max-pxcor/min-pxcor and max-pycor/min-pycor
Comment: Thanks, for the reply. I added the condition of  "if can-move? 1" before updating the x-y coordinates and my problem is solved!


Weird MySQL Errors After Distrib Upgrade (SQL 5.0 > 5.1)

Question: Just updated Debian from Lenny to Squeeze on one of my servers. It hosts a MySQL server. Upgrade went fine, but afterwords, when MySQL starts up, it checks the databases to make sure they are okay. I am getting errors though for tables that are in the mysql database.
I did an extensive Google search and attempted to do a myiasmchk -r to those tables. Outside of that, I have not found any other possible answers.
Is this just a bug? Is there a way to fix it?

ERROR 1034 (HY000) at line 1: Incorrect key file for table 'columns_priv'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'db'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'func'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'host'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'tables_priv'; try to repair it

Thanks in advance for your help!
Answer: Confirmed as bug, patch and details here
Answer: connect to mysql server and do a commands
repair table func;
repair table db;
repair table host;
etc...
Comment: Gave that a shot but unfortunately it did not resolve the problem.


Search a directory for a .txt file, without needing full pathname. - Java

Question: I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time.  This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;

public class FileHandler {
    public static boolean fileCheck = true;
    public static File logFile;
    public static PrintWriter logPrinter;
    public static PrintWriter handMadeFile;
    public static LocalDate date = LocalDate.now();
    public static File fileFromScanner;
    public static File directory = new File("/Users/mizu/homework");
    public static String fileName;
    public static File file;
    public static String created = "Log has been created.";
    public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
    public static String mainFileName = "/Users/mizu/homework/main_file.txt";
    public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
    public static String fileMessage = "I just wrote my own file contents.";

    public static void main(String[] args) {

        if (!directory.exists())
        {
            // create new directory called homework
            directory.mkdir();
        }

        // gets file request from user
        System.out.print("Enter file to find: ");
        Scanner in = new Scanner(System.in);
        String fileName = in.nextLine();

        // initialize the main_file
        fileFromScanner = new File(mainFileName);

        // if main_file exists or not, print message to my_log
        if (!fileFromScanner.exists())
        {
            // create my_log file (logFile), to keep track of events
            writeToLog(created);
            writeToLog("File path you entered: "
                    + fileName + " does not exist.");
            System.out.println(fileName + " - does not exist.");

            // create file since it doesn't exist
            File mainFile = new File(mainFileName);
            try {
                PrintWriter pwMain = new PrintWriter(new BufferedWriter
                        (new FileWriter(mainFile)));
                writeToLog("Created " + mainFileName);
                pwMain.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            writeToLog(fileName + " already exists.");
            System.out.println(fileName + " - already exists.");
        }

        // use writeToFile method to write file, create new file name
        FileHandler testFile = new FileHandler(fileFromMethod);
        testFile.writeToFile(testFile, fileMessage);

    } // end Main

All of the other methods are below here, but not shown to keep it short.
Comment: Instead of reinventing the wheel there are a ton of applets that already do this. Example: `find ` http://unixhelp.ed.ac.uk/CGI/man-cgi?find
Comment: Searching the entire computer could take a long time.
Comment: Hmm, maybe that is a good point.
Comment: Depending on how you're launching the program, it might be easier to launch it from the directory the file you're looking for is in, or possibly add a file browser dialog to let the user select it graphically?
Comment: Thanks Evan, that sounds nice. I am only creating a Java application in Eclipse though, and this is an exercise I need to do for homework (unfortunately, I don't know how to do graphics). Is there a way to narrow down the search to one directory only? Like a user can type the `file_name.txt` and it will only search in one directory? It sounds so simple yet I don't know how to do it. Right now, the full path name must be typed into the console, so a full pathname search can be done. I just want to use the file name only in the console.
Comment: Thanks @Jared, except I just need it for a Java application. (I don't know much about applets).
Answer: As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
    // Get the absolute path from where your application has initialized
    File workingDirectory = new File(System.getProperty("user.dir"));
    // Get user input
    String query = new Scanner(System.in).next();
    // Perform a search in the working directory
    List<File> files = search(workingDirectory, query);
    // Check if there are no matching files
    if (files.isEmpty()) {
        System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
                + query + "'");
        return;
    }
    // print all the files that matched the query
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
    }
}

public static List<File> search(File file, String query) {
    List<File> fileList = new ArrayList<File>();
    // Get all the files in this directory
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) {
                // use recursion to search in all directories for the file
                fileList.addAll(search(f, query));
            } else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
                // if the filename matches the query, add it to the list
                fileList.add(f);
            }
        }
    }
    return fileList;
}

Comment: Thanks Jared, that seems like it could work. I'm not very skilled in Java yet though, so I'm not sure how to implement it into my code, or even understand what is happening here. I will need to take time to study this. But I hope others find this useful. Thanks for your help.
Comment: Thanks that helps a lot! I have to read up on recursion, but this looks great.
Comment: Going to change my question to search in directory, instead of whole computer. Thanks again!
Answer: 1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.


Tmux open 4 panes and set each of those panes to a specific directory

Question: Is there a way to create a script to have tmux open with 4 panes and each of those panes opens into a specific directory?
Comment: Yes, there is. What have you tried so far?
Answer: Both tmux new-window and tmux split-window come with a -c option that can specify a start-directory. So you can do a new-window followed by three consecutive split-windows to get your four pane window. You can also provide an additional tmux select-layout command to setup the wanted layout of those four panes.
example
tmux new-window -c ~
tmux split-window -h -c /tmp
tmux split-window -v -c /
tmux select-pane -t 1
tmux split-window -v -c /home
tmux select-pane -t 1


VSTI plugin to combine different plugins

Question: I use Cubase and Miroslav Philharmonik. I want to play a melody with many different instruments as single instrument in cubase. Copy pasting the same melody to different instruments is an overkill, innefficient and makes changes really hard.
I used Reason 10 years before. I remember a plugin in Reason which combines different instruments like this. How can I do the same thing in Cubase?
Thank you.
Comment: Almost all DAWs has such feature. In FL Studio it is called layer channel. The whole concept of layering is play one note on virtual instrument that triggers multiple other instruments at one. You can also set the areas of the keyboard in order to limit one of such instruments to only one octave for example.
Comment: OK Thank you. I will search for layer chanelling in Cubase. If I can find a proper answer I will write it here. I think this question would be very beneficial for many musicians.
Answer: In most instrument VST's like Kontakt, you can choose the input/output of the VST.
If you just open multiple instruments and route them to the same midi channel, every change you'll do in this midi channel will then affect all VST's
Answer: Create a MIDI track instead of an instrument track to hold the MIDI notes. Create multiple instrument tracks for all the instruments. Use the "Sends" section on the MIDI track to send the one set of MIDI data to multiple instruments. One advantage of this method is you retain independent mixing of the different instruments.
Another way to deal with this is to make shared copies of the MIDI region in Cubase. With a shared copy, when you change one of the copies, it updates all the others. One advantage of this method is all the instruments could play the same melody at one point using a shared copy, and then they could all play something different at another time using different MIDI regions.


How to include @Autowired for dynamically invoked methods

Question: I am having a class(Service layer) which creates class instance dynamically and calls the method- model.getClassInstance().method();,this method intern calls one more method which is abstract and implemented in inherited classes.
Inherit class contains @autowired to access DB but since this class is called by instantiating like new Object() i am unable to autowire the fields(NullPointer exception).
So is there any way to autowire the field without having @Service or @Controller or @Component??
I tried by adding the inherited class to spring-servlet.xml as bean but no use.
Please help me.
Answer: Is it possible to create that object using spring beans instead of new object? because then spring will have no control over this object.
If that's not an option, then you can do this by making use of AutowireCapableBeanFactory and calling autowireBean(Object existingBean) on you're object. This method makes the object treat as if Spring created it.
private @Autowired AutowireCapableBeanFactory autowireCapableBeanFactory;

public void func()
{
   Employee employee = // Dynamically loaded object.

   // After this below line, employee object will have its dependecies injected.
   autowireCapableBeanFactory.autowireBean(employee);
}


what are the condition for differentiating both side with respect to x?

Question: $$x^2 -5x+6=0\\\Rightarrow  \frac{d}{dx}{(x^2 -5x+6)}=0\\ \Rightarrow 2x-5=0\\ \Rightarrow x= \frac{5}{2}$$
But the exact solution for the quadratic equation is $x = 2, 3$. Then, what are the conditions for differentiating both sides with respect to $x$?
Comment: The first line is not an identity. It is true only for some specific values of $x$. So you cannot differentiate it.
Comment: "$f(x)=0$" asks which $x$ are roots of $f$. "$f'(x)=0$" which emerges in this case , if we differentiate both sides , asks for possible localizations of local extrema , obviously something completely different.
Comment: If two functions are equal (in other words, they are the same function) then their derivatives are equal.
Comment: It helps to write in complete sentences, not just write down equations. In particular, $x$ should be introduced before it is referred to. What is $x$? This might clarify the situation.
Comment: Also: https://math.stackexchange.com/q/3160946/42969, with links to more similar questions.
Answer: Let's think about solving an equation for a second. When presented an equation like $3x + 7 = 22$ to solve, you are given two expressions representing numbers, $3x + 7$ and $22$, and told they are the same. You don't know which number $x$ is yet, but whatever it is, it will make $3x + 7$ the same as $22$.
To solve this equation, you can perform whatever numerical operation on the left side that you want, so long as you do the same on the right. You can perform any operation that deals in numbers, e.g. you can add $4$, multiply by $-17$, take both sides to the power of $9$, etc. Any operation that does something to a number, you can do to both sides, and the numbers you get as a result, will still be the same.
Differentiation does not operate on numbers, it operates on functions. When you take the derivative of $x^2 - 5x + 6$ at, say, $x = 1$, you don't just take into account the value of $x^2 - 5x + 6$ at $x = 1$ (which is $2$), you take into account the value at $x = 1$ and all the values around $x = 1$. We can't just replace $x^2 - 5x + 6$ with the number $2$, and differentiate. Even though they are the same number when $x = 1$, differentiation treats $x^2 - 5x + 6$ not as a number, but as a function.
The equation $x^2 - 5x + 6 = 0$ is not saying that $x^2 - 5x + 6$ is the same function as the constant $0$, it's saying that, whatever number $x$ may be, the number $x^2 - 5x + 6$ happens to be $0$. There will be many potential values of $x$ where $x^2 - 5x + 6$ is not $0$. So we should treat these quantities as numbers, not functions. We can perform any numerical operation we want to both sides, and maintain equality. As functions, $x^2 - 5x + 6$ is not the same as $0$, so taking the derivative of both sides has no guarantee to it will produce equal functions.
As an example to contrast, take the identity $\cos^2(x) = 1 - \sin^2(x)$. This is not just an equality between numbers, but it is an identity, i.e. an equality between functions. This is true for every number $x$. Since the two functions are the same, it is legitimate to differentiate both sides:
$$2\cos(x) \cdot (-\sin(x)) = 0 - 2\sin(x) \cdot \cos(x).$$
Note that, because we started with two functions that were the same, and applied the same operation on functions to both sides, we once a gain get two functions that are the same.
In short: you can apply differentiation both sides when dealing with an identity. If you need to find the few points $x$ that satisfy the equation, then you are not dealing with an identity, and you cannot perform differentiation.
Answer: Simply, to say $f(x) = 0$ means when f(x) is evaluated, it's result is zero.  These are typically called the x-intercepts.
However, $f'(x) = 0$ means the slope of the tangent line is zero, or that the function f, when graphed levels off.  Or $g'(x) = h'(x)$ means that g and h have the same slopes at x.
These are two different statements entirely.  The derivative is an operator which can change the meaning of the equation.
Comment: I find this answer oversimplistic... are you sure it helps the OP? It does not disambiguate the definition of a (null) function $\{f(x)=0 \text{ for all }x\in\mathbb R\}$ from the set of values that satisfy an equation  $\{x\in\mathbb R\text{ such that }f(x)=0\}$, which I think was the source of confusion.


Computed multiplication

Question: I have a webform where I am using the Twig Computed module to calculate an amount. It is simple and straight forward: I have a field that captures the amount and I'm using Twig to multiply it to find the fee; the fee amount is a fixed rate
The Computed Value/Markup is {{ data['license_amount']|number_format(2) * 0.019 }}. It works when data['license_amount'] is lower than 999; it shows a wrong total when data['license_amount'] is higher than 999.
If the amount is 500 the value is 9.5 as it should.
If the amount is 5000 the value is returned as 0.095
Comment: I agree with the locale part in the comment. Thousands separator seem to play you tricks here. However, the only change I'd suggest in the case is to add the second(decimal_point) and third(thousand_sep) parameters as explained in twig.symfony.com/doc/2.x/filters/number_format.html and this should be perfectly fine.
Answer: You should drop the number_format altogether (not sure what the requirement is), or place it at the end of the calculation, i.e.
{{ (data['license_amount'] * 0.019)|number_format(2) }}
number_format is a wrapper around PHP's number_format function
From PHP's documentation page:
// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

It seems like you are running the calculation on something like 5'000 or 5,000 (depending on your locale), which would explain the results you are getting.
Good luck!

Computed multiplication


Show that any right angled triangle with hypotenuse 1 may be approximated arbitrarily close by one with rational sides

Question:
Taken from Mathematics and Its History Book by John Stillwell, page 8.
Please check if there are any flaws in my answer (have I actually understood the meaning of "arbitrarily close" and also, if you could suggest a more elementary answer, I would appreciate it.
Solution
Each and every possible right angled triangle with hypotenuse $1$, and sides $x$ and $y$ can be uniquely indexed with one of it's angle, $\theta$ defined between the side $x$ and the hypotenuse.
For
$0 < \theta < \frac{\pi}{2}$, it covers all possible such triangles.
$$\{(x,y) | x^2 + y^2 = 1\} \sim \{\theta | (\sin \theta)^2 + (\cos \theta)^2 = 1\} $$
Thus we need to show that it is possible to find 2 rational sides $p$ and $q$ for any given level of precision (say n digits) such that the error between them and the real sides is less than $10^{-n}$. Note they say that $n$ can be arbitrarily chosen. i.e.
$$|p-\sin \theta| < 10^{-n} $$ and
$$|q-\cos \theta| < 10^{-n} $$
There exists such a $p,q \in \mathbb{Q}$ for any $n \in \mathbb{N}$ and $0 < \theta < \frac{\pi}{2}$
We can show this using the Taylor series of $\sin$ and $\cos$, we can evaluate upto the required number of terms until we reach the required arbitrary threshold.
$${\displaystyle {\begin{aligned}\sin(x)&=x-{\frac {x^{3}}{3!}}+{\frac {x^{5}}{5!}}-{\frac {x^{7}}{7!}}+\cdots \\[8pt]&=\sum _{n=0}^{\infty }{\frac {(-1)^{n}}{(2n+1)!}}x^{2n+1}\\[8pt]\end{aligned}}}$$
$${\displaystyle {\begin{aligned}\cos x&=1-{\frac {x^{2}}{2!}}+{\frac {x^{4}}{4!}}-{\frac {x^{6}}{6!}}+\cdots \\&=\sum _{n=0}^{\infty }{\frac {(-1)^{n}x^{2n}}{(2n)!}}\end{aligned}}}$$
Since the finite sum of rational numbers are sure to be rational, the desired $p$ will be the truncated taylor series of $\sin \theta$ and $q$ will be the truncated taylor series of $\cos \theta$.
Comment: The flaw in your proof is that although $p$ and $q$ are close to $\sin\theta$ and $\cos\theta$ you have **not** shown that $p^2+q^2=1$.
Comment: *It goes from $x^2 + y^2 = 0.999^2 + 0.0001^2 = 1$ to $x^2 + y^2 = 0.00001^2 + 0.9999^2 = 1$ covering all possible such triangles.*
Not only these equalities are wrong, but you seem to believe that there is a smallest of all real numbers.
Comment: @ArnaudMortier Thanks for pointing that out. I'll fix that. I was actually trying to give an illustration of the edge case. I realise now that there is no single edge case. But that flaw should not affect the proof right?
Comment: It does not affect the rest of the proof but it does affect what the reader is going to think, and it may deter people from reading any further.
Answer: As pointed out in a comment, your proof is incomplete if not flawed, because the condition $p^2+q^2=1$ is not justified/satisfied.
An easier way to construct $(p,q)$ is to use Pythagorean triples of the form $(2mn,\, m^2-n^2,\, m^2+n^2)$. For any fixed positive integer $m$, let $p(n)=\frac{2mn}{m^2+n^2}$. It can be shown that $0\le p(n)-p(n-1)\le\frac2m$ for every $n\in\{1,2,\ldots,m\}$. Hence $p(n)$ can be made arbitrarily close to any $a\in(0,1)$. In turn, $q(n)=\frac{m^2-n^2}{m^2+n^2}=\sqrt{1-p(n)^2}$ is arbitrarily close to $b=\sqrt{1-a^2}$.
Answer: Start with
$(1-t)^2+(2t)^2
=(1+t)^2
$,
so that
$(\frac{1-t}{1+t})^2+(\frac{2t}{1+t})^2
=1
$.
To approximate
the right triangle
with sides
$(\sin z, \cos z, 1)$,
we want
$\sin z \approx \frac{1-t}{1+t}
$
or
$(1+t)\sin z \approx 1-t
$
or
$t(1+\sin z) \approx 1-\sin z
$
or
$t
\approx \frac{1-\sin z}{1+\sin z}
$.
Choose $t$ as a rational close to
$\frac{1-\sin z}{1+\sin z}
$
and the resulting
right triangle
will be rational
and close to
the original
right triangle.
I'll let others work out
how close if actually enough.
Answer: EDIT: This proof is incorrect. The fact that $y^{2} \in \mathbb{Q}$ does not guarantee that $y \in \mathbb{Q}$.
I am working through Stillwell's book too, and came up with this solution. I would also appreciate any comments on my proof.
Let $a, b \in \mathbb{R}$, so that $a^{2}+b^{2}=1$. If $a, b \in \mathbb{Q}$, then we are done, so the interesting case is when $a, b \in \mathbb{I}$.
By the density of $\mathbb{Q}$ in $\mathbb{R}$, we can find a rational between two real numbers. In particular, let $\epsilon > 0$ be the approximation threshold, making sure that $a-\epsilon>0$, and $a+\epsilon<1$.
Let $x \in \mathbb{Q}$ so that $a-\epsilon < x < a+\epsilon \ $ (by the density mentioned above). Because of the way we chose $\epsilon$, it holds that $x^{2} \in (0,1)$. Finally, let $y^{2} = 1 - x^{2}$. Since both $x$ and $y$ are rational, we proved the desired result.


How do I update a multi-dimensional commerce product field with Views Bulk Operation?

Question: I'm converting from an old UPS module to the newer Commerce UPS. The old module used integer fields for height, length, width. The Commerce UPS module demands a multi-dimensional field 'Product_Dimensions'. So I want to update the Product_Dimensions field with the old data.
I created a View with a VBO column and I selected Execute Arbitrary PHP Script as my operation. Here is my code:

$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( "und" => array(0 => array( length=>"91", width=>"22", height=>"11", unit=>"in") ) );
commerce_product_save($product);
// dpm($product->field_package_dimensions);

...the product_dimensions field is being updated BUT each dimension of the array is being assigned a single character '9'. ie. the length, width and height are all '9'. So clearly there is something wrong with my array assignment?
Can someone tell me what I'm doing wrong? I'm sure it's an obvious mistake... or there is a 'proper' procedure for programmatically updating commerce product fields that I'm missing.
TIA.
Answer: For any future travelers.
This may be my ignorance but it seems like you -must- use commerce_product_load(), even thought it kinda looks like the $entity object is the same as the $product object.

$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( LANGUAGE_NONE => array( 0 =>
    array('length'=>  $entity->field_length['und'][0]['value'],
          'width'=>   $entity->field_width['und'][0]['value'],
          'height' => $entity->field_height['und'][0]['value'],
          'unit'=>"in") ) );
commerce_product_save($product);


Use the Lebesgue number lemma to prove that $f$ is uniformly continuous if $M$ is compact and $f$ continuous

Question:
Suppose that $M$ is covering compact and that $f: M \to N$ is continuous. Use the Lebesgue number lemma to prove that $f$ is uniformly continuous.

Given $\epsilon >0$, the set $\mathcal{U} = \{B_{\epsilon/2}(p) \mid p \in N\}$ is an open covering of $f(M)$. Since $f$ is continuous, $f^{-1}(B_{\epsilon/2}(p))$ is open. But $M$ is compact, then $f(M)$ too. Thus, we can find a finite subcovering
$$f(M) \subset B_{\epsilon/2}(p_{1})\cup \cdots \cup B_{\epsilon/2}(p_{n}).$$
Therefore,
$$f^{-1}(B_{\epsilon/2}(p_{1}))\cup \cdots \cup f^{-1}(B_{\epsilon/2}(p_{n}))$$
is a finite subcovering of $M$. By the Lebesgue nummber lema, there is a $\delta>0$ such that for every $x \in B_{\delta}(x) \subset f^{-1}(B_{\epsilon/2}(p_{i}))$ for some $i$. So, if $d(x,y) < \delta$, the "$y$" are in some $B_{\delta}(x) \subset f^{-1}(B_{\epsilon/2}(p_{i}))$, then $d(f(x),f(y)) \leq d(f(x),p) + d(f(y),p) < \epsilon.$
Is this correct?
Answer: The Lebesgue number lemma I know (e.g. as stated here) needs no finite cover but any open cover.
So just use the open cover $\{f^{-1}[B(f(x), \frac{\varepsilon}{2})]: x \in M\}$ for $M$ and find $\delta >0$ such that any set with diameter $< \delta$ sits inside one member of the cover.
If then $d(x,x') < \delta$ apply this to $\{x,x'\}$, so that for some $p \in M$ we have $\{x,x'\} \subseteq f^{-1}[B(f(p), \frac{\varepsilon}{2})]$ which means $f(x), f(x') \in B(f(p), \frac{\varepsilon}{2})$ and then the triangle inequality via $f(p)$ yields $d(f(x), f(x')) < \varepsilon$, as required.
Comment: Thank you! Your answer is much clearer


Outbound traffic in amazon ec2 instance not working

Question: Outbound requests are not working in my instance.
When I give a wget a url https:
it happens
Solving www.facebook.com (www.facebook.com) ... 126.96.36.199, 2a03: 2880: f111: 83: face: b00c: 0: 25de
Connecting to www.facebook.com (www.facebook.com) | 220.127.116.11 |: 80 ... connected.
The HTTP request was sent, awaiting response ... 302 Found
Location: https://www.facebook.com/ [redirecting]
--2017-04-19 11: 32: 20-- https://www.facebook.com/
Connecting to www.facebook.com (www.facebook.com) | 18.104.22.168 |: 443 ...
And be like this forever...
Already configured in the security group area for all traffics 0.0.0.0/0 and it still does not work.
In other instances it works perfectly
Comment: Does this happen *just* for Facebook.com?
Comment: for all https urls
Answer: Have you checked:

The Outbound rules of the Security Group associated with the
Instance?
The Outbound and Inbound rules of the Network ACL associated with the Subnet the Instance is on? Remember that NACLs are stateless so you have to add both inbound and outbound rules for the traffic.
The Route table associated with the Subnet the instance is on to make sure Internet traffic is being forwarded to the Internet Gateway
Comment: how i check te rules of network acl??


Violin - Best way to treat rosin build up on the strings?

Question: Recently, my violin's sound wasn't coming very well. I searched it on Google, and found out it was because of rosin build up on my strings, a common case. What is the best way to treat rosin build up on the strings?
Answer: Rosin can be easily and safely cleaned from strings with isopropyl (rubbing) alcohol.  Put a bit on a rag and wipe the strings with it.  Be very careful not to drip any alcohol on the instrument, though.
Comment: Perhaps hold the instrument upside-down, so it doesn't drip alcohol onto the instrument.


Set of primes $p$ for which $x^3-4x-1$ factors completely over $GF(p)$

Question: Find the set of primes $p$ (either a modular congruence or quadratic form) such that $x^3-4x-1$ factors into three linear factors over the field $GF(p)$. I noted that these primes $p$ include $37, 53, 173, 193, 229, 241$. For example,
$x^3-4x-1 = (x + 8)(x + 13)(x + 16)$ in the finite field of order $37$, $GF(37)$ hence $37$ is one of these primes in the set.
I would expect some statement such as $x^3-4x-1$ factors into only linear factors over the finite field $GF(p)$ if and only if $p$ is of the form $x^2+ay^2$ for some integer $a$, or if $p$ holds a specific modular congruence.
Comment: Potentially: https://oeis.org/A141166
Answer: In A Course in Computational Algebraic Number Theory by Henri Cohen, see Appendix B.4, Table of Class Numbers and Units of Totally Real Number Fields, pages 521-523. Apparently I made a jpeg of this years ago.
The material underlying my conclusion is the main Theorem in Spearman Williams (1992)
If you wish, you may use
$$ p = x^2 - 229 y^2 $$
First Version:
$$ p = x^2 + 15 xy - y^2  $$
Represented (positive) primes up to  10000
<code>    37    53   173   193   229   241   347   359   383   439
   443   449   461   503   509   541   593   607   617   619
   643   691   907   967   977  1019  1051  1063  1097  1109
  1249  1277  1291  1303  1321  1399  1429  1583  1667  1741
  1783  1993  1997  2003  2087  2137  2143  2333  2347  2351
  2371  2381  2393  2503  2579  2657  2677  2687  2699  2729
  2749  2767  2791  2803  2897  3019  3023  3121  3203  3371
  3373  3391  3491  3517  3539  3581  3583  3631  3637  3761
  3767  3823  3847  3881  3889  3907  3919  4001  4019  4127
  4139  4177  4217  4273  4339  4397  4421  4481  4483  4523
  4547  4597  4637  4663  4679  4691  4871  4889  5087  5119
  5167  5209  5399  5479  5507  5521  5581  5647  5683  5689
  5737  5741  5843  5869  5879  5939  6007  6037  6203  6263
  6277  6301  6397  6421  6449  6547  6563  6581  6653  6701
  6719  6827  6871  6907  6967  7019  7039  7253  7283  7331
  7333  7499  7573  7621  7691  7823  7883  7907  8011  8059
  8123  8147  8219  8233  8243  8269  8429  8537  8573  8581
  8669  8677  8713  8753  8849  8863  8951  9007  9049  9187
  9221  9281  9341  9403  9497  9619  9643  9689  9739  9769
  9787  9851  9883
</code>
---------------------------------------
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
<code> these are the collection of remainders when dividing by   229

      0      1      3      4      5      9     11     12     14     16
     17     19     20     25     26     27     36     37     42     43
     44     45     46     49     51     53     55     56     57     60
     61     62     64     70     71     76     78     80     81     82
     83     85     91     94     95     97     99    100    103    104
    108    111    118    121    126    129    130    132    134    135
    138    144    146    147    148    149    151    154    158    159
    161    165    167    168    169    171    172    173    176    180
    181    183    184    185    186    187    193    196    202    204
    209    210    212    213    214    217    218    220    225    226
    228
</code>
=====================================================

Next are two pages from the 1976 article by Daniel Shanks, which states the theorem  about cubic fields without proof. It is the paragraph on page 29 that begins "The general rule is simply this:"
Comment: Thanks, Will. A bit of homework for me.
Comment: Can you remind me what was the passage from that cubic to this quadratic form? Also, I've been under the impression that the set of totally split primes can be described by congruences only when the extension is abelian. I believe class field theory has a lot to say about this. I have waded through Milne's notes, but I have these gaps leaving the various pieces.disconnected.
Comment: @JyrkiLahtonen please see http://zakuski.math.utsa.edu/~jagy/Hudson_Williams_1991.pdf about positive binaries of form class number three. Discriminant 229 is one I did for that blog for MSE. However, I am not so sure I can, um, justify this completely.  The form (classes) are $\langle 1,15,-1 \rangle \; \; ,  \; \; $ $\langle 5,13,-3 \rangle \; \; ,  \; \; $ $\langle 3,13,-5 \rangle \; \; ,  \; \; $
Comment: @JyrkiLahtonen I forgot about this one, I think it may have what you want: http://zakuski.math.utsa.edu/~jagy/Spearman_Williams_1992.pdf   the Theorem on page 398
Comment: @JyrkiLahtonen for convenience, I have added the first two pages of Spearman Williams (1992) to my answer as jpegs.


Finding optimal lag order for an exogenous regressor in a VAR model

Question: I can't use VARselect as it gives lags in a VAR model which considers all the variables to be endogenous. In my case, one of the variables is exogenous and affects dependent variable with a certain lag.
Is there any package or function in R which can help me find the optimal lag order of the exogenous regressor?
Comment: I tried to shorten the title so as not to scare people away :) If you find my edit not satisfactory, feel free to undo. By the way, I am not aware of any functions to do the job.
Answer: I suggest constructing a transfer function (single endogenous model) using identifiable lag structure for all the inputs. Care should be taken to consider any necessary level shifts/local time trends/seasonal and regular pulses along with any necessary ARIMA structure to account for unspecified/omitted stochastic inputs. The more general solution is a Vector ARIMA model with user specified exogenous series but this is largely intractable/unavailable when Gaussian Violations are present as they almost nearly are.
Answer: As of now, as far as I know, it is:
<code>df <- data.frame(x1 = rnorm(50), x2 = rnorm(50))
model <- VARselect(df, exogen = cbind(x3 = rnorm(50)))
model

$selection
AIC(n)  HQ(n)  SC(n) FPE(n)
     1      1      1      1

$criteria
               1         2         3         4         5        6         7
AIC(n) 0.3819556 0.5409510 0.5559532 0.6966488 0.7490992 0.721105 0.8037243
HQ(n)  0.5040847 0.7241447 0.8002114 1.0019715 1.1154865 1.148557 1.2922407
SC(n)  0.7197315 1.0476148 1.2315050 1.5410885 1.7624269 1.903321 2.1548279
FPE(n) 1.4671137 1.7254929 1.7627647 2.0509437 2.1971864 2.187764 2.4554746
               8         9       10
AIC(n) 0.9664021 0.8381916 0.616336
HQ(n)  1.5159831 1.4488371 1.288046
SC(n)  2.4863936 2.5270711 2.474103
FPE(n) 3.0198382 2.8162782 2.434792
</code>


How does e, or the exponential function, relate to rotation?

Question: $e^{i \pi} = -1$. I get why this works from a sum-of-series perspective and from an integration perspective, as in I can evaluate the integrals and find this result. However, I don't understand it intuitively.
Intuitively, what this means to me is that if you rotate pi radians around a unit circle, you will end up exactly opposite of where you started.
Expanding upon this, for any theta, $e^{i\theta}$ is equivalent to rotating $\theta$ radians around a unit circle. So it's obvious (if not intuitive) to me that $e^{(\pi/2)i} = i$ and $e^{2\pi i} = 1$ and so on.
What I'm wondering is, intuitively, how is the natural logarithm related so closely to circles? My understanding of $e$ stems from exponential growth, and I don't see how that ties to rotation around a unit circle.
I know the formulas, but I'm looking for an intuitive explanation. For example, when I used to ask how sin and cos related to circles, people would show me taylor series or tables with a bunch of values or tell me to use a calculator, but it didn't click until somebody told me that sin is just a measure of the height of a point as you travel around the unit circle. Then it all makes sense.
I'm looking for that kind of explanation of $e$ - how is $e$ related to circles and why does $e^{ix} = \cos(x) + i\sin(x)$?
Comment: FWIW the moving particle argument is presented in the book Visual Complex Analysis by Tristan Needham. I would recommend a reading to anyone interested. It is an excellent book, but without any disrespect to the author, I find the answer below to be of higher quality than the book's.
Answer: There is a closely related discussion at this math.SE question with lots of details. Let me see if I can summarize it as concisely as I can:

Let $r(t) : \mathbb{R} \to \mathbb{R}^2$ parameterize a particle moving uniformly around the unit circle. Then $|r(t)|^2 = \langle r(t), r(t) \rangle = 1$ (where $\langle \cdot, \cdot \rangle$ denotes the dot product). Differentiating this relation gives $\langle r(t), r'(t) \rangle = 0$; in other words, the displacement is always orthogonal to the velocity. (This should make physical sense.)
Since in addition $r(t)$ is moving uniformly we have $|r'(t)|^2$ is a constant, and we may as well assume $|r'(t)| = 1$ by a suitable change of units. Hence $r'(t)$ is either a $90^{\circ}$ clockwise or counterclockwise rotation from $r(t)$.
Now identify $\mathbb{R}^2$ with $\mathbb{C}$ and identify $r$ with a function $z(t) : \mathbb{R} \to \mathbb{C}^2$. If the particle is moving counterclockwise, then the above implies that $z'(t) = i z(t)$.
But this differential equation clearly has unique solution $z(t) = e^{it} z(0)$.

So the fact that multiplication by $i$ is the same as rotation by $90^{\circ}$ actually immediately implies the more general fact about arbitrary rotations through Euler's formula (although one does not need Euler's formula to see this, of course). The other lesson to keep in mind here is that $e$ shows up whenever you solve linear ODEs. Abstractly this is because $e^{\lambda z}$ is an eigenvector for the derivative operator of eigenvalue $\lambda$.
I think these are important and fundamental questions, and it's a pity they aren't more clearly addressed anywhere in the undergraduate curriculum.

So, to summarize: $e^{it}$ is a complex number $\cos t + i \sin t$ which describes counterclockwise rotation by $t$ radians. It follows that if $z$ is a complex number of absolute value $1$, then the possible values of $\log z$ are the purely imaginary numbers $it$ such that $e^{it} = z$; in other words, they're the possible values of $t$ such that $z$ describes rotation by $t$ radians. So taking the logarithm of a rotation gives you an angle.
Comment: @Mitch: I'm not sure I understand the question. Take everything I said about $e$ and take the natural log of both sides. If you accept that $e^z$ is related to rotation, then its inverse is automatically also related to rotation.
Comment: @Mitch: I have added a remark that I hope clarifies this. You are taking the logarithm of a complex number that represents a rotation and getting the angle of the rotation.
Comment: This explains something about $e$ and exponeniation. What about the inverse, the natural log?
Comment: I hope I'm not being obtuse, but I just don't see immediately what the composition inverse of exponentiation (the natural log) corresponds to here. Is it rotation in the other direction? That seems to be the multiplicative inverse (the negative angle). What corresponds to taking the log of ...well of what? The log of a complex number is an angle? That's what isn't obvious.
Answer: When I personally went on the quest for an intuitive grasp of the relationship between Euler's Number and Rotations. I would almost invariably find explanations that missed the point entirely and instead simply explained the motivation for imaginary exponents in general. Yes this is required knowledge but it's not the end of the story. As the picture below illustrates any Real Number to an Imaginary Exponent will create a Parametrization of a Unit Circle in the Complex Plane.
The real reason we choose to use Euler's Number over any other is because it is the unique "Growth Factor" that correlates a Unit Circle Parametrization with Arc Length.
That is to say, for $B^{i t}$, the Arc Length of a Unit Circle = 1 when t = 1, if and only if $B = e$.
So $e^{it}$ is a pretty nice and convenient little formula with the Parameter $t$ corresponding exactly to our measure of Arc Length. From which we also indicate Angle in general through Radians.
However we are again left with another question now. Why exactly is it that Euler's Number  is the "Growth Factor" that correlates a Unit Circle Parametrization with Arc Length?
After all $e$ usually presented in a purely analytic fashion, related to function growth and certainly doesn't seem to have such direct connection to the Arc Length of a Circle.
This is really the crux of the matter and is something that I think can only really be seen by examining the "Moving Particle" analogy in detail.
Warning: Wordy explanation ahead!
Part 1:
I find that thinking about this in terms of the Physics is the clearest and most complete explanation.
Interestingly enough it shows how the so-called "deep connection" between Euler's Number and Pi turns out to be nothing more then the familiar property of the Natural Exponential Function being equal to all of its Derivatives.

There's a lot going on in the above three pictures so let me explain them point by point.
Each graph represents a Unit Circle Parametrization in the Complex Plane with Real Numbers going horizontally and Imaginary Numbers vertically.
The first graph uses the equation $f(z) = 2^{i t}$. The second $f(z) = e^{i t}$ and the third  $f(z) = 3^{i t}$.
Where $t$ runs from $[0,1]$.
For each graph the Light Blue Curve corresponds to function itself while the Yellow, Green and Orange Curves are the 1st, 2nd and 3rd Derivatives.
The correspondingly colored Vectors stemming from the Origin are the Position Vectors that "sweep out" their respective Curve.
The Light Blue Position Vector (which is the function itself, not one of its Derivatives) also has additional Vectors stemming from it which indicate its Velocity (Dark Blue), Acceleration (Red) and Jolt (Purple). Where Jolt is simply the Derivative of the Acceleration.
Notice how in all three different bases the Velocity, Acceleration and Jolt Vectors are always Perpendicular to each other.
However only the formula using Euler's Number as a Base has Derivatives that seem to "line-up" with each other.
The understand why this is and why it's important we'll have to go full on Physics mode.
Part 2
First, assume the Unit Circle Parameter is Time in Seconds.
The essential idea is that in order for a Radius of Length 1 to move 1 Arc Length in 1 Second it is required to have a Velocity of 1, Acceleration of 1, Jolt of 1, etc.
(As well as all being Perpendicular to each other, but any Growth Factor of a General Exponential Function gives the Perpendicular Derivatives property.)
If we interpret Arc Length as a general measure of Distance.
In order for a Particle to move 1 Meter in 1 Second it is required to have a Velocity of 1 Meter Per Second.
For this to hold true indefinitely, it is required to have a Parallel Acceleration of zero. That is to say, it can neither slow down nor speed up.
However it may have Perpendicular Acceleration. This Perpendicular Acceleration should preserve the above properties no matter the magnitude as long as it is only ever strictly perpendicular to the Velocity.
If we now add an additional constraint, that of a "Stable Orbit" of the form of perfect eternal circular motion.
Then we find that the Perpendicular Acceleration should change the Velocity by 1 Meter Per Second every Second (given an Orbit with a Radius of 1 Meter).
This is because it must always be pointing "inwards" but which direction "inwards" corresponds to constantly changes as the particle orbits.
Consequently we find that none of the Particle's Derivatives (up to the Infinitith Order Derivative!) can be Zero and in fact must all be Constant. In this situation in fact they must all be 1. (That is to say, of course, that all their Magnitudes must be Constant and in this case are equal to 1. Their Directions are constantly spinning around to maintain their positions perpendicular to each other.)
This is because in eternal circular motion all of a Particle's Derivatives must be constantly "correcting" the Derivatives lower than it in order to maintain the constant instantaneous changes in motion forever.
I hope this rambling explanation was helpful. I only post it because after spending weeks reading about Euler's Number, Trigonometry and Complex Numbers this was the only explanation that finally made all the details "click" for me and I couldn't find such an explanation on-line anywhere after much searching.
Answer: The complex logarithm is quite different from the real-valued logarithm.  In fact, it is multi-valued.
http://en.wikipedia.org/wiki/Complex_logarithm
While it agrees with the real-valued logarithm on the real axis, if you take $R>0$, then as you traverse the circle $|z| = R$, the value of the complex logarithm increases linearly with the $\arg z$ until you return to the same place.  For example, if you take the unit circle, start at $1$, pass through $i$, $-1$, and $-i$, then when you return to $1$ the logarithm will have increased by $2\pi i$.  This comes from the fact that $\exp$ is periodic, as you have noted by realizing its relationship to Euler's identity.
Typically, we take one branch of the complex logarithm (which has discontinuities along a ray from the origin, whose location we can choose, and we typically choose either the positive or negative real axis), but the actual function looks a bit like a helix or a spiral.
Therefore, the relationship between $\log$ and the circle is that, each time you go once around the circle, you gain $2\pi i$.
If you are interested in more of this, you should study holomorphic functions and residues.  In a region where a holomorphic function is holomorphic (with certain nice properties like being simply connected), the integral around any closed curve is zero.  Simple poles of a holomorphic function $f$ are points where, locally, $f$ looks like $1/z$.  You will recall that, in real analysis, the anti-derivative of $1/z$ is $\log(z)$.  Since $\log$ has a branch cut, this fails to be a holomorphic anti-derivative of $1/z$, so you need some more power to integrate $1/z$, but it turns out that the integral along a circle around a pole like that will be exactly $2\pi i$, and this is precisely because, by taking one branch of $\log$, you get a jump of $2\pi i$ when you return to your starting point.

More simply, recall that multiplication is the same as addition of logarithms.  In the complex numbers, multiplication corresponds to addition of arguments (angles).  Therefore, you can add something ($2\pi i$ it turns out) to your logarithm, which corresponds to multiplying by something that takes you once around the circle.  This is maybe an easier to see, more intuitive relationship.
Answer:
How is the natural logarithm related so closely to circles ?

The natural logarithm is $\ln x=\displaystyle\int_1^x\frac1t~dt.~$ Now, $f(t)=\dfrac1t~$ is a hyperbola, which, when
rotated by an angle of $45^\circ,$ and scaled by a factor of $\sqrt2,~$ yields $x^2-y^2=1,$ which looks
remarkably similar to the equation of the unit circle, $x^2+y^2=1,$ whose constant is $\pi.$
Substituting y by iy in the former equation will yield the latter expression, and vice-versa.
Also, circles and hyperbolas are both conic sections. So it should come as no surprise if one
were to find a formula involving Euler's constant e and imaginary numbers, ultimately
linking the two famous types of geometric shapes, known and studied since ancient times.

I also recommend the following related questions:

Why are $e$ and $\pi$ so common as results of seemingly unrelated fields?
Am I wrong in thinking that $e^{i \pi} = -1$ is hardly remarkable?
Is it possible to intuitively explain, how the three irrational numbers $e$, $i$ and $\pi$ are related?
What could the ratio of two sides of a triangle possibly have to do with exponential functions?
Factorial in power series; intuitive/combinatorial interpretation?
How fundamental is Euler's identity, really?
Answer: $ \ln{\left( x+ \hat{i}\,y \right)} =
  \ln{\sqrt{\left( x^2+y^2 \right)}+ \hat{i}\,\tan^{-1}\left(\dfrac{y}{x}\right)}
 $
when polar coordinates are used $x=r\,\cos\theta$ , $y=r\,\sin\theta$
$ \ln{\left( r\,\cos\theta+ \hat{i}\, r\,\sin\theta \right)} =
  \ln{r} + \hat{i}\,\theta
 $
So the logarithm of an complex number represents the rotation angle in the imaginary units.


CocoaPods added a new project but I can't add it to existing GitHub

Question: I am fairly new to GitHub and I can't figure out how to add a folder to my current repository.  I was able to create a repository and push my first project up to it.
I created a new branch, checked it out, and then added pods to it using CocoaPods.  I have everything working the way I like and would like to push everything back up to GitHub.  Xcode does not recognize the new Pods folder as part of the branch, nor can I add the files to it.
I have the GitHub application on my MacBook and it recognized the new workspace that was created by CocoaPods and pushed it up to the GitHub repository.  But it doesn't recognize the Pods folder either.  I tried dragging the folder onto the GitHub app but it want's to create a new repository.
All I need to do is include the Pods directory in my existing GitHub branch.  How is this accomplished?  Any help is greatly appreciated.
Answer: I finally discovered the problem.  For some reason the .gitignore file had the PODS folder included. Then I used the "git add" command to add the folder.  Xcode still appeared to have problems committing the new files, so I used the GitHub application to perform the commit.  Once that was finished I went back to Xcode and pushed the latest changes up to GitHub.  It finally worked.


Unique decoding

Question: Suppose that we have a block code $C$ which has unique decoding, meaning that for all words $x$ (not necessarily in the code) there exists a unique word $c$ in the code with minimum distance (i.e. the other words in $C$ are at distance strictly greater than $c$ from $x$).
I want to know if under this condition the code is a Hamming code, i.e. the Hamming bound is attained.
Comment: _"a Hamming code, i.e. the Hamming bound is attained"_ Some terminology issue here. A code where "the Hamming bound is attained" is not a Hamming code, but a "perfect code". (Hamming codes happen to be perfect codes, but that's other thing)
Comment: Sorry - I meant a perfect code, not a Hamming code.
Answer: For a rather trivial counterxample, consider some perfect code, and augment it by adding a 0 in the last position.
Comment: Very nice counterexample. Thanks a lot.

Unique decoding


Is it possible to play bongos on bed?

Question: I'm not sure if this the right place to ask this, can a patient play bongos while in bed? He cannot bend one of his knees. I understand that there is a bongo stand that can be put on the ground, but this won't work in his case.
I would like to know if there are any ideas to play it
Comment: Yes, but only if he's in a private single room...
Answer: Using a normal drum/cymbal stand with a boom arm would be likely to tip over while playing it. So my thinking would be to have a stand that straddles the bed with legs on either side and a bar going across the bed. The stand would be similar to a drum rack like this:

These type of drum racks are quite expensive (at least $200 or more) and probably overkill for just a set of bongos, but you could probably rig up a similar design using inexpensive PVC pipe. Something like this:

PVC pipe will be lighter but place something heavy over the bottom feet and it should stay in place and not move around. This type of PVC stand will also come apart easily so you can store it away when he's not playing.
Next you will need some kind of bongo clamp that will grip the bongos themselves like this (but without using the part that attaches to the seat):

And finally a clamp that will clamp the bongo stand to the main drum rack/PVC rack.

Or you could try to DIY some kind of clamp/strap that will attach the bongos to the main stand and hold them in place to save money. Buying actual drum hardware will be a lot more expensive than rigging up something yourself.
So hopefully these give you some ideas. And if you decide to go with the PVC stand, then as an optional designer note you can spray paint it black so it doesn't look as bad as the cheesy white PVC pipe. :)
Answer: "Proper" bongo technique requires the player siting with the instrument between his/her legs. This allows the arms and hands to approach the top of the instrument with the best angle (the bongos slightly bending outward from the player).
I expect it will difficult while sitting in bed to obtain this optimal situation and furthermore almost for sure the instrument will be to high in relation to the body, forcing to bend the wrists and/or keeping the arms to high, which will be prone to cause fatigue or even injury.
Also, a good pair of bongos is relatively heavy (and blunt) object, laying it over ones legs, let alone an injured one, for a long period of time will probably bee very uncomfortable.
Having said that, and in the interest of the patient :-) here are a couple of ideas:

A smaller instrument - serious players will frown upon this, but if the purpose is to entertain and/or allow to practice, a smaller, lighter instrument will be more favorable to use in bed.

A plastic (ABS) instrument - again, this won't probably satisfy a serious player, but it's very light and comfortable to handle (no blunt "bumps") , which may be the most relevant factor in this case.

A wooden "bongo cajon". I gather this is a comparatively expensive option but seems to provide the most stable base and seems to be a little less tall than regular bongos, which in this case will be an advantage. Note that I've never tried this tpye of instrument, so I don't know what kind of sound it produces and if the touch and feel is comparable to a "real" bongo (probably not).

If you have the chance look for these kind of alternatives in a store and see what could work best, if not, probably an ABS "regular" bongo would be most sure and cost effective bet.

Is it possible to play bongos on bed?


Why can't 184.108.40.206 resolve a certain name (SERVFAIL)?

Question: I've noticed that the cloudflare nameserver can't resolve certain DNS-names and replies with a SERVFAIL. However, when I run the dig command, I still get a reply. Why is that?
$ dig sdo.gsfc.nasa.gov @188.8.131.52

; <<>> DiG 9.11.4-4-Debian <<>> sdo.gsfc.nasa.gov @126.96.36.199
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 2956
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1452
;; QUESTION SECTION:
;sdo.gsfc.nasa.gov.     IN  A

;; ANSWER SECTION:
sdo.gsfc.nasa.gov.  300 IN  CNAME   gs671-sdoweb.ndc.nasa.gov.
gs671-sdoweb.ndc.nasa.gov. 827  IN  A   18.104.22.168

;; Query time: 763 msec
;; SERVER: 22.214.171.124#53(18.104.22.168)
;; WHEN: Di Aug 28 10:56:15 CEST 2018
;; MSG SIZE  rcvd: 93

Comment: @Esa You have to look at it twice. It's a SERVFAIL with two entries in the answer section section. I...don't think I've actually seen that before.
Comment: Where's the example of it not working as expected?
Comment: Totally missed that it was in the same example. Didn't see that coming! Now it has become interesting.
Answer: Assuming that your paste has not been modified in any way (i.e. combining pastes from two different outputs by accident), what you've posted is not a behavior commonly seen in the wild. I was not able to reproduce the behavior at the time of this answer.
A SERVFAIL indicates an immediate failure in DNS resolution, and is usually accompanied by 0 answers. To provide an answer in this context would normally be a contradiction: if you were able to provide an answer, why would you would you flag the response as a server failure?
Unless this is an implementation of a new experimental RFC that I have not seen yet (I'll ping some vets in the comments), this is most likely to be a bug within the software itself. No one on Serverfault can provide technical assistance for a bug of this nature, so your best bet is to open up a ticket with Cloudflare and ask them to look into it.
Comment: @PaulVixie Have either of you seen this in the wild before? I'm not aware of any standards (experimental or otherwise) that assign a meaning to SERVFAIL with >0 answers.
Comment: @Alnitak (had to split this into two comments, only one notification allowed per)
Comment: Cloudflare is big on writing their own server software. I would not be surprised to find out it's a bug in a custom DNS server.
Comment: It appears that they've fixed it.

Why can't 1.1.1.1 resolve a certain name (SERVFAIL)?


STM32 blinking LED wrong register?

Question: Has anyone an idea why the code doesn't work?
RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
GPIOB->MODER &= ~(0x3u << 6u);
GPIOB->MODER |= (0x1u << 6u);
for (int i = 0; i < 1000; i++) {
    GPIOB->ODR |= (0x1u << 0x3u);
}

I'm using a STM board (STM32L432KC) which has an integrated LED that is called pin PB3 (Port 26) but after flashing nothing happens. Actually there should shine a LED. Do I use the right register?
Comment: one sets bit 3 the other sets bit 19, if you look at the bsrr register you see that one bit makes that pin high one makes it low.  one of the two high or low will turn the led on the other off.  so i fyou want to blink it as in your title question, then you need to go on and off at human speed.
Comment: you are not blinking the led with that code and you dont have a delay in there anyway.  depending on how your board is designed you may need to make the pin low to turn the led on.  you can use the bsrr register and you can just use GPIOB->BSRR = 1<<3 and then try 1<<(3+16).  and to blink use those two register bits with a delay in between
Comment: assuming that all the magic numbers, the structure and defines are correct per the manual then you are doing the steps needed to set up the port, correctly and that is the minimum required.
Comment: Thank you but why I've to do the second shift 1 << (3+16)?
Comment: if your code is not turning the led on then as mentioned try making the pin low and see if that makes the led go on.  Have you looked at the schematic?  What does it show?
Comment: what does the disassembly of both this section and the vector table show?  (will ultimately confirm the register addresses being used and how).
Comment: To you mean the main.S file?
Comment: no, disassembly of the binary that helps show if your vector table is right and the part is booting correctly, if the register addressing is right, etc.
Comment: if you had indicated the board being a nucleo, and that would have shown that 1 on the pin turns the led on, and that the led was turning on for you, but not turning off (blinking) that would have more directly lead to an answer instead of us guessing.
Answer: You're setting a bit in the ODR but never clearing it, so it won't flash, you will need a delay between on/off transitions to be able to visibly see it flashing.
It's good practice to write to the BSRR register instead of the ODR too where possible, this allows you to avoid read-modify-write cycles.
If that code is your whole main() then you might want to replace the for (int i = 0; i < 1000; i++) with a while(1), you generally don't want to return from main in an embedded context.
Comment: Is this a commercially available board, what board is it?
Comment: Thank you very much! but the LED isn't still flashing. Actually it isn't even glowing. Do I am on the right path how I'm using the register addresses? The LED is as said PB3. Maybe the LED is only damaged?
Comment: It's  STM32 by ST NUCLEO-L432KC Nucleo Development Board. The schematic shows PB3 as green LED.
Answer: This sequence is wrong (I did not check if you use the correct RCC register)
RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
GPIOB->MODER &= ~(0x3u << 6u);

When you enable the peripheral clock you need to readback the value or add some delay your changes to propagate through the bus. I usually use the barrier instruction for that.
RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
__DMB();
GPIOB->MODER &= ~(0x3u << 6u);

If you do not add this delay (or readback) the first opearation will fail as it will be performed on the non clocked GPIO periperal.
Comment: Never had that problem with any of these parts, this is C code, plenty of delay.  Technically possible with some designs, but not the STM32s.
Comment: right per that document, this code is written in C...so more than two clocks, done, no need to read anything.
Comment: @old_timer it well known issue using the STM32s. I am surpised that you have not heard about it. If you access the peripheral befoe the clock is set, the next accesses to the registers can be also wrong.  For example STM in low level driver does the readback
Comment: Thank you, makes sense! I've add this line but the it's still nothing happens (I checked the pin already).
Comment: I found the problem it executes the program only once (I push this problem in another thread cause the title problem is solved).
Comment: I found the problem. Seems like I have only to push the start/restart button (after pushing it works).
Comment: @old_timer I afraid you do not have too much experience with stm32. Read the Referance Manual RCC section of **any** STM32.  And the remark about the plenty of time in C code does not make any sense.
Comment: dozens of different stm32 chips, almost every family. countless custom chips and fpgas, etc with special timing...Im sorry you dont understand.
Comment: even if asm you would have to specifically put effort into violating that timing intentionally arranging the instructions and then you cant guarantee that you violate it .
Comment: yes, a read will insure it in most designs (not all)(in general), but can be overkill.  Wasnt the problem here clearly, for product firmware the read back is a good idea to insure the timing is exceeded.  calling a bx lr function from C would also exceed it as well.
Comment: If you worded your answer as being free advice rather than this is the problem because from experience you should know it wasnt, then that would have been fine.
Comment: I have a board on order, will try it out.
Comment: `#define __HAL_RCC_GPIOB_CLK_ENABLE()   do { \
                                        __IO uint32_t tmpreg = 0x00U; \
                                        SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\
                                        /* Delay after an RCC peripheral clock enabling */ \
                                        tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\
                                        UNUSED(tmpreg); \
                                          } while(0U)`

STM32 blinking LED wrong register?


php regex non-match group

Question: i have string
sdasdsa

how to match string with regex
sdasdsa

i tried this pattern but it cannot match
[^()]*?

Comment: If you know, there's no tags inside ``...`` the simplest way possibly is just to match [negated](http://www.regular-expressions.info/charclass.html#negated) `<` between. Pattern like `~[^<]*~` ([see regex101](https://regex101.com/r/nS1fH5/1))
Answer: You can use the following:
(?:(?!).)*?<\/font>

See DEMO

php regex non-match group


Resgatar valor querystring pelo load do jquery

Question: Estou tentando chamar uma pagina através do load, essa pagina terá uma querystring que eu quero pega-la na pagina de chamada, porém o valor vem como null quando eu tento através do load, fora dele chamando a pagina sozinha, está tudo ok.
São 2 páginas, 1 principal e a 2 que trara um alert de acordo com o valor passado pela query
Página Principal (index.html)

resultado

Segunda página (video.html)

Se você fizer o teste chamado já a segunda pagina com a query assim /video.html?v=teste123 um alert de "teste123" vai aparecer, porém quando tento fazer isso pela página principal passando o parametro da query e trazendo o resultado por load, simplesmente da erro e o valor vem como null.
Alguém poderia me explicar aonde estou errando?
Answer: O seu código está correto, o problema ocorre onde o javascript é executado. Como você faz uma chamada Ajax e joga o conteúdo em "#content", o javascript é executado na mesma página que você está, ou seja, o "window.location.href" é o da página inicial (index.html). Você pode fazer um teste adicionando "v=teste" ao carregar a página principal.


Command Line Args in pascal

Question: I am new in pascal I have a program which gives result ....
I need to pass command line input in in given variable ip1 and ip2.
Its can be achieved by ParamStr[1] but it doesn't work.
  program main;
      var
        output : integer;
      var
        ip1 : integer;
      var
        ip2 : integer;

    function add(input1,input2:integer) : integer;
       var
       result: integer;
    begin
       if (input1 > input2) then
          result := input1
       else
          result := input2;
       add := result;
    end;

    begin
      ip1 := 2533;**{ command line input}**
      ip2 := 555;**{ command line input}**

      output := add(ip1,ip2);
      writeln( ' output : ', output );
    end.K

Comment: What exactly do you mean by `its not works`? Are you having trouble converting the ParamStr values to integer, or what?
Comment: Your function `add` should be called `max` because it does not add the arguments but returns the maximum.
Comment: Hello all, Its Not matter what my function name my problem is how can i pass ip1 and ip2 value using command line. is there any function like args or argv in C or something else....
.pls help...
Answer: As the other answer says, you use ParamCount and ParamStr to access command line parameters.
ParamCount returns the number of parameters passed on the command line, so you should check it first to see if you've received enough information.
ParamStr allows you to access each of the parameters passed. ParamStr(0) always gives you the full name of the executing program (including the path). Additional parameters are retrieved using the ordinal order in which they were passed, with ParamStr(1) being the first, and ParamStr(ParamCount) being the last. Each value received using ParamStr is a string value, and therefore has to be converted into the appropriate type before you can use it.
Here's a working example (pretty trivial, and all error checking omitted - you should, for instance, protect the code using StrToInt to handle errors if something is provided that won't convert to an integer).
program TestParams;

uses
  SysUtils;

var
  Input1, Input2, Output: Integer;

begin
  if ParamCount > 1 then
  begin
    Input1 := StrToInt(ParamStr(1));
    Input2 := StrToInt(ParamStr(2));
    Output := Input1 + Input2;
    WriteLn(Format('%d + %d = %d', [Input1, Input2, Output]));
  end
  else
  begin
    WriteLn('Syntax: ', ParamStr(0));  { Just to demonstrate ParamStr(0) }
    WriteLn('There are two parameters required. You provided ', ParamCount);
  end;
  WriteLn('Press ENTER to exit...');
  ReadLn;
end.

Calling it without parameters (or only one) displays the following:
C:\Temp>TestParams
Syntax: C:\Temp\TestParams.exe
There are two parameters required. You provided 0
Press ENTER to exit...

C:\Temp>TestParams 2
Syntax: C:\Temp>TestParams.exe 2
There are two parameters required. You provided 1
Press ENTER to exit...

Calling it with two parameters displays
C:\Temp\TestParams 2 2
2 + 2 = 4
Press ENTER to exit...

Comment: I'd certainly like to hear from the downvoter what the reason was for doing so, so I can improve my answer by addressing the deficiency.
Comment: Facing this error...!!!

 Free Pascal Compiler version 2.6.2 [2013/02/16] for x86_64
    Copyright (c) 1993-2012 by Florian Klaempfl and others
    main.pas(22,22) Error: Identifier not found "StrToInt"
    main.pas(23,22) Error: Identifier not found "StrToInt"
    main.pas(30) Fatal: There were 2 errors compiling module, stopping
    Fatal: Compilation aborted
    Error: /usr/bin/ppcx64 returned an error exitcode (normal if you did not specify a source file to be compiled).

Is there any pascal version error....?
Comment: You need to add `SysUtils` to your uses clause, just like mine does.
Answer: You need to understand the difference between a string and an integer.
To convert betwwen an integer such as 123 and the string of characters 1 2 3 you need to use a function. strtoint is one such function, converting a string to an integer. inttostr is another, converting from an integer to a string.
The command-line data is supplied via paramstr(n) as a string.
intvar := strtoint(paramstr(n));

assigns the value of the string to the integer variable intvar.
Whereas writeln has facilities to convert an integer argument to a formatted string, the way you have used it is attempting to output a string, so you need to convert the integer output to a string.
writeln(' output : ', inttostr(output) );

should do that very nicely.

var
  x : string;
  pcnt : integer;

begin
  writeln('Parameter count=',inttostr(paramcount));
  for pcnt := 1 to paramcount do
    writeln('Parameter ',pcnt, ' of ',paramcount,' = ',paramstr(pcnt));
  readln(x);
end.

should display the parameter list.
Indeed it is the case that the writeln procedure will recognise the variable type and take steps to format the value appropriately as a string, as has arrogantly been pointed out.
The issue to me is the difference between a string and an integer. paramstr returns a string which must be converted to an integer. After more than forty years' experience in Pascal, it's my opinion that it's better for a beginner to go through the exercise of converting each way and then use the conversion facility inbuilt in writeln.
First walk, then run. You first need to understand the steps in the procedure. Then you can start using the shortcuts - once you've mastered the basics.
Comment: Can you give me example how can  use ParamStr and paramCount using command line in above mention example....its very helpful.

Command Line Args in pascal


How to add / edit a cookie in php?

Question: I'm using the following functions to set an array of values in a cookie in PHP, but I also need an "add" and "edit" function - any suggestions on how I can do that?
function build_cookie($var_array) {
  if (is_array($var_array)) {
    foreach ($var_array as $index => $data) {
      $out.= ($data!="") ? $index."=".$data."|" : "";
    }
  }
  return rtrim($out,"|");
}

function break_cookie ($cookie_string) {
  $array=explode("|",$cookie_string);
  foreach ($array as $i=>$stuff) {
    $stuff=explode("=",$stuff);
    $array[$stuff[0]]=$stuff[1];
    unset($array[$i]);
  }
  return $array;
}

Usage:
setcookie("mycookies", build_cookie($cookies_array), time()+60*60*24*30);

$cookies_array2 = break_cookie(urldecode($_COOKIE['mycookies']));

    foreach ($cookies_array2 as $k => $v) {
        echo "$k : $v
\n";
    }

Answer: One thing that you should consider using is serialize and unserialize to encode your cookie data.  Just be careful though, from my experience you have to use stripslashes on the cookie value before you unserialize it.  This way you can unserialize the data, change the  values, reserialize the cookie and send it again.  Serialize will make it easier in the future if you want to store more complex data types.
for example:
setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

// This won't work until the next page reload, because $_COOKIE['mycookies']
// Will not be set until the headers are sent
$cookie_data = unserialize(stripslashes($_COOKIE['mycookies']));
$cookie_data['foo'] = 'bar';
setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

Comment: This looks simpler! Btw, isn't it stripslashes(), not strip_slashes()?
Answer: I would store just an id in the cookie and use a flat file (ini, serialized or plain text) or database to store the values. The thing is - cookie are severely space-limited and you should add as little as possible. One one of my latest projects i had to store alot of information and, since i had access to ssd drives, i put the arrays and objects serialized in zipped files and in the cookies i saved the id, and then some hashes of varios parts of the data to be able to do some quick validation.

And, from a security point of view, having just an id (and a hash of the local data so one can't easily change the id or some other form of verification of that id) is more secure than putting the data in the cookie.

Do you have any special reason to save data as cookies?

How to add / edit a cookie in php?


Oracle Apex Restful Services VS Code

Question: I have created Oracle Apex free account using link https://apex.oracle.com/en/
I have created tables and configured restful services for table. I can do get calls to API end point from Postman web as well as client version, but when I try to run python code in VS Code, I don't get any response back.
<code>import requests

url = "https://apex.oracle.com/pls/apex/my_workspacename/sample/"

payload = {}
headers = {
  'Authorization': 'Bearer token_copied_from_postmn',
  'Cookie': 'copied_from_postman'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
</code>
Answer: It worked when I used HTTP client instead of Requests

Oracle Apex Restful Services VS Code


Ruby dúvida apis

Question: Estava lendo na documentação do ruby no link sobre as classes padrões do ruby, porém eu vi que ele tem mais classes que a documentação mostra como yaml, onde posso encontrar essas apis? Quero saber quais apis existem em ruby.
Answer: esse link são para os core methods. Para consultar os métodos extras do Ruby a própria documentação já exibe, mas em outro local. Segue o link.
PS: inclui a documentação YAML que você citou!
Boa sorte.
Comment: Muito obrigado pela ajuda!!
Comment: @CarlosHenrique por nada! Precisando estamos ai!

Ruby dúvida apis


Flask returns no response - Postman 'java.lang.NullPointerException" error

Question: I'm trying to build a flask app that takes a file from the client, process it and send a return response. The problem is the application is giving the right response on a failed case (if no file is received), but, returning no response to client in a success case i.e., after processing the file.
from flask import Flask, request, jsonify

@application.route('/file', methods=['GET', 'POST'])
def sid():
    """
    Process the PDF File, and return response
    :return:
    """
    print(request)
    if request.method == 'POST':
        if request.files:
            result_after_processing = #After processing
            print(result_after_processing) # This is giving expected output
            return jsonify({'result': result_after_processing}, 200)
        else:
            return jsonify({'result': 'No file recieved'}, 400)

if __name__ == "__main__":
    application.run(debug=True)

I used postman to POST the file (though File upload (multipart/for-data)) to the endpoint.
If I POST any object other than a File, like empty or text (a fail case), I'm receiving the {'result': 'No file received'} which is expected. However, when I send the file, java.lang.NullPointerException is the result.
I even tried to hard code the valid case response to {'result': 'HardCodedValue'}, but the Pycharm RESTful service still returns java.lang.NullPointerException. In original, my output, result_after_processing is a JSON.
Note: the java.lang.NullPointerException is on Pro PyCharm's RESTful Webservice, not from Python. Python prints the expected result correctly.
I worked around for 5 hours, trying all possible solutions on the internet but still unsuccessful in figuring out the solution. Please help to give your inputs on this.
Thanks.
Comment: Try to use other client to upload a file.
Comment: Are you using Jython? and please give the error stack trace.
Comment: @Jacky, I'm working on Python 3.6. I think, the `NullPointerException` is from postman, as my return response is empty.
Comment: @stamaimer Thanks for the comment, I tried and it worked. Also, postman is correct, I was using the Pycharm's RESTful service.
Answer: Looks like the problem is with Pro PyCharm's "Test RESTful Webservice", I received the expected output when I used POSTMAN.


About LDA model, I need a true expert to tell me that what is the real benefits of the Dirichlet prior?

Question: Well,you know ,the only difference between pLSI and LDA is that the latter has a Dirichlet prior,thus the number of model parameters do not increase with the size of corpus,and this avoid the overfitting problem in pLSI.Furthermore,having a prior in the level of documents is good for making inference when handling a unseen doc.
Plus,the Dirichlet distribution is conjugate to Multinomial distribution ,which makes it easy for computing the posterior.
However,personally,the aforementioned there advantages are not the most powerful  benefit of Dirichlet prior! I think when D.Blei introduced this hyperparameter,some other wonderful ideas might strike him.
So,who could tell me the hidden power of this Dirichlet prior?
Answer: The answer is in your question. The only reason a Dirichlet prior is used is because it's the multinomial distribution's conjugate prior, which makes computation of the posterior easier, and collapsed Gibbs sampling feasible.
There is nothing magic about this distribution, or David Blei for that matter.