text:
Q: How do you take a screenshot of an angularjs app? I've tried:

*

*node-webshot

*phantomjs

I could do it locally but I couldn't take screenshots of other websites that are based on angularjs.
Bounty
Be able to take a screenshot of any angularjs app which includes jquery and angular on the page. Every single site here: http://builtwith.angularjs.org/ should look as if I loaded it in my browser.
Must be able to get the screenshot via the terminal so it could be run in a background process like a worker or something.
One random server (or whatever should be able to go to an offsite website and take a screenshot of it.)
It just needs to take an url that will inevitably host an angularjs app and output what you'd expect to see in your browser.
Does not need to be phantomjs or node-webshot.
Update 1
As of last night this is how I'm doing it.

*

*node-webkit (nodejs inside of chromium) compiled to linux-32

*leave open on a random laptop

*when it detects a screenshot needs to be taken (via firebase temporarily) it opens a iframe with that url

*waits 10 seconds (reasonable time to load a site/app)

*uses node-webkit api to screenshot itself

I have some work to do on this solution.

Update 2
This appears to be a potential solution but I've found that most of these solutions require opening a browser and taking the screenshot versus a headless browser like phantomjs.

*

*http://browsershots.org/documentation#HowToCreateANewScreenshotFactory

*Browserstack.com

Update 3
I'm continuing development on a production ready solution for this on github.
https://github.com/clouddueling/angular-snapshot
If you take this code and build it with node-webkit.app you will be able to run a screenshot server.

A: Have you tried wkhtmltopdf? It comes with a tool called wkhtmltoimage. It uses QtWebKit (A Qt port of the WebKit rendering engine) to render a web page, and converts the result to PDF or image format of your choice, all done at server side.
Because it uses WebKit, it renders everything (images, css and even javascript) just like a modern browser does. You can fine tune the parameters such as tweaking the JavaScript execution grace period.
In my use case, the results have been very satisfying and are almost identical to what browsers would render.
Here's a list of command options:
Name:
  wkhtmltoimage 0.11.0 rc2

Synopsis:
  wkhtmltoimage [OPTIONS]... <input file> <output file>

Description:
  Converts an HTML page into an image,

General Options:
      --allow <path>                  Allow the file or files from the specified
                                      folder to be loaded (repeatable)
      --checkbox-checked-svg <path>   Use this SVG file when rendering checked
                                      checkboxes
      --checkbox-svg <path>           Use this SVG file when rendering unchecked
                                      checkboxes
      --cookie <name> <value>         Set an additional cookie (repeatable)
      --cookie-jar <path>             Read and write cookies from and to the
                                      supplied cookie jar file
      --crop-h <int>                  Set height for croping
      --crop-w <int>                  Set width for croping
      --crop-x <int>                  Set x coordinate for croping
      --crop-y <int>                  Set y coordinate for croping
      --custom-header <name> <value>  Set an additional HTTP header (repeatable)
      --custom-header-propagation     Add HTTP headers specified by
                                      --custom-header for each resource request.
      --no-custom-header-propagation  Do not add HTTP headers specified by
                                      --custom-header for each resource request.
      --debug-javascript              Show javascript debugging output
      --no-debug-javascript           Do not show javascript debugging output
                                      (default)
      --encoding <encoding>           Set the default text encoding, for input
  -H, --extended-help                 Display more extensive help, detailing
                                      less common command switches
  -f, --format <format>               Output file format
      --height <int>                  Set screen height (default is calculated
                                      from page content) (default 0)
  -h, --help                          Display help
      --htmldoc                       Output program html help
      --images                        Do load or print images (default)
      --no-images                     Do not load or print images
  -n, --disable-javascript            Do not allow web pages to run javascript
      --enable-javascript             Do allow web pages to run javascript
                                      (default)
      --javascript-delay <msec>       Wait some milliseconds for javascript
                                      finish (default 200)
      --load-error-handling <handler> Specify how to handle pages that fail to
                                      load: abort, ignore or skip (default
                                      abort)
      --disable-local-file-access     Do not allowed conversion of a local file
                                      to read in other local files, unless
                                      explecitily allowed with --allow
      --enable-local-file-access      Allowed conversion of a local file to read
                                      in other local files. (default)
      --manpage                       Output program man page
      --minimum-font-size <int>       Minimum font size
      --password <password>           HTTP Authentication password
      --disable-plugins               Disable installed plugins (default)
      --enable-plugins                Enable installed plugins (plugins will
                                      likely not work)
      --post <name> <value>           Add an additional post field (repeatable)
      --post-file <name> <path>       Post an additional file (repeatable)
  -p, --proxy <proxy>                 Use a proxy
      --quality <int>                 Output image quality (between 0 and 100)
                                      (default 94)
      --radiobutton-checked-svg <path> Use this SVG file when rendering checked
                                      radiobuttons
      --radiobutton-svg <path>        Use this SVG file when rendering unchecked
                                      radiobuttons
      --readme                        Output program readme
      --run-script <js>               Run this additional javascript after the
                                      page is done loading (repeatable)
      --disable-smart-width           Use the specified width even if it is not
                                      large enough for the content
      --enable-smart-width            Extend --width to fit unbreakable content
                                      (default)
      --stop-slow-scripts             Stop slow running javascripts (default)
      --no-stop-slow-scripts          Do not Stop slow running javascripts
      --transparent                   Make the background transparent in pngs
      --user-style-sheet <url>        Specify a user style sheet, to load with
                                      every page
      --username <username>           HTTP Authentication username
  -V, --version                       Output version information an exit
      --width <int>                   Set screen width, note that this is used
                                      only as a guide line. Use
                                      --disable-smart-width to make it strict.
                                      (default 1024)
      --window-status <windowStatus>  Wait until window.status is equal to this
                                      string before rendering page
      --zoom <float>                  Use this zoom factor (default 1)

Specifying A Proxy:
  By default proxy information will be read from the environment variables:
  proxy, all_proxy and http_proxy, proxy options can also by specified with the
  -p switch

  <type> := "http://" | "socks5://"
  <serif> := <username> (":" <password>)? "@"
  <proxy> := "None" | <type>? <sering>? <host> (":" <port>)?

  Here are some examples (In case you are unfamiliar with the BNF):

  http://user:password@myproxyserver:8080
  socks5://myproxyserver
  None

Contact:
  If you experience bugs or want to request new features please visit
  <http://code.google.com/p/wkhtmltopdf/issues/list>, if you have any problems
  or comments please feel free to contact me: <uuf6429@gmail.com>

A: Although not personally tried it myself, I have seen service deployed in production that takes screenshots using Webdriver from Selenium.

*

*Build the selenium Webdriver https://code.google.com/p/selenium/

*Use the RESTful API to communicate with the server. There are specific calls where you can issue request to fetch a website, and take a screenshot of the current instance

everything is done in the background, so I think it fits your requirement.

A: Use browserstack to test your application in all browsers without having to install each one, including mobile browsers, different phones, tablets, etc.
There is support for Selenium automated testing and screenshots. Local testing is supported, no public URL is needed.
The screenshots API is available for configuring the screenshots you need, Screenshooter is a a tool for generating BrowserStack screenshots from the command line.
There is a trial period for this as it's a commercial product, but it's very well made and worth every penny. You can subscribe for only one month. I have used personally and I highly recommend it.

A: Probably this will help https://bitbucket.org/vodolaz095/site-shooter
This is nodejs+phantomjs application to make site screenshots
You need a heroku free tier service to run this.
BTW, you can try this application - https://pageshooter.herokuapp.com
i think it can make screenshots of angularjs sites

A: Node-Webshot uses PhantomJS which in turn uses QtWebkit which doesn't work with AngularJS.
More info: https://github.com/angular/angular.js/issues/2985
Suggestion. Make sure the PhantomJS you have bundled within Node-Webshot is absolutely the latest version. If not, replace the PhantomJS with the latest version and prey for them to have fixed it by now.
If you have access to the command line options of PhantomJS, you could try a few of them in here: https://github.com/ariya/phantomjs/wiki/API-Reference
The ones particularly riging the bell are:
--ignore-ssl-errors=true
--local-to-remote-url-access=true
--web-security=false


