text: Q: Get device storage path on android (Firefox Add-on) I would like to get path smthing like: storage/emulated/0 using Firefox Add-On SDK under Android OS. Analog in android sdk is getExternalStorageDirectory(). Is it possible?


text:
Q: How to save custom snippets to existing ace snippet file We have developed an application for editing code snippets available in the ace editor for each mode. We are using ng2-ace-editor in angular 6. Snippet file for each language mode is saved inside the ace library. we need to edit each snippet and user must be able to save his snippets into the same file. We have accomplished editing the snippet and registered the newly added snippet, thus the user can add the newly added snippet on the editor real-time. But when the page is reloaded it will be lost. We need to save the snippet to the file already exist in the ace library, as this is saved in a different format with some "\n tab" characters. The snippet is available for editing after it is parsed using SnippetManager. But we couldn't find any documentation to make it to the old format with our newly added snippets.
//snippet manager is included for managing snippets
var snippetManager =  ace.acequire('ace/snippets').snippetManager;
// getting existing snippet array (free from special characters, \n etc)
var m = snippetManager.files[this.editor._editor.session.$mode.$id];
m.snippetText = this.snippettext;
// unregister already esisting snippets
snippetManager.unregister(m.snippets);
m.snippets = snippetManager.parseSnippetFile(m.snippetText, m.scope);
// register newly added snippets along with old snippets
snippetManager.register(m.snippets,'tex');

After this, I need to save these registered snippets to the existing file with the asking format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS : access scope object from parent to child Query : Want to access the Main Controller scope object into ui-view states.
Problem Statement :
Here, I am creating one scope object($scope.myVar) based on the response getting from the API that will be applicable across the application. hence, I wrote an API in Main Controller to create this scope object as it is a parent controller and all other states(ui-view) are child.

Here, I want to access that $scope.myVar in all the states in ui-view.
Tried so far : HTML
<body ng-controller="MainController">
  <div class="className">
    <ui-view></ui-view>
  </div>
</body>

Main Controller
app.controller('MainController', function($scope, $http) {

$http({
  method: 'GET',
  url: '/someUrl'
  }).then(function successCallback(response) {
    $scope.myVar = 'xyz'; // This variable i want to access into the state controller.
  }, function errorCallback(response) {
  });
});

State controller :
app.controller('StateController', function($scope, $timeout) {

  console.log($scope.myVar); // undefined (Not working)

  $timeout(function() {
    console.log($scope.myVar); // xyz (working)
  }, 500);
});

I want to access $scope.myVar without using $timeout service. What is the correct way to do this ?

A: you can use $parent.myVar to access data of parentScope
For your situation(async call), you can add $scope.$watch to watch the parent scope variable.
$scope.$watch("$parent.myVar", function(newValue, oldValue) {
  $scope.data = newValue;
)

Here you want to get data immediately when child state initializing, you can try with resolve.
$stateProvider.state({
  name: 'hello',
  url: '/hello',
  templateUrl: '...',
  resolve: {
    testData: function($http) {
      // invoke your async call here again
    }
  }
})

here are some issues about resolve which may help.

*

*how to resolve $http result

*Is it ok to $http request in resolve

A: You can use angular $q service
Using promises and $q to handle asynchronous calls
var app = angular.module("MY_APP", []);
//Parent Controller
app.controller("MyCtrl1", [
    '$scope','$q','$timeout', function($scope,$q,$timeout) {

 $scope.async = function(name) {
  var deferred = $q.defer();
  //Async call: Use your ajax call here instead of $timeout
  /*
  $http.get('/someUrl')
       .success(function(data) {
          $scope.myVar = 'xyz';
          deferred.resolve(data);
       }).error(function(msg, code) {
          deferred.reject(msg);
          $log.error(msg, code);
       });
  */
  $timeout(function() {
    deferred.notify('About to greet ' + name + '.');
     if (name) {
      deferred.resolve('Hello, ' + name + '!');
     } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
     }
   }, 1000);
  return deferred.promise;
}
}]);
//Child Controller
app.controller("MyCtrl2", [
    '$scope','$q', function($scope,$q) {
 // call parent async method
var promise = $scope.$parent.async('Sai');
promise.then(function(greeting) {
//check your variable here
/*
console.log($scope.$parent.myVar);
*/
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

}]);

Fiddle example


text:
Q: Can't get settings button to display for live wallpaper I want to add settings to a live wallpaper I created.  I am missing something very fundamental about how SharedPreferences work.  The code and XML are based on the cube live wallpaper example and I can't figure out what I did wrong.   My problem is that no "Settings" button shows up when I choose my live wallpaper from the list.  Only the "Set Wallpaper" button is displayed.  I suspect that I screwed up something in the XML.
This is a very simple live wallpaper I made just to fool around with settings.  All it does is set the background to either blue or green (and that part works).
What I believe to be the pertinent code and xml follows:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.android.BGWallpaper"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-feature android:name="android.software.live_wallpaper" />

    <application
        android:icon="@drawable/icon" android:label="@string/AppName">

        <service
            android:icon="@drawable/icon"
            android:label="@string/AppName"
            android:name="com.android.BGWallpaper.BlueGreen"
            android:permission="android.permission.BIND_WALLPAPER" android:debuggable="false">
            <intent-filter android:priority="1">
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>
            <meta-data android:name="android.service.wallpaper" android:resource="@xml/bg" />
        </service>
        <activity
            android:label="BGSettings"
            android:name="com.android.BGWallpaper.BGPrefs"
            android:theme="@android:style/Theme.Light.WallpaperSettings"
            android:exported="true">
        </activity>
    </application>
</manifest>

Preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="Title Preference"
        android:key="BGSettings">
    <ListPreference
            android:key="background"
            android:title="Background Title"
            android:summary="Background Summary"
            android:entries="@array/BackgroundChoices"
            android:entryValues="@array/BackgroundChoices" />
</PreferenceScreen>

bg.xml
<?xml version="1.0" encoding="utf-8"?>
<wallpaper
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:thumbnail="@drawable/icon"/>

BlueGreen.java (the wallpaper service)
public class BlueGreen extends WallpaperService
{
    public static final String strSharedPrefs="BGSettings";

   @Override
    public Engine onCreateEngine()
    {
         return new BGEngine();
    }

    class BGEngine extends Engine  implements SharedPreferences.OnSharedPreferenceChangeListener
    {
        private SharedPreferences msPrefs;

        private final Runnable mDraw = new Runnable()
        {
            public void run()
            {
                draw();
           }
        };

        BGEngine()
        {
            msPrefs = BlueGreen.this.getSharedPreferences(strSharedPrefs, MODE_PRIVATE);
            msPrefs.registerOnSharedPreferenceChangeListener(this);
            onSharedPreferenceChanged(msPrefs, null);
        }
    }
    // ...
}

BGPrefs.java:
public class BGPrefs extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
    @Override
    protected void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        getPreferenceManager().setSharedPreferencesName(BlueGreen.strSharedPrefs);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }
    // ...
}

So what am I missing?
Also, part of my XML/code is being eaten by the automatic formatting.  Is there a way to have it treat a block of text as literal so it doesn't format it?

A: In your bg.xml...
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="something"
    android:thumbnail="@drawable/icon"
    android:description="something"
    android:settingsActivity="com.android.BGWallpaper.BGPrefs">
</wallpaper>

android:settingsActivity is the param that you need to set against your live wallpaper XML file.
Good luck :)


text:
Q: If a variable does not exist in a batch I am stuck.  I have a section of a script that looks for a filenumber, and if it exists, I want it to go to the next command of the script.  If it does not exist, I want it to go back to the spot where the user enters the filenumber again.  Basically, if they enter a file number that does not exist, I want them to re-enter the filenumber.  If it does exist, I wnat them to proceed.  What I am getting is a loop and I can't figure out where I can get out of it.  Here is the code I have
    :FileNum
cls
set /P "FileNumber=Please enter File Number: "
if defined FileNumber for /R "\bpclient\A001\M0093" %%I in ("*%FileNumber%*.xml") do copy /Y "%%I" "\IlnevalExtractionTool\Data\"

IF NOT EXIST "%FileNumber%" (
   echo File Number %FileNumber% Does Not Exist
   echo Try again
   pause
   goto :FileNum
)
IF EXIST "%FileNumber%" (
goto: result
)
@echo off

:result
cls
@echo off
copy Data\*.xml Results.txt

If I enter a filenumber that exists, it copies them to the data folder, but then gives me the echo text I have for "File Number XXXX Does not exist. try again" and takes me back to the Please Enter File Number prompt.  How can I get it to go to the result section of the script if the variable exists, but loop back if it doesn't?

A: You are asking it if the number you typed exists, which I suppose never will, instead you want to test if the actual file exists. So to directly fix the issue.
:FileNum
cls
set /P "FileNumber=Please enter File Number: "
if defined FileNumber for /R "\bpclient\A001\M0093" %%I in ("*%FileNumber%*.xml") do (
    copy /Y "%%I" "\IlnevalExtractionTool\Data\"
    set "fname=%%~I"
)

IF NOT EXIST "%fname%" (
   echo File Number %FileNumber% Does Not Exist
   echo Try again
   pause
   goto :FileNum
)
IF EXIST "%fname%" (
goto: result
)
@echo off

:result
cls
@echo off
copy Data\*.xml Results.txt

But I would instead do:
@echo off
:FileNum
set fname=
set /P "FileNumber=Please enter File Number: "
if defined FileNumber for /R "\bpclient\A001\M0093" %%I in ("*%FileNumber%*.xml") do (
    copy /Y "%%I" "\IlnevalExtractionTool\Data\"
    set "fname=%%~I"
)
if defined fname (
    copy "data\*.xml" Results.txt
) else (
    echo File not found Please try again.
    goto :fileNum
)


text:
Q: Finding all shortest paths between two vertices The built-in FindShortestPath and GraphDistance functions find the shortest path between two particular vertices in a graph. I can't think of a simple way to finding all shortest paths between two vertices. Any ideas?
My graph has weighted edges and the weights are arbitrarily large, so I'm dead against mapping weighted edges to many unweighted edges.
Motivation: I have a graph of city traffic routes from point A to point B. I'd like to take the union of shortest paths from A to B to get a subgraph that, I posit, contains (many of) the most frequented intersections.

A: With V10, you can use a combination of FindPath and GraphDistance. A (hopefully) self-explanatory example:
g = RandomGraph[{15, 44}, VertexLabels -> "Name"];
s = 1;
t = 2;
FindPath[g, s, t, {GraphDistance[g, s, t]}, All]
HighlightGraph[g, %]

In short, we find all paths between $s$ and $t$ of distance $d(s,t)$.