text:
Q: Linear Layout grid showing in emulator but not on device, what could be cause? I am currently running an activity that works fine on an emulator (Nexus 5X API 27), however when executing it on a device (Samsung S8 Plus); the linear layout grid does not appear. I've added the proper constraints but they still don't show.
Tried shifting the textviews to make more space for the Linear Layout grid but still no use.
A screenshot of how the activity should look like:
https://imgur.com/a/I2wEgZW
Here is the Activity Code:
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class Badges extends AppCompatActivity {
    private static String TAG = "Badges.Class";
    private static ImageView badge1,badge2, badge3, badge4, badge5, badge6, badge7, badge8, badge9, questionBadge;
    private Button summaryButton;
    public static int b1, b2, b3, b4, b5, b6, b7, b8, b9;
    public static String currentUser;
    public static int badgePoints;
    public static TextView textPointsValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_badges);

        //Creating Badge Icons and greying them out
        badge1 = findViewById(R.id.imageBadge1);
        badge2 = findViewById(R.id.imageBadge2);
        badge3 = findViewById(R.id.imageBadge3);
        badge4 = findViewById(R.id.imageBadge4);
        badge5 = findViewById(R.id.imageBadge5);
        badge6 = findViewById(R.id.imageBadge6);
        badge7 = findViewById(R.id.imageBadge7);
        badge8 = findViewById(R.id.imageBadge8);
        badge9 = findViewById(R.id.imageBadge9);

        badge1.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge2.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge3.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge4.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge5.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge6.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge7.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge8.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
        badge9.setColorFilter(this.getResources().getColor(R.color.transparentDarken));

        //Creating Summary Button
        summaryButton = findViewById(R.id.summaryButtonBadge);
        summaryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(Badges.this,BadgesSummary.class);
                startActivity(myIntent);
            }
        });

        //Create Back Button
        ImageView backButton = findViewById(R.id.badgeBackButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(Badges.this,Home.class);
                startActivity(myIntent);

            }
        });

        //Question Mark Button
        //Have yet to set up logic for this
        questionBadge = findViewById(R.id.questionButBadge);
        questionBadge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //******Add Logic in here*****
            }
        });

        //Points text
        textPointsValue = findViewById(R.id.textPointsValue);

        Log.d(TAG, "onCreate: the value of current user is " + currentUser);

        //Staged Scenarios
        if(currentUser.equals("test")){
            //badge1.setColorFilter(this.getResources().getColor(R.color.transparentDarken));
            Log.d(TAG, "onCreate: Ran the currentUser test method, and the value of current " +
                    "user " + currentUser);

            badgePoints = 0;
            badge1.setColorFilter(null);
            addPoints(50);
            b1=1;
            badge2.setColorFilter(null);
            addPoints(200);
            b2=1;
            badge3.setColorFilter(null);
            addPoints(300);
            b3=1;
            badge4.setColorFilter(null);
            addPoints(50);
            b4=1;

        }

        else if(currentUser == "gg"){

        }

        else if(currentUser == "jason"){

        }
        //Scenario one

    }

    //Public method to reset the values
    public static void resetBadge (){
        //This resets all badges.
        //Should only be ran when a new user is created.
        b1 = 0;
        b2 = 0;
        b3 = 0;
        b4 = 0;
        b5 = 0;
        b6 = 0;
        b7 = 0;
        b8 = 0;
        b9 = 0;

        badgePoints=0;
        textPointsValue.setText(String.valueOf(badgePoints));

        Log.d(TAG, "resetBadge: Badges have been reset due to new user login");

    }

    public static void setCurrentUser(String user){
        Badges.currentUser = user;
        Log.d(TAG, "setCurrentUser: User has been updated " + user);
    }

    public static void addPoints(int value){
        badgePoints = badgePoints  + value;
        textPointsValue.setText(String.valueOf(badgePoints));
    }

    public static void achieveBadge1(){
        //Create Avatar and profile
        if(b1 == 0){
            badge1.setColorFilter(null);
            addPoints(50);
            b1=1;
        }
    }

    public static void achieveBadge2(){
        //Choose major
        if(b2 == 0){
            badge2.setColorFilter(null);
            addPoints(200);
            b2=1;
        }
    }

    public static void achieveBadge3(){
        //Finish Degree
        if(b3 == 0){
            badge3.setColorFilter(null);
            addPoints(300);
            b3=1;
        }
    }

    public static void achieveBadge4(){
        //Redeem a Reward
        if(b4 == 0){
            badge4.setColorFilter(null);
            addPoints(50);
            b4=1;
        }
    }

    public static void achieveBadge5(){
        //Log in 7 days
        if(b5 == 0){
            badge5.setColorFilter(null);
            addPoints(100);
            b5=1;
        }
    }

    public static void achieveBadge6(){
        //Earn 500 points
        if(b6 == 0){
            badge6.setColorFilter(null);
            addPoints(100);
            b6=1;
        }
    }

    public static void achieveBadge7(){
        //Reviewed a Course
        if(b7 == 0){
            badge7.setColorFilter(null);
            addPoints(200);
            b7=1;
        }
    }

    public static void achieveBadge8(){
        //Saved a course
        if(b8 == 0){
            badge8.setColorFilter(null);
            addPoints(50);
            b1=1;
        }
    }

    public static void achieveBadge9(){
        //Update a wam
        if(b9 == 0){
            badge9.setColorFilter(null);
            addPoints(100);
            b9=1;
        }
    }
}

Here is the XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Badges">

    <ImageView
        android:id="@+id/badgeBackButton"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginStart="3dp"
        android:layout_marginTop="29dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/back_arrow" />

    <ImageView
        android:id="@+id/questionButBadge"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/question" />

    <TextView
        android:id="@+id/textPointsBadge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="176dp"
        android:layout_marginEnd="176dp"
        android:text="Points"
        android:textColor="@color/colorLightPurple"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textPointsValue" />

    <TextView
        android:id="@+id/textPointsValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="176dp"
        android:layout_marginEnd="177dp"
        android:text="650"
        android:textColor="@color/colorLightPurple"
        android:textSize="35sp"
        app:layout_constraintBottom_toTopOf="@+id/textPointsBadge"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView13" />

    <TextView
        android:id="@+id/badgesText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="139dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="139dp"
        android:gravity="center"
        android:text="Badges"
        android:textAlignment="center"
        android:textColor="@color/colorLightPurple"
        android:textSize="40dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/summaryButtonBadge"
        android:layout_width="161dp"
        android:layout_height="48dp"
        android:layout_marginStart="69dp"
        android:layout_marginEnd="69dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/purple_square_button"
        android:text="See Summary"
        android:textAllCaps="false"
        android:textColor="@color/colorWhite"
        android:textSize="17dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <LinearLayout
        android:id="@+id/linIconGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="10dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textPointsBadge">

        <LinearLayout
            android:id="@+id/linTopRow"
            android:layout_width="match_parent"
            android:layout_height="114dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageBadge1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge1" />

            <ImageView
                android:id="@+id/imageBadge2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge2" />

            <ImageView
                android:id="@+id/imageBadge3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge3" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linMidRow"
            android:layout_width="match_parent"
            android:layout_height="114dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageBadge4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge4" />

            <ImageView
                android:id="@+id/imageBadge5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge5" />

            <ImageView
                android:id="@+id/imageBadge6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge6" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linBotRow"
            android:layout_width="match_parent"
            android:layout_height="114dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageBadge7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge7" />

            <ImageView
                android:id="@+id/imageBadge8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge8" />

            <ImageView
                android:id="@+id/imageBadge9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                app:srcCompat="@drawable/badge9" />

        </LinearLayout>
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView13"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginStart="178dp"
        android:layout_marginEnd="178dp"
        android:textAlignment="center"
        app:layout_constraintBottom_toTopOf="@+id/textPointsValue"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/badgesText"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/onboarding2_logo2" />

</android.support.constraint.ConstraintLayout>

A: I think your Layout is exceeding the screen size but not scrolling. You have assigned fixed size for some the layout elements. Try enclosing the constraintLayout using a nestedScrollView.
But also note one thing:
<LinearLayout
    android:id="@+id/linIconGrid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="10dp"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textPointsBadge">

why are using match_parent for a direct child of constraintLayout? If you want to use the full width set the width as 0dp and use these
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintStart_toStartOf="parent"

A: I found that images being used were too large (in terms of capacity e.g. 7mb each). I made the images smaller in size and everything began working fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding "${SDK_DIR}/usr/include/libxml2" to Header Search Paths breaks cocoapods I used this solution to add libxml2.2.dylib to an old project I'm updating.
The imports look like
#import <libxml/HTMLparser.h>
so I'm pretty sure I need to add "${SDK_DIR}/usr/include/libxml2" to Header Search Paths.
Trouble is when I do that I get a linker error because cocoapods blows up.
ld: library not found for -lBolts
When I set Header Search Paths back to default the pods work but the HTMLParser.h file is not found.
I tried changing the import to #import <libxml2/libxml/HTMLParser.h> but there's imports within the library using the libxml and I can't change them.
Any ideas how I can make this work?  Thanks!

A: Add $(inherited) & /usr/include/libxml2 to the HEADER_SEARCH_PATHS and
-lxml2 into OTHER_LDFLAGS in the build settings.
#import <libxml/HTMLparser.h>

Hope it will work.


text:
Q: Audit file modifications over ssh in linux I wanted to monitor all the modifications made to a file in a Linux server (Redhat). I made some research and found this auditing tool which I have already installed and configured using following commands:
yum install audit # installation

/etc/init.d/auditd start # started service

auditctl -w /root/file-name -p war -k password-file # configured rule to audit file

ausearch -f /root/file-name    # Command to search modifications

It has recorded all of the modifications made to the specific file. Everything was good until I came across the following following scenarios:
Case 1 :
I have deleted the file which I am monitoring using the aforementioned audit tool from the server using following command:
rm -rf /root/file-name

It recorded the following results:
type=SYSCALL msg=audit(1540222267.321:1057): arch=c000003e syscall=2 success=yes exit=3 a0=7ffe22abf91a a1=941 a2=1b6 a3=7ffe22abed70 items=2 ppid=21053 pid=42458 auid=14628 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=5 comm="touch" exe="/bin/rm" key="password-file"
Case 2 :
I have deleted the file from a remote server using following command:
ssh host "echo 'rm -rf /root/file-name'|sudo su - root"

It recorded the following results:
type=SYSCALL msg=audit(1540222588.196:1118): arch=c000003e syscall=263 success=yes exit=0 a0=ffffffffffffff9c a1=ce70c0 a2=0 a3=7fff52a6af40 items=2 ppid=42520 pid=42533 auid=14628 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=9 comm="rm" exe="/bin/rm" key="password-file"
Now the point that confuses me is why tty is recorded as none when I executed the command remotely. I have searched on the web regarding this but unfortunately I was not able to find anything which can clarify my confusion.
Could someone explain why it was recorded as tty=(none) in case 2?
Thanks in advance, please let me know if my question is unclear or something is missing, I will correct it.

A: When you give ssh a remote command to execute, it doesn't allocate an interactive tty, because one is not required. If you want to force tty allocation, use -t.


text:
Q: How to map a keyboard shortcut to CTRL+R in iTerm 2? I am trying to map the Command + Shift + Z shortcut to what vim uses for redo, CTRL + R:

What is the proper code I should enter in? It seems that \c is not the correct code, but I cannot find it on their website.

A: Instead of using the Send Text with "vim" Special Chars option, just send the hexadecimal code for the control character CTRL+R which is 0x12 as you can see from this table.
So to set it up for your desired combination of characters choose Send Hex Code and insert 0x12 as value:


text:
Q: AttributeError: 'Values' object has no attribute 'tab_width' when running sphinx-build When running:
sphinx-build -M html . _build

I get the following error:
Running Sphinx v3.0.3
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 9 source files that are out of date
updating environment: [new config] 9 added, 0 changed, 0 removed
/home/vinzee/.pyenv/versions/3.6.14/envs/venv/lib/python3.6/site-packages/recommonmark/parser.py:75: UserWarning: Container node skipped: type=document
  warn("Container node skipped: type={0}".format(mdnode.t))
reading sources... [ 66%] api
Exception occurred:
  File "/home/vinzee/.pyenv/versions/3.6.14/envs/venv/lib/python3.6/site-packages/sphinx/ext/autodoc/__init__.py", line 440, in get_doc
    tab_width = self.directive.state.document.settings.tab_width
AttributeError: 'Values' object has no attribute 'tab_width'
The full traceback has been saved in /tmp/sphinx-err-tm3jn6xm.log, if you want to report the issue to the developers.
Please also report this if it was a user error, so that a better error message can be provided next time.
A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks!

My versions:
Python: 3.6.14
sphinx-build: 3.0.3

How can I solve this error?

A: Pinning docutils<=0.16 works.
I found the answer on the Sphinx github repository.
The error is found on all docutils>0.16 versions.


text:
Q: Switch with 2 values or other mothode? I've got 2 variables: "tl_language" and "filterLanguage".
Right now I use this code:
switch($GLOBALS['TL_LANGUAGE'])
                        {
                            case 'de':
                                if (!$entry->field('beschreibung')->value()){

                                    include ("includes/mediacenter_content_de.php");
                                }else{
                                    include ("includes/mediacenter_content_en.php");
                                }
                                break;
                            case 'en':
                                if (!$entry->field('beschreibung')->value()){

                                    include ("includes/mediacenter_content_en.php");
                                }else{
                                    include ("includes/mediacenter_content_de.php");
                                }
                                break;
                            case 'fr':
                                if (!$entry->field('beschreibung')->value()){

                                    include ("includes/mediacenter_content_fr.php");
                                }else{
                                    include ("includes/mediacenter_content_en.php");
                                }
                                break;
                            case 'nl':
                                if (!$entry->field('beschreibung')->value()){

                                    include ("includes/mediacenter_content_nl.php");
                                }else{
                                    include ("includes/mediacenter_content_en.php");
                                }
                                break;
                            default:
                                echo $entry->field('beschreibung_englisch')->value();
                                break;
                        }

                        ?>

Now I want to add a Filter, that the user can seperatly filter for language.
E.g. if tl_language is "de" show germ an content or if filterLanguage is "de" show german content.
Right now, I'm tring someting like this:
    if($GLOBALS['TL_LANGUAGE'] =="de" or $cc_language == "de"){
    if (!$entry->field('beschreibung')->value()){

        include ("includes/mediacenter_content_de.php");
    }else{
        include ("includes/mediacenter_content_en.php");
    }
}
if($GLOBALS['TL_LANGUAGE'] =="en" or $cc_language == "en"){
     if (!$entry->field('beschreibung')->value()){

        include ("includes/mediacenter_content_en.php");
    }else{
        include ("includes/mediacenter_content_de.php");
    }
}

But it shows double content.

A: I would suggest to use a third variable. I assume $cc_language has more priority. Use your first code.
$lang = ( isset($cc_language)  && !empty($cc_language) ) ? $cc_language : $GLOBALS['TL_LANGUAGE'];

switch( $lang ) {


text:
Q: Neo-4j ETL Tool won't connect to local postgres Server. org.postgresql.util.PSQLException: The authentication type 10 is not supported I am using Neo4j version 1.4.1 and PostgresSQL 13 with PgAdmin 4.30. I recently installed PostgreSQL 13, before that I had PostgreSQL 12 and PgAdmin 4.24 when this ETL import thing worked.
But now, after removing PostgreSQL 12, I was trying to import my local postgres database to Neo-4j using the neo4j ETL tool.
My input connection detail:

Host= localhost
Port= 5432
Database= mydatabasename
Connection URL= jdbc:postgresql://localhost:5432/mydatabasename
Username=myUsername password="mypassword"

But when I click the Test and Save Connection button, it shows this error:

Jan 30, 2021 1:10:43 AM org.postgresql.Driver connect SEVERE:
Connection error:  org.postgresql.util.PSQLException: The
authentication type 10 is not supported. Check that you have
configured the pg_hba.conf file to include the client's IP address or
subnet, and that it is using an authentication scheme supported by the
driver.   at
org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:614)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:222)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.(PgConnection.java:194)   at
org.postgresql.Driver.makeConnection(Driver.java:431)     at
org.postgresql.Driver.connect(Driver.java:247)    at
java.sql.DriverManager.getConnection(DriverManager.java:664)  at
java.sql.DriverManager.getConnection(DriverManager.java:247)  at
org.neo4j.etl.rdbms.Support.testConnection(Support.java:32)   at
org.neo4j.etl.rdbms.Support.main(Support.java:74)
Connection failed. SQL state: 08004, message: The authentication type
10 is not supported. Check that you have configured the pg_hba.conf
file to include the client's IP address or subnet, and that it is
using an authentication scheme supported by the driver.

I took the help of this post Unable to connect to Postgress DB due to the authentication type 10 is not supported. I tried changing my pg_hba.conf settings and set the method to md5:

local   all             all                                     md5

I also configured my postgresql.conf like this:

listen_addresses = '*' port = 5432 max_connections = 100 password_encryption = md5