A: Directed Shortest Paths
Here's a friendly amendment to Heike's solution that shows the distance remaining to the finish vertex (in white).  The starting vertex is green. Edges are directed to show the appropriate direction toward the finish.  According to the documentation on GraphDistance, "For a weighted graph, the distance is the minimum of the sum of weights along any path between s and t." So it should automatically work with weighted graphs.
First, here's Heike's routine, which does most of the heavy lifting, with a simple tweak to produce directed edges:
paths[gr_, {i_, j_}] :=
  Module[{sub, dist, indices, dd, nbrs}, dist = GraphDistance[gr, i, j];
  indices = {};
  dd = dist;
  Reap[Nest[Function[{vv}, dd -= 1;
  nbrs = VertexList[NeighborhoodGraph[gr, #]] & /@ vv;
  nbrs = Pick[#, GraphDistance[gr, #, j] & /@ #, dd] & /@ nbrs;
  Sow /@ Flatten[Thread /@ Thread[vv \[DirectedEdge] nbrs]];
  Union[Flatten[nbrs]]], {i}, dist]][[2, 1]]]

The following produces the directional routes. Numbers refer to GraphDistance from the current vertex to the finish vertex.
gr = RandomGraph[{30, 40}];
ends = {1, 30};
sub = paths[gr, ends];
e = EdgeList[gr] /. {x_ \[UndirectedEdge] y_ /;
 GraphDistance[gr, x, 30] < GraphDistance[gr, y, 30] :> y \[DirectedEdge] x,
   x_ \[UndirectedEdge] y_ /;
 GraphDistance[gr, y, 30] <= GraphDistance[gr, x, 30] :>  x \[DirectedEdge] y}
gr1 = Graph[e, ImagePadding -> 15];

HighlightGraph[gr1, {Graph[sub], Style[1, Green], Style[30, White]},
 VertexLabels ->  Table[i -> Style[GraphDistance[gr1, i, 30], 16], {i,
    Union[Level[sub, {-1}]]}],
    VertexSize -> {1 -> Large, 30 -> Large},
    GraphHighlightStyle -> "Thick", ImagePadding -> 15]

Below is a variant that  displays (a) the vertex indices (small font size) and the distance from the finish vertex on the EdgeLabel (large font).
HighlightGraph[gr1, {Graph[sub], Style[1, Green], Style[30, White]},
   VertexLabels -> (v = Union[Level[sub, {-1}]]) /. {i_Integer :> (i -> i)},
   EdgeLabels -> sub /. {x_ \[DirectedEdge] y_ :> (x \[DirectedEdge] y) ->
   Style[ GraphDistance[gr, x, 30], 14, Background -> White]},
   VertexSize -> {1 -> Large, 30 -> Large},
   GraphHighlightStyle -> "Thick", ImagePadding -> 15, ImageSize -> 600]

A: To get the union of the shortest paths from i to j in graph gr you could do something like this
paths[gr_, {i_, j_}] := Module[{sub, dist, indices, dd, nbrs},
  dist = GraphDistance[gr, i, j];
  indices = {};
  dd = dist;
  Reap[Nest[
     Function[{vv},
      dd -= 1;
      nbrs = VertexList[NeighborhoodGraph[gr, #]] & /@ vv;
      nbrs = Pick[#, GraphDistance[gr, #, j] & /@ #, dd] & /@ nbrs;
      Sow /@ Flatten[Thread /@ Thread[vv \[UndirectedEdge] nbrs]];
      Union[Flatten[nbrs]]
      ], {i}, dist]][[2, 1]]]

This method works by selecting all neighbours of i whose distance to j is one less than the minimal distance from i to j. For each vertex in this list we then select the neighbours whose distance to j is two less than the minimal distance, etc. until we reach j.
Usage
gr = RandomGraph[{30, 50}];
ends = {1, 30};
sub = paths[gr, ends];
HighlightGraph[gr, {Graph[sub], Style[ends, Green]}]

A: findMinPathsPoints[k_, ends_] := Module[{dist},
   dist = (GraphDistance[k, #[[1]]] + GraphDistance[k, #[[2]]]) &@ends;
   Complement[Flatten@Position[dist, Min[dist]], ends]];

(*Usage*)

n = 50;
points = {1, 10};
k = PetersenGraph[n, IntegerPart[n/4]]

Subgraph[k, Range@VertexCount@k, VertexStyle ->
          Join[
              (# -> Red &)    /@ points,
              (# -> Yellow &) /@ findMinPathsPoints[k, points]]]


text:
Q: Make longtable notes fit to page I used longtable and threeparttablex to make table notes. I wonder the way to adjust table notes to fit page. Also, if possible, I want to hide the endfoot line. Any help will be appreciated.
\documentclass[11pt]{article}
\usepackage{longtable, booktabs, tabu}
\usepackage[flushleft]{threeparttablex}
\usepackage[hang,footnotesize,bf]{caption}
\usepackage[paper=a4paper, margin=1in]{geometry} % set margins
\renewcommand{\arraystretch}{1.2}

\begin{document}
\centering
\linespread{1}
\footnotesize
\begin{ThreePartTable}

\begin{TableNotes}
        \item\textbf{Notes}: Insert Whatever Important Notes hHere.
\end{TableNotes}

\begin{longtabu} to \textwidth {@{\extracolsep{\fill}} cccccc}
\caption{\textbf{Insert the Table Caption}} \\
\toprule
   & \multicolumn{5}{c}{\textbf{B/M}} \\
    \cmidrule{2-6}    \textbf{Size} & 1  & 2  & 3  & 4  & 5 \\
\midrule
\endfirsthead
        \caption{\textbf{Continued}} \\
\toprule
   & \multicolumn{5}{c}{\textbf{B/M}} \\
    \cmidrule{2-6}    \textbf{Size} & 1  & 2  & 3  & 4  & 5 \\
\midrule
\endhead
    \multicolumn{6}{c}{\textit{Continued on Next Page}} \\   \bottomrule
\endfoot
    \multicolumn{6}{c}{\textit{End of Table}} \\  \bottomrule
    \insertTableNotes
\endlastfoot

   & \multicolumn{5}{c}{a} \\
1  & 0.305 & 0.244 & -0.270 & -0.829*** & -0.846* \\
   & (1.24) & (1.24) & (-1.44) & (-3.61) & (-1.66) \\
2  & 0.787*** & 0.357** & -0.083 & -0.371 & -0.995 \\
   & (4.68) & (2.45) & (-0.50) & (-1.01) & (-1.43) \\
3  & 0.898*** & 0.472*** & 0.006 & -0.847** & -1.16 \\
   & (6.22) & (3.20) & (0.03) & (-2.28) & (-1.54) \\
4  & 0.793*** & 0.319** & 0.062 & -0.274 & -1.93*** \\
   & (5.90) & (2.00) & (0.25) & (-0.61) & (-2.81) \\
5  & 0.732*** & 0.367*** & -0.088 & -0.343 & -0.857 \\
   & (10.04) & (2.85) & (-0.40) & (-0.96) & (-1.31) \\
\midrule
   & \multicolumn{5}{c}{b} \\
1  & 0.815*** & 0.838*** & 0.873*** & 0.854*** & 0.580*** \\
   & (12.19) & (16.55) & (15.31) & (13.48) & (3.63) \\
2  & 0.862*** & 0.826*** & 0.793*** & 0.802*** & 1.358*** \\
   & (17.95) & (20.88) & (18.61) & (8.31) & (7.43) \\
3  & 0.915*** & 0.875*** & 0.845*** & 0.867*** & 1.068*** \\
   & (21.92) & (21.34) & (16.40) & (8.98) & (5.88) \\
4  & 0.930*** & 0.881*** & 0.874*** & 1.052*** & 0.663*** \\
   & (22.84) & (17.97) & (11.98) & (8.37) & (3.96) \\
5  & 0.813*** & 0.813*** & 0.815*** & 0.815*** & 0.939*** \\
   & (40.48) & (21.97) & (12.98) & (8.02) & (4.94) \\
\midrule

\pagebreak
   & \multicolumn{5}{c}{hml} \\
1  & \textbf{0.694***} & \textbf{0.693***} & \textbf{0.829***} & \textbf{0.770***} & 0.477 \\
   & \textbf{(8.31)} & \textbf{(7.81)} & \textbf{(8.40)} & \textbf{(6.86)} & (1.47) \\
2  & \textbf{0.724***} & \textbf{0.592***} & \textbf{0.584***} & \textbf{0.455**} & \textbf{0.991***} \\
   & \textbf{(8.68)} & \textbf{(9.91)} & \textbf{(8.16)} & \textbf{(2.47)} & (3.73) \\
3  & \textbf{0.465***} & \textbf{0.561***} & \textbf{0.455***} & \textbf{0.655***} & -0.261 \\
   & \textbf{(6.59)} & \textbf{(8.61)} & \textbf{(5.11)} & \textbf{(4.63)} & (-0.74) \\
4  & \textbf{0.469***} & \textbf{0.489***} & \textbf{0.370***} & \textbf{1.007***} & 0.158 \\
   & (6.58) & (5.57) & (3.31) & (5.75) & (0.46) \\
5  & 0.0532 & \textbf{0.188***} & \textbf{0.397***} & \textbf{0.311*} & -0.142 \\
   & (1.52) & (3.12) & (4.11) & (1.71) & (-0.44) \\
\midrule
   & \multicolumn{5}{c}{R2} \\
1  & 0.589 & 0.693 & 0.745 & 0.650 & 0.188 \\
2  & 0.760 & 0.806 & 0.740 & 0.381 & 0.269 \\
3  & 0.794 & 0.774 & 0.630 & 0.381 & 0.159 \\
4  & 0.813 & 0.730 & 0.494 & 0.389 & 0.117 \\
5  & 0.908 & 0.753 & 0.530 & 0.310 & 0.168 \\
\bottomrule\
\end{longtabu}
\end{ThreePartTable}
\end{document}


text:
Q: Make other nodes follow when dragging a node in Cytoscape.js I'm new to cytoscape.js, I just want to make other nodes follow when dragging one node.
Appreciate your help

A: Write a listener, and update the other node positions appropriately in your callback:

*

*eles.on()

*node.position()

A: Here is how I did it. Note you have to save off the original positions at the grab event, and then update during the drag event.
function add_drag_listeners()
{
    var all = cy.elements("node");
    for (j = 0; j < all.length; j++)
    {
        cynode = all[j];
        cynode.on("grab",handle_grab);
        cynode.on("drag",handle_drag);
    }
}
var grab_x = 0;
var grab_y = 0;
var drag_subgraph = [];
function handle_grab(evt)
{
    grab_x = this.position().x ;
    grab_y = this.position().y ;
    var succ = this.successors();
    drag_subgraph = [];
    var succstr = "";
    for (i = 0; i < succ.length; i++)
    {
        if (succ[i].isNode())
        {
            var old_x = succ[i].position().x;
            var old_y = succ[i].position().y;
            succstr += " " + succ[i].data("id");
            drag_subgraph.push({old_x:old_x, old_y:old_y, obj:succ[i]});
        }
    }
}
function handle_drag(evt)
{
    var new_x = this.position().x;
    var new_y = this.position().y;
    var delta_x = new_x - grab_x;
    var delta_y = new_y - grab_y;
    for (i = 0; i < drag_subgraph.length; i++)
    {
        var obj = drag_subgraph[i].obj;
        var old_x = drag_subgraph[i].old_x;
        var old_y = drag_subgraph[i].old_y;
        var new_x = old_x + delta_x;
        var new_y = old_y + delta_y;
        obj.position({x:new_x, y:new_y});
    }
}


text:
Q: XSD with length value 0 isn't being honored I have a question with an XSD that I am working with.
I have the following block:
          <xs:element name="Artist">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:length value="0" />
              </xs:restriction>
            </xs:simpleType>
          </xs:element>

I would expect that the string would be limited to 0. However when I use an online sample generator, the string can be of any length.
Could anyone give me some insight as to what is really happening? Does 0 have a special action for xml generation?


text:
Q: Entity framework & CRUD with a partial class ASP.Net v4 page, I have setup an EntityDataSource for EF4, and am binding this to a DetailsView allowing view, edit and new for an Entity.
All works fine until I add a property to the partial class of the entity being bound:
namespace MyProject.EntityFramework
{
    public partial class Member
    {
        public bool CurrentMember
        {
            get
            {
                //do some stuff
                return true;
            }
        }

Because 'CurrentMember' is calculated there is no set for the property and I get a variety of errors when trying to either insert or update.
Adding an attribute of [ReadOnly(true)] to the property does not help, nor does setting visible to false.
This seems basic. What am I doing wrong?


text:
Q: An issue with communication between parent-process and child-process using pipe I'm writing a C program, that given an executable a.out and input files in_1.txt, in_2.txt ... in_n.txt, will run a.out on all n input files and will produce corresponding output to each and every input file in the argument list.
I ran into some weird behaviour from my program (call it tester.out), and after couple of hours, I was able to identify my problem, but could not figure out what to solve it.
I will first post the code and will then explain the problem...
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<limits.h>
#include<string.h>

#define PERM S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP  // 660

int main(int argc, char* argv[]) {

    if (argc<3) {
        printf("Arguments required; an executable file and at least one input file.\n");
        return 1;
    }

    int channel[2];
    if (pipe(channel)<0) {
        perror("pipe");
        return 1;
    }

    int i;
    for (i=2; i<argc; ++i) {

        pid_t p=fork();
        if (p<0) {
            perror("fork");
            return 1;
        }

        if (p) { // parent

            // closing read end
            close(channel[0]); // *** The problem lies here! ***

            int indicator;

            if ((indicator=write(channel[1], argv[i], strlen(argv[i])+1))<0) {
                perror("write");
                return 1;
            }

            printf("Parent wrote %d bytes\n", indicator);

            int status;
            wait(&status);

            if (WIFEXITED(status)) {
                printf("Your program terminated normally with exit code %d\n", WEXITSTATUS(status));
                printf("See output file: %s_output\n", argv[i]);
            }
            else if (WIFSIGNALED(status)) {
                printf("Your program terminated by a signal! signal code: %d\n", WTERMSIG(status));
            }

        }
        else { // child

            // closing write end
            close(channel[1]);

            char input_file[PATH_MAX]={0};
            char output_file[PATH_MAX+10]={0};

            int indicator;

            // read input_file from pipe
            if ((indicator=read(channel[0], input_file, PATH_MAX))<1) {
                perror("child process: read");
                return 1;
            }

            printf("child read %d bytes\n", indicator);

            sprintf(output_file, "%s_output", input_file);
            printf("Got %s and output is %s\n", input_file, output_file);

            sleep(5); /* later, I will call execl() here to run argv[1] on input_file */
            return 1;
        }

    }

    return 0;
}

This works as expected for when I run:
$ ./tester.out a.out input1.txt

But fails for when I run it with more than one input file:
$ ./tester.out a.out input1.txt input2.txt

As the highlighted comment in the code suggests, the problem lies in the line calling to close(channel[0]), because closing channel[0] in the parent on the first iteration, means that on the second iteration, the child process has its channel[0] closed (by its parent - in the first iteration).
Any suggestions on how to solve this situation?

A: You should create a new pipe for each child process, and close both ends of the pipe when you are finished with it.  You need to close both ends in both the parent and the child.

A: A simple fix would be:
Move from before the loop to inside the loop, just before the line that calls fork().  Then define the choice[2] variable and do the call to pipe().


text:
Q: mpl_toolkits.axes_grid1.ImageGrid : invert_yaxis not working How can I invert the Y axes in an ImageGrid plot grid?
This is my current test code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, [im1, im2, im3, im4]):
    # Iterating over the grid returns the Axes.
    # ax.imshow(im)
    ax.pcolormesh(im)
    ax.invert_yaxis() # This seems to have no effect.

plt.show()

ax.invert_yaxis() has no effect and I always get increasing Y values like in this picture:

A: Ok, the problem was that ax.invert_yaxis() toggles the Y axis direction instead of just setting it.
Since I looped an even number of times, it had no effect.
Here are two possible solutions:

*

*Use ax.yaxis.set_inverted(True). Cf: set_inverted

*Invert the Y axis only for one plot in each row:
if idx in [0,2]:
  ax.invert_yaxis()
idx+=1

Working example code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

idx=0
for ax, im in zip(grid, [im1, im2, im3, im4]):
    # Iterating over the grid returns the Axes.
    # ax.imshow(im)
    ax.pcolormesh(im)
    # ax.invert_yaxis()

    # Directly setting the axis direction, rather than toggling it.
    ax.yaxis.set_inverted(True)

    # Alternative method:
    # if idx in [0,2]:
    #   ax.invert_yaxis()
    # idx+=1

plt.show()


text:
Q: Run script in remote linux pc and continue execution when closing ssh I've a python script that must run forever (it's a websocket data collector that put data into a database). The script sometimes write some output to console.
What I want to do is to execute the script in a remote server that I can reach with ssh. When I run the script, I want to close the connection while the script continue to be executed, and from time to time I want to log again in there and check the output of the script.
How can I start the script in the remote server, and checking its output while running every time that I connect to remote server?


text:
Q: How do I create tuple types that depend on each other in TypeScript? I have the following function that allows me to handle async errors similar to Go.
type AsyncResults<ErrorType, DataType> = Promise<
    readonly [undefined, DataType] | readonly [ErrorType, undefined]
>;

const asyncHandler = <ErrorType, DataType>(
    asyncFunc: Promise<DataType>,
): AsyncResults<ErrorType, DataType> => {
    return asyncFunc
        .then((data: DataType) => [undefined, data] as const)
        .catch((error: ErrorType) =>
            Promise.resolve([error, undefined] as const),
        );
};

When I call it, I usually get error type to be 'unknown', which is ok, but my result type is always whatever is inferred union undefined
const [err, verifiedUser] = await asyncHandler(
        getPasswordVerifiedUser(db, {
            email,
            password,
        }),
    );
if (err) throw err
const user: VerifiedUser = {
   firstName: verifiedUser.firstName (TS complains that object may be undefined)
}

So verifiedUser above has inferred type 'Document | undefined'. Is there a way for TypeScript to know that if err is undefined then verifiedUser cannot be undefined (and vice versa)? I want that if I handle the err by throwing or returning, TS recognizes that verifiedUser can no longer be undefined.

A: What you are trying to do is impossible. TypeScript does not make any difference between a resolution and a rejection. This is how reject and resolve are being typed:
reject<T = never>(reason?: any): Promise<T>;
resolve<T>(value: T | PromiseLike<T>): Promise<T>;

They both return Promise<T> so there is no possible way to narrow down a Promise's return type based on the control-flow.
More information about this here: https://github.com/Microsoft/TypeScript/issues/7588#issuecomment-199079907
Edit:
If you want to narrow the tuple type union, just don't destructure it:
// Considering ErrorType is number and DataType is { firstName: string }

const result = await asyncHandler<number, { firstName: string }>(
    getPasswordVerifiedUser<{ firstName: string }>(),
);

if (result[0] !== undefined) throw result[0]

const user = {
    firstName: result[1].firstName // works
}

It's the only solution that I found and it seems to be confirmed here: Control flow not type-narrowing with union tuple?


text:
Q: About spatialite views and Attribute table I try to use views with spatial column in spatialite. I can connect to spatialite database and load the layer without problems but when I try to view data in Attribute Table I can't get eny data; all rows and field show ERROR.
Data render well and information in point show correct data.
Has someone get the same error?.
Is this a bug?
I get this results in different versions of qgis (osg4w in windows, master version in ubuntu 12.04 and qgis version included in osgeolive 6.0)

A: As I've got a similar problem with Geopackage spatial views I thought I'd share what I've seen elsewhere. Some people are reporting that if you select both the ROWID column and geometry column and alias both using " as " in the view SQL, but give them aliases that are exactly the same as the column names, then this fixes the problem in Spatialite. This however doesn't seem to fix it in Geopackage.


text:
Q: Why is my neighbor ping 20ms less in online games? My friend/neighbor has the same ISP than me (cable provider). In fact, he has a lower speed package. But when we game online he always have 10-20ms less ping than me.
I tried connecting my PC directly to my modem and the result is still the same.
Our other friend in the same city with the same provider has arround my ping too. Why is that?
EDIT:
Here's the start of my tracert
  2    11 ms    17 ms     8 ms  10.33.104.1
  3    12 ms    14 ms    23 ms  216.113.124.61
  4     9 ms    14 ms     9 ms  216.113.122.154

Here's my friend's
2 8 ms 7 ms 7 ms 10.78.96.1
3 9 ms 11 ms 11 ms 216.113.126.170
4 7 ms 9 ms 8 ms 216.113.122.230

You can clearly see where i'm loosing those 15-20ms... The rest of the route is the same.

A: Option 1: Check if your connection passes through an ISP proxy.

Put in Google "What is my ip", choose one of the thousands similar
webs and look where it says "Proxy Detected:".
Repeat the same with your friend connection.

Option 2: Try a traceroute to the server game.

For this open a prompt and type:
Linux -> "traceroute [put_here_ip_server]"
Windows -> "tracert [put_here_ip_server]"
Compare both traceroutes.

If you have a Dynamic IP address, you can try to reboot your router to get a new IP and, hopefully, a better route to the server.
However, the best option will always be to hire FTTH(Fiber To The Home) to reduce the latency of the line.

A: If you pay attention to your tracert, you'll notice right away that your traceroute isn't even taking the same path as your neighbor -- your traffic is being routed through different hosts.
That said - and since you can't control it, nor can your neighbor - maybe you want to find other pursuits for your time rather than this sort of stuff.
Your question is akin to asking: "My co-worker lives next door to me.  We leave in the morning at the same time.  He takes his car, I take my car.  They're both Toyota Prius models.  Why don't we arrive at work within 20 ms of one another?"

A: If you are serious about finding the answer, you'll need to remove variables.

*

*Cable Modem

*Router

*Coax and Network cables

*Network Card / Computer

The easiest one to test, would be to trade computers for a day.
My money would say that it is your network card / configuration is the biggest factor.
Different network chipsets perform differently. Just look at some of the video cards marketed as low latency. Supposedly firmware tweaks can take dozens of milliseconds off your ping.
If you try the computer swap experiment, please let me know how big of a difference it makes.


text:
Q: Is there a way to get the soundtrack for the first KoPaP game from Steam? There's no way to get the soundtrack for the first game on Steam, right? I can only find it on Bandcamp and Apple Music.
Unlike with the second game, it seems like the first game's Deluxier edition doesn't contain the soundtrack, and if it ever was on Steam, it isn't any more?
GOG's description of the Deluxier Edition says nothing about soundtracks...

A: According to a thread on steam, which the developer answered, the soundtrack is included in the base installation itself and the files are available if you browse the game's local files:

MACAXEIRA Jun 18, 2013 @ 1:58pm
where can i find the game soundtrack?
prunk  [developer] Jun 18, 2013 @ 2:04pm
It's on the Knights instalation folder. You can find it by right-clicking on the game on your Steam Library>Properties>Local Files tab>Browse Local Files.

The thread is specific about the Mac installation, but there's no indication that the Windows installation should be any different.

After a bit more investigation, I've figured out the following.
The previous information posted by the developer was correct in 2013 (and why I have the digital files of the music  ). When the game was first made available, the soundtrack files were simple standalone files within the game installation and you could browse the local directory to find them.
However, since then the game has had numerous updates through the publisher, Paradox Interactive. At some point around 2014, the soundtrack files stopped being available. It turns out that the way the game was originally packaged for sale, the soundtrack was considered a "DLC" or expansion. The +1 Edition available on Steam does not have the soundtrack. The "Deluxe Edition" has an expansion/DLC, but not the soundtrack. The archive.org listing of steamapps in the comments shows the expansion was once available, but the publisher decided to remove it for whatever reason.
The developer (not the publisher! two separate entities here) confirmed this in a thread and said that the way to officially get the soundtrack was through the Bandcamp page.

gty  [developer] Apr 1, 2014 @ 3:00pm
When I said you can't it's because in the current build/version of the game that can't be done. Sorry for the kind of misleading info.
I asked my friends here and I honestly don't know why the soundtrack isn't listed on humblebundle. Paradox might had a specific deal with them maybe? Carl (Paradox producer) once posted here regarding the DLC that they are currently checking the possibility of this upgrade button.
You may directly buy the soundtrack here: http://beholdstudios.bandcamp.com/album/knights-of-pen-paper

(Recall that the PC version was initially offered through and gained popularity from a Humble Bundle offering.)
Anyway, there's a massive Q&A thread that you can search and the topic does drift back to the soundtrack a few times, but at the end of the day the answer seems to be that the publisher didn't make it available via Steam.

*

*Thread: https://steamcommunity.com/app/231740/discussions/0/540732889584230498/

*SteamApp DB listing: https://steamdb.info/app/238652/ (note the state is "eStateComingSoonNoPreload")


text:
Q: HTML line break in PHP string? In Wordpress editor, following code is kind of different to me:
case #1
this is a test

case #2
this is a test

The first case will add a space after the sentence, and the #2 case will leave an empty line under the sentence.
Now I am writing a PHP that will include html code in a PHP string,
$post_content = "...."

How to distinguish the two cases above in this $post_content variable?
If I write
$post_content += "this is a test";
$post_content += "&nbsp";

It's the fist case, how to write the #2 case?

A: Newlines are represented by "\n":
$post_content += "this is a test\n ";

A: $post_content += "this is a test\n";
$post_content += "&nbsp";

A: The difference is a newline. You denote it with \n In PHP you do it like this
$str = "This is a string.\nThis is the second line.";

In your case
$post_content = "this is a test\n&nbsp";


text:
Q: Can I use DDR3 1600MHz RAM in a Mac instead of 1067MHz? I'm trying to get a 16 GB (2x of 8 GB) RAM to boost my computer, even though Apple says that it's only 8 GB on macs, but we know Apple is wrong on that. However, when I searched the online shopping place, they only have 1600 variants.
Can I use DDR3 1600 RAM sticks in a 1067 Mac? …and what are the consequences? and when you buy a RAM, does the PC3-8500 things matter or not?
Hardware Specifications:
MacBook Pro 13″ mid-2010 running OS X 10.9.1 Mavericks
Running on 2.4GHz Intel Core 2 Duo
Currently have 4 GB installed (2x of 2 GB) that is DDR3 1067MHz PC3-8500

A: You could add the 1600 MHz memory for your MacBook Pro even though it's designed for a slower memory (1066 MHz) - it ought to work, but you'd be better off buying from a place that accepts returns. Here's some relevant information from Crucial on memory speeds (emphasis mine):

Memory is designed to be backward-compatible, so generally speaking, you can safely add faster memory to a computer that was designed to run slower memory. However, your system will operate at the speed of the slowest memory module.

In "DDR3-1600 PC3-12800"

*

*"DDR3" is the type (and must be the same as what your computer has)

*"1600" is the data transfer rate per second specified in millions (the technical term is "clock frequency") - "1600" here means it supports up to 1600 million transfers per second - in your case, it will be slowed down to 1066 million transfers per second since that's what your Mac is designed for

*"PC3-12800" is the name used in the memory industry - 12800 indicates a peak transfer rate of 12800 MB/s (of course, the actual performance in your case would be brought down to 8533 MB/s, matching PC3-8500).

A: Just tried this in a mid-2009 macbook pro. It almost works. If you replace only one slot, everything works fine, since "your system will operate at the speed of the slowest memory module", as @MK said. But if you replace both of them at the same time, it will NOT work, since the system will try to operate at 1600 MHz (the speed of the slowest memory module).
Update: Tried it again, but using a different memory, and it did not work at all. It seems that macs are indeed picky. (Both memories were 1600 MHz, 4GB - the one that worked partially was a Patriot, the one that did not work at all was a Samsung).

A: Most new memory uses low voltage 1.2v. Mac before 2013 is still using 1.5V. Your mid 2010 macbook will not be able to support the 1.2V. Issue is not with the speed

A: I bought two DDR3 4 Gb Ram ( 8Gb) crucial mac memory 1600, 12800 Mhz to increase the two 2 GB (4Gb) that came with my Mac book Pro late 2012. I have know 8Gb.
The two 2 Gb 1600, 12800 DDR3 Ram Mem that I take out from my Mac book were installed in a Mac 21 Inches late 2009, DDR3 1067, 8500. It works fine and the system tell me that I have installed 1067 RAM me not 1600. No malfunction.

A: Was able to install four (4) mixed serial 8GB SO-DIMMs of Samsung PC3-12800 (1600Mhz) DDR3 SDRAM memory modules (Samsung Memory sticker IDs listed as M471B1G73DB0-YK0 1338 and M471B1G73CB0-CK0 1251) in a Mid-2010 27" iMac with an Intel 2.93Ghz i7-870 processor. Started up and works without a hitch. Memory under "About this Mac" is reported as "32GB of 1333 Mhz DDR3." Therefore, not reported as its native 1600 Mhz. Trick is to make sure the memory you get supports 1.5V as most of the newer memory is lower voltage (eg., 1.35V or 1.2V) that is NOT SUPPORTED by the iMacs older than 2013. Speed is not the issue. So, some people will report Samsung as working, and others will say it does not. Samsung, like Crucial, Elpida, Kingston, Corsair, etc all make good memory, but even the best memory will not work if it is does not support the correct voltage type. Issue is not with higher speed memory which just defaults down to the lower speed that the BIOS supports. In this case, the 1333 Mhz speed is what is reported. So look up the serials on the manufacturer or vendor website that lists the specs and go from there. Also, be aware that this 32GB max is reported only to work with the i5s and i7s, not the i3s or the older Core 2 Duo processors which max out with 16GB Ram at 1.5V setting.


text:
Q: Git reset --hard without losing history I have the following situation:
A-B-C-D (master)

I want to undo all local changes from D and go from D to where everything was like in B, but i don't want to just go to B. I want the stage of B to be appended to the current history, so that i end up with:
A-B-C-D-B' (master)

So like reverting from D to B but with keeping this Reverting in the history.
When i do a reset --hard I lose my history from B to D and i end up with:
A-B (master)

I just want to append a point in history to the history and start working on this top point and this without creating new branches stashes etc. Like getting everything how it was in B and commiting it (with commit message: "reverted from B") on top.
Is this somehow possible?

A: Yes, git revert is exactly what you're looking for. It creates a new commit that reverts the changes of the given commits.
In your case, the following commands are all equivalent:
git revert HEAD~2..
git revert HEAD~1 HEAD
git revert <hash_of_C>..<hash_of_D>
git revert <hash_of_B>..

See the documentation for more info.


text:
Q: thymeleaf disable message argument Is it possible to disable the arg {0} output when it is not available?
Example:
messageSource.getMessage("my.message.property", new Object[]{12}, "fallback", LocaleContextHolder.getLocale());

this displays:
Child 12 Years old

now sometimes I don't have the age of the children, so my args would be:
messageSource.getMessage("my.message.property", null, "fallback", LocaleContextHolder.getLocale());

the display is now:
Child {0} Years old

Is it possible to disable the {0} on the output?

A: I found a simple solution:
message.replaceAll("\\s*\\{\\d+\\}\\s*", ""));

Another solution is to define multiple message properties. One with the Argument and another one without the argument

A: I hope your looking for avoid the null/undefined filed hiding. we can use the if condition in UI if the argument is not available/null, please check this link for your reference.
Thymeleaf: check if a variable is defined


text:
Q: sessionStorage: 10 itens diferentes com o mesmo nome Amigos, estou fazendo um sessionStorage para 10 itens. Eu estou contabilizando cada clique que faço em uma div e somo um númerol. até aí tudo bem, mas que que esse número volte ao zero quando clico em cada um dos próximos itens.
Segue o cógigo;

etc.
e o JS:
    function addIdade(idade) {
if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("idade"+idade).innerHTML =  + sessionStorage.clickcount;
sessionStorage.removeItem("conforto");
}

Porque isso? Pois quando clico no próximo item, obviamente já aparece o valor da variável "clickcount" guardada no sessionStorage. Por exe.: Se clico 4 vezes no idade1(vai de 0 a 4) e depois uma vez no idade9 já começa no 5 e eu quero que comece do 0 novamente.
Agradeço uma ajuda!


text:
Q: Itertools to break an array into subarrays I have an array of strings that looks something like this
['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

I want to break this into something like
[['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'],
 ['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3'],
 ['a', 'b', 'd.4']]

How do I go about doing this ? My Idea was to use groupby in itertools
to get something like
['a', 'b', ['c.1', 'c.2', 'c.3'], ['d.1', 'd.2', 'd.3', 'd.4']]

and then probably something like
result = []
for elem in nestedList:
    if isinstance(elem, list):
        temp = []
        for elem in nestedList:
            if not isinstance(elem, list):
                temp.append(elem):
        temp.append(elem)
    result.append(temp)

In order to do that I would need to access the next element in groupby
(Something like lambda x: '.' not in x and nextelement.split('.')[0] != x)

How do I do that?

A: Youd don't need itertools.
You can simply use list comprehensions to filter strings with '.' or not, and combine them again in another list comprehension:
data = ['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

lone_letters = [x for x in data if '.' not in x]
combined_letters = [x for x in data if '.' in x]

print([lone_letters + [x] for x in combined_letters])
# [['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'], ['a', 'b', 'c.4'], ['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3']]

A: Most simple approach:
l = ['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']
result = [l[:2] + [i] for i in l[2:]]
print(result)

The output:
[['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'], ['a', 'b', 'c.4'], ['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3']]

A: Here is an interactive demonstration of a general approach.
First define input list:
>>> l = ["a", "b", "c.1", "c.2", "c.3", "c.4", "d.1", "d.2", "d.3"]
>>> l
['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

Gather common prefix elements:
>>> p = [e for e in l if "." not in e]
>>> p
['a', 'b']

Compute rest of elements:
>>> r = [e for e in l if e not in p]
>>> r
['c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

Compute product of prefix with each element of the rest:
>>> from itertools import product
>>> [x[0] + list(x)[1:] for x in product([p],r)]
[['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'], ['a', 'b', 'c.4'],
 ['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3']]

A: Use a list comprehension like this:
my_list = ['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']
res = [[my_list[0], my_list[1], item] for item in my_list[2:]]

Output:
>>> from pprint import pprint
>>>
>>> pprint(res)
[['a', 'b', 'c.1'],
 ['a', 'b', 'c.2'],
 ['a', 'b', 'c.3'],
 ['a', 'b', 'c.4'],
 ['a', 'b', 'd.1'],
 ['a', 'b', 'd.2'],
 ['a', 'b', 'd.3']]


text:
Q: PHP: Is it safe to use any value for the filename of a download? For example, with the following code to output a file to the user
header('Content-Disposition: attachment; filename="' . $file_name . '"');
Is it safe to use any value there? The file is stored with an alphanumeric ID, but ideally it'd like to serve the download with the same filename it was uploaded with. However, I'm hesitant to allow this as I'm not sure what the implications could be.


text:
Q: Geogebra spline command in Mathematica Spline(pts, order, Weight Function)

Creates a spline with given order through all points. The weight function says what should be the difference of t values for point $P_i$ and $P_{(i+1)}$ given their difference $P_{(i+1)} - P_i = (x, y)$. To get the spline you expect from "function" algorithm you should use abs(x) + 0*y, to get the GeoGebra's default spline you can use sqrt(x^2+y^2).

Its implementation may be here.
Is there a corresponding function in Mathematica? I checked the documentation of the Interpolation and BSplineFunction,
I don't know how to set the weight function to reproduce the result. Let's say I have points pts like this, I generated the corresponding curve in Geogebra, which I converted into Mathematica code.
pts={{0,0},{1,1},{2,-1},{3,2},{4,1}};

cond={t<0.17,t<0.44,t<0.83,True};

val={{-11.52t^3+6.16t,-125.22t^3+9.52t},
{2.14t^3-7.05t^2+7.37t-0.07,159.41t^3-146.79t^2+34.75t-1.45},
{12.42t^3-20.72t^2+13.44t-0.97,-108.17t^3+209.4t^2-123.29t+21.93},
{-19.62t^3+58.87t^2-52.48t+17.23,115.04t^3-345.13t^2+335.92t-104.83}};

f[t_]=Piecewise[Transpose[{val,cond}]]

Show[ParametricPlot[Join[{f[t]},val]//Evaluate,{t,0,1},PlotStyle->{Black,Dashed,Dashed,Dashed,Dashed}],
Graphics[{PointSize[Large],Point[pts]}],PlotRange->{{0,5},{-2,3}}]

A: Your link documents the default weight function but it doesn't say which kind of boundary constraints are used to obtain a unique spline.
pts = {{0, 0}, {1, 1}, {2, -1}, {3, 2}, {4, 1}};

(* Geogebra default weight *)
ts = Prepend[Accumulate[N[Normalize[Norm /@ Differences[pts], Total]]], 0]
(* {0, 0.17190381, 0.44370759, 0.82809619, 1.} *)

To get a spline with these parameter values for the points you can use Interpolation, but the result still differs because the boundary is handled differently:
ParametricPlot[Interpolation[Thread[{ts, pts}], Method -> "Spline"][x] // Evaluate, {x, 0, 1}, AspectRatio -> 1]


text:
Q: Why there is huge difference between PSI score of mobile and desktop sites? I want to know why there is a big difference between PSI scores of mobile site and desktop site

A: Google Page Speed Insights uses different parameters for desktop vs mobile testing.
For desktop the connection speed used is not throttled, it will load as fast as a web browser will allow (i.e. limited by round trip times, maximum simultaneous downloads per domain and CPU processing power of a decent PC).
For mobile however Google tries to simulate a real world example of a mobile phone on a 4G connection.
4 x CPU slowdown as mobile phones are less powerful and network throttling that includes slow upload and downloads and more importantly simulates a high Round Trip Time for each resource request (higher latency).


text:
Q: how to prevent list hiding under tabbar in SliverPersistentHeader in flutter? I'm making tiktok clone flutter app
now i'm on profile screen

I've making it like this

as you can see ,
when I scroll up , gif list hide under SliverPersistentHeader
so pictures are not full size
this is I wanna fix it
I wanna prevent hiding  under tabbar in SliverPersistentHeader like tiktok profile screen
here's my code

SliverPersistentHeader(
  floating: false,
  pinned: true,
  delegate: _SliverAppBarDelegate(
    TabBar(
      indicatorColor: Constants.kPrimaryOrange,
      labelColor: Colors.black87,
      unselectedLabelColor: Colors.grey,
      tabs: [
        Tab(text: "비디오"),
        Tab(text: "이미지"),
      ],
    ),
  ),
),

body: TabBarView(
  children: [
    /// gif Loading
    Container(
    ),
    /// image Loading
    Container(
    ),
  ],
),

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new Container(
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}


text:
Q: mysqli_query Return Value and Set as $variable I know this is probably going to be a very simple answer, but I can't seem to figure this out! I'm a newbie when it comes to mysqli_query.
Example.
$con = my connection variable.
In database the Row id = 5
$post_id = mysqli_query($con, "SELECT id FROM posts SET id as '$post_id"');
echo $post_id

If I were to echo $post_id now it would return 5.
What am I doing wrong?

A: Calling mysqli_query returns a mysqli_result object - not a string. So you need to loop through the results of your query. This query will get all rows where the id of the post is the same as $post_id.
$post_id = mysqli_query($con, "SELECT id FROM posts WHERE id = '.$post_id.'");

while ($row = $post_id->fetch_assoc())
{
    foreach($row as $value) echo "<td>$value</td>";
}

You'd probably want to change the name of the variable from $post_id to something a bit more generic but you get the idea.

A: I don't know if you're getting an SQL error. But assuming your SQL is right, you have to fetch the results like this:
$sql = "select 99 id, 'Peter' name"; //this SQL throws a single row
$query = mysqli_query($con, $sql);
//if you expect only 1 row:
$row = mysqli_fetch_assoc($query);
echo $row['id']; //output: 99
echo $row['name']; //output: Peter


text: Q: Как дать доступ к бд в другом пк? Объясните плиз вот у меня есть приложение на C# и бд составленная на субд MySQL Workbench и вот у меня такой вопрос как дать доступ к бд на другом пк если я захочу свое приложение запустить на другом пк?


text:
Q: Novice to DB - Oracle I'm pretty new to Oracle and Database.
I'm trying to write a stored procedure with cursors. How do I write a select statement inside the cursor loop, and how do I loop through the result set that I get from the select inside that cursor loop?
For example:
    Open Curs1;
    Exit When Curs1%NotFound;
    Loop
       Select column1,column2  from table -- Returns multiple records. How to loop through this record set and perform CRUD operations.
    End loop;
    Close Curs1;

A: Use a FOR-loop cursor - they are faster and simpler than the open/fetch/close syntax.
begin
    for results1 in
    (
        select ...
    ) loop
        --Do something here
        for results2 in
        (
            select ...
            where some_table.some_column = results1.some_column
        ) loop
            --Do something here
        end loop;
    end loop;
end;
/

Although this literally answers the question, you generally do not want to have loops inside loops like this.  If possible, it would be better to combine the two SQL statements with a join and then loop through the results.

A: You need to declare the CURSOR and FETCH the records in the loop.
DECLARE
CURSOR  curs1
IS
  SELECT column1,
         column2
  FROM   yourtable;

  v_column1 yourtable.column1%TYPE;
  v_column2 yourtable.column2%TYPE;
BEGIN
 OPEN curs1;
  LOOP

    FETCH curs1
    INTO  v_column1,
          v_column2;
  EXIT
  WHEN curs1%NOTFOUND;

    INSERT INTO yourtable2(col1)VALUES( '000'||v_column1  );
    -- A sample DML operation.

    --Do other operations on individual records here.
  END LOOP;
  CLOSE curs1;
END;

A: Try to use the following example that fetches rows one at a time from the cursor variable emp_cv into the user-defined record emp_rec:
declare
   TYPE YourType IS ref cursor return YourTable%rowtype;
   tab_cv  YourType;
   tab_rec YourTable%rowtype;
begin
   loop
      fetch tab_cv into emp_rec;
      exit when tab_cv%notfound;
      ...
   end loop;
end;

The BULK COLLECT clause lets you fetch entire columns from the result set, or the entire result set at once. The following example, retrieves columns from a cursor into a collection:
declare
   type NameList IS table of emp.ename%type;
   names NameList;
   cursor c1 is select ename from emp where job = 'CLERK';
begin
   open c1;
   fetch c1 bulk collect into names;
   ...
   close c1;
end;

The following example uses the LIMIT clause. With each iteration of the loop, the FETCH statement fetches 100 rows (or less) into index-by table acct_ids. The previous values are overwritten.
declare
   type NumList is table of number index by binary_integer;
   cursor c1 is select acct_id from accounts;
   acct_ids NumList;
   rows natural := 100;  -- set limit
begin
   open c1;
   loop
      /* The following statement fetches 100 rows (or less). */
      fetch c1 bulk collect into acct_ids limit rows;
      exit when c1%notfound;
      ...
   end loop;
   close c1;
end;


text:
Q: In matplotlib animation, saving the animation looks different than showing them I have written a matplotlib animation. In general terms it works well. However for some reason when I save it to a mp4 file, the output is not the same as when I show it
The part of the script for this is
anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=nf, interval=interval_ms, blit=True,repeat=False)
if args.save_video!=None:
    fps=1/args.time
    writervideo = FFMpegWriter(fps=fps)
    anim.save(args.save_video, writer=writervideo)
    print("done")
    plt.close()
else:
    plt.legend()
    plt.show()

The difference is like this

Show
Video

No legend
legends shows

Grid
No Grid

X,Y labels
No X,Y labels

Text is written
Text does not appear

My most urgent feature that I want to fix how can I add a text to the plot that actually shows in the video
Right now I add a text with ax.text and set_text and set_position.
This text is returned every frame for the animation together with the lines but the text only shows when I do plt.show(). It does not show when I do anim.save(args.save_video, writer=writervideo)
How can I add text to an animation and that actually appears when saved to a video?


text:
Q: Unable to sort Customer address collection I have an attribute in eav_attribute "group_id" for customer/address, I am trying to sort my collection by this attribute.What I am doing is.
$customer = Mage::getSingleton('customer/session')->getCustomer();
$addresses = $customer->getAddressesCollection();
$addresses->addAttributeToSort('group_id', 'DESC');

I have also tried following, but nothing is working.
$addresses->getSelect()->order('group_id', 'DESC');

And
$addresses->setOrder('group_id', 'DESC');

A: If group_id is not an attribute of Customer address type.
So You cannot short address collection by group then that is not possible easily.
For this case,you need to add a left join with Customer/address resource collection Class Mage_Customer_Model_Resource_Address_Collection
public function addGroupId(){

         $this->joinAttribute('customer_group_id', 'customer/group_id', 'parent_id', 'entity_id', 'left');
  };

Then  at customer model (app/code/core/Mage/Customer/Model/Customer.php) and modify getAddressesCollection() method
public function getAddressesCollection()
{
if ($this->_addressesCollection === null) {
    $this->_addressesCollection = $this->getAddressCollection()
        ->setCustomerFilter($this)
        ->addAttributeToSelect('*')
    ->addGroupId()  // add this line at Collection for adding groupid  customer address collection
        ->addAttributeToSort('customer_group_id'); // This line has been added for sorting
    foreach ($this->_addressesCollection as $address) {
        $address->setCustomer($this);
    }
}
return $this->_addressesCollection;
}

If group_id is an attribute of entity_type_id=2
if If group_id is an attribute of entity_type_id=2  mean it is an attribute of customer_address then only need to modify at getAddressesCollection().
Just need to add ->addAttributeToSort('group_id') as per as your share lik How do I sort all of the multiple shipping addresses associated with a customer

A: Instead of this code :
$addresses->getSelect()->order('group_id', 'DESC');

You can try this :
$addresses->getSelect()->order('group_id DESC');

It's working fine for me.

A: Just replace:
$addresses->addAttributeToSort('group_id', 'DESC');

With:
$addresses->addAttributeToFilter('group_id', 'DESC');

Please tell me if it worked.


text:
Q: call subprocess with various optional parameters How can I call a subproccess with a lot of optional parameters?
def subproccess_call(process_name, arg1=None, arg2=None, arg3=None):
  cmd = ['sudo', '%s', '%s', '%s'] % (process_name, arg1, arg2)
  subprocess.Popen(cmd, stdout= subprocess.PIPE,                                  stderr=subprocess.PIPE)

The subproccess method can bei called with zero, one or two additional arguments.


text:
Q: How to wrap d3.svg.line? I have a webpage with multiple sparklines in it. The user selects certain parameters to control the sparklines, some require loading data from the server, and others don't require loading new data, for example, changing chart type (line, area, bar, etc).
I dont want to reload the whole chart for those parameters, and so I've been trying to manipulate the paths, but I am stuck because I also need to get the original data of each path to rebuild x and y functions as well as my custom built color schema function which is based on a threshold that I compute from the data.
This is how I build the paths:
var chart = d3.svg.line()
    .x(function(d,i) { return x(i); })
    .y(function(d) { return height-y(d); })
    .interpolate('basis');
g.append("path")
    .datum(data)
    .attr("class", "chart-path-" + me.id)
    .attr("d", chart);

This is how I want to update it:
var line = function(data) {
    return d3.svg.line()
        .x(function(d,i) {
            var x = d3.scale.linear().domain([0, data.length]).range([0, width]);
            return x(i);
        })
        .y(function(d, i) {
            var y = d3.scale.linear().domain([0, d3.max(data)]).range([0, height]);
            return height-y(d);
        })
        .interpolate('basis');
}
d3.selectAll(".chart-path-" + me.id)
    .attr("d", function(data) { return line(data); });

The reason I am wrapping the line function is because d3.svg.line doesnot keep the original data passed to it, see the source code here. But it seems like d3 does not accept a function. It throws this error:
Error: Problem parsing d="function n(n){function a(){s.push("M",u(t(f),l))}for(var o,s=[],f=[],h=-1,d=n.length,g=c(e),p=c(r);d>++h;)i.call(this,o=n[h],h)?f.push([+g.call(this,o,h),+p.call(this,o,h)]):f.length&&(a(),f=[]);return f.length&&a(),s.length?s.join(""):null}"

I read that it expects a path or a path generated by d3 helper methods (line, area, etc) which is what I am returning in my function. How can I do this? Am I working in the wrong direction? Please ask if something is not clear.

A: The d3.svg.line component returns a function, but you need to call that function on your data to get a path string. Try something like:
var line = function(data) {
    var generator = d3.svg.line()
        .x(function(d,i) { ... })
        .y(function(d, i) { ...})
        .interpolate('basis');
    return generator(data);
}

D3 is trying to assign the generator function itself to the d attribute, coercing it to a string, hence the weird error.


text:
Q: linux headers reinstall error Hi I have recently started getting the following error:
apt_pkg.Error: E:The package linux-headers-4.19.0-041900 needs to be reinstalled, but I can't find an archive for it.
I have tried to follow everything I found on this
link but nothing seemed to fix it and every step I got this error. When I tried to update the manager I got this:
Traceback (most recent call last):
  File "/usr/bin/update-manager", line 117, in <module>
    app = UpdateManager(data_dir, options)
  File "/usr/lib/python3/dist-packages/UpdateManager/UpdateManager.py", line 122, in __init__
    self.meta_release = MetaRelease(
  File "/usr/lib/python3/dist-packages/UpdateManager/MetaReleaseGObject.py", line 44, in __init__
    MetaReleaseCore.__init__(self, useDevelopmentRelease, useProposed)
  File "/usr/lib/python3/dist-packages/UpdateManager/Core/MetaRelease.py", line 100, in __init__
    cache = apt.Cache()
  File "/usr/lib/python3/dist-packages/apt/cache.py", line 170, in __init__
    self.open(progress)
  File "/usr/lib/python3/dist-packages/apt/cache.py", line 233, in open
    self._depcache = apt_pkg.DepCache(self._cache)

The Software updater also keeps crashing unexpectedly when I try to open it, which I guess is caused because of this.
Any ideas of how I should fix this?
Thanks
I will add this to the answers in the future, but this seemed to help me link


text:
Q: Configuring Spring Social to serve static content I am currently using Spring Boot and Spring Social to allow people to log in using Facebook, Twitter, or LinkedIn, within my project, which is based on an already existing Spring project -
https://github.com/spring-projects/spring-social-samples/tree/master/spring-social-quickstart/src/main/java/org/springframework/social/quickstart/config
I want to be able to serve static content (CSS, JS, Images) within my project. I am also using Thymeleaf to template my views. The problem is that when I run the project, Spring can't find the static content. I have researched on other websites and found an article -
http://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-serve-static/
that said that if your static content was in a /resources folder, Spring would be able to find it. Other articles and projects that I've looked at are -

*

*https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-static

*https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
Here is a picture of my file tree and where the files are located.

Here is the signin.html page
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<link href="/index.css" rel="stylesheet" />
</head>
<body>
<form th:action="@{/signin/facebook}" method="POST">
    <button id="facebookloginelementbutton" type="submit" class="loginelementbutton">Login with <i class="fa fa-facebook-square"></i></button>

    <input type="hidden" name="scope" value="email,publish_stream,offline_access" />
</form>

<script src="js/index.js"></script>
</body>
</html>

If you need to see more files or if I am going about this wrong, please tell me!
Thanks in advance,
Adam

A: You need to have project structure like below, static folder inside resources folder, then inside static folder you can have css, images, js etc:

Then CSS is referred in the code like:
<link href="/assets/css/dashboard.css" rel="stylesheet" />

and javascripts like:
<script src="/assets/js/project_angular.js"></script>


text:
Q: WP PHP - Foreach adding different classname - how does it work? I am trying to learn some PHP by creating my own Wordpress theme. I seem to have struck a blank on a problem and Google aint helping much!
I am trying to add a unique classname to each item within my foreach loop. I have gotten it to work with the post ID but this is not a viable solution.
The problem:
I am creating 3 boxes with the 3 latest posts. All posts needs a different classname so they can be placed within a CSS grid (hard to explain the design, but that's essentially what I need). My idea was that each post could get a classname or ID like "item1" for the first, "item2" for the next etc. So that on each loop it adds +1 to the classname.
How would I get around doing that? Building on my knowledge of React I wondered if there is a key-function alike it in PHP?
Here is my code for reference:

<?php
$args = array( 'numberposts' => 3, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) :  setup_postdata($post); ?>

        <img src="<?php the_post_thumbnail_url('blog-small');?>" alt="<?php the_title();?>" style="margin-right: 20px">

<?php endforeach; ?>

A: You can try something like this.
<?php

$i = 1;
foreach ($postslist as $post) :  setup_postdata($post); ?>
    <div class="testrun <?php echo "item".$i; ?>">
        <img src="<?php the_post_thumbnail_url('blog-small');?>" alt="<?php the_title();?>" style="margin-right: 20px">

<?php $i++; endforeach; ?>

A: Add the index to your foreach loop:
foreach ($postslist as $index => $post) :

and use that to append to the class name:
<div class="testrun<?= $index ?>">

As long as the array is an indexed array, you'll get testrun0, testrun1, testrun2 etc.
If you want to start with 1 instead of 0, just change it to:
<div class="testrun<?= $index + 1 ?>">


text:
Q: Show that every non-zero proper ideal of $R$ can be written as a product of finitely many prime ideals of $R$, determined uniquely, upto order.

Theorem $:$

Let $R$ be a Noetherian domain such that it is integrally closed and every non-zero prime ideal of $R$ is maximal. Then every non-zero proper ideal of $R$ can be written as a product of finitely many prime ideals, determined uniquely, upto order.
Proof $:$
Let $S$ denote the collection of all non-zero proper ideals of $R$ which cannot be factored into product of finitely many prime ideals. if possible let $S \neq \varnothing.$ Let $A \in S$ be such that $A \supseteq p_1p_2 \cdots p_m$
    with $m$ minimal. Clearly $m \neq 1.$ $\exists$ a prime ideal $p$ such that $p_1p_2 \cdots p_m \subseteq p.$ $\implies$ some $p_i$ say $p_1 \subseteq p.$ But since every non-zero prime ideal of $R$ is maximal so we have $p_1 = p.$ But then $p_2p_3 \cdots p_m \subseteq Ap^{-1} \subseteq pp^{-1} = R.$ Therefore $\text {Ap}^{-1} \notin \text S.$ So $Ap^{-1} = q_1 q_2 \cdots q_r \implies A = pq_1q_2 \cdots q_r,$ a contradiction. Hence $S = \varnothing.$

In the above proof I dont understand why $Ap^{-1} \notin S.$ Would anybody please help me in understanding this?
Thank you very much.


text:
Q: Trying to download and install eclipse Trying to download and install Eclipse but when i try to open it i get this error

A: You are not supposed to run applications while they're inside a .dmg file. Copy it somewhere else first.


text:
Q: facebook like comments error in php i am using facebooking connection script following
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1" type="text/javascript" ></script>
<script type="text/javascript">
//<![CDATA[
document.write("<fb:like-box href='http://www.facebook.com/pages/mailData /172363602798423' width='692' show_faces='true' stream='true' header='true'></fb:like-box>");
//]]>
</script>

from last three months it working fine but now it give me the following reponse and the comments section completly black
for (;;);{"__ar":1,"payload":null,"domops":[["replace","#stream_loading_indicator",false,{"__html":"\u003Cul class=\"uiList uiStream translateParent\" id=\"ulvg59_1\">\u003C\/ul>"}]],"css":["zz0nI"],"onload":["DOM.scry($(\"ulvg59_1\"), \"a\").forEach(function(a) {  a.target=\"_blank\";  if (a.rel == \"theater\") {    a.rel = \"\";    a.ajaxify = \"\";  }})"],"resource_map":{"zz0nI":{"type":"css","permanent":1,"src":"http:\/\/static.ak.fbcdn.net\/rsrc.php\/v1\/y0\/r\/w7wDxOViCoW.css"}}}

A: From the Facebook docs (http://developers.facebook.com/docs/reference/fbml/):

FBML has been deprecated. Starting June 1, 2012 FBML apps will no
  longer work as all FBML endpoints will be removed. If you are building
  a new application on Facebook.com, please implement your application
  using HTML, JavaScript and CSS. You can use our JavaScript SDK and
  Social Plugins to embedded many of the same social features available
  in FBML.

Instruction for setting up a like box with the current API can be found at http://developers.facebook.com/docs/reference/plugins/like-box/


text:
Q: pthread and kinda "broadcast stream" What is the best way to have some shared stream with data for all threads?
If i have a threads interacting with each user connection, and then every users input must be available for all threads. We can imagine like a simple chat, where everyone sees everyones messages.
So i though that i can use some kind of "shared stream", which i can use for some kind of select() between this stream and users input socket, to write there when i got an input and read from there when there is something new available. I though about having some shared socket, but it wan't work this way, because when first thread will read data from socket, it wan't be available for othrer threads anymore.
So what it the best and idiomatic way to achieve this?

A: I think youy might be taking the engineering here a bit too far..
what you are looking for is an SMP like this or this of some sort, not a stream. The "stream" concept could be handled by a different process (a manager process, if you will) that will handle that stream of incoming information. In the chat scenario you described, it's not neccery because each thread can add to the SMP whatever is received on its own input stream.


text:
Q: Code reuse using an abstract class:hurdles I have two classes. Class A and Class B. They both inherit from an abstract class. There is a method in both the classes that has the exact same code and I am trying to move it to the abstract class
The method goes like this in Class A:
public void updateResult(OutputA output)
{

    var Class c = new Class C();
    var result = c.process();

    output.result = result;
}

Similarly the method is in Class B with an OutputB parameter. The property result is common in classes A and B.
Both types OutputA and OutputB derive from a base type Output.
When I move the method to the abstract class and use the parameter type as Output, the compiler is not able to recognize the result property.
What would be a better way of solving this problem so that the method can be moved to an abstract class and can be used by Class A and Class B.

A: Ensure the result property of the OutputA and OutputB class is defined in the Output class and is public, and then set the parameter type of updateResult to Output (as you've discussed in your question).

A: You could create an interface that exposes the result property and implement it in both the OutputA and OutputB classes, then you can pass your parameter as the interface type.

A: You need to cast the Output parameter to the appropriate type, OutputA or OutputB.  If you post your code, then I can see where the casts need to happen.


text:
Q: Dockerfile CMD not accepting variables for substitution Unable to use variables on the CMD line:
#CMD ["/opt/jdk/bin/java", "-jar", "${ARTIFACTID}-${VERSION}.${PACKAGING}"]
CMD ["/opt/jdk/bin/java", "-jar", "ssltools-domain-LATEST.jar"]

Latest line works, not the first.
Any help or workaround very appreciated

A: Try this little trick first:
CMD ["sh", "-c", "/opt/jdk/bin/java -jar ${ARTIFACTID}-${VERSION}.${PACKAGING}"]

A: When you write the arguments to CMD (or ENTRYPOINT) as a JSON string, as in...
CMD ["/opt/jdk/bin/java", "-jar", "ssltools-domain-LATEST.jar"]

...the command is executed directly with the exec system call and is not processed by a shell.  That means no i/o redirection, no wildcard processing...and no variable expansion.  You can fix this in a number of ways:

*

*You can just write it as a plain string instead, as in:
  CMD /opt/jdk/bin/java -jar ${ARTIFACTID}-${VERSION}.${PACKAGING}

When the argument is not a JSON construct, it gets passed to sh -c.

*You can do as suggested by Philip, and pass the arguments to sh -c yourself:
  CMD ["sh", "-c", "/opt/jdk/bin/java -jar ${ARTIFACTID}-${VERSION}.${PACKAGING}"]

Those two options are basically equivalent.

*A third option is to put everything into a shell script, and then run that:
  COPY start.sh /start.sh
  CMD ["sh", "/start.sh"]

This is especially useful if you need to perform more than a simple command line.


text:
Q: (Weird) Author first name become author second name and incorrect I found it a bit weird, where author second name appear in indirect cite.
Incorrect, when added in
This is correct, but adding this will make second name appear all J. Hollandet al. (1998)

@article{holland1998use,
  title={Use },
  author={Holland, JK and Kemsley, EK and Wilson, RH},
  journal={Journal of the Science of Food and Agriculture},
  volume={76},
  number={2},
  pages={263--269},
  year={1998},
  publisher={Wiley Online Library}

Correct, when without the
This is correct, but adding this will make second name appear all J. Hollandet al. (1998)

@article{holland1998use,
  title={Use },
  author={Holland, JK and Kemsley, EK and Wilson, RH},
  journal={Journal of the Science of Food and Agriculture},
  volume={76},
  number={2},
  pages={263--269},
  year={1998},
  publisher={Wiley Online Library}

How can I solve it?
My full MWE:
\documentclass{article}
\usepackage{xpatch}
% \usepackage[style = authoryear-comp, maxnames = 99]{biblatex}

\usepackage[backend=biber,
% style=authoryear,
 style=authoryear-comp,
% citestyle=authoryear,
dashed=false,
maxcitenames=2,
maxbibnames=99,
giveninits,
alldates=comp,
dateabbrev=false,
uniquename=init]{biblatex}

% to make volume (number), eg. 4(2)
\newcommand*{\volnumdelim}{}
\DeclareFieldFormat[article,periodical]{number}{\mkbibparens{#1}}

\renewbibmacro*{volume+number+eid}{%
  \printfield{volume}%
  \setunit*{\volnumdelim}%
  \printfield{number}%
  \setunit{\addcomma\space}%
  \printfield{eid}}

\newcommand*{\jourvoldelim}{\addcomma\space}
\newcommand*{\jourserdelim}{\newunitpunct}
\newcommand*{\servoldelim}{\jourvoldelim}
\newcommand*{\volnumdatedelim}{\addspace}

\renewbibmacro*{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\jourvoldelim}%
  \iffieldundef{series}
    {}
    {\setunit*{\jourserdelim}%
     \printfield{series}%
     \setunit{\servoldelim}}%
  \usebibmacro{volume+number+eid}%
  \setunit{\volnumdatedelim}%
  \usebibmacro{issue+date}%
  \setunit{\addcolon\space}%
  \usebibmacro{issue}%
  \newunit}
% to make volume (number), eg. 4(2)
\DeclareNameAlias{sortname}{family-given} %for second and third author name
\DeclareFieldFormat{postnote}{\printtext[bibhyperref]{#1}}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage[english]{babel}
\usepackage{csquotes}

\addto\captionsenglish{
\renewcommand{\listfigurename}{\textsf{List of Figures}}
\renewcommand{\listtablename}{\textsf{List of Tables}}
}

% Flag for whether to add front matter to TOC
\newtoggle{fulltoc}
\toggletrue{fulltoc}  % Change to \togglefalse{fulltoc} to remove front matter
\renewcommand{\contentsname}{Table of Contents}

\usepackage[unicode,colorlinks,citecolor=blue]{hyperref}

% for a chapter edited by a book
\usepackage{xpatch}
% \renewcommand*{\finalnamedelim}{\addspace\&\space}
% \renewcommand*{\intitlepunct}{\space} (to become In:)
\renewcommand{\labelnamepunct}{\space} %to delete . after (1997)
% \DeclareFieldFormat[article, incollection, unpublished]{pages}{#1} % to add in PP. (page)
\DeclareFieldFormat[article, incollection, unpublished]{title}{#1}
% \renewcommand{\bibpagespunct}{\ifentrytype{article}{\addcolon}{\addperiod\addspace}} %cancel out this in order to add in PP. (page)

% for title italic
% \DeclareFieldFormat*{title}{\mkbibemph{#1}} %for title italic in all format (conference, paper..)
\DeclareFieldFormat*{title}{#1} %for conference title delete ".."
\DeclareFieldFormat[incollection]{title}{\mkbibemph{#1}} %for incollecion title italic ONLY
\DeclareFieldFormat[thesis]{title}{\mkbibemph{#1}} %for phdthesis title italic ONLY
% for title italic

% to delete "In:" for article
\renewbibmacro{in:}{%
  \ifentrytype{article}{}{\printtext{\bibstring{in}\intitlepunct}}}
% to delete "In:" for article

% for delete comma after Author A and Aurhor b
\DefineBibliographyExtras{english}{%
   \let\finalandcomma\empty
   \let\finalandsemicolon\empty
 }
\renewcommand{\compcitedelim}{\space\&\space}
\DeclareNameAlias{editorin}{given-family}

\newbibmacro*{byeditor:in}{%
  \ifnameundef{editor}
    {}
    {\printnames[editorin]{editor}%
     \setunit{\addcomma\space}%
     \usebibmacro{editorstrg}%
     \clearname{editor}}}

\DeclareDelimFormat[textcite]{postnotedelim}{\addcolon\space}
\DeclareDelimFormat[parencite]{postnotedelim}{\addcolon\space}

% \DeclareFieldFormat{postnote}{#1}
\DeclareFieldFormat{postnote}{\printtext[bibhyperref]{#1}}
\DeclareFieldFormat{multipostnote}{#1}

% for references 's studies (year)
\renewcommand*{\nameyeardelim}{\addcomma\space}
\newcommand{\mycite}[1]{\citeauthor{#1}'s \citeyear{#1}}

\DeclareCiteCommand{\citeauthor}
  {\boolfalse{citetracker}%
   \boolfalse{pagetracker}%
   \usebibmacro{prenote}}
  {\ifciteindex
     {\indexnames{labelname}}
     {}%
   \printtext[bibhyperref]{\printnames{labelname}}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\DeclareCiteCommand{\citeyear} % <======================================
    {}
    {(\bibhyperref{\printdate})}
    {\multicitedelim}
    {}

\DeclareCiteCommand{\parencite}[\mkbibparens]
  {\renewcommand*{\postnotedelim}{\addcolon\space}%
   \usebibmacro{cite:init}%
   \usebibmacro{prenote}}
  {\usebibmacro{citeindex}%
   \printtext[bibhyperref]{\usebibmacro{cite}}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\DeclareCiteCommand{\cbx@textcite}
  {\renewcommand*{\postnotedelim}{\addsemicolon\space}%
   \usebibmacro{cite:init}}
  {\usebibmacro{citeindex}%
   \usebibmacro{textcite}}
  {}
  {\usebibmacro{textcite:postnote}}

\makeatletter
\let\abx@macro@textciteOrig\abx@macro@textcite
\renewbibmacro{textcite}{% <============================================
   \bibhyperref{%
   \let\bibhyperref\relax\relax%
   \abx@macro@textciteOrig%
   }%
}%
\makeatother
% for references 's studies (year)

\DeclareFieldFormat[book]{title}{\mkbibemph{#1}}

\DeclareFieldFormat{url}{Available at\addcolon\space\url{#1}}
\DeclareFieldFormat{urldate}{\mkbibbrackets{\bibstring{urlseen}\space#1}}
\DeclareFieldFormat[online]{title}{\mkbibemph{#1}}
\DefineBibliographyStrings{english}{%
  urlseen = {Accessed},
}

\DefineBibliographyExtras{english}{%
  \protected\def\mkdaterangecomp{%
    \mkdaterangetrunc{long}}%
  \protected\def\mkdaterangeterse{%
    \mkdaterangetrunc{short}}%
  \protected\def\mkdaterangecompextra{%
    \mkdaterangetruncextra{long}}%
  \protected\def\mkdaterangeterseextra{%
    \mkdaterangetruncextra{short}}%
  \protected\def\mkbibdatelong#1#2#3{%
    \iffieldundef{#3}
      {}
      {\thefield{#3}%
       \iffieldundef{#2}{}{\nobreakspace}}%
    \iffieldundef{#2}
      {}
      {\mkbibmonth{\thefield{#2}}%
       \iffieldundef{#1}{}{\space}}%
    \iffieldbibstring{#1}
      {\bibstring{\thefield{#1}}}
      {\dateeraprintpre{#1}\stripzeros{\thefield{#1}}}}%
}

% \DeclareFieldFormat{doi}{\bibstring{urlfrom}\addcolon\space\url{#1}}
% \DefineBibliographyStrings{english}{%
%     urlfrom = {Available at}
% }

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}

@article{harris2009using,
  title={Using Statistics to},
%   author={Harris, Lr and Holland, Saleh},
  journal={Proceedings of the Institute of Acoustics},
     author={Harris, L. E. and Holland, K. R.},
  year={2009},
  volume={31},
}

 @article{ghasemi2012normality,
   title={Normality },
   author={Ghasemi, Asghar and Zahediasl, Saleh},
   journal={International journal of endocrinology and metabolism},
   volume={10},
   number={2},
   pages={486},
   year={2012},
   publisher={Kowsar Medical Institute}
 }

@article{holland1998use,
  title={Use },
  author={Holland, JK and Kemsley, EK and Wilson, RH},
  journal={Journal of the Science of Food and Agriculture},
  volume={76},
  number={2},
  pages={263--269},
  year={1998},
  publisher={Wiley Online Library}

}

\end{filecontents*}

\addbibresource{\jobname.bib}

\begin{document}
\nocite{WinNT}

Text is \textcite{harris2009using} sentences.

This is  \textcite{ghasemi2012normality} sentences.

% This is correct, but adding this will make second name appear all \textcite{holland1998use}

% \textcite{primarysource}\parencite[cited in][]{secondarysource}

\printbibliography
\end{document}

A: Your bibliography has two different authors with the last name "Holland". Biblatex has added the initials in order to disambiguate them.
This happens because you have the uniquename=init option in your preamble. To disable this functionality, remove the option or change it to uniquename=false.
The biblatex manual (section "4.11.4 Name Disambiguation") also lists other possible settings:

uniquename=true, false, init, full, allinit, allfull, mininit, minfull
default: false
Whether or not to update the uniquename counter, see § 4.6.2 for details. This feature will disambiguate individual names in the labelname list. This option is also settable on a per-type, per-entry, per-namelist and per-name basis. The possible choices are:

*

*true - An alias for full.

*false - Disable this feature.

*init - Disambiguate using initials only.

*full - Disambiguate using initials or full names, as required.

*allinit - Similar to init but disambiguates all names in the labelname list,beyond maxnames/minnames/uniquelist.

*allfull - Similar to full but disambiguates all names in the labelname list,beyond maxnames/minnames/uniquelist.

*mininit - A variant of init which only disambiguates names in identical lists of base nameparts (by default, lists of family names).

*minfull - A variant of full which only disambiguates names in identical lists of base nameparts (by default, lists of family names).


text:
Q: django - how to implement a 2-step publish mechanism I'm new to both web development and django so maybe that's a noob question.
I want to do the following:

*

*Ask user to fill some form and submit it.

*Then, parse and format the content and display it back to the user to let him verify it.

*User can accept the result or go back to the previous view, update data and resend.

This is as far as I can think:
views.py
def add_content(request):
    if request.method == 'POST':
        form = AddContentForm(request.POST)
        if form.is_valid():
            content = form.save(commit=False)
            return verify_content(request, content)
    else:
        form = AddContentForm()
    return render(request, 'myapp/add_content.html', {'form' : form})

def verify_content(request, content):
    return render(request, 'myapp/verify_content.html', {'content' : content})

The verify_content template will obviously contain two buttons ('back', 'ok'), but I don't know how to pass the content object to a view for saving it in the db, or send it back to the previous view from there. Should I use js? Can i do it with just server side code?
Maybe my whole logic is wrong. Should I save the object in the db before verification and then delete it if needed (sounds ugly)?  What is a good way to implement this?
Thanks in advance for your time.

A: You could use the users session for this:
request.session['content'] = content

and in the view where the user should verify his input do:
content = request.session['content']

and voilá you got the content between 2 views.
Django also secures that users can't tinker with its data by either saving it server side, or in a signed cookie.

A: I would save the form with commit=True in the add_content view, and would add a verified field or something to the model. Then you can append the pk as GET parameter to the link which will get you back to add_content view from verify. You can extract the parameter from request.GET dict.


text:
Q: Will calling audio.play() pre-cache an HTML5 audio in the browser? I have a bunch of audio clips that I need to repeatedly play in the browser.
As far as I understand doing audio = new Audio(src) does not do any IO on the actual source file until audio.play() is called.
Is there any guarantee that the code below would cache the audio in the browser and minimize latency?
audio = new Audio(src);
audio.volume = 0;
audio.play();

Is there any downside to this approach apart from the fact that volume=0 does not work in some Safari-based browsers, like the ones on IOS?
Is there a better approach for caching short audio clips?

A: you can try setting the preload attribute of the audio element as auto :
audio = new Audio(src);
audio.preload = 'auto';

Demo:

var aud = new Audio('http://upload.wikimedia.org/wikipedia/commons/5/5b/Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg')
aud.preload = 'auto'
var bData = document.createElement('span')
document.body.appendChild(bData)
setInterval(() => bData.innerText = 'Buffered Time(in seconds): ' + (aud.buffered.length && aud.buffered.end(0)), 300)


text:
Q: How to add multiple pinpoints into GoogleMap in Titanium Framework for iphone? I have used Googlemap using titanium framework for iphone,I am able to dispaly 1 pinpoint/marker for given location using latitude and longitude,but when i am going to display multiple markers/pinpoints , not able to show it on Map.
I have tried to create ARRAY of points to display on the google maps, but it is just showing single pinpoint to display it on Map.
Can anybody help me out for how to display multiple pinpoints to google map using tianium.
Any useful link or code will be appreciated!!
Thanks,
Mishal Shah

A: sample code and documentation
http://wiki.appcelerator.org/display/guides/Using+Location+services
It appears the link has changed:
https://wiki.appcelerator.org/display/guides/Native+Maps+and+Annotations#NativeMapsandAnnotations-Annotations


text:
Q: Script stops at YAHOO.util.Event.addListener I am new to YUI.  Just trying to get a most basic functioning example working on my site.
Here is the code:
    <button id="mytest">test</button>

    <script type="text/javascript">
    var helloWorld = function(e) {
            alert("Hello World!");
    }
    </script>

    <script type="text/javascript">
    alert('xx');
    YAHOO.util.Event.addListener("mytest", "click", helloWorld);
    alert('x2');
    </script>

The xx alert shows, but the x2 alert never does.  And, clicking on the button does not fire the HelloWorld function.
I have the necessary include files:
    <!-- Required CSS -->
    <link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.8.1/build/progressbar/assets/skins/sam/progressbar.css">

    <!-- Dependency source file -->
    <script src = "http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom.event.js" ></script>
    <script src = "http://yui.yahooapis.com/2.8.1/build/element/element-min.js" ></script>
    <!-- Optional dependency source file -->
    <script src="http://yui.yahooapis.com/2.8.1/build/animation/animation-min.js" type="text/javascript"></script>

    <!-- ProgressBar source file -->
    <script src = "http://yui.yahooapis.com/2.8.1/build/progressbar/progressbar-min.js" ></script>

A: you should be sure the js files are included on you html files,the code your write is write!

A: Believe I found it.  Or at least I was able to find other examples which worked.  But in my case I believe the problem is the js files I was referencing in fact did not exist.  Namely this file:
http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom.event.js

A: sure, it is yahoo dash dom DASH event, not yahoo dash dom DOT event


text:
Q: Database localization (multilingual) design for Python/Django I am currently in the process of creating an app, on which the information will be accessed by people who speak different languages. The information will be highly unique, so using translation tools will not be good enough. All the information will need to be in different languages, and when the user logs in, the information is displayed according to his settings. Now, the application is based off Django and MySQL. I see that Django has a localization feature, but I don't quite understand it. Is it calling a translation mechanism or something? I don't get it.
Putting that aside, I was wondering what was the best approach to solve this issue. The number of different languages is unknown for now. So I don't think storing the exact translation of each column within one table is a good idea, even though it would save time when querying. (no inner joins etc).
1) Should I look into the Django localization feature? What is it exactly? [I don't really want to store the translations into files.]
2) What Database design is best for multilingual applications? I found those ones:

*

*http://www.codeproject.com/Articles/8084/Creating-multilingual-websites-Part-2

*Storing the translation of each information in the same table, with _language appended in the different columns.

*Schema for a multilanguage database
How people usually solve this issue? Thanks a lot!
EDIT: I am not looking especially for something that is THAT easy to use. Mostly for something that is performant and won't create a giant mess in my DB... is that possible?

A: 1) Django i18n mechanism is used to allow localization of static text- labels in templates, field names, error messages- basically every text you don't store in database. It won't help much for translation of database contents.
2) Every major effort at multilingual django models I have seen uses one of the following approaches:

*

*Adding modlename_lang columns to the same table.

*Storing shared fields in one table and translations in another.

I would advise you to decide which of these approaches you like more, and just use the best documented model translation app for the chosen approach.
If you're going to have a few languages, then I'd advise to go for the first approach. On the other hand, if the number of languages gets larger, the second approach may be more viable.


text:
Q: Will my Wordpress installation persist across an EC2 retirement? I have a site running Wordpress on an EC2 instance. It is now down and AWS is telling me the instance will be retired in a couple weeks. The instance retirement docs say that I need to create an AMI from my instance and restore from that AMI to another instance. This process has failed me so far on three attempts (with the three AMI creation attempts still pending after 24 hours).
While backup via AMI creation is recommended in this situation, is it necessary? If I just stop/start my instance, will my whole Wordpress installation (including posts, content, and other stuff store in MySQL) come right back up once it's started on a healthy host?

A: Yes. Stopping the instance and Starting it again will work fine.
Any data stored on an EBS volume will be preserved. Data on an Instance Store device will be lost. (It is unlikely you would be using instance store, but worth checking.)
When started, the instance will be provisioned on a different host.


text:
Q: How to fix location of Windows from second grub I originally had Windows Vista, later upgraded to 7.
Then I used wubi to install Kubuntu alongside Windows 7 - my load screen became the black one with white writing (grub legacy I believe).
Then I (deliberately) somehow deleted Kubuntu, though I can't remember how. I may have just removed the partition!
Then I installed an SSD, and cloned Windows 7 partition to the SSD.
Then I installed Ubuntu on the original drive, and deleted the old Windows.
The problem is that somehow I've ended up with two boot screens.
The first is the blue screen (grub 2 I believe) which lists Ubuntu and Windows.
Ubuntu boots fine, but if I select Windows, it takes me to the original black and white boot screen, offering Kubuntu and Windows 7. Unfortunately, both of these options no longer point to an existing OS, and the real Windows 7 is hidden!
I tried using boot-repair, but same result. I've linked the disk summary from boot-repair below.
http://paste.ubuntu.com/5714899/
I guess the problem must be that there is an old grub legacy hanging around somewhere - how can I get rid of it?

A: Alex, You installed Kubuntu using wubi, that's called inside windows installation not alongside.
In  wubi installation , kubuntu splits windows bcd file and creates entry for kubuntu.  When kubuntu crashed, you needed  to fix windows bcd using rebuild bcd command as guided here, beacuse grub installs after splitting windows' bcd file.
This will remove old grub completely. After this You will able to boot windows only , and you need to reinstall grub. After successfully  grub installation you will get both boot entries.