But nothing worked. I even tried reinstalling PostgreSQL 13 and PgAdmin 4.30.
I downloaded the latest JDBC version and tried to connect using that postgresql-42.2.18.jre7, but the same error. When I'm using a Java program to connect to this database, the connection is successful.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JavaPostgresIntegration {
    public static void main(String[] args) {
        Connection c = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydatabase", "postgres", "mypassword");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Opened database successfully");
        try {
            c.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output: Opened database Successfuly
(I am using the downloaded postgresql-42.2.18.jre7 for this program.)
Edit: I installed PostgreSQL 12 and it solved the problem. While when I was connecting to PostgreSQL 13 using Neo4j the error was still there.


text:
Q: Prevent Dismissal of UIViewController Presented with presentViewController I have two UIViewControllers in my app. Performing an action on UIViewControllerA loads UIViewControllerB or UIViewControllerC with no problem.
let destinationViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UIVCB") as! ViewControllerB
destinationViewController.results = result
self.presentViewController(destinationViewController, animated: true, completion: nil )

(I want to present the second view controller (B or C) modally because I want the user to deal with something there and not return to UIViewControllerA until he or she has done so.)
The problem is that clicking anywhere on UIViewControllerB or UIViewControllerC returns the user to UIViewControllerA. At first I thought I was instantiating these incorrectly, but someone has answered here and indicated that is not the problem. (And I find it hard to believe the problem is with code in B or C because it's affecting both of them.)
I have found dozens (hundreds?) of search results detailing how to dismiss a presented viewcontroller, but I can't seem to find any explaining how to prevent dismissing one.
Am I wrong to be using presentViewController() this way to load the second view? Or am I simply missing something obvious to prevent the second controller being dismissed by clicking anywhere on the screen?
Update: If I use this code to instantiate B or C, the problem of "clicking anywhere to dismiss" goes away:
self.navigationController?.pushViewController( destinationViewController, animated: true )

But I was under the assumption that I shouldn't be invoking the navigationController and / or pushing and popping because B and C are supposed to be modal and outside the navigation stack.


text:
Q: MVC Full Calendar doesn´t show the events I am implementing a calendar and I have encountered some difficulties because I am learning JavaScript alone and I have not mastered yet.
My problem is this: I can create the event and save it in the database, but the event and the color of it ... do not appear on the calendar ... can someone find out the solution or where is the problem?
If possible ... to create events ... being the color of this event always in random color?
View

                <button type="button" class="close" data-dismiss="modal">×</button>

                <button id="btnDelete" class="btn btn-default btn-sm pull-right">
                     Remover
                </button>
                <button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
                     Editar
                </button>

                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

                <button type="button" class="close" data-dismiss="modal">×</button>

Salvar Evento

                <form class="col-md-12 form-horizontal">
                    <input type="hidden" id="hdID_Reserva" value="0" />

                        Cliente
                        <input name="Nome" class="form-control" type="text" placeholder="Introduza o Nome" id="txtCliente">
                        <input type="hidden" id="txtID_Cliente" name="ID_Cliente" />

                        Data de Entrada

                            <input type="text" id="txtDataEntrada" name="DataEntrada" class="form-control" />

                        Data de Saida

                            <input type="text" id="txtDataSaida" name="DataSaida" class="form-control" />

                        Número Quarto

                        @Html.DropDownList("ID_Quarto", null, "Selecione o Quarto", htmlAttributes: new { @class = "form-control" })

                        Número Pessoas
                        <input id="txtNumeroPessoas" name="NumeroPessoas" class="form-control" />

                        Número Noites
                        <input id="txtNumeroNoites" name="NumeroNoites" class="form-control" />

                        Preço
                        <input id="txtPreço" name="Preço" class="form-control" />

                        Observações
                        <input id="txtObservaçoes" name="Observaçoes" class="form-control" />

                    <button type="button" id="btnSave" class="btn btn-success">Salvar</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </form>

<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.min.css" rel="stylesheet" />
<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.print.min.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
@section Scripts{

controller
namespace WebApplication.Controllers
{

    public class CalendárioReservasController : Controller
    {
        private HotelEntities db = new HotelEntities();
        // GET: CalendárioReservas
        public ActionResult Index()
        {
            ViewBag.ID_Quarto = new SelectList(db.Quarto, "ID_Quarto", "ID_Quarto");
            return View();
        }

        public JsonResult GetEvents()
        {
            try
            {
                var events = db.Reserva.Select(p => new
                {
                    ID_Reserva = p.ID_Reserva,
                    ID_Cliente = p.ID_Cliente,
                    ID_Quarto = p.ID_Quarto,
                    DataEntrada = p.DataEntrada,
                    DataSaida = p.DataSaida,
                    NumeroNoites = p.NumeroNoites,
                    NumeroPessoas = p.NumeroPessoas,
                    Preço = p.Preço,
                    Observaçoes = p.Observaçoes

                }).ToList();

                return Json(events, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(ex.Message);
            }
        }

        [HttpPost]
        public JsonResult SaveEvent(Reserva e)
        {
            var status = false;
            using (HotelEntities dc = new HotelEntities())
            {
                if (e.ID_Reserva > 0)
                {
                    //Update the event
                    var v = dc.Reserva.Where(a => a.ID_Reserva == e.ID_Reserva).FirstOrDefault();
                    if (v != null)
                    {
                        v.ID_Cliente = e.ID_Cliente;
                        v.DataEntrada = e.DataEntrada;
                        v.DataSaida = e.DataSaida;
                        v.ID_Quarto = e.ID_Quarto;
                        v.NumeroPessoas = e.NumeroPessoas;
                        v.NumeroNoites = e.NumeroNoites;
                        v.Preço = e.Preço;
                        v.Observaçoes = e.Observaçoes;
                    }
                }
                else
                {
                    dc.Reserva.Add(e);
                }

                dc.SaveChanges();
                status = true;

            }
            return new JsonResult { Data = new { status = status } };
        }

        [HttpPost]
        public JsonResult DeleteEvent(int eventID)
        {
            var status = false;
            using (HotelEntities dc = new HotelEntities())
            {
                var v = dc.Reserva.Where(a => a.ID_Reserva == eventID).FirstOrDefault();
                if (v != null)
                {
                    dc.Reserva.Remove(v);
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }
    }
}

Model
public partial class Reserva
    {
        public int ID_Reserva { get; set; }
        public int ID_Cliente { get; set; }
        public int ID_Quarto { get; set; }
        public System.DateTime DataEntrada { get; set; }
        public Nullable<System.DateTime> DataSaida { get; set; }
        public int NumeroPessoas { get; set; }
        public Nullable<int> NumeroNoites { get; set; }
        public Nullable<decimal> Preço { get; set; }
        public string Observaçoes { get; set; }

        public virtual Cliente Cliente { get; set; }
        public virtual Quarto Quarto { get; set; }
    }

A: Your event objects do not conform to the specification laid out at https://fullcalendar.io/docs/event-object .
Here is the problem:
$.each(data, function (i, v) {
  events.push({
    eventID: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    inicio: moment(v.DataEntrada),
    fim: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

FullCalendar doesn't speak Portuguese. The event property names have to match the ones in the documentation otherwise it will ignore them. It doesn't magically know that inicio means start, for example. This means it cannot read any start time from your event, and therefore it doesn't know how to display it on the calendar.
Again as per the documentation, your events are also required to have a title, which you didn't appear to include at all.
Try this instead:
$.each(data, function (i, v) {
  events.push({
    id: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    title: '[You need to choose something to put here]',
    start: moment(v.DataEntrada),
    end: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

I have just changed the properties which matter for displaying the event. For other custom properties, you can call them anything you like, but the ones which have a defined purpose in fullCalendar must be named correctly.
P.S. You may need to change the code in your eventDrop function in a similar way.


text:
Q: IDisposable / RAII in TypeScript? What is the idiomatic way of achieving deterministic clean-up in TypeScript? In other words, is there an equivalent of C#'s using (IDisposable) or C++'s RAII?
Or should I just stick to finally?

Context: In a SPA application (Aurelia / ASP.NET Core Web API), I'm trying to give an indication to the user that data is currently being fetched from the Web API. Once the fetch is finished, I'd like to remove the UI indication even if an exception has been thrown. I'm looking into wrapping that into a "RAII class" for reuse and cleaner syntax (so I don't have to pepper the code with finally)...

A: There is no using statement in Typescript, you can always fall back on try-finally which is what using is syntactic sugar for in C# anyway.
Another approach would be to create your own using with a function.
interface IDisposable {
    dispose();
}

function using<T extends IDisposable,
    T2 extends IDisposable,
    T3 extends IDisposable>(disposable: [T, T2, T3], action: (r: T, r2: T2, r3: T3) => void);
function using<T extends IDisposable, T2 extends IDisposable>(disposable: [T, T2], action: (r: T, r2: T2) => void);
function using<T extends IDisposable>(disposable: T, action: (r: T) => void);
function using(disposable: IDisposable[], action: (...r: IDisposable[]) => void)
function using(disposable: IDisposable | IDisposable[], action: (...r: IDisposable[]) => void) {
    let disposableArray = disposable instanceof Array ? disposable : [disposable];
    try {
        action(...disposableArray);
    } finally {
        disposableArray.forEach(d => d.dispose());
    }
}

// Usage
class UserNotify { dispose() { console.log("Done"); } }

class Other { dispose() { console.log("Done Other"); } }

using(new UserNotify(), userNotify => {
    console.log("DoStuff");
})
// It will type the arrow function parameter correctly for up to 3 parameters, but you can add more overloads above.
using([new UserNotify(), new Other()], (userNotify, other) => {
    console.log("DoStuff");
})

If you want to use it with promises, you could create an async version in which disposable returns a promise and the action parameter returns a promise as well:
interface IDisposableAsync {
    dispose(): Promise<void> | void;
}
function usingAsync<T extends IDisposableAsync, T2 extends IDisposableAsync, T3 extends IDisposableAsync>(disposable: [T, T2, T3], action: (r: T, r2: T2, r3: T3) => Promise<void>): Promise<void>;
function usingAsync<T extends IDisposableAsync, T2 extends IDisposableAsync>(disposable: [T, T2], action: (r: T, r2: T2) => Promise<void>): Promise<void>;
function usingAsync<T extends IDisposableAsync>(disposable: T, action: (r: T) => Promise<void>): Promise<void>;
function usingAsync(disposable: IDisposableAsync[], action: (...r: IDisposableAsync[]) => Promise<void>): Promise<void>
async function usingAsync(disposable: IDisposableAsync | IDisposableAsync[], action: (...r: IDisposableAsync[]) => Promise<void>): Promise<void> {
    let disposableArray = disposable instanceof Array ? disposable : [disposable];
    try {
        await action(...disposableArray);
    } finally {
        for (let d of disposableArray) {
            let result = d.dispose();
            if (result !== null) {
                await result;
            }
        }
    }
}

// Usage
class UserNotify { dispose() { console.log("Done"); } }
class Other { dispose() { console.log("Done Other"); } }
function delay() {
    return new Promise((r)=> setTimeout(() => {
        r();
    }, 100));
}
(async function () {
    await usingAsync(new UserNotify(), async userNotify => {
        await delay()
        console.log("DoStuff");
    })

    await usingAsync([new UserNotify(), new Other()], async (userNotify, other) => {
        await delay()
        console.log("DoStuff");
    })
})();

A: Unfortunately, there isn't language statements for it (like destructors and deterministic destruction). You have to use try { ... } finally { ... } statements for it.
If you want to know how it could be done in a way similar to C++, please take a look at https://github.com/cardinalby/ts-raii-scope when I tried to use RAII container and TypeScript decorators for that. But I'm not sure it's good for production code, because other developers could be confused with this approach.
Also I think it could be implemented by TypeScript transforms

A: You can use WeakRef with a timer to check if the object exists.
function registerObject(object) {
    console.log('Start!')
    const ref = new WeakRef(object)
    const id = setInterval(() => {
      // Check if object does not exist anymore
      if (!ref.deref()) {
        console.log('End!')
        clearInterval(id)
      }
      console.log(`${typeof ref.deref()}`)
    }, 1000)
}

{
  let a = new Date();
  registerObject(a)
}


text:
Q: How to save tableView custom cells to mutablearray I have a tableView with custom cells.
Tableview is empty.
I have "+" button which add my custom cell with label and textfield
Question: how can i save to mutable array textfield.text of all tableview cells when user pressed "+" button
Code of a "+" button here...
- (IBAction)addButtonPress:(UIBarButtonItem *)sender {

    MYCustomTableViewCell *nextCell =[self.myTableViewProperty dequeueReusableCellWithIdentifier:cellId];
    if (!nextCell) {
        nextCell = [[MYCustomTableViewCell alloc] init];
    }
    MYCustomTableViewCell *previousCell =[self.myTableViewProperty dequeueReusableCellWithIdentifier:cellId];
    NSIndexPath *saveTextIndex = [NSIndexPath indexPathForItem:myCustomCellCount inSection:1];

    // -- i can't get my customCell.textField.text
    previousCell = [self.createTableView cellForRowAtIndexPath:saveTextIndex];
    NSLog(@"%@", previousCell.textField.text); ////- its null=(

    [cellArray addObject:nextCell];
    [self.myTableViewProperty reloadData];
}

A: Add tag property to your textField that equals to you indexPath then you can simply access your textfields by their tag property.
Example:
Creating your new customCell
cell.textField.tag = indexPath.row;

Getting your cell's textField
MYCustomTableViewCell *previousCell =[self.myTableViewProperty cellForRowAtIndexPath:indexPath];
UITextField *txtF = (UITextField*)[previousCell viewWithTag:myCustomCellCount];

A: Please, have a look at the documentation UITableViewDataSource Protocol Reference before beginning. This link might be usefult as well. UITableView is just to display the content of your model (called datasource). So when addButtonPress: is called you should insert a data object into your datasource (e.g. an array) and tell the table view to reload it's content. In almost all cases dequeueReusableCellWithIdentifier: is ONLY called in tableView: cellForRowAtIndexPath:. That's where a new table view cell representing your datasource's data objects is created. And there's no need to store the table view's cells in an array because that's done by the table view itself. When the user is done pressing the button you just iterate over your datasource array and read it's data objects.


text:
Q: NoClassDefFoundError when using java impl of leveldb for those who've managed to use this java implementation of leveldb https://github.com/dain/leveldb/
I'm getting the following stacktrace when I try to execute the code in the readme:
NoClassDefFoundError occurs when runing the following line:
DB db = factory.open(new File("example"), options);
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Lists
at org.iq80.leveldb.impl.DbImpl.(DbImpl.java:95)
at org.iq80.leveldb.impl.Iq80DBFactory.open(Iq80DBFactory.java:59)
at com.test.LevelDBDain.main(LevelDBDain.java:23)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Lists
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

I confirmed that new File("example") returns a non-null value; same as the variable options
I import two jars built from the source into my library:
1.leveldb-api.jar
2.leveldb.jar

I've tried this with releases 0.6, 0.7 and 0.8-SNAPSHOT and always get the same error.
Could it be something I'm doing wrong ...or missing?

A: com.google.common.collect.util from guava is a dependency of the leveldb library but for some reason adding it explicitly as a dependency for my java project solved the problem.


text:
Q: should I change my javascript jquery functions to meteor format? I am new to meteor. I already have a js file with a series of functions. When I tried a meteor starter project, it seems it have other structures for jquery events. like:
Template.body.events({

  'submit .new-task'(event) {
   ...

I wonder what is the benefit of rewriting my current js functions in the above format? I want my website works as a mobile app, and I've heard Meteor does that. Is it important to implement the site in the format so I get the best performance and compability?


text:
Q: New default search bar focus text color added with Xcode 8.1 update, how to change it? Question:
How do I set the "focused" state of a UISearchBar text color from the default white, to black?
I created the search bar programmatically, see end of post for that code.
Description:
Previously I was using this extension to set the search bar color:
public extension UISearchBar {

    public func setTextColor(color: UIColor) {
        let svs = subviews.flatMap { $0.subviews }
        guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return }
        tf.textColor = color
    }

}

Which worked great and is still working. However, search bars seem to be "focusable" in a sense. If they are focused, then the text color switches to white (which is the same as the search bar background color) making the text invisible.
Under my search bar I have a table view, where I populate it with data regarding what the person was searching.
When I focus any of the table cells, the UISearchBar text color goes to the black I had originally specified.
Programmatically created SearchBar
Called in AppDelegate.swift
func configueSearchController() -> UIViewController {

        let storyboard = UIStoryboard(name: "Search", bundle: nil)
        guard let searchResultsController = storyboard.instantiateViewController(withIdentifier: SearchViewController.storyboardIdentifier) as? SearchViewController else {
            fatalError("Unable to instatiate a SearchResultViewController from the storyboard.")
        }

        /*
         Create a UISearchController, passing the `searchResultsController` to
         use to display search results.
         */

        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchResultsUpdater = searchResultsController
        searchController.searchBar.placeholder = NSLocalizedString("Enter keyword (e.g. Gastric Bypass)", comment: "")
        searchController.view.backgroundColor = Constants.Color.backgroundcolor
        searchController.searchBar.keyboardAppearance = UIKeyboardAppearance.dark
        searchController.searchBar.tintColor = Constants.Color.backgroundcolor
        searchController.searchBar.backgroundColor = Constants.Color.backgroundColorSearch
        searchController.searchBar.setTextColor(color: .black)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.obscuresBackgroundDuringPresentation = true
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.sizeToFit()

        //searchResultsController.tableView.tableHeaderView = searchController.searchBar

        // Contain the `UISearchController` in a `UISearchContainerViewController`.
        let searchContainer: UISearchContainerViewController = UISearchContainerViewController(searchController: searchController)

        // Finally contain the `UISearchContainerViewController` in a `UINavigationController`.
        let searchNavigationController = UINavigationController(rootViewController: searchContainer)
        searchNavigationController.navigationBar.isTranslucent = true
        searchNavigationController.navigationBar.tintColor = Constants.Color.backgroundcolor
        searchNavigationController.tabBarItem.title = "Search"
        return searchNavigationController

    }


text:
Q: Regex: How to match pattern only once? I'm trying to extract data from a .config file (generated by using kconfig).
The default format is:
SYMBOL=y (in case of a bool)
SYMBOL="str" (in case of a string)

I did managed to get it working with the following regex:
sed -e '/^#/d;s/\(.+\)=\(.+\)/def \1 "\1"\n/g' configfile > formattedfile

It is working for any case except for this one:
SYMBOL="http://my.domain/toast?id=150"

As a result, I have in my output file:
def SYMBOL="http://my.domain/toast?id "SYMBOL="http://my.domain/toast?id="

Because the pattern XXX=XXX appears twice in this line.
How can I avoid this please ?
Regards,

A: You need to escape the + symbol and also turn the first .+ to [^=]\+ because .+ is greedy and matches upto the last = symbol.
$ sed -e '/^#/d;s/\([^=]\+\)=\(.\+\)/def \1 "\1"\n/g' file
def SYMBOL "SYMBOL"

def SYMBOL "SYMBOL"

def SYMBOL "SYMBOL"

A: The problem is that .+ is greedy: it tries to match the longest possible string. This extends to the second =. Since identifiers can't contain a = character, it is best to be more specific in matching the first part:
sed -e '/^#/d;s/^\([^=]*\)=\(.*\)/def \1 \2\n/' configfile > formattedfile

Note that I changed the second \1 to \2 since I think this is what you meant. I also avoided the extended regular expression quantifier + in favor of the basic regular expression quantifier * which is more portable.

A: Just drop the g in your command:
sed -e '/^#/d;s/\(.+\)=\(.+\)/def \1 "\1"\n/'
                                            ^

instead of
sed -e '/^#/d;s/\(.+\)=\(.+\)/def \1 "\1"\n/g'
                                            ^

From info sed:
`g'
     Apply the replacement to _all_ matches to the REGEXP, not just the
     first.

See another example:
$ echo "hello" | sed 's/l/X/'   #without g
heXlo
$ echo "hello" | sed 's/l/X/g'  #with g
heXXo


text:
Q: Magento change product details in packing slip printing I need to change the product details of magento packing slip currently they are showing as follows

but I need to display as below to reduce the space taken for one product

Which file should I look for doing this I have looked at
app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php

and
app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php

but no luck :(

A: The file that is responsible for this task is:
app/code/core/Mage/Sales/Model/Order/Pdf/Shipment/Packaging.php for simple product.
code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php for bundle product.
For Items Rendering
app/code/core/Mage/Sales/Model/Order/Pdf/Items/Shipment/Default.php

A: Add this to Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php,
replace ATTRNAME as appropriate.:-
public function draw() {      product=Mage::getModel('catalog/product')->loadByAttribute('sku',         $this->getSku($item), array('ATTRNAME')); if ($product) { $lines[0][]
array('text'=>Mage::helper('core/string')->str_split($product->getData('ATTRNAME'), 15), 'feed' => 305 );
}
Then add this to Mage/Sales/Model/Order/Pdf/Invoice.php,
replace ATTR_TITLE as appropriate and OFFSET with the left offset.

/* Add table head */ … $page->drawText(Mage::helper('sales')->__('ATTR_TITLE'), OFFSET, $this->y, 'UTF-8′); if (!empty($settings['table_header']))
{
 $page->drawText(Mage::helper('sales')->
('ATTR_TITLE'), OFFSET, $this->y,  'UTF-8′);
}

There is no definitive solution as you need to change a few other details to limit column widths in other areas depending on where you are trying to put your values (ie. description is usually made narrower and forced to line-wrap).
Referenced from: http://www.magentocommerce.com/boards/viewthread/18142/P15/#t20162


text:
Q: How to pass named variables to a function in tupled form Python I have a class with a method:
class Learner:
    def fit(x,y,iterations=1,subsample_proportion=0.1):
         etc...
    def predict(X):
         etc..

And a function:
def error(learner,learner_args,X,Y):
     learner.fit(learner_args)
     Y_pred = learner.predict(X)
     etc...

How do I make the learner_args tuple to pass into this function in Python?
Right now I have:
learner = ada_boost.AdaBoost
learner_args = (train_x,train_y,4,0.2)

And it doesn't work.
Also, is there a way to pass named parameters to a function call?
so, for instance, in my function, I would do:
learner_args = (train_x,train_y,subsample_proportion=0.2)

Ignoring iterations.  Is there a way to do this in Python? (internal to the language...not by using a dictionary and testing for values everywhere)

A: Use ** before a dictionary. Example:
def f(a,b, c=0, d='a'):
    print a,b,c,d

kwargs = {'a' = 1, 'b' = 2}
f(**kwargs)
>>> 1 2 0 a

edit:
According to your comments, you might want something like:
args = ('first argument', 'second argument')
kwargs = {'c':'named argument c', 'd':'named argument d'}
f(*args, **kwargs)
>>> 'first argument', 'second argument', 'named argument c', 'named argument d'

A: learner_args is fine; you just need to pass it properly.
learner.fit(*learner_args)


text:
Q: How to set class between two days to datepicker? I'm using jquery ui datepicker and I want to give class all rows(td) between two selected days but my datepicker is not date range I have to use like this because of some reason and my question is how can I set css between two selected days is that possible with jquery ui or just only with js?

$(function() {
  var ilktarih = ['2017-03-23'];
  var sontarih = ['2017-04-10']
  var bostarihler = ['2017-03-15', '2017-03-16', '2017-03-17', '2017-03-18', '2017-03-19', '2017-03-20', '2017-03-21', '2017-03-22', '2017-03-23', '2017-03-24', '2017-03-25', '2017-03-26', '2017-03-27', '2017-03-28', '2017-03-29', '2017-03-30'];
  var dolutarihler = ['2017-02-22', '2017-02-23', '2017-02-24', '2017-02-25', '2017-02-26', '2017-02-27', '2017-02-28', '2017-03-01', '2017-03-02', '2017-03-03', '2017-03-04', '2017-03-05', '2017-03-06', '2017-03-07', '2017-03-08', '2017-03-09', '2017-03-10', '2017-03-11', '2017-03-12', '2017-03-13', '2017-03-14'];
  var sstarihler = [];

  var dateFormat = "mm/dd/yy",
    from = $("#checkin").datepicker({
      changeMonth: true,
      numberOfMonths: 2,
      firstDay: 1,
      minDate: new Date(ilktarih),
      maxDate: new Date(sontarih),
      onSelect: function(selectedDate) {
        var yenitarih = new Date();

        var date = $(this).datepicker('getDate');
        date.setTime(date.getTime() + (1000 * 60 * 60 * 24))

        $("#checkout").datepicker("option", "minDate", date);
      },

      beforeShowDay: function(date) {
        var y = date.getFullYear().toString(); // get full year
        var m = (date.getMonth() + 1).toString(); // get month.
        var d = date.getDate().toString(); // get Day
        if (m.length == 1) {
          m = '0' + m;
        } // append zero(0) if single digit
        if (d.length == 1) {
          d = '0' + d;
        } // append zero(0) if single digit
        var currDate = y + '-' + m + '-' + d;

        if (jQuery.inArray(currDate, dolutarihler) >= 0) {
          return [false, "ui-highlight"];
        }

        if (jQuery.inArray(currDate, bostarihler) >= 0) {
          return [true, "ui-bos"];
        }

        if (jQuery.inArray(currDate, sstarihler) >= 0) {
          return [false, "ui-ss"];
        } else {
          return [true];
        }

      },
      isTo1: true,
    }).on("change", function() {
      to.datepicker("option", "minDate", getDate(this));
    }),
    to = $("#checkout").datepicker({
      changeMonth: true,
      changeYear: true,
      firstDay: 1,
      numberOfMonths: 2,
      minDate: new Date(ilktarih),
      maxDate: new Date(sontarih),
      onSelect: function(selectedDate) {
        $("#checkin").datepicker("option", "maxDate", selectedDate);
      },
      beforeShowDay: function(date) {
        var y = date.getFullYear().toString(); // get full year
        var m = (date.getMonth() + 1).toString(); // get month.
        var d = date.getDate().toString(); // get Day
        if (m.length == 1) {
          m = '0' + m;
        } // append zero(0) if single digit
        if (d.length == 1) {
          d = '0' + d;
        } // append zero(0) if single digit
        var currDate = y + '-' + m + '-' + d;

        if (jQuery.inArray(currDate, dolutarihler) >= 0) {
          return [true, "ui-highlight-donus"];
        }

        if (jQuery.inArray(currDate, bostarihler) >= 0) {
          return [true, "ui-bos"];
        }

        if (jQuery.inArray(currDate, sstarihler) >= 0) {
          return [true, "ui-ss-donus"];
        } else {
          return [true];
        }

      }
    }).on("change", function() {
      from.datepicker("option", "maxDate", getDate(this));
    });

  function getDate(element) {
    var date;
    try {
      date = $.datepicker.parseDate(dateFormat, element.value);
    } catch (error) {
      date = null;
    }

    return date;
  }
});
.form {
  width: 960px;
  margin: 120px auto;
}

.form input {
  width: 250px;
  padding: 10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />

<div class="form">
  <input type="text" id="checkin" />
  <input type="text" id="checkout" />
  <input type="submit" value="Ara" />
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

A: Try the beforeShowDay callback.
$('input').datepicker({
  beforeShowDay: function (date) {
    var endDate = $('.end_date').datepicker('getDate');
    var startDate = $('.start_date').datepicker('getDate');
    if (date >= startDate && date <= endDate) {
      return [true, 'my-custom-class', '']; //In range
    }
    return [true, '', '']; //Default return
  }
});

Documentation Reference:
https://api.jqueryui.com/datepicker/#option-beforeShowDay


text:
Q: Applying memoization makes golom sequence slower I am trying to wrap my head around memoization using c++, and I am trying to do an example with the "golom sequence"
int main(int argc, char* argv[])
{
    std::unordered_map<int, int> hashTable;

    int value = 7;

    auto start = std::chrono::high_resolution_clock::now();
    std::cout << golomS(4, hashTable) << std::endl;
    auto stop = std::chrono::high_resolution_clock::now();

    auto start1 = std::chrono::high_resolution_clock::now();
    std::cout << golom(4) << std::endl;;
    auto stop1 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(stop1 - start1);

    std::cout << "Time taken by function 1: "
           << duration.count() << " microseconds" << std::endl;

    std::cout << "Time taken by function 2: "
          << duration1.count() << " microseconds" << std::endl;

    return 0;
}

int golom(int n)
{
    if (n == 1) {return 1;}
    return 1 + golom(n - golom(golom(n - 1)));
}

int golomS(int n, std::unordered_map<int, int> golomb)
{
    if(n == 1)
    {
        return 1;
    }
    if(!golomb[n])
    {
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    }
    return golomb[n];
}

As an output I get this:
4
4
Time taken by function 1: 687 microseconds //This is Golom S
Time taken by function 2: 242 microseconds //This is Golom
Shouldn't GolomS be faster with memoization? I tried wrapping my head around the debugger, but im not sure where the effective "slowness" is coming from.
My question is: How can I change the method I made golomS, to be faster than golom.
Thank you. -Adam

A: On top of the other answers, I would like to add that this could really benefit from proper benchmarking.
In order to get reliable results you want to run the tests multiple times, and take steps to ensure that memory caches and other system-level shenanigans aren't interfering with the results.
Thankfully, there are libraries out there that can handle most of these complexities for us. For example, here's a better benchmark of your code using google's Benchmark library:
N.B. the fixes proposed by the other answers have been integrated.
#include <chrono>

int golom(int n)
{
    if (n == 1) {return 1;}
    return 1 + golom(n - golom(golom(n - 1)));
}

int golomS(int n, std::unordered_map<int, int>& golomb)
{
    if(n == 1)
    {
        return 1;
    }
    if(!golomb[n])
    {
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    }
    return golomb[n];
}

static void TestGolomb(benchmark::State& state) {
  for (auto _ : state) {
    benchmark::DoNotOptimize(golom(state.range(0)));
  }
}
BENCHMARK(TestGolomb)->DenseRange(1, 17, 2);

static void TestGolombS(benchmark::State& state) {
  for (auto _ : state) {
    // Make sure we always start from a fresh map
    std::unordered_map<int, int> golomb;

    // Ignore construction and destruction of the map
    auto start = std::chrono::high_resolution_clock::now();
    benchmark::DoNotOptimize(golomS(state.range(0), golomb));
    auto end = std::chrono::high_resolution_clock::now();

    auto elapsed_seconds =
      std::chrono::duration_cast<std::chrono::duration<double>>(
        end - start);

    state.SetIterationTime(elapsed_seconds.count());
  }
}
BENCHMARK(TestGolombS)->DenseRange(1, 17, 2);

Which gives us the following profile suggesting that the breakeven point is around 14-15:

see on quick-bench

A: int golomS(int n, std::unordered_map<int, int> golomb)
{
    if(n == 1)
    {
        return 1;
    }
    if(!golomb[n])
    {
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    }
    return golomb[n];
}

In your goloms function, you pass golomb as a value, not a reference. That means that every time you call goloms, the compiler will make a copy of golomb and destroy that copy when it's out of scope, not changing the actual golomb value.
You should pass by reference instead.
int golomS(int n, std::unordered_map<int, int>& golomb)
{
    if(n == 1)
    {
        return 1;
    }
    if(!golomb[n])
    {
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    }
    return golomb[n];
}

A: There are two issues in your code. First main issue is that you pass unordered map by value. You have to pass it by reference to make it faster, to avoid copying whole map on every function call. Also if you pass map by value then on return newly computed values are not preserved, but if you pass it by reference then new values will give benefit to caller functions.
Second important issue is that you use very small value 4 as input of a function to measure time, it takes very little time for 4 to compute, you have to use bigger value like 50, so that it takes more time to compute and hence gives more accurate time measurement.
Fixed version of your code has already very improved timings of first function compared to second (for input 50):
13
13
Time taken by function 1: 110 microseconds
Time taken by function 2: 118345 microseconds

Fixed code:
Try it online!
#include <unordered_map>
#include <iostream>
#include <chrono>

int golom(int n)
{
    if (n == 1) {return 1;}
    return 1 + golom(n - golom(golom(n - 1)));
}

int golomS(int n, std::unordered_map<int, int> & golomb)
{
    if(n == 1)
        return 1;
    if(golomb.find(n) == golomb.end())
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    return golomb[n];
}

int main(int argc, char* argv[])
{
    std::unordered_map<int, int> hashTable;

    auto start = std::chrono::high_resolution_clock::now();
    std::cout << golomS(50, hashTable) << std::endl;
    auto stop = std::chrono::high_resolution_clock::now();

    auto start1 = std::chrono::high_resolution_clock::now();
    std::cout << golom(50) << std::endl;;
    auto stop1 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(stop1 - start1);

    std::cout << "Time taken by function 1: "
           << duration.count() << " microseconds" << std::endl;

    std::cout << "Time taken by function 2: "
          << duration1.count() << " microseconds" << std::endl;

    return 0;
}

A: Very good. Please try and continue to learn about memoization.
I will give an additional method. You can also "memoize" values in a DP table. DP like dynamic programming.
If you go for speed and can afford a big memory consumption, then this is the fastest and most efficient solution. Using recursion for that sequence is basically a bad idea and will result in very slow code and potential stack overflows.
Converting the recursive into an iterative solution with memoization in a DP table, will give you a very fast result. Even for big numbers. With compiler optimizations on, you can calculate the complete sequence for example up to 100000 ultrafast.
See the below:
#include <iostream>
#include <array>
#include <cstdint>

// We will calculate a Golomb sequence up to the below specified element
constexpr size_t MaxValues = 100000;

using MyDataType = uint_fast16_t;
using GolombSequence = std::array<MyDataType, MaxValues>;

// This is the Golomb Sequence
GolombSequence golombSequence{};

// Iterative Function to calculate a Golomb sequence using a DP table
void createGolombSequence() {

    golombSequence[1] = 1;
    for (int i = 2; i < MaxValues; ++i) {
        golombSequence[i] = 1 + golombSequence[i - golombSequence[golombSequence[i - 1]]];
    }
}

// Test
int main() {
   createGolombSequence();

   std::cout << golombSequence[777] << '\n';
   std::cout << golombSequence[7777] << '\n';
   std::cout << golombSequence[77777] << '\n';
}

We can even go one step ahead and use "compile time memoization", meaning, we will calculate the complete sequence at compile time. So, let the compiler do the work.
This will of course result in the fastest possible solution with the downside of high memory consumption and a little bit limited by the cababilities of the compiler.
Please see below. All Golomb value calculation is done at compile time. At runtime, we just use an ultrafast indexing operation:
#include <iostream>
#include <array>
#include <cstdint>

// We will calculate a Golomb sequence up to the below specified element
constexpr size_t MaxValues = 100000u;
using MyDataType = uint_fast16_t;
using GolombSequence = std::array<MyDataType, MaxValues>;

// Iterative Function to calculate a Golomb sequence using a DP table
constexpr GolombSequence createGolombSequence() {

    GolombSequence golombSequence{};
    golombSequence[1] = 1;
    for (int i = 2; i < MaxValues; ++i) {
        golombSequence[i] = 1 + golombSequence[i - golombSequence[golombSequence[i - 1]]];
    }
    return golombSequence;
}
// This is the Golomb Sequence
constexpr GolombSequence golombSequence = createGolombSequence();

// Test
int main() {

   std::cout << golombSequence[777] << '\n';
   std::cout << golombSequence[7777] << '\n';
   std::cout << golombSequence[77777] << '\n';
}

I added my code to Franks Benchmark. The result is dramatically outperforming everything else. The green line at 0ms is for the above algorithm.

Used benchmark code
#include <chrono>
#include <iostream>
#include <array>
#include <cstdint>

// We will calculate a Golomb sequence up to the below specified element
constexpr size_t MaxValues = 10000u;
using MyDataType = uint_fast16_t;
using GolombSequence = std::array<MyDataType, MaxValues>;

// Iterative Function to calculate a Golomb sequence using a DP table
constexpr GolombSequence createGolombSequence() {

    GolombSequence golombSequence{};
    golombSequence[1] = 1;
    for (int i = 2; i < MaxValues; ++i) {
        golombSequence[i] = 1 + golombSequence[i - golombSequence[golombSequence[i - 1]]];
    }
    return golombSequence;
}
// This is the Golomb Sequence
constexpr GolombSequence golombSequence = createGolombSequence();

inline int golombFast(size_t i) { return golombSequence[i]; };

int golom(int n)
{
    if (n == 1) {return 1;}
    return 1 + golom(n - golom(golom(n - 1)));
}

int golomS(int n, std::unordered_map<int, int>& golomb)
{
    if(n == 1)
    {
        return 1;
    }
    if(!golomb[n])
    {
        golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
    }
    return golomb[n];
}

static void TestGolombFast(benchmark::State& state) {
  for (auto _ : state) {
    benchmark::DoNotOptimize(golombFast(state.range(0)));
  }
}
BENCHMARK(TestGolombFast)->DenseRange(1, 17, 2);

static void TestGolomb(benchmark::State& state) {
  for (auto _ : state) {
    benchmark::DoNotOptimize(golom(state.range(0)));
  }
}
BENCHMARK(TestGolomb)->DenseRange(1, 17, 2);

static void TestGolombS(benchmark::State& state) {
for (auto _ : state) {
    std::unordered_map<int, int> golomb;

    // Be extra-generous, ignore construction and destruction of the set
    auto start = std::chrono::high_resolution_clock::now();
    benchmark::DoNotOptimize(golomS(state.range(0), golomb));
    auto end = std::chrono::high_resolution_clock::now();

    auto elapsed_seconds =
      std::chrono::duration_cast<std::chrono::duration<double>>(
        end - start);

    state.SetIterationTime(elapsed_seconds.count());
  }
}
BENCHMARK(TestGolombS)->DenseRange(1, 17, 2);


text:
Q: Get Details of retired jobs in hadoop I need to get the following Details for  retired jobs in hadoop job tracker using Java.

*

*job id

*user

*Name (of job)

*status

*Start time

*finish Time.

*duration

Basically most of these above are displayed by the jobtracker.jsp URL.
And i need to capture them for auditing purposes.
Please let me know how to access the above fields.
Code examples would be very helpful
With the below mention code , I can only able to get Completed jobs details, sample code snippet:
JobClient client = new JobClient(getConf());
for (JobStatus job : client.getAllJobs()) {
    if (job.isJobComplete()) {
        Stirng jobName = job.getJobName();
        int jobStatus = job.getJobStatus();
        // .. you get the idea
    }
}

Need help!!
Thanks ins advance !!!!

A: I guess you need to check in
In the Job History
Key: hadoop.job.history.location
Key (H21): mapreduce.jobtracker.jobhistory.location
Default: file:///${hadoop.log.dir}/history
Retention: up to a max. of 30 days  (see General Job File Notes below)
Note: The value for this key is treated as a URI, in other words you can store the job files in HDFS or on the local file system (which is the default).
For more info
http://blog.cloudera.com/blog/2010/11/hadoop-log-location-and-retention/


text:
Q: Sterling Map Editor : Conditional Null Value I have a XML to XML map on IBM Sterling B2B Integrator map.
I am trying to set an empty tag on a conditional variable as follows:
empty($my_var[counter][1].#my_var);

The result is that on output the empty tag does not show up.
Expected result:
<my_var/>

Is there any way to achieve this?

A: The XML element should be declared as mandatory in the map.
The PCDATA property should not have Mandatory checked if it is not required, but the element level should be mandatory.
Note also this known problem:
http://www-01.ibm.com/support/docview.wss?uid=swg21701246


text:
Q: why *ngIf doesnt'work with ng-template? I have a condition in the template as follows:
<ng-container>

        <template *ngIf="seat.section">
            Section {{seat?.section}} ,
        </template>
        <template *ngIf="seat.row">
            Row {{seat?.row}},
        </template>
        <template *ngIf="seat.seatNo">
            Seat number {{seat?.seatNo}}
        </template>

</ng-container>

I have dataset that contains row and seatNo, but it does not seem to print in the template. what is the issue here?

A: Read the doc here https://angular.io/guide/structural-directives especially for

{{hero.name}}

The asterisk is "syntactic sugar" for something a bit more
  complicated. Internally, Angular desugars it in two stages. First, it
  translates the *ngIf="..." into a template attribute, template="ngIf
  ...",  like this.

{{hero.name}}

Then it translates the template attribute into a
  element, wrapped around the host element, like this.
<ng-template [ngIf]="hero">
{{hero.name}}
</ng-template>

*

*The *ngIf directive moved to the  element where it    became a property binding,[ngIf].

*The rest of the , including    its class attribute, moved inside the  element.

So for it we have ng-container
 <ng-container *ngIf="seat.section">
    Section {{seat.section}} ,
 </ng-container>

or use span or div or regular html tag.

    Section {{seat.section}} ,

or if you still want to use ng-template (not recommended)
<ng-template [ngIf]="seat.section">
  Section {{seat.section}} ,
</ng-template>


text:
Q: Mulesoft condense array of nested objects to single array of objects I have a dataset that is an array of objects, and each object is another object with an array inside of it. I am trying to flatten everything to a single array of the innermost objects, without the keys of the middle layer objects. I have tried to use the pluck functionality, but I cannot seem to get to what I am after. Example below.
Input:
[
  {
    "1234": [
      {
        "store": "07",
        "category": "1234",
        "account": "987"
      },
      {
        "store": "07",
        "category": "1234",
        "account": "555"
      },
      {
        "store": "07",
        "category": "1234",
        "account": "555"
      }
    ]
  },
  {
    "567": [
      {
        "store": "07",
        "category": "567",
        "account": "987"
      },
      {
        "store": "07",
        "category": "567",
        "account": "555"
      },
      {
        "store": "07",
        "category": "567",
        "account": "555"
      }
    ]
  }
]

Output:
[
      {
        "store": "07",
        "category": "1234",
        "account": "987"
      },
      {
        "store": "07",
        "category": "1234",
        "account": "555"
      },
      {
        "store": "07",
        "category": "1234",
        "account": "555"
      },
      {
        "store": "07",
        "category": "567",
        "account": "987"
      },
      {
        "store": "07",
        "category": "567",
        "account": "555"
      },
      {
        "store": "07",
        "category": "567",
        "account": "555"
      }
]

A: *

*You need to iterate using map.

*Convert object with key to array using pluck.

*Covnert Nested array to 2d array using flatten.

*Convert 2d array to 1d array using  Reduce
DW
%dw 2.0
output application/json
---
flatten(payload map ($ pluck $)) reduce ($$++$)

Output
[
  {
    "store": "07",
    "category": "1234",
    "account": "987"
  },
  {
    "store": "07",
    "category": "1234",
    "account": "555"
  },
  {
    "store": "07",
    "category": "1234",
    "account": "555"
  },
  {
    "store": "07",
    "category": "567",
    "account": "987"
  },
  {
    "store": "07",
    "category": "567",
    "account": "555"
  },
  {
    "store": "07",
    "category": "567",
    "account": "555"
  }
]

A: Below is one way of doing it. May be there is better way than this.
%dw 2.0
output application/json
---
flatten(payload map ($ pluck $)) reduce ((val, acc) -> acc ++ val)


text:
Q: Strange behaviour of golang exec.Command program I have such code:
func main() {
        s := "foobar"
        cmd := exec.Command("wc", "-l")
        stdin, err := cmd.StdinPipe()
        if err != nil {
                log.Panic(err)
        }
        stdout, err := cmd.StdoutPipe()
        if err != nil {
                log.Panic(err)
        }
        err = cmd.Start()
        if err != nil {
                log.Panic(err)
        }
        io.Copy(stdin, bytes.NewBufferString(s))
        stdin.Close()
        io.Copy(os.Stdout, stdout)
        err = cmd.Wait()
        if err != nil {
                log.Panic(err)
        }
}

and its output is:
0
But when I will do simple modification:
func main() {
        runWcFromStdinWorks("aaa\n")
        runWcFromStdinWorks("bbb\n")
}

func runWcFromStdinWorks(s string) {
        cmd := exec.Command("wc", "-l")
        stdin, err := cmd.StdinPipe()
        if err != nil {
                log.Panic(err)
        }
        stdout, err := cmd.StdoutPipe()
        if err != nil {
                log.Panic(err)
        }
        err = cmd.Start()
        if err != nil {
                log.Panic(err)
        }
        io.Copy(stdin, bytes.NewBufferString(s))
        stdin.Close()
        io.Copy(os.Stdout, stdout)
        err = cmd.Wait()
        if err != nil {
                log.Panic(err)
        }
}

It works, but why? Its just calling method why first version is not working?

A: The string s in the first example does not have a new line, which causes wc -l to return 0. You can see this behavior by doing:
$ echo -n hello | wc -l
0


text:
Q: Pdf file in Asymptote I know that some tags do not correspond but I wanted to draw your attention to this question. I made two graphics in asymptote.ualberta.ca/, but I want to download them as pdf file, but it keeps loading infinitely, that does not happen if I try to download it as png. Does anyone else have this problem or is it that maybe the problem is my machine? Any way to solve this problem in case the problem is located in my code?
First:
settings.render=8;
import graph3;
import palette;

currentprojection=orthographic(1,1,0.3);
//currentlight.background = gray(0.7);

typedef triple newtriple(pair);
// https://en.wikipedia.org/wiki/Hyperboloid
newtriple f(real a, real b, real c)
{
  return new triple(pair k){
    real u=k.x,v=k.y;
    real x,y,z;
    x=a*cosh(v)*cos(u);
    y=b*cosh(v)*sin(u);
    z=c*sinh(v);
    return (x,y,z);
  };
}
triple F(pair z){ return f(1,1,1)(z); }

// Gauss map
triple g(pair z)
{
  real u=z.x, v=z.y;
  triple U=(-cosh(v)*sin(u),cosh(v)*cos(u),0);
  triple V=(sinh(v)*cos(u),sinh(v)*sin(u),cosh(v));
  return 1.5*cross(U,V)/abs(cross(U,V));
}

// https://trecs.se/hyperboloidOfOneSheet.php
path3 vector(pair z) {
  real u=z.x, v=z.y;
  real a=1, b=1, c=1;
  real x,y,z;
  x=-b*c*cosh(v)^2*cos(u);
  y=-a*c*cosh(v)^2*sin(u);
  z=a*b*sinh(v)*cosh(v);
  return O--(-(x,y,z)/sqrt(x^2+y^2+z^2));
}

size(13cm);

surface sf=surface(F,(0,-1.5),(2pi,1.5),40,Spline);
//sf.colors(palette(sf.map(zpart),Rainbow()));
draw(sf,RGB(0,153,216),render(merge=true));
label("$(\mathcal{H})$",(-1,2.2,2.7),dir(45));
add(vectorfield(vector,F,(0,-1.5),(2pi,1.5),10,0.5,red,render(merge=true)));
xaxis3(Label("$x$",EndPoint),0,3.5,Arrow3);
yaxis3(Label("$y$",EndPoint),0,3.5,Arrow3);
zaxis3(Label("$z$",EndPoint),0,3,Arrow3);
pair z=(pi/3,1);
dot("$P$",F(z),dir(-10),white+3bp);
draw(Label("$N(P)$",EndPoint,LeftSide),shift(F(z))*vector(z),white,Arrow3);

transform3 t=shift(5*(Y-X));
surface sg=surface(g,(0,-1.5),(2pi,1.5),20,Spline);
//sg.colors(palette(sg.map(zpart),Rainbow()));
draw(t*sg,RGB(231,76,60),render(merge=true));
label("$N\left(\mathcal{H} \right)$",t*(-.5,0.5,1.2),dir(45));
dot(t*(0,0,1.5/sqrt(2)),white+3bp);
draw(Label("$x$",EndPoint),t*((0,0,0)--(3.5,0,0)),Arrow3);
draw(Label("$y$",EndPoint),t*((0,0,0)--(0,3.5,0)),Arrow3);
draw(Label("$z$",EndPoint),t*((0,0,0)--(0,0,3)),Arrow3);

draw(Label("$N$",Relative(.5),N),subpath((0,0,0)--t*(0,0,0),0.4,0.6),Arrow3);

label("$\frac{1}{\sqrt{2}}$",t*(0.9,0,1.4),dir(45));

Second:
settings.render=8;
import graph3;
import palette;

currentprojection=orthographic(1,1,0.3);
//currentlight.background = gray(0.7);

typedef triple newtriple(pair);
// https://en.wikipedia.org/wiki/Hyperboloid
newtriple f(real a, real b, real c)
{
  return new triple(pair k){
    real u=k.x,v=k.y;
    real x,y,z;
    x=-a*u;
    y=b*v;
    z=c*exp(u)*sin(v);
    return (x,y,z);
  };
}
triple F(pair z){ return f(1,1,1)(z); }

// Gauss map
triple g(pair z)
{
  real u=z.x, v=z.y;
  real x,y,z;
  x=exp(u)*sin(v);
  y=exp(u)*cos(v);
  z=sqrt(1+exp(2*u));
  return -7*(x,y,-1)/z;
}

// https://trecs.se/hyperboloidOfOneSheet.php
path3 vector(pair z) {
  real u=z.x, v=z.y;
  real a=1, b=1, c=1;
  real x,y,z;
  x=-b*c*exp(u)*sin(v);
  y=-a*c*exp(u)*cos(v);
  z=a*b*sqrt(1+exp(2*u));
  return O--(-(x,y,-1)/z);
}

size(480,400,false);

surface sf=surface(F,(-10,-12),(3,6),40,Spline);
//sf.colors(palette(sf.map(zpart),Rainbow()));
draw(sf,RGB(0,153,216),render(merge=true));
add(vectorfield(vector,F,(-10,-12),(3,6),10,2.5,red,render(merge=true)));
//xaxis3(Label("$x$",BeginPoint),0,7,Arrow3);
draw(Label("$x$",EndPoint),(12,0,0)--(-12,0,0),Arrow3);
yaxis3(Label("$y$",EndPoint),0,12,Arrow3);
zaxis3(Label("$z$",EndPoint),-18,22,Arrow3);
label("$\mathcal{H}$",(-.5,5.5,18),dir(45));

transform3 t=shift(20*(Y-X));
surface sg=surface(g,(-2.7,-12),(3,6),20,Spline);
//sg.colors(palette(sg.map(zpart),Rainbow()));
draw(t*sg,RGB(231, 76, 60),render(merge=true));
label("$N\left(\mathcal{H} \right)$",t*(-.5,6,6),dir(45));
draw(Label("$x$",EndPoint),t*((0,0,0)--(12,0,0)),Arrow3);
draw(Label("$y$",EndPoint),t*((0,0,0)--(0,12,0)),Arrow3);
draw(Label("$z$",EndPoint),t*((0,0,0)--(0,0,13)),Arrow3);
//dot(Label("$(0,0,1)$",black),t*(0,0,7),dir(135),white+5bp);
label("$(0,0,1)$",t*(.5,0,7),dir(135));

draw(Label("$N$",Relative(.5),N),subpath((0,0,0)--t*(0,0,0),0.4,0.6),Arrow3);

A: I just updated asymptote.ualberta.ca to the latest development version
(which will soon released as Asymptote 2.71) and confirmed that your first example works fine.


text:
Q: Find area of the polygon with corners defined by the roots of $\sqrt{7}+3i-x^{2n}=0$, as $n\to \infty$ Find area of the polygon with corners defined by the roots of $\sqrt{7}+3i-x^{2n}=0$, as $n\to \infty$.
Source: IME 1967 (Instituto Militar de Engenharia, Brazil, Entrance Exame, no answer provided)
My solution:
The polygon is defined by the $2n$ roots of $x^{2n}=\sqrt{7}+3i=4(\frac{\sqrt{7}}{4}+i\frac{3}{4})$,
defined by
$$x_k=4^{\frac{1}{2n}}\text{cis}(\frac{\theta + 2k\pi}{2n}), k=0,\ldots,2n-1.$$
The polygon is regular with $2n$ corners and converges to a circle centered at (0,0) with radius $2^{\frac{1}{n}}$, as $n\to \infty$ with area
$$\lim_{n\to \infty} A_n=\pi\ 2^{\frac{2}{n}}=\pi$$
Question/Comment: I believe the solution is correct but is rather informal/based on intuition. I would like a more formal answer, based on algebraic arguments. Is it possible?
Help is appreciated. Sorry if this is a duplicate.

A: Given that $x_k = 2^{\frac1n}e^{i\frac{\theta+2k\pi}{2n}}$, there are $2n%$ isosceles triangles with side length $a=2^{\frac1n}$ and vertex angle $\frac{\pi}n$. Thus, the area of the $2n$-polygon is
$$A_n = 2n\cdot \frac12 a^2\sin\frac{\pi}n =2^{\frac2n} n\sin\frac\pi n $$
After take the limit, the area approaches
$$\lim_{n\to\infty} A_n = \lim_{n\to\infty} 2^{\frac2n} \cdot \lim_{n\to\infty} \frac{\sin\frac\pi n}{\frac1n} = 1\cdot \pi =\pi$$


text:
Q: Turning List Comprehension into Functional Application I have a function which was written in list comprehension. As a learning I decided to try to convert this function into a functional application using map, zip, fold, etc. I am having a really hard time converting this particular one.
It might seem unreasonable for what it is doing, but it is part of a bigger function and I want to get this piece working first.
combination :: Int -> [a] -> [([a],[a])]
combination 0 xs     = [([],xs)]
combination n (x:xs) = [ (x:ys,zs) | (ys,zs) <- combination (n-1) xs ]

A: It's just a map:
combination :: Int -> [a] -> [([a],[a])]
combination 0 xs     = [([],xs)]
combination n (x:xs) = map (\(ys, zs) -> (x:ys,zs)) (combination (n-1) xs)


text:
Q: How to create mapping of 2nd level child node in Spicelib/Parsley for Flex I have an XML structure that looks like this:
<ROOT>
  <P att1="" att2="">
    <KEYWORDS>
      <K name="" />
      <K name="" />
    </KEYWORDS>
  </P>
  <P att1="" att2="">
    <KEYWORDS>
      <K name="" />
    </KEYWORDS>
  </P>
</ROOT>

I would like to map the P nodes and the K nodes, but not the KEYWORDS nodes.
I have a class for the P and K nodes
package
{
    [XmlMapping(elementName="P", ignoreUnmappedAttributes="true", ignoreUnmappedChildren="true")]
    public class Package
    {
      [ChoiceType("Keyword")]
      public var keywords:Array;
    }
}

package
{
    [XmlMapping(elementName="K", ignoreUnmappedAttributes="true", ignoreUnmappedChildren="true")]
    public class Keyword
    {
        public var name:String;
    }
}

And then I have my mapper:
var mapper:XmlObjectMapper = XmlObjectMappings
    .forUnqualifiedElements()
    .withRootElement(Package)
    .mappedClasses(Keyword)
    .build();

But this always results in keywords of the P class being null. The only way I have gotten this to work is to create a "throwaway" class called Keywords that I map to the keywords property of Package and that class also has a keywords property that is mapped to the Keyword class. And then in Package I use a setter to pull out the actual keywords I want like so:
//mapping the new Keywords class
var mapper:XmlObjectMapper = XmlObjectMappings
    .forUnqualifiedElements()
    .withRootElement(Package)
    .mappedClasses(Keywords, Keyword)
    .build();

//the new Package class
package
{
    [XmlMapping(elementName="P", ignoreUnmappedAttributes="true", ignoreUnmappedChildren="true")]
    public class Package
    {
        private var _keywords:Array;

        [ChoiceType("Keywords")]
        public function set keywords(value:Array):void
        {
          //there is always only one KEYWORDS node
          _keywords = value[0].keywords
        }

        public function get keywords():Array
        {
            return _keywords;
        }
    }
}

//the new intermediary Keywords class
package
{
    [XmlMapping(elementName="KEYWORDS", ignoreUnmappedAttributes="true", ignoreUnmappedChildren="true")]
    public class Keywords
    {
        [ChoiceType("Keyword")]
        public var keywords:Array;
    }
}