text:
Q: Tracking Multiple Youtube Videos with Youtube Api and Google Analytics So I've successfully setup Google Analytics tracking for one video displayed using the Youtube Api. However, when I have more than one video on the same page the event tracking stops working.
This is my code:

Can anyone figure this out?

A: The function onPlayerStateChange references the first player directly.
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            _gaq.push(['_trackEvent', 'Videos', 'Play',
            **player**.getVideoUrl()]);
        }
        // -- snip --
    }

So ALL the events are getting attributed to player, and NONE to player2 or player3.
I think that instead of:
player.getVideoUrl()

you want to use:
event.target.getVideoUrl()

FYI, I find that for debugging GA code like this, it is very helpful to use the Google Analytics Debugger


text:
Q: Mostrar SplashScreen mientras se carga la aplicación en Android Tengo implementado una splashcreen mediante una activity que se infla de su layout con una imagen centrada, pero lo que me encuentro que si es la primera vez que se instala la app, durante la carga/compilación se muestra una pantalla en blanco, más o menos 6 segundos, la segunda vez que inicias la app inicia directamente con la SplashScreen.
Graficamente así
La Primera vez que se ejecuta la app despues de instalación o borrar datos del menú configuración
(click abrir app).........................(splashscreen)------(listo)
La segunda vez que se abre la app
(click abrir app)(splashscreen)------(listo)
Mi pregunta si hay alguna forma de poner una splashcreen durante ese periodo de pre-carga de Android.
Manifest.xml
<activity
    android:name=".SplashActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:theme="@style/AppTheme.SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Estilo AppTheme.SplashTheme del Tema que hereda la activity
<style name="AppTheme.SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
</style>

Layout XML splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorSplashScreen">

    <LinearLayout
        android:id="@+id/splashscreen"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:contentDescription="@string/about.alt_logo"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:layout_gravity="center"/>

        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:layout_marginTop="8dp" />

    </LinearLayout>

</LinearLayout>

SplashActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;

/*
config_longAnimTime   = 400
config_mediumAnimTime = 300
config_shortAnimTime  = 150
*/
public class SplashActivity extends AppCompatActivity {

    private String TAG = "SplashActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final int SPLASH_DISPLAY_LENGTH = 1200;
        final int SPLASH_DISPLAY_OFFSET = getResources().getInteger(android.R.integer.config_shortAnimTime);;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        Log.d(TAG, "onCreate() called with: " + "savedInstanceState = [" + savedInstanceState + "]");
        final Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                final LinearLayout img = (LinearLayout) SplashActivity.this.findViewById(R.id.splashscreen);

                Animation fadeOut = new AlphaAnimation(1, 0);
                fadeOut.setInterpolator(new AccelerateInterpolator());
                fadeOut.setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));

                fadeOut.setAnimationListener(new Animation.AnimationListener()
                {
                    public void onAnimationEnd(Animation animation)
                    {
                        img.setVisibility(View.GONE);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //Create an intent that will start the main activity.
                                Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
                                SplashActivity.this.startActivity(mainIntent);

                                //Apply splash exit (fade out) and main entry (fade in) animation transitions.
                                overridePendingTransition(R.anim.zoom_enter, android.R.anim.fade_out);

                                //Finish splash activity so user cant go back to it.
                                SplashActivity.this.finish();

                            }
                        }, SPLASH_DISPLAY_OFFSET);

                    }
                    public void onAnimationRepeat(Animation animation) {}
                    public void onAnimationStart(Animation animation) {}
                });

                img.startAnimation(fadeOut);

                Log.d(TAG, "finish SplashScreen: " + SPLASH_DISPLAY_LENGTH);

            }
        }, SPLASH_DISPLAY_LENGTH);

    }

}

Actualización:
Se muestra la pantalla blanca porque hereda del tema light, porque si añado el estilo del tema, se muestra negra la pantalla.
    <item name="android:background">#FF000000</item>
    <item name="android:colorBackground">#FF000000</item>

Creo que la solución recae en implementar dibujar el icono mediante la carga del tema antes de usar un layout xml,  abrir app ---> se aplica tema ----> carga layout en la interfaz.

A: Cuando deseas que al iniciar la pantalla de inicio de la aplicación  (SplashScreen) no muestre ese molesto fondo blanco, se pude solucionar fácilmente creando un tema el cual relacionarias a la actividad:
 <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/fondo_splash</item>
   </style>

En realidad la propiedad que define el fondo al iniciar la actividad es android:windowBackground y puedes agregar una imagen (@drawable/ )
    <item name="android:windowBackground">@drawable/fondo_splash</item>

o un color (@color/):
    <item name="android:windowBackground">@color/fondo_splash</item>

Dentro de nuestro AndroidManifest.xml podemos definir el tema en el nivel de la aplicación :
  <application
        android:theme="@style/SplashTheme">

o de alguna actividad especifica:
<activity android:name=".SplashScreenActivity"
   android:theme="@style/SplashTheme" >

con esto siempre aseguramos cargar un fondo (drawable o color), antes de cargar una imagen o iniciar completamente la aplicación.

A: Update
Leyendo ese post Un splashscreen eficiente (en)
Añado lo opaque
Definir el fondo del splashscreen en un drawable background_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item android:drawable="@color/colorSplashScreen"/>
    <item android:top="-48dp">
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>
</layer-list>

Aplico un desplazamiento superior para ajustar bien la transición de la pantalla pre-carga hacia el splashscreen
Asignar como fondo el drawable creado en styles.xml
<style name="AppTheme.SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>

De paso elimino la idea de tener texto que aparece debajo del icono de la app, porque no encontrado como hacerlo directamente como un drawable.
layout splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@color/colorSplashScreen">

    <LinearLayout
        android:id="@+id/splashscreen"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal">

        <ImageView
        android:layout_width="wrap_content"
        android:contentDescription="@string/about.alt_logo"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"/>

</LinearLayout>

Código opcional para cambiar el tema al vuelo, en caso de no hacer un splascreen con un activity intermedio:
public class MyMainActivity extends AppCompatActivity {
 @Override
  protected void onCreate(Bundle savedInstanceState) {

    setTheme(R.style.Theme_MyApp); //Tu Tema general
    super.onCreate(savedInstanceState);
    // ...
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Css loading font: What does the # in a url mean and how to add a GET-parameter? I'm using fontawesome with css/scss. The font is embeded in the scss like this:
src: url('#{$fa-font-path}/fa-regular-400.eot');
src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');

To make a preload run correctly on our server, I need to add a GET-parameter (this is due to session-things), so I need to change
fa-regular-400.woff2

to
fa-regular-400.woff2?preload

But what does the # do? In a "normal" URL on a webpage it would be the anchor, but in a font-file? How do I correctly add the preload-parameter to:
fa-regular-400.eot?#iefix
fa-regular-400.svg#fontawesome

Is it:
fa-regular-400.eot?#iefix&preload
fa-regular-400.svg#fontawesome?preload

or
fa-regular-400.eot?preload#iefix
fa-regular-400.svg?preload#fontawesome

??

A: fa-regular-400.eot?preload#iefix
fa-regular-400.svg?preload#fontawesome

this is the correct way. The #part is just a fragments and is usually entirely ignored when parsing HTTP requests. I even suspect most browsers don't even send it to the server.
You might want to double check fa-regular-400.eot?preload#iefix on older IE versions though (pre IE11), the entire reason for it in the first place is that their CSS parser ignores everything after the ? which we abused to ignore other font formats.
For the SVG font, the #id is just there to tell the browser which svg element in the file to use as font.

A: If the font is an OpenType collection, the fragment indicates which font from the collection to load.
If it's unspecified or unrecognised, it loads the first font from the collection (ref)
If it's not an OpenType collection, it's ignored.


text:
Q: pass form name variable into url in django I would like to pass the name variable of a selected inputbox in my django template into a url without going through the django views or url.py. Is there an easy way to do this.

    Chapter

      <input class="form-control" type="text" name="chapter_text" value="1"></input>

I want the name value of the input class to be passed into the name argument of the url in the div button below

Download

A: You should do it through javascript.
Store your url value as a JS variable:

Change the anchor to a button with a onClick event that calls a function.
In that function you can build the URL with my_url and recovering the name of the input you want with JS.
After that, make a redirection:
window.location = "http://www.yoururl.com";


text:
Q: Find the sum pair of the elements inside the array? Have the function ArrayChallenge(arr) take the array of integers stored in arr, and determine if any two numbers (excluding the first element) in the array can sum up to the first element in the array. For example: if arr is [7, 3, 5, 2, -4, 8, 11], then there are actually two pairs that sum to the number 7: [5, 2] and [-4, 11]. Your program should return all pairs, with the numbers separated by a comma, in the order the first number appears in the array. Pairs should be separated by a space. So for the example above, your program would return: 5,2 -4,11
If there are no two numbers that sum to the first element in the array, return -1
Input: [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]
Output: 6,11 10,7 15,2
Final Output: --6--,--1----1-- --1--0,7 --1----5--,2

Input: [7, 6, 4, 1, 7, -2, 3, 12]
Output: 6,1 4,3
Final Output: --6--,--1-- 4,3

My approach
 function ArrayChallenge(arr) {

 var sum = []

 for (var i = 0; i < arr.length; i++){
    for (var j = i + 1; j < arr.length; j++){
    if(arr.[i] + arr[j]=== )
    }
   }
   // code goes here
   return arr;

   }

     // keep this function call here
    console.log(ArrayChallenge(readline()));

Can you please help me with this ?

A: Logic

*

*Loop through the array.

*Start from index 1 to last node (except index 0) in the outer loop.

*Srart from one node next to the outer loop in the inner loop.

*Check the sum of both nodes.

*If the sum value is same as the node at first index, push that to sum array in required format.

*Check the length of sum array. If length > 0 the join sum array and return. Else return -1

Working Code

const input = [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7];
const input2 = [7, 6, 4, 1, 7, -2, 3, 12];
const input3 = [37, 6, 4, 1, 7, -2, 3, 12];
function ArrayChallenge(arr) {
  var sum = []
  for (var i = 1; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] === arr[0]) {
        sum.push([arr[i], arr[j]].join());
      }
    }
  }
  return sum.length > 0 ? sum.join(" ") : -1;
}
console.log(ArrayChallenge(input));
console.log(ArrayChallenge(input2));
console.log(ArrayChallenge(input3));

A: You could use a reducer followed by a forEach loop in order to push the pairs to an empty array, then join them at the end.

const ArrayChallenge = (nums) => {
  const pairs = []

  // Get the first and remove it from the array
  const first = nums.splice(0, 1)[0]

  nums.reduce((all, curr) => {
    all.forEach((a) => {
      // Check if we have a match
      if (curr + a === first) {
        // check if it's already in the array
        // we don't want duplicates
        if (pairs.indexOf(`${a},${curr}`) === -1 && pairs.indexOf(`${curr},${a}`) === -1) {
          // push the pair to the array separated by a space
          pairs.push(`${curr},${a}`)
        }
      }
    })

    return all
  }, nums) // we pass in nums as the starting point

  // If there are no pairs then return -1
  if (pairs.length === 0) {
    return -1
  } else {
    // Join the pairs together with a space
    const result = pairs.join(' ')
    // Replace each digit (\d) with hyphens before and after
    const parsed = result.replace(/(\d)/g, '--$1--')

    return parsed
  }
}

const result1 = ArrayChallenge([17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7])
console.log(result1)
const result2 = ArrayChallenge([7, 6, 4, 1, 7, -2, 3, 12])
console.log(result2)

A: Your approach uses a O(n^2) level complexity. This can be solved using O(n) if you're willing so sacrifice a little on space complexity.
What you can do is :

*

*Make an empty object.

*store all values of the array (not the 0th element) in the object as key and add it's value as true.

*Loop the array (from 1st index). Take the value and subtract it from the 0th element. find this subtracted value from the object, If it does not return undefined, make a pair and save it.

One drawback of this method is, you'll find duplicate entries in the result.
This Approach uses O(n) Time complexity and O(n) space complexity

function ArrayChallange(arr) {

  let numObj = {}
  let i = 1
  let result = []
  let tempVal

  // Pushing all elements of arr (from index 1) inside numObj
  while(i<arr.length){
    numObj[arr[i]] = true
  }

  i = 1

  // Looping the array to find pairs
  while(i < arr.length){
    tempVal = numObj[Math.abs(arr[0] - arr[i])]
    if(tempVal){
      result.push(arr[i].toString() +","+tempVal.toString())
    }
  }

  if(result.length !== 0)
    return result.join(" ")
  else
    return -1
}


text:
Q: Return target object in array based on two properties, one min/max and one boolean How can I return a target object from an array based on two properties, one which requires min/max and the other, in this case, is a boolean?
For example, in the below array, I'd like to return the object with the smallest order attribute and whose isComplete is false.
var a = [
    {
        order: 3,
        isComplete: false,
        name: 'A',
    },
    {
        order: 2,
        isComplete: false,
        name: 'B',
    },
    {
        order: 1,
        isComplete: true,
        name: 'C',
    },
    {
        order: 4,
        isComplete: false,
        name: 'D',
    },
    {
        order: 5,
        isComplete: false,
        name: 'E',
    },
];

If I check for order attribute, reduce correctly returns smallest object:
var r = a.reduce((prev, curr) => {
    return (
        prev.order < curr.order
    ) ? prev : curr;
});

// CORRECT Output: {order: 1, isComplete: true, name: "C"}

However, if I also want to return the one with isComplete as false, Order 4 is incorrectly returned. Expected is the next smallest Order 2 to be returned:
var r = a.reduce((prev, curr) => {
    return (
        prev.order < curr.order
        &&
        !prev.isComplete
    ) ? prev : curr;
});

// INCORRECT Output: {order: 4, isComplete: false, name: "D"}
// EXPECTED Output: {order: 2, isComplete: false, name: "B"}

I'm assuming reduce will not work for what I'm trying to do.
One way I can think of is to pre-filter on the other attributes and then sort, but this doesn't seem optimal:
var r = a.filter(el => !el.isComplete).reduce((prev, curr) => {
    return (
        prev.order < curr.order
    ) ? prev : curr;
});

// CORRECT Output: {order: 2, isComplete: false, name: "B"}

A: Use this
let r = a.filter((cur) => !cur.isComplete).reduce((prev, curr) => prev.order < curr.order ? prev : curr );

A: You could sort by

*

*isComplete and then by

*order.

const
    array = [{ order: 3, isComplete: false, name: 'A' }, { order: 2, isComplete: false, name: 'B' }, { order: 1, isComplete: true, name: 'C' }, { order: 4, isComplete: false, name: 'D' }, { order: 5, isComplete: false, name: 'E' }];

array.sort((a, b) =>
    b.isComplete - a.isComplete ||
    a.order - b.order
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You will need to evaluate the boolean comparison. If they are equal, move onto the order. If they are not equal, reverse the sort by multiplying by -1.
If you want to find the first incomplete, using a reducer, just compare the current order to the previous, only if it is incomplete.

const data = [
  { order: 3 , isComplete: false , name: 'A' },
  { order: 2 , isComplete: false , name: 'B' },
  { order: 1 , isComplete: true  , name: 'C' },
  { order: 4 , isComplete: false , name: 'D' },
  { order: 5 , isComplete: false , name: 'E' },
];

const firstIncomplete = data.reduce((prev, curr) =>
  prev ? !curr.isComplete && curr.order < prev.order ? curr : prev : curr);

console.log(firstIncomplete);

const compareBoolean = (a, b) => a === b ? 0 : a ? -1 : 1;

const sorted = data.sort((
  { order: orderA, isComplete: isCompleteA },
  { order: orderB, isComplete: isCompleteB }
) =>
  (compareBoolean(isCompleteA, isCompleteB) * -1) || (orderA - orderB));

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }

The output should read:
[
  { order: 2 , isComplete: false , name: "B" },
  { order: 3 , isComplete: false , name: "A" },
  { order: 4 , isComplete: false , name: "D" },
  { order: 5 , isComplete: false , name: "E" },
  { order: 1 , isComplete: true  , name: "C" },
]

Without the boolean comparator function
Although you can subtract boolean values, doesn't mean you should. I would advise against this and evaluate the boolean values as numerical values instead.
See: "Sort array of objects by a boolean property"

const data = [
  { order: 3 , isComplete: false , name: 'A' },
  { order: 2 , isComplete: false , name: 'B' },
  { order: 1 , isComplete: true  , name: 'C' },
  { order: 4 , isComplete: false , name: 'D' },
  { order: 5 , isComplete: false , name: 'E' },
];

const sorted = data.sort((
  { order: orderA, isComplete: isCompleteA },
  { order: orderB, isComplete: isCompleteB }
) =>
  (isCompleteA - isCompleteB) || (orderA - orderB));

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }

A: I do not see a need to do double sort here. You can just sort array by 1 property and find first element with property b that match your requirement.
Code:

const a = [{order:3,isComplete:!1,name:"A"},{order:2,isComplete:!1,name:"B"},{order:1,isComplete:!0,name:"C"},{order:4,isComplete:!1,name:"D"},{order:5,isComplete:!1,name:"E"}];

const sortedByOrder = a.sort((a, b) => a.order - b.order)
const res = sortedByOrder.find(e => !e.isComplete)

console.log(res)


text:
Q: How to make tutorial with popovers usage? I am trying to show first time users how to use my website. I've decided to use popovers for this. So, I've created several elements like:

<a href="/rss/{{ user_id }}" id="help-rss" rel="popover" data-title="RSS feed" data-placement="bottom" data-trigger="manual" data-content="Use your favourite RSS reader to get our news!

Next">RSS

And the code like below to show popovers one by one:
$('#help-movie').popover('show');

$("#help-next-movie").click(function() {
  $('#help-movie').popover('hide');
  $('#help-subscribe').popover('show');
});
$("#help-next-subscribe").click(function() {
  $('#help-subscribe').popover('hide');
  $('#help-rss').popover('show');
});

But it doesn't work properly - first popover is shown (help-movie), then I press Next, next one is shown (help-subscribe); but after that Next button doesn't work, help-rss is not shown. But if I show help-subscribe first, then Next button works and help-rss is shown. What can be the reason?

A: I think if the element id hidden when you call .click it will not work once it is shown, you need to use jquery .on http://api.jquery.com/on/
so try replacing your .click with .on like so:
$('body').on("click", "#help-next-subscribe", function(event){
     $('#help-subscribe').popover('hide');
     $('#help-rss').popover('show');
});

.on basically tells the browser to listen for these elements so your jquery will still act upon those elements if they suddenly appear in the page (e.g. are shown, created or pulled in via ajax request.


text:
Q: Using recursion to search all combinations of elements in an array of integers I am working on this problem from Coderbyte using JS:
Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
The problem seems ripe for a recursive solution, given the branching nature of the need to explore the various combinations of array elements.  I would also like to use recursion to get some extra practice.. I'm still very new to coding.
Here is the solution I came up with, and I was very happy about it until I started testing and discovered that it is not at all a solution:
function ArrayAdditionI(arr) {
  // sorting the array to easily remove the biggest value
  var sArr = arr.sort(function (a, b) {
    return a-b;});
  // removing the biggest value
  var biggest = sArr.pop();
  // count will be iterated to stop the recursion after the final element of the array has been processed
  var count = 0;
  function recursion (start, i) {
    if (sArr[i] + start === biggest) {
      return true;
    }
    else if (start + sArr[i] < biggest) {
      return recursion(start + sArr[i], i+1);
    }
    else if (start + sArr[i] > biggest && count < sArr.length) {
      count++;
      return recursion(0, count);
    }
    else {
      return false;
    }
  }
  return recursion(0,0);
}

This code works only if the array elements which can be summed to fulfill the base case are adjacent to each other; calling ArrayAdditionI([1,2,3,4]), for example, will not work because the two elements which must be summed to reach the target value("1" in position 0, and "3" in position 2) are not adjacent.
My flow will return 1, then 1+2, then 1+2+3, then 2, then 2+3, then 3, and finally return false since the target (4) was not reached.
I can visualize how a proper solution needs to flow through a given array, but I don't know how to make this happen through recursion.  For the given array [1,2,3,4], the flow should check results in this pattern: (position0, pos0+pos1, pos0+pos2, pos0+pos1+pos2, pos2, pos2+pos3, pos3).  Can anyone give me a nudge?  I'm going to think on this more before I sleep in an hour and give it a fresh go in the morning.. maybe my brain just needs a recharge.
Again, I'm really new to this, if I've made some very silly mistakes please let me know, I'll learn from them.  Thanks!

A: Your algorithm has a flaw. Your function looks only one step forward.
You need to add loop inside to look over all rest values.
function ArrayAdditionI(arr) {
    // sorting the array to easily remove the biggest value
    // slice added to prevent original array modification
    var sArr = arr.slice().sort(function (a, b) {
        return a - b;
    });
    // removing the biggest value
    var biggest = sArr.pop();
    function recursion(start, i) {
        var result = false;
        // looking over all rest values of array
        for (var j = i; j < sArr.length && !result; j++) {
            if (sArr[j] + start === biggest) {
                result = true;
            }
            else if (start + sArr[j] < biggest) {
                result = recursion(start + sArr[j], j + 1);
            }
        }
        return result;
    }
    return recursion(0, 0);
}

A: function ArrayAdditionI (arr) {
    var sArr = arr.sort(function (a,b) {
        return a-b;
    });
    var biggest = sArr.pop();
    function recursion (start, indx) {
        if (start + sArr[indx] === biggest) {
            return true;
        }
        else if (sArr.length < indx) {
            return false;
        }
        else if (start + sArr[indx] < biggest) {
            return recursion(start + sArr[indx], indx + 1) || recursion(start, indx+1)
        }
        else {
            return false;
        }
    }
    return recursion(0,0);
}


text:
Q: Obtener y copiar archivo .db de SQLite en Android mediante ADB Tengo una aplicación en android que hace uso de la clase SQLiteOpenHelper para trabajar una base de datos local con 3 simples tablas, para obtener el archivo MY_DATABASE.db hago uso de comandos mediante el ADB de la siguiente forma:
$ adb shell
shell@device:/ $ run-as com.my.package
shell@device:/data/data/com.my.package $ cp databases/MY_DATABASE /sdcard/MY_DATABASE.db
shell@device:/data/data/com.my.package $ exit
shell@device:/ $ exit
adb pull /sdcard/MY_DATABASE.db

Mi problema es que dichos comandos no funcionan en todos los dispositivos que he probado:

Moto E (con root y sin este) FUNCIONA
  Moto G (con root y sin este) FUNCIONA
  Nexus 5x (con root y sin este) NO FUNCIONA
  Samsung J1 (sin root) NO FUNCIONA
  Samsung J2 (sin root) NO FUNCIONA
  Huawei (sin root) NO FUNCIONA

¿Qué puedo hacer para que los comandos me funcionen en cualquier dispositivo?
Logré hacer esto sin ningún problema en todos los dispositivos mencionados arriba mediante esta función:
public void copy(File src, File dst) throws IOException {
    Log.d(TAG, "copying...");
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
    Log.d(TAG, "copied");
}

String strSrc = "/data/data/com.my.package/databases/MY_DATABASE"
String strDst = "/sdcard/MY_DATABASE.db";

File fSrc = new File(strSrc);
File fDst = new File(strDst);

try{
    copy(fSrc, fDst);
}catch(IOException e){
    Log.e(TAG, e.toString());
}

Sin embargo quiero poder realizar este proceso mediante el ADB

A: Que el terminal esté rooteado o no es indiferente al usar el comando run-as. Si quieres hacer uso de los privilegios especiales del usuario root para realizar la copia debes teclear primero el comando su (y aceptar elevar los permisos en tu gestor de root) y posteriormente hacer el cp para copiar las bases de datos.
No todos los terminales soportan run-as o les funciona correctamente. He visto en foros en los que no estaba disponible o tenía permisos incorrectos y han tenido que remontar como rw el sistema de archivos /system y ajustar los permisos correctamente con chmod 4750 /system/bin/run-as (ver este ejemplo).
En otros casos puedes tener problemas con los permisos de la aplicación. Como run-as te otorga exactamente los mismos permisos de una aplicación en particular, es probable que dicha aplicación no tenga permisos para escribir en la microSD, por lo que te dará permiso denegado al copiar en /sdcard.
En versiones modernas de Android las aplicaciones no pueden escribir en el raíz de la microSD sin ayuda de la aplicación de sistema Documentos (y en muchos terminales ésta viene inhabilitada por defecto).
Debes ponerme exactamente el mensaje de error que te impide usar run-as para determinar en qué caso te encuentras. Un simple FUNCIONA o NO FUNCIONA no ayuda en la resolución de tu problema.


text:
Q: proving that a function that's continous on $[a, +\infty$) with an horizontal or oblique asymptote (at +$\infty$) is uniformally continious here's how I tried this (I guess it must be wrong),
let's firstly prove the part about the horizontal one,
if there exists an horizontal asymptote $\implies \lim_{x\to +\infty}f(x)=k\in \mathbb{R} $ therefore, for the Heine-Cantor theorem the function f is uniformally continous on $[a,k] \forall x \in \mathbb{R}$ , i'm stuck in here on how to prove it in $(k,+\infty)$


text:
Q: Why is repeating typename keyword in function argument list necessary? I have written a toy program that defines a templated function which takes as an argument a std::vector<T> and a std::vector<T>::size_type.
Here's the working code:
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> foo(std::vector<T> v, typename std::vector<T>::size_type n) {
    n = std::min(v.size(), n);
    return std::vector<T>(v.begin(), v.begin()+n);
}

int main() {
    std::vector<int> v{1,2,3,4,5};
    v = foo(v, 3);
    for (auto i: v) std::cout << i << " "; std::cout << "\n";
}

When I leave out the typename before std::vector<T>::size_type compilation fails after producing this error:
test.cc:5:54: error: 'std::vector<T, std::allocator<_CharT> >::size_type' is not a type
 std::vector<T> foo(std::vector<T> v, std::vector<T>::size_type n) {
                                                      ^

I wonder why that is? Can someone explain why that typename is needed here?

A: You need typename because std::vector::size_type is a depended name.


text:
Q: Manage SSDT project file properly with version control (*.sqlproj) We have constant problem with project XML file (*.sqlproj). If the files are added/renoved/changed location then it automatically adds/removes records in some unexpected places. After that we have big troubles by merging it when somebody changes that file also.
We came to conclusion that we might sort it before checkin. We would alphabetically sort it and in that case merge tool will understand it much better.
So, my questions would be:

*

*Is it possible to re-arrange sqlproj file somehow before EVERY check-in? Maybe there are somekind of options/tools that doing that already?

*Are there any other ways to make developers life easier?

UPDATE:
Once again I got the same problem. sqlproj file was modified 3 times and I want to merge to production only the last change, other 2 are not tested yet. in the merge tool I have the option to add all these 3 new objects or leave it without changes. I am not able to select only the last change ...
EXAMPLE:

*

*developerA created tableA and checked in;

*developerB got the latest version of dev branch, created tableB and checked in;

*developerC got the latest version of dev branch, created tableC and checked in. DeveloperC tested the code and ready to go to production. He tries to merge his code to QA and get's the conflict where he has an option only to go with ALL changes.

A: I understand the scenario you are running into very well. This typically happens when you have multiple work streams happening in the context of a single repository and you don't have a common promotion schedule (as in all work will go to QA at the same time and PROD at the same time).
There's a few ways I can think to get around this problem and there are pros and cons to each option.

*

*Lock each environment until everything can promote together. Not realistic in most cases.

*When you are ready to promote, create a promotion branch from source environment and take things out of the promotion branch that aren't ready to promote to destination environment. This allows devs to keep working and be able to promote without freezing.

*Hybrid approach... Don't source control anything in Dev until it's ready to promote to test. Then either do option #1 or 2 from there onward.

*Create a more flexible ecosystem that can spin up an environment for each Feature branch in order to demo/test with others(or at least allocate/rotate enough between the developers to accomplish the same objective). Once it's accepted promote. This is what we are working towards currently but building out the infrastructure and process when you have a ton of interconnected databases and apps that share them is a bit challenging to say the least (especially in the Microsoft world).
Anyways hopes this helps...

A: 1 - what source control are you using? No source control that I am aware of understands the context of sqlproj files but this isn't normally a problem.
2.a - This shouldn't be a problem you get constantly, are you checking in/out regularly? I would only expect to see issues if different developers are making large scale changes to the projects and not checking out / checking in before and after.
2.b - It is also possible you are not merging correctly, if you take both both sets of changes then it is normally fine.
ed


text:
Q: Are the densities of a continuous stochastic process locally positive in time? Let $X=(X_t)_{t\in I}$ ($I\subset\mathbb{R}$ a (non-degenerate) interval) be a stochastic process with continuous sample paths and such that $X_t$ admits a continuous Lebesgue density $\chi_t\in C(\mathbb{R}^d)$ for each $t\in I$.
Notation: Given $\delta>0$ and $t_0\in I$, we write $I_\delta(t_0):= I\, \cap \,(t_0-\delta, t_0+\delta)$.
Are you aware of (minimal) sufficient conditions on $X$ which guarantee that for each $K\subset\mathbb{R}^d$ compact the following implication holds:
$$\tag{$\star$}\min_{x\in K}\chi_{t_0}(x) > 0 \quad(\text{some }t_0\in I)\ \quad \Longrightarrow \quad \exists\,\delta>0 \, : \, \inf_{t\in I_\delta(t_0)}\,\min_{x\in K}\chi_{t}(x) > 0.$$
(A sufficient condition for $(\star)$ would be that $(t,x)\mapsto\chi_t(x)$ is continuous, but it is not clear how this translates to a natural condition on $X$.)


text:
Q: calling UIViewController through UITabBarController for push In my app I have UINavigationController as initial view ,
Hierarchy is like this

UINavigationController-->LoginViewController
  -->UITabBarController-->UINavigationController -->MasterViewController

MasterViewController has tableView in itself
when a push notification comes , I click on push notification while app is working at background , then app opens masterViewController,  the problem is that I want to update tableList in MasterviewController when I open the app from push notification.
I try to navigate to MasterViewController from AppDelegate like this
 -(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    UINavigationController * navController = (UINavigationController *) self.window.rootViewController;

    MasterViewController * masterController = [navController.viewControllers objectAtIndex:0];

    [masterController updateList];

    }

It is not working,  How can I update MasterViewController when I get the push?
Thanx.

A: You should try in this way:
UINavigationController * navController = (UINavigationController *) self.window.rootViewController;
for (id viewController in navController.viewControllers) {
    if ([viewController isKindOfClass:[MasterViewController class]]) {

              MasterViewController * masterController = (MasterViewController*) viewController;
              [masterController updateList];
             break;
    }
}

A: This could work as well.
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    MasterViewController * masterController = [storyboard instantiateViewControllerWithIdentifier:@"Your_StoryboardID"];
[masterController updateList];
}

A: UINavigationController * navController = (UINavigationController *) self.window.rootViewController;

MasterViewController * masterController = [navController visibleViewController];
if ([viewController isKindOfClass:[masterController class]]) {
    [masterController updateList];
}
eles{
   //Hierarchy maybe not as your description
}

A: Getting the tabbar view controllers and call that view method with pop...
    NSArray *array=[self.tabBarViewController viewControllers];

                    for(int i=0;i<array.count;i++)
                    {

                        UINavigationController *navCont=[array objectAtIndex:i];
                        NSArray *navArray=[navCont viewControllers];
                        for (id view in navArray)
                        {
                            if ([view isKindOfClass:[MasterViewController class]])
                            {
                                MasterViewController * masterController =        (MasterViewController*) viewController;
                                 [masterController updateList];

//if you want to pop to that view controller then use below two lines of code else put comments..

                                [self.tabBarViewController setSelectedIndex:0];
                                [navCont popToRootViewControllerAnimated:YES];
                            }
                            break;
                         }
                   }

Hope it will solve your issue....


text:
Q: how to drop certain data points from a list wo = 2*Pi*50;
tau = 5*Pi;
tstart = 0;
tend = 1;
numpts = 256;
tstep = (tend - tstart)/(numpts - 1);
function =
N[Table[{t,
 Exp[-(I wo + tau + 5*\[Pi]) (t)] +
  Random[NormalDistribution[0, .1]] +
  I Random[NormalDistribution[0, .1]]}, {t, tstart, tend, tstep}]];

ListPlot[Re[function], PlotRange -> All, Joined -> True]

I want to selectively drop certain time points from the function. For example 10 points from t between 0.10 and 0.15 and drop 40 points from t between 0.60 and 0.80.

A: one way might be
ListPlot[Re[function], PlotRange -> All]

newData  = DeleteCases[function,{t_,_}/;(0.1<t<0.15||0.6<t<0.8)];
ListPlot[Re[newData],PlotRange->All,Joined->True]

A: Update:

How do I specify the number of points which I want to delete. Like not delete all the points but some.

tests = {.10 <= # <= .15 & , .6 <= # <= .8 &};
numberofpointstobedropped = {10, 40};
deleted = Join @@ Table[RandomSample[Position[function, _?(i[[1]][#[[1]]] &), {1},
   Heads -> False], UpTo[i[[2]]]], {i, Transpose[{tests, numberofpointstobedropped}]}];
dta = SplitBy[Delete[function, deleted], Or @@ Through @ tests @ #[[1]] &];
ListPlot[Re @ dta,  Joined -> True]

Length /@ {function, Join @@ dta}

{256, 206}

Original answer:
testF = .10 <= # <= .15 || .6 <= # <= .8 &;
dt = Select[SplitBy[function, testF @ #[[1]]&],   Not @ testF @ #[[1, 1]] &];

ListPlot[Re @ dt,  Joined -> True]

Use the option PlotStyle->ColorData[97, "ColorList"][[1]] to get all three pieces in the same color:


text:
Q: WPF application stops interacting on screen rotate We have a WPF app which runs fine, but a user reported that it locks up when the screen is rotated.  (Tablets will do that!)
The app actually renders fully after the rotate but stops responding to the mouse/keyboard.  It doesn't show as 'non-responding' in a Windows sense.
We can simulate the "lock up" here, but debugging this is odd:

*

*Lock up does not occur while in VS debugger

*If you try and attach to the locked up process, VS says the process was built without debug information

*Before the lockup VS can attach/deattach to the same EXE process

We have put trace outputs in global unhandled exceptions but nothing is fired.
I can only think of one next step to debug which is start to hack out chunks of code and find the breaking area.
Anyone seen this before or got any suggestions?
Thanks!

A: The issue was with an update library we were using called Sparkle.
It was creating a hidden WinForms form in it's constructor.  There must be some kind of WPF/WinForms interop bug during screen rotations.  Removing that form or removing the library fixed the issue.


text:
Q: paypal express (or any express option) - magento - "terms and conditions" UPDATED
(Option One):
In magento, at Step 6 of One Page Checkout you see Terms and Conditions.
Now the problem:
Using PayPal Express Checkout (or any express option e.g. Amazon Payments, Google Checkout) there is no Terms and Conditions for the user to agree to.
I need to:
A. Call Magento "Terms and Conditions" block into a modal window (i don't know how + might be too intrusive?)
B. use -- fake -- express checkout buttons and fake/not-magento-native "Terms and Conditions" on Cart Page that user must agree to - before proceeding to: any Express Checkout.
Goal:
User clicks and any express checkout option on cart page >
User encounters popup that has "Terms and Conditions" they must agree to >
Until they agree (probably via ticking a check-box) the real express checkout button is grayed out (or something similar) >
User agrees and then the real express checkout button is active >
User clicks express button and completes express checkout.
go to:
http://pro-tools-training.com/new-magento2/index.php/highslide#
My question is about how to swap the real express checkout buttons on the cart page for fake ones (just images with some sort of onclick event) and then how to place the real express checkout buttons in the popout.
--

(Option Two):
here is another option I am looking at.
i created a static block with a Terms form and assigned a Widget to "PayPal Review Order page"
OK so it shows up but of course its in the wrong place and it does not interact with the Place Order button.
Pros: could work for paypal
Cons: at this point, it's not an obvious solution for other express checkout buttons
so my fist post tries to address this before hand and this post tries to address it at the last stage.
Option 2 appears too limited. I am now looking closer at option one.
...any feedback helpful
UPDATE THREE:
I'm sure there are many other ways to do this but I came up with this if it will help anyone out there.
go to this page:
http://pro-tools-training.com/new-magento3/index.php/html5-video.html
add to cart > got to cart > click paypal express button
and see i made a popout for express buttons
In  general, you can see the code with firebug but it is just (highslide based)
JavaScript firing a popout and the popout contents are written in shortcut.phtml (for paypal exress) and each express button type has its own .phtml file that is similar (e.g. googlecheckout i used link.phtml).
OPEN ISSUES:
1. On iPhone (my iPhone anyway) the popout launches but the checkout buttons are missing. SOLVED: All I needed to do was adjust the width in the js config and the width of the text area in the html.

*

*I want to make the same "terms and conditions" on onestep checkout page - but not a popout.  i want it hidden unless the user clicks the paypal radio button. then it appears - in page - and is required to proceed.

any tips?

A: I think this problem is solved in the Magento 1.11.2.0: After the PayPal page, the T&Cs are displayed on the order review page.


text:
Q: What does the expression "the school first XI rugger team" mean? I found this sentence in a novel set in Cornwall. The complete sentence is:

Daddy is very proud that you have made the school first XI rugger team.

The boy in the team il 16 y.o. and he lives in the Thirties of the Twentieth century.
Can you help me understand the meaning of this expression?

A: Rugger often stands for Rugby Football, usually called Rugby, in informal English. And that makes sense in combination with team.
'Made the team' means 'joined the team'.
The first team is the best of the teams in the school.
And XI stands for the number of players in the field, 11 in this case, so a reduced size team, as explained in a comment by @KillingTime. Or it may be that the boy made the XV team and somewhere it got an error like the mother understood it wrongly and used the wrong number, and the V became a I.
The actual team will be bigger but this is the number playing at one time.
Even when allowing for the time of writing, this sentence is surly non-standard, it sounds like 'poetic' rather than 'everyday' use of English.
No sources for this, I have learned all these words from my English friends many of whom have played rugby.


text:
Q: How can I restore all the queries of MySQL workbench workspace? I have been making queries since 6 months from now and they were all available when I opened the mysql workbench workspace. Although when I opened mysql wokbench today I received this error messsage.

I lost all the queries that I made. I cannot restore the workspace. Can you please help? :(
Thank you very much in advance.


text:
Q: IdentityServer4 - How is the API token being validated behind the scenes? In IdentityServer4 Protecting an API using Client Credentials documentation it is written that:

The job of that middleware is:

*

*validate the incoming token to make sure it is coming from a trusted
  issuer

*validate that the token is valid to be used with this api (aka
  scope)

I have an IdentityServer4 server running on port 5000 and my API is running on port 5001 (2 different servers). I'm wondering what happens behind the scenes in the API when a request comes in with the access token... Does the IdentityServer middleware in the API makes an http call to IdentityServer for each request coming in to the API to validate the token? Does it cahche the token in some way? What actually happen?


text:
Q: Need to modify the data type of a view column Alter view [dbo].[M12_qry_DQBase_Figures]
Alter column [Good_Objects] Integer;

Convert (Integer, [dbo].[M12_qry_DQBase_Figures].[Good_Objects] )

the above two queries are not working to change data type from Varchar to Integer in SQL server help me if possible
Column details mentioned below
Good_Objects: [ARIS_Output].[Number_Objects]-If(IsNull([M11_qry_DQ_Objects_with_errors].[Number_Objects]),0,[M11_qry_DQ_Objects_with_errors].[Number_Objects])

A: if you need the integer type only in the view you can acess de view script and cast the column from varchar to int, if you need to set and get the value into the DB you must update the view and the table.
note that view works like a "mask" of a select statement or complex procedure/validation.


text:
Q: highcharts redraw and reflow not working I am trying to build a dynamic page that has any number between 1-4 graphs on it that can be added or removed as needed but I have run into a huge problem and I can't seem to get the graph to resize after resizing the containing div. for example if I add a graph on the page it will be width 800, then click a button to add another graph it should resize to be 400 a piece but I cannot make it happen. As a very simplistic model I have the following
$(function () {
  $('#container').highcharts({
      chart: {
          type: 'line',
          width: 300
      },
      title: {
          text: 'Width is set to 300px'
      },

      xAxis: {
          categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      },

      series: [{
          data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
      }]
  });
  $('#resize').click(function() {
      $('#container').attr('style', 'width: 800px');
      $("#container").highcharts().reflow();
      console.log($('#container').width());
  });
});

now when that is run it will log 800 to the dev tools window in chrome but the graph will not resize. I have tried both redraw() and reflow() as suggested in the documentation for highcharts. I even setup a really quick demo on jsfiddle here, http://jsfiddle.net/7cbsV/
can anyone please help me. It is kind of important. Thank you in advance for the help.

A: How about using simple chart.setSize(w,h)? See docs.
$("#container").highcharts().setSize(800, height);

A: Just remove the width of the chart from
$('#container').highcharts({
  chart: {
      type: 'line',
      width: 300
  },

so that it is like this
$('#container').highcharts({
  chart: {
      type: 'line'
  },

and set the container width to 300 like this
#container {
   width: 300px;
}

then just resize the container div as you are already doing. the chart will resize according to the width of the container div.
hope this helps.


text:
Q: Do a Function, Delay and Refresh Page Afterwards Sorry if it's a dumb question. Just started PHP learning a week ago
I'm making a very simple password system with one right answer. Goal: You type in an incorrect password, and it displays "Incorrect Password" for 2 seconds, and then refreshes the page to avoid Confirm Form Re-submission.
echo '
 Incorrect Password!';
sleep(2);
echo '';
echo '';
exit;

this is what i have right now, but it completely ignores the 'incorrect password' and just refreshes the page 2 seconds later. Is there any way i can achieve my goal without using other languages?

A: This should work (but I wouldn't use it for serious stuff...):
<?php

echo <<<EOL

 Incorrect Password!

EOL;

exit;

sleep will block the page for 2 seconds on server-side -> so it will not work as intended for the client.
Use Javascript setTimeout instead.


text:
Q: I can't say I blame you vs I don't blame you Is there any real difference?
What are some examples, where the phrases are NOT interchangeable?

A: Any two different phrases are, well different. They always have some difference in the set of their possible connotations.
Whether two phrases are interchangeable depends on (1) the context and (2) just what you mean by "interchangeable", that is, (1) how different their meanings are in that given context, and (2) whether you consider that amount of difference sufficiently significant in that context to decide that they are not interchangeable.
IOW, without (1) a clear understanding of the context of use and (2) a clear definition of what constitutes interchangeableness in that context, the question cannot be answered usefully - it is then just opinion-based.

In general, "I can't say that..." means that you either (1) don't really know for sure that... or, less often, (2) you know it but you don't feel that you can say it.

A: There seems to be a subtle distinction between the phrases which means they are not always interchangeable.
"I don't blame you" can have two meanings. Either "you did it but I do not fault you for it," or "I don't think you did it". In other words, it can mean that you were responsible but justified or that you were not responsible.

I don't blame you for the world financial crisis. You just wanted to buy a house.
I don't blame you for punching Derek. He insulted your mother.

"I can't say that I blame you" seems to be used only to mean the you were responsible but justified, not that you were not responsible. It is often used as a response to a confession.

"Yes, it was I who stole the spoons."
"I can't say that I blame you, after all, they belonged to your mother."

A: In addition to the sentiments expressed in the accepted answer, I'd like to add that "I can't say I blame you" can differ from "I don't blame you" in that the latter tends to imply sympathy, e.g. "I'd likely have done the same if I were in your position" while the former merely implies understanding, e.g. "I may not have done the same if I were in your position, but I understand why you did it."
This is because "I can't say I blame you" abbreviates "I'd blame you if I could, but I can't"; it acknowledges that the action being discussed might be questionable and blameworthy, but indicates that the speaker can't assign blame. The reason is idiomatically because the speaker feels it would be hypocritical. It's rarely if ever used in a literal sense (e.g. "There's not enough proof for me to blame you, so I technically can't").

A: "I can't say I blame you" has a conspiratorial feel to it, maybe hinting that you would be tempted to do likewise despite some disapproval from some people. This phrase excuses rather than forgives, downplaying the fault rather than denying it. It can't be used for something accidental.

Ha! Well, you shouldn't actually have hit him in the meeting, but I can't say I blame you; if he does keep going on and on about eventually someone's going to snap.

On the other hand, "I don't blame you" feels either defiant or conciliatory, depending on the tone of voice. It suggests justification or actual lack of fault.
With an indignant tone, it could be used in similar contexts to "I can't say I blame you," but has a less conspiratorial feel, suggesting that the speaker would be prepared to defend the behaviour to others:

I don't blame you. What he did was completely outrageous. No-one should have to put up with that, and you were right to stick up for yourself.

With a gentler tone, it's more forgiving and can be used to express genuine innocence:

I don't blame you. You couldn't have known it would have that effect.

Summary: "I can't say I blame you" says it wasn't all your fault, whereas "I don't blame you" says it wasn't really your fault.
Thus this doesn't work: "I can't say I blame you; it was a complete accident."

A: Both are used idiomatically to mean

Your actions/feelings are understandable or correct.

See, for example, the definition at Oxford Dictionaries.
This generally has the implication that the other person did do something, but that action was not actually blameworthy:

I can't say I blame you or I don't blame you for breaking that vase--it was
the ugliest, cheapest thing I've ever seen, and I would have 'accidentally' dropped it, too.

If, however, something truly bad happened, and you want to make clear that you don't hold the person you're talking to responsible, then you would only use the direct I don't blame you:

Of course I don't blame you for the broken vase--the table gave way
under it because it was defective, and you had no way of knowing that.

In the latter case, using I can't say I blame you would ring of the idiomatic use, and so would suggest that you don't actually believe the story about the defective table; kind of a verbal wink-wink, nudge-nudge.

A: Actually, there is a real difference between them.  "I can't say I blame you" is a comment about a choice, whereas "I don't blame you" is a conclusion or judgement about an action.
The difference is that in the second case carries the implication that you are in a position to assign blame, whereas the first, being merely a comment, does not carry that implication, but does imply that the actions were a matter of choice.
For instance, let's say that at a cafeteria, someone bumped into you and made you drop your coffee.  If they then explained that they had slipped, you might say "I don't blame you", because it is a situation where you might be expected decide whether they have wronged you.  You probably would not say "I can't say I blame you" because agreeing with them in this case would also mean that you accepted that they had bumped you involuntarily no choice in the matter.
On the other hand, if they said that they had bumped you because they saw a wasp, you might say either, both because you had a right to judge it (it impacted you directly), and also because they made a choice which you could choose to comment on.
Finally, if instead of being the person bumped into, you were told this story later on by a friend who saw a spider and bumped into someone else and made them drop their coffee, you might comment "I can't say I blame you" indicating that their reaction seems reasonable to you.  However, you probably would not say "I don't blame you", because it implies that you have the right to assign blame, which as a non-participant you normally would not.

A: Sometimes the two are interchangeable, sometimes not.  It depends on context.
Generally speaking "I can't say I blame you" is less direct than "I don't blame you".   Saying "I can't say I blame you" might acknowledge a behaviour without taking any stand on whether it is right, wrong, or acceptable.   In comparison saying "I don't blame you" suggests some agreement or acceptance.

A: They are no different in that they mean the same exact thing.
The difference would arise in the emphasis placed on certain words. For example, emphasizing the word "say" would implicitly mean that there could be some blame present. Alternatively, emphasizing the word "I", in "I don't blame you" is going to have a similar implication; namely that there could be blame from someone else.
In the field of communications, there is a very common phrase used as an example for this. That phrase is

"I didn't say he stole your wallet"

Emphasizing each word will change the implicit meaning of this sentence. For example:

*

*emphasizing the word wallet could imply that something else was stolen,

*emphasizing the word your could imply that someone else's wallet was stolen,

*emphasizing the word stole could imply that something else was done with the wallet,

*emphasizing the word he could imply that someone else stole the wallet,

*emphasizing the word say could imply another means was used to show the wallet was stolen,

*emphasizing the word didn't directly states that statement wasn't made,

*emphasizing the word I could imply that someone else said he stole your wallet

So really it all depends on emphasis. Giving emphasis to one of these words will make more of a difference than using either "I can't say I" versus "I don't".

A: "I can't say I blame you" does not sound entirely honest. It can be interpreted as:

I wish I could blame you but it's obvious that I can't.

Saying "I don't blame you" is as direct as it can get.

A: The difference is implied responsibility. Like "I'm sorry" and "I apologize", the difference is most clearly highlighted if you consider speaking to the parents about their daughter's death, at the funeral.

"I don't blame you."

*

*reads as "her death may have been unfortunate, but you should not hold yourself responsible for it - there's nothing you could have done."

"I can't say I blame you."

*

*reads as "her death was bad, and you're clearly responsible and intended it to happen, but there's a moral argument that could defend your actions, most likely that your girl was so awful that any reasonable person would want her dead."

Consider also:

I'm sorry for your loss.

and

I apologize for your loss.

Small differences in implied responsibility, significantly amplified by the circumstance.


text:
Q: How do I compare 3 numbers with a function that takes only 2 variables in Python with a code that I have written I have written a code in Python Jupyter with the below instructions:
Write a function which will always return the bigger of  2 unequal numbers ( do not use max or any built-in function) name it show_max
def show_max(x,y):
if(x == y):
    r = ("Both the numbers are equal")
elif(x > y):
    r = (f"{x} is the maximum number")
else:
    r = (f"{y} is the maximum number")
return(r)

Thereafter, I have to code as per the below instruction:
Using the show_max function write a code to find the biggest of 3 unequal numbers
I am unable to code the 2nd portion. Could anybody help. Thanks!!!

A: I suppose you could also use this approach:
def show_max(x,y,z):
    nums = [x,y,z]
    nums.sort()
    return f"{nums[-1]} is the maximum number"

No need for comparisons.


text:
Q: Build Json with Objects in Objects(JS) I want one json object but get multiple.

let example = {
  test1: '',
  test2: '',
  oTest: {
    oTest1: '',
    oTest2: ''
  },
  ooTest: {
    ooTest1: '',
    ooTest2: null,
  }
};

let result = JSON.stringify({
  example,
  'oTest': example.oTest,
  'ooTest': example.ooTest
});

console.log(JSON.stringify(example));

My Result is that i get 3 seperate Json Objects(example,oTest,ooTest) but my goal is to have 1 Json Object "example" including oTest and ooTest. Also "example" dont show oTest and ooTest.
Goal:
{
  "test1": "",
  "test2": "",
  "oTest": {
    "oTest1": "",
    "oTest2": ""
  },
  "ooTest": {
    "ooTest1": "",
    "ooTest2": ""
  }
}

A: What you are doing doesn't make sense at all. Your expected result is returned by just passing example to JSON.stringify
JSON.stringify(example);

A: JSON.stringify(Object.assign(example,{'oTest': example.oTest},{'ooTest': example.ooTest})

This is merge all the 3 object in one, and return back a stringified object.


text:
Q: BibLaTeX alphabetic style - Choose letters for authors manually I use BibLaTeX with the citation style alphabetic. Sometimes, the abbreviation letters for my citation (e.g. [ABC20]) isn't appropriate for a specific case. For example, if I have a citation of "The Apache Software Foundation", then there will be the abbreviation "[The20]". Instead, I would like it to be e.g. "[Apa20]". Is there any way to achieve this? I am using XeLaTeX in combination with Biber.
Update:
I wrote a short working example:
\documentclass{scrartcl}

\RequirePackage{filecontents}

\begin{filecontents}{example.bib}
@software{Lucene.2020,
    author = {{The Apache Software Foundation}},
    year = {2020},
    title = {{Apache Lucene Core}},
    version = {8.7.0}
}
\end{filecontents}

\usepackage[backend=biber,%
style=alphabetic,%
natbib=true,%
hyperref=true,%
minnames=1,%
maxnames=2]{biblatex}

\renewcommand{\mkbibnamefirst}[1]{\textsc{#1}}
\renewcommand{\mkbibnamelast}[1]{\textsc{#1}}
\renewcommand{\mkbibnameprefix}[1]{\textsc{#1}}
\renewcommand{\mkbibnameaffix}[1]{\textsc{#1}}

\addbibresource{example.bib}

\begin{document}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua \parencite{Lucene.2020}.

\printbibliography

\end{document}


text:
Q: What is the release schedule for Lubuntu Alternate patch releases? The Lubuntu Alternate ISO does not always get released simultaneously with the rest of the ISO's. For example, according to TrustyTahr/ReleaseSchedule, as of April 30th, 2015, the following releases should be available:

*

*14.04(.0) LTS, released on April 17th, 2014

*14.04.1, released on July 24th, 2014

*14.04.2, released on February 19th, 2015

In reality, only 14.04 and 14.04.1 Lubuntu Alternate images are available on the archives. Judging by the files' timestamps, they were released on schedule, as well as the desktop 14.04.2 variants. However, the Alternate variants aren't there. When, if at all, can we expect the Alternate images to appear?
When I look at the corresponding directory for 12.04 LTS, I see no patch releases at all, although, according to the release schedule, there should be 4 already. I have no particular interest in the older LTS version, but I'd like to understand: what can I expect; what is the guiding principle here?

A: There were significant, insurmountable challenges faced with debian-installer in the transition from tasks to metapackages that led to the decision to skip the alternative ISO for Trusty 14.04.2. The release press release explains in additional detail. To my knowledge, there are no plans to go back and generate alternatives for that release.
If installation from the desktop installer is not possible on your system (or otherwise not desired), please consider the mini ISO/netboot option. If netboot wouldn't work, installing from a previous 14.04 alternate and upgrading will get you there.
Lubuntu lacks 12.04 patch releases because Lubuntu 12.04 was not an LTS and is no longer supported.


text:
Q: How to catch a redirection RedirectResponse from Vuejs and redirect I'm trying to make a payment with laravel/cashier-mollie. I use only vuejs for the front-end.
Here is my controller :
public function __invoke(string $plan)
    {
        $user = Auth::user();

        $name = ucfirst($plan) . ' membership';

        if(!$user->subscribed($name, $plan)) {

            $result = $user->newSubscriptionViaMollieCheckout($name, $plan)->create();

            if(is_a($result, RedirectResponse::class)) {
                return $result; // Redirect to Mollie checkout
            }

            return response()->json([
               'status' => 'Félicitation, vous êtes inscrit au ' . $plan . ' plan'
            ]);
        }

        return response()->json([
            'status' => 'Vous êtes déjà inscrit au ' . $plan . ' plan'
        ]);
    }

I should normally be redirected to an internal Mollie page to make the payment. As I use Vuejs, I'm not.
In chrome, I get a good xhr. When I copy / paste the link into the browser, I'm redirecting to Mollie.

I tried this, but the answer only returns empty items :
return response()->json($result);

Response :
{"headers":{},"original":null,"exception":null}

How can I get the redirect link so I can redirect the user to Mollie with Vuejs?

A: When you're doing XHR request and your server sends Redirect response, then it redirects this XHR request, not the browser itself.
You should either respond with some JSON that contains redirect URL that could be used in your client to redirect browser to (not recommended), or don't send XHR request at all, and just send client's browser on URL that will be redirected later.


text:
Q: Mediaquery not working for iPhone I am building a website on a template which has some media-queries. Only the lowest max-width is 479, which is not for iPhone if I'm correct (and if it is, it's not working).
I can't really simulate the screen of an iPhone by resizing my browser so it's hard to test, since the only iPhone I got to test on is in use a lot of the time.
Looking at another template which does have iPhone support, I took the mediaquery from there, but it's not working.
The code that I added:
@media (max-width: 359px) {
    .smaller{
        font-size: 10px;
    }
}

This should work right?
Anybody know the correct media-query? And maybe something to test the iPhone responsive version without using an iPhone?
Thanks!

A: The issue in your media query is in the "max-width", which refers to the target display area.
You should use "min-device-width" / "max-device-width" instead, which refers to the device's rendering area.
Regarding the testing iPhone specific styles without using the actual device - here are some browser based examples you might want to check out:

*

*Google Chrome developer tools device mode (https://developer.chrome.com/devtools/docs/device-mode)

*Firefox Responsive Design View (https://developer.mozilla.org/en-US/docs/Tools/Responsive_Design_View)

A: There are many ways to do this. Below link will help you to write your media queries for iPhone.
http://stephen.io/mediaqueries/
iPhone 5 Media Queries

iPhone 5 in portrait & landscape

@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px) { /* STYLES GO HERE */}

iPhone 5 in landscape

@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : landscape) { /* STYLES GO HERE */}

iPhone 5 in portrait

@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : portrait) { /* STYLES GO HERE */ }


text:
Q: reauthenticateWithCredential throws error: session-expired - The sms code has expired. Please re-send the verification code to try again On a real Android device, reauthenticateWithCredential() throws the error message below. The code works fine on an Android emulator (with no errors)!
[auth/session-expired] The sms code has expired. Please re-send the verification code to try again.

I understand that this error can result from calling PhoneAuthProvider.credential(). I am a bit puzzled to get it after calling reauthenticateWithCredential()! What puzzled me even more, is that calling firebase.auth().currentUser before calling reauthenticateWithCredential() displayed the user object, which proves that the user is logged in!
Authentication Screen:
firebase.auth.PhoneAuthProvider.credential(state.confirmResult.verificationId, state.codeInput);

// Then, credential is saved in Redux

Email Linking Screen:
const currentUser = firebase.auth().currentUser;
console.log("currentUser:", currentUser); // this displays the user object correctly

// props.credential is the credential, which was saved in Redux in the Autherntication Screen above
await firebase.auth().currentUser.reauthenticateWithCredential(props.credential);

// the above statement throws the following error message.
// [auth/session-expired] The sms code has expired. Please re-send the verification code to try again.


text:
Q: How to run iOS app in iPhone without USB connection to Mac I have developed my first apple app and i wish to run it in iphone (its working well in XCode). By running in iphone i don't mean to connect it with mac and run with USB connection.
I mean something like there will be uuid of iphone and i upload my app some where and it can be run by Iphone user without any wire-connection to my MAC where i have app in xcode.
Is it possible to achieve by anyway? Is that way to achieve is free of cost ?

A: What I understand from you question is you want to distribute your application to others,
If you have apple developers account , you can use TestFlight ITunes Connect, where you can distribute upto 1000 users
Or you could use other free providers like,

*

*Fabric

*Hockey
I personally recommend Fabric , it's free, has lot of features

A: In your project set your distribution profiles in code signing options
Then click on product-->Build wait for a moment until it opens an Organizer window .
After opening organizer window select save for AdHoC deployment --> choose your organization--> select for all devices compatibility(if you are running with latest Xcode 7.3 version otherwise devices compatibility window won't appear) click next next.
Finally you can get an api file in the Organizer window. In that select the first api file which has recently you built -> click on export to your any finder location.
Then open your api file location in your Finder.
Then open your browser and open https://www.diawi.com and drag and drop your api in the specified field and wait until it reaches 100% to upload and click on send so that you can get a link. Now you can share your link.
Note: In iOS device he can install the api by using safari browser with the link we have shared


text:
Q: How to use plotcandle() function only if the statement is true? candleplot = input(defval=false , title='Plot Candle')
plotcandle(0,var7, 0, var7, color=var7>xrf(var7,1)?#FFF700:#3FFF00 ,editable=false)
i am writing like this
if candleplot
plotcandle(0,var7, 0, var7, color=var7>xrf(var7,1)?#FFF700:#3FFF00 ,editable=false)

But its giving error cannot use plotcandle in local scope.
I want to plot the candel when someone tick the checkbox

A: You can put a ternary conditional on the value of close
plotcandle(0,var7, 0, candleplot ? var7 : na, color=var7>xrf(var7,1)?#FFF700:#3FFF00 ,editable=false)


text:
Q: How to solve code: 'EAUTH', response: '535-5.7.8 Username and Password not accepted.responseCode: 535, command: 'AUTH PLAIN' I have a contact me form in my website and I'm trying to send an email using gmail service and it's working flawlessly in my local dev environment, but I'm having this issue:

{code: 'EAUTH', response: '535-5.7.8 Username and Password not accepted. Lear…mail/?p=BadCredentials e19sm4851511qty.16 - gsmtp', responseCode: 535, command: 'AUTH PLAIN'}

I googled a lot and looked in the docs but all I found was to make the "Less secure app access" option in Google accounts turned on, and I did that, I tried turning it off and on and I made sure it was working in my local machine, but unfortunately it's not working in when I send the request to my API in Vercel endpoint.
my React code
const sendContactForm = (e) => {
    e.preventDefault()

    Axios.post(
      `${
        process.env.NODE_ENV === 'development'
          ? process.env.REACT_APP_API_LOCAL_URL
          : process.env.REACT_APP_API_URL
      }/contact`,
      {
        theName,
        email,
        subject,
        msg
      }
    )
      .then(({ data }) => {
        setSendStatus(data.sendStatus)
        setSendStatusMsg(data.sendStatusMsg)
        console.log(data)
      })
      .catch((err) => console.error(err))
  }

And my NodeJS code is:
const nodemailer = require('nodemailer')
const smtpTransport = require('nodemailer-smtp-transport')

module.exports = (req, res) => {
  const { theName, email, msg, subject } = req.body
  // const { MAILER_EMAIL, MAILER_PASS } = process.env

  let transporter = nodemailer.createTransport(
    smtpTransport({
      service: 'gmail',
      port: 465,
      // secure: true,
      auth: {
        user: process.env.MAILER_EMAIL,
        pass: process.env.MAILER_PASS
      }
    })
  )

  const mailOptions = {
    from: email,
    to: process.env.MAILER_EMAIL,
    subject: subject,

    html: `<p>here is simply HTML code</p>`
  }

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      res.send({
        sendStatusMsg: 'Sorry! something went wrong!',
        errResponse: err,
        sendStatus: 0
      })
    } else {
      res.send({
        sendStatusMsg: 'Thanks for contacting us',
        infoResponse: info.response,
        sendStatus: 1
      })
    }
  })
}

And thanks a lot.

A: I found this question with the same issue. It has other recommendations besides enabling less secure apps, you can review it and see if it helps

Also, some recomend to use XOAuth2 instead to authenticate


text:
Q: RShiny: modify numericInput based on data Here's a sample code where I generate random vector and plot its histogram. In addition, there's a numericInput field that I use to clip data, i.e. to assign values lower than a threshold to that threshold. The initial value of the numericInput field is assigned based on data.
The problem is that when I press the button to generate data, the plot is evaluated twice, which I want to avoid. I emphasise this by adding sleep routine in the plotting function.
It seems to me that I'm updating the numericInput incorrectly. When I simply hard-code initial field value of that field, the issue is gone and the plot is evaluated once.
library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("test data clipping"),

  sidebarLayout(
    sidebarPanel(
      actionButton('inDataGen', 'Generate dataset'),
      br(),
      br(),
      uiOutput('resetable_input_clip'),
      actionButton('inDataClipReset', 'Reset data clipping')
    ),
    mainPanel(plotOutput("plotHist", width = "100%"))
  )
))

server <- shinyServer(function(input, output) {
  rValues <- reactiveValues(dataIn = NULL,
                            dataMin = -10e10)

  # generate random dataset
  userDataGen <- observeEvent(input$inDataGen, {
    cat(file = stderr(), '\nuserDataGen\n')

    # assign result to shared 'dataIn' variable
    x <- rnorm(1000)
    rValues$dataIn = x
    rValues$dataMin = min(x)
  })

  # modify data
  userDataProc <- reactive({
    cat(file = stderr(), 'userDataProc\n')

    dm = rValues$dataIn

    if (is.null(rValues$dataIn))
      return(NULL)
    else {
      # Data clipping
      dm[dm < input$inDataClipMin] <-
        input$inDataClipMin

      return(dm)
    }
  })

  output$resetable_input_clip <- renderUI({
    cat(file = stderr(), 'output$resetable_input_clip\n')

    times <- input$inDataClipReset
    div(
      id = letters[(times %% length(letters)) + 1],
      numericInput(
        'inDataClipMin',
        'Clip data below threshold:',
        value = rValues$dataMin,
        width = 200,
        step = 100
      )
    )
  })

  output$plotHist <- renderPlot({
    cat(file = stderr(), 'plotHist \n')

    if (is.null(rValues$dataIn))
      return(NULL)
    else {
      plot(hist(userDataProc()))
      Sys.sleep(2)
    }
  })
})

shinyApp(ui = ui, server = server)

The flow after pressing the button to generate data involves two evaluations of plotHist:
output$resetable_input_clip
plotHist

userDataGen
plotHist
userDataProc
output$resetable_input_clip
plotHist
userDataProc

SOLVED ELSWHERE
This issue has been solved on Shiny Google group. The final solution is available here and is a combination of changing observeEvent + reactiveValues to reactive(), and using freezeReactiveValue.

A: I believe your issue is occurring in
# modify data
  userDataProc <- reactive({
    cat(file = stderr(), 'userDataProc\n')

    dm = rValues$dataIn

    if (is.null(df))
      return(NULL)
    else {
      # Data clipping
      dm[dm < input$inDataClipMin] <-
        input$inDataClipMin

      return(dm)
    }
  })

Since input$inDataClipMin is dependent on the reactive value rValues$dataMin, you end up rendering this for the initial value of rValues$dataMin, the rValues$dataMin is being reevaluated, which triggers a reevaluation of input$inDataClipMin.
If you replace this snippet with what I have below, you should get your desired behavior.
# modify data
  userDataProc <- reactive({
    cat(file = stderr(), 'userDataProc\n')

    dm = rValues$dataIn

    if (is.null(df))
      return(NULL)
    else {
      # Data clipping
      dm[dm < rValues$dataMin] <-
        rValues$dataMin

      return(dm)
    }
  })

As an alternative, you could put the following in your ui
numericInput(
        'inDataClipMin',
        'Clip data below threshold:',
        value = rValues$dataMin,
        width = 200,
        step = 100
      )

And then use updateNumericInput to replace it's value.  This would require a lot more tinkering in your current code, however, and depending on what else is happening in your app, may not be the ideal solution anyway.

A: Here's what I came up with. The key difference is introduction of a shared reactive variable rValues$dataClip that stores clipped data. Previously, data modification was achieved by a reactive function userDataProc. The output of that function was used for plotting which, as suggested by @Benjamin, was the culprit of double evaluation of plotting. In this version, the userDataProc is turned into observeEvent that monitors input$inDataClipMin numeric input field.
library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("test data clipping"),

  sidebarLayout(
    sidebarPanel(
      actionButton('inDataGen', 'Generate dataset'),
      br(),
      br(),
      uiOutput('resetable_input_clip'),
      actionButton('inDataClipReset', 'Reset data clipping')
    ),
    mainPanel(plotOutput("plotHist", width = "100%"))
  )
))

server <- shinyServer(function(input, output, session) {
  rValues <- reactiveValues(dataIn = NULL,
                            dataClip = NULL,
                            dataMin = -10e10)

  # generate random dataset
  userDataGen <- observeEvent(input$inDataGen, {
    cat(file = stderr(), '\nuserDataGen\n')

    # assign result to shared 'dataIn' variable
    x <- rnorm(1000)
    rValues$dataIn = x
    rValues$dataMin = min(x)
  })

  # modify data
  userDataProc <- observeEvent(input$inDataClipMin, {
    cat(file = stderr(), 'userDataProc\n')

    dm = rValues$dataIn

    if (is.null(rValues$dataIn))
      rValues$dataClip = NULL
    else {
      dm[dm < input$inDataClipMin] <-
        input$inDataClipMin

      rValues$dataClip <- dm
    }
  })

  output$resetable_input_clip <- renderUI({
    cat(file = stderr(), 'output$resetable_input_clip\n')

    times <- input$inDataClipReset
    div(
      id = letters[(times %% length(letters)) + 1],
      numericInput(
        'inDataClipMin',
        'Clip data below threshold:',
        value = rValues$dataMin,
        width = 200,
        step = 100
      )
    )
  })

  output$plotHist <- renderPlot({
    cat(file = stderr(), 'plotHist \n')

    if (is.null(rValues$dataClip))
      return(NULL)
    else {
      plot(hist(rValues$dataClip))
      Sys.sleep(2)
    }
  })
})

shinyApp(ui = ui, server = server)

Now, there's only one evaluation of plotHist after pressing the button to generate data:
output$resetable_input_clip
plotHist
userDataProc

userDataGen
output$resetable_input_clip
userDataProc
plotHist


text:
Q: Java Powershell Exchangeonline in Tomcat directly doesn't work but using tomcat in netbean works I've the following java code to start a powershell script that connect using Connect-ExchangeOnline.
It works perfectly when invoking it from command line and from within a JSP with the tomcat within Netbean IDE.
However, if I run the same JSP in just tomcat itself (without Netbean) it hang with error timeout.
Do note, the environment I am running this code has a Proxy Server and all the necessary netsh winhttp set proxy xxxx has been performed.
Have anyone encounter this before?
Best Regards
StringBuilder sbInput = new StringBuilder();
StringBuilder sbError = new StringBuilder();

String[] commandList =
{
  "powershell.exe", "-ExecutionPolicy", "Unrestricted", "-noprofile", "-noninteractive", "c:/temp/test.ps1"
};
ProcessBuilder pb = new ProcessBuilder(commandList);
Process proc = pb.start();
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

String line;
while ((line = bufferedreader.readLine()) != null)
{
    sbInput.append(line + "\n");
}

inputstream = proc.getErrorStream();
inputstreamreader = new InputStreamReader(inputstream);
bufferedreader = new BufferedReader(inputstreamreader);
while ((line = bufferedreader.readLine()) != null)
{
    sbError.append(line + "\n");
}


text:
Q: Server processing time in tomcat access logs In order to debug a performance issue I enabled access logs in tomcat. We are not using any apache server. Its the embedded tomcat that we are using.
I'm using following pattern for access logs.
access-patten = %h %l %u %t "%r" %s %b %D

%D = time at which first byte of the request is received ~ time at which last byte of the response is send.
So %D includes network latency as well.
But how do I print time difference between first byte of the request received and first byte of the response sent.

A: Try %F
You can use %F:

%F - Time taken to commit the response, in milliseconds

Added in 2013
As mentioned by Tomer, since Tomcat version 7.0.42 there is a new log element %F available in the AccessLogValve implementation. You can find a better description of the difference between %D and %F in the case description:
Bug 55102 - Add ability to report time taken to prepare response:

Tomcat's AccessLogValve is able to report the time taken to send an entire request using %D. This is the total processing time and may be affected by network conditions. It is sometimes useful to be able to record the time taken by the server to prepare the response and send the first content to the client.
Attached is a patch that records the time the response is committed and then allows that to be reported in the access log using a %F pattern (which is the same as used by the mod-log-firstbyte module for HTTPD).

A: How about:

write time until first byte is written (commit time) in millis - %F

from AccessLogValve.html

A: In my opinion, access log's duty is to record the informs of the  program itself, which means tomcat looks the program package as a whole, so we may not get the byte details only.
If you want to get the application logging details, you can log the program webapp log, may be log4j or logback logging details inner your program. Such as 'System.currentTimeMillis()' at the beginning of your program and also add to the end. Please use your webapp logs but not access logs.
Thanks, hope it helps.


text:
Q: is it possible to return new observable inside operator, nested observable

var url = "http://domain.com/some/url";
// this endpoint will return websocket URL

Rx.DOM.ajax({
  url: url,
  method: 'GET',
  responseType: 'json'
}).scan(function(o, data) {
  // data.websocker is websocker url
  return Rx.DOM.fromWebSocket(data.websocket_url, null, function(o) {
    console.log(o);
  }, function(o) {
    console.log(o);
  });
}).subscribe(function(data) {
  // Success Message
  console.log(data);
}, function(error) {
  // Log the error
  console.log(error);
});

As shown in above example. is it possible to send the Observable from inside the operators like promises ?

A: Sure this is quite common and there are alot of operators that exist to process inner observables in various ways.  In this example, you might use flatMap instead of scan:
var url = "http://domain.com/some/url";
// this endpoint will return websocket URL

Rx.DOM.ajax({
  url: url,
  method: 'GET',
  responseType: 'json'
}).flatMap(function (data) {
  // data.websocker is websocker url
  return Rx.DOM.fromWebSocket(data.websocket_url, null, function(o) {
    console.log(o);
  }, function(o) {
    console.log(o);
  });
}).subscribe(function(data) {
  // will receive messages that are received from the websocket
  console.log(data);
}, function(error) {
  // Log the error
  console.log(error);
});


text:
Q: Как разбить по папкам ресурсы drawable В общем, в проекте в папке res/drawable скапливается много ресурсов и трудно найти потом то, что нужно. Попробовал просто раскидать ресурсы по созданным мною папкам, но они потом не находятся через getResources().getDrawable()
Вопрос: каким образом можно разбить ресурсы по папкам внутри папки res/drawable ?

A: В ранних версиях можно было разбить ресурсы по "Экранам". Вместо каталога res будут:

*

*\res-main\

*\res-screen\%НАЗВАНИЕ_ЭКРАНА%\

В app.gradle добавляется:
sourceSets {
    main {
        res.srcDirs = [
                'src/main/res-main',
                'src/main/res-screen/login',
                'src/main/res-screen/home',
                'src/main/res-screen/about',

        ]
    }
}

Но сейчас этот подход не описан в документации:

*

*http://tools.android.com/tech-docs/new-build-system/resource-merging

*https://developer.android.com/studio/write/add-resources
Не проверял лично, работает ли этот метод.
Источник: Структура Android проекта – альтернативный путь


text:
Q: Pointing my domain to concrete5 folder I have a domain name, and have installed concrete5 under my public_html folder. So it is public_html/concrete5.4.1 folder. Now how would I redirect my traffice to concrete5 folder ? That is when the user types in www.domainname.com it should show the index.php page from public_html/concrete5.4.1 folder.
Thank you very much.

A: You want to do this in your server setup (it has nothing to do with concrete5 itself). In Apache, it's called "Virtual Host" (not sure about IIS -- I think it's something similar).
Search around for that term and you will find many many tutorials and instructions on how to do it.
For example: Apache: Virtual Host configuration


text:
Q: Generating a unique file path with Polymorphic Paperclip I'm running into an issue with different users uploading files with the same name being overwritten with the Polymorphic Paperclip plugin. What I'd like to do is inject the current user's ID into the URL/path. Is this possible? Would I be better off generating a random name?
Here are my current :url and :path parameter values in asset.rb:
:url => "/assets/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/:id/:style/:basename.:extension"

What I'd like to be able to do is this:
:url => "/assets/#{current_users_id}/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/#{current_users_id}/:id/:style/:basename.:extension"

A: Use Paperclip interpolations:
file config/initializers/paperclip.rb:
module Paperclip
  module Interpolations
    def user_id(attachment, style)
      current_user.id
    end
  end
end

has_ attached_file option:
:url => "/assets/:user_id/:id/:style/:filename"

(The syntax changed from Paperclip 2.x to 2.3; :path is not necessary; Use the latest version and have a look at the source, it's quite well documented.)

A: Every time I see the word random and it relates to strings, I think GUID. Perhaps they could work for you.

A: for me it didnt work bypaperclip.rb but it works like this:
In the model class:
class Micropost < ApplicationRecord
  Paperclip.interpolates :user_id do |attachment, style|
    attachment.instance.user_id
  end

 has_attached_file  :pic1,
    :url => "/Microposts/:user_id/:style/:basename.:extension"

In case if you want to do it by Paperclip interpolations you should find a path like this:
first find gem file path. type this in your terminal:
$ gem env

Then, it  will show you a path in "- GEM PATHS:"
in my case this was the path :
:/usr/local/lib/ruby/gems/2.4.0/gems/paperclip-5.0.0/lib/paperclip

In this direction you can find "paperclip.rb" .


text:
Q: Database generated dropdown giving more variables a value from the same database when selected I hope the title wasn't too cryptic, and I am sure there will be other threads like this one but cannot seem to put my finger on the correct terminology.
I have a form that has 3 dropdowns. Let's call them 'sales consultant', sales email & sales team.
What I am looking to do is give a value to 'sales email' & 'sales team' when the sales consultant is chosen from the dropdown 'sales consultant'
The catch, I am using mysql to pull the data for each dropdown. See below:

    Sales Consultant
    <input class="" type="text" list="salesconsultant" name="salesconsultant" placeholder="Start typing consultants name" required />
    <datalist id="salesconsultant">
        <?php
            $sql = "SELECT consultant, id FROM salesconsultants";

            $result = $conn->query($sql);

            if (!$result) die($conn->error);

            if($result->num_rows > 0 ) {
                while($row=$result->fetch_assoc()) {
                    echo "<option value=\"".$row["id"]."\">".$row["consultant </option>";
                }

                echo "</datalist>";
            } else {
                echo"record 0";
            }
        ?>

The other rows I have in the database are 'salesemail', 'id', 'consultant' and 'teamid'.
So when sales consultant 1 is selected it will give the variable $salesemail the value of consultant 1's 'salesemail' and so on.
Is this possible?

A: Just change below line to :
echo '<option value="'.$row["id"].'".','."'.$row["salesemail"].'">'.$row["consultant"].'</option>';

In above code you are separating both value by , And you can get these values like this :
        $result = $_POST['yourselectbox'];
        $r1 = explode(',', $result);
        echo "id: ". $r1[0]."
";
        echo "email: ". $r1[1]."
";

Hope this will work!


text:
Q: How to fix all object values being NaN in JavaScript I am currently working on a solar system physics simulator in the JavaScript canvas. I have a object named "earthState" with some info that should be used by the physics system to create earth's orbit. I have attributed a numerical value to each of the keys in the object, but when I log the object to the console it says that all values are NaN.
"earthState":
    let earthState = {
        distance: {
            value: 1.496 * Math.pow(10, 11),
            speed: 0.00
        },
        angle: {
            value: Math.PI/2,
            speed: 1.990986 * Math.pow(10, -7)
        }
    };

    console.log(earthState);

I have the object logging when the page first loads, and I have stopped the page before it finishes loading and I get the correct values in the console:

{distance: {…}, angle: {…}}
    angle: {value: 1.5707963267948966, speed: 1.9909859999999998e-7}
    distance: {value: 149600000000, speed: 0}
    __proto_: Object

But, as soon as I let the page finish loading, I get NaN as all the values:

{distance: {…}, angle: {…}}
    angle: {value: NaN, speed: NaN}
    distance: {value: NaN, speed: NaN}
    __proto_: Object

The only thing that changes when the page loads is that an animation loop starts. There are no variables that should change anything in the "earthState" object. I have had a hard time trying to figure out the problem. It may be something simple that I am not aware of. Please let me know if this is the case, and if there is anything I should change to fix this problem. Thank you in advance!

A: Thank you all for your comments and ideas! My friend has helped me debug and find the error. I was simply using the "earthState" object instead of the "sunState" object in one of the functions. Cheers!


text:
Q: Push is not a function I get the error
this.items.push is not a function
From googling I've found out that this means that items is not an array. I've tried to account for this by checking if it's undefined and using this.items = this.items || []; I also tried to change data and make it an array but when I enclose data in square brackets, nothing gets pushed to items.
It's very hard to troubleshoot because the error only shows up in the developer console after I've deployed it. No errors show up in the developer console when I am in development mode.
items = [];
storageKey = 'MyDataStorageKey';

public onSubmit(thumbnail, quantity, product_name, product_price){

var data = {
   thumbnail,
   quantity,
   product_name,
   product_price
};

this.items = this.items || [];
if (typeof this.items !== 'undefined')
this.items.push(data);
localStorage.setItem(this.storageKey, JSON.stringify(this.items));
this.isSubmitted = true;
}
ngOnInit(): void {
   this.items = this.getStorageItems();
 }

I also get the error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. I get the error for the following:

{{item.quantity}}
{{item.product_name }}
{{item.product_price }}

A: I wouldn't know what causes the problem in the first place or how to solve it properly I am afraid (you're right though, by the look of the error, it seems like you are not getting an array with this.items in production)
One thing I noticed, however, is that you are checking against the string "undefined" instead of undefined. I believe, however, instead of checking if what you get is not undefined, it's better to check if what you get is actually an array? To check if something is an array or not, you could use Array.isArray() method. So maybe rewriting your condition like this might help until you figure out what's the root cause of the problem:
if (Array.isArray(this.items))
  this.items.push(data);
  localStorage.setItem(this.storageKey, JSON.stringify(this.items));
  this.isSubmitted = true;
}

A: You are getting this error because items is not an array and the ngFor expecting an iterable object. Better to check the type of items using isArray() function before you push items to items object.
if (Array.isArray(this.items))


text:
Q: how to refresh select box without reloading the whole form in js? I am using a form in a modal where i add new fields to the select box and would like to refresh the select box such that the new options are added to it. And this without reloading the entire page . Can someone please tell me if this is possible or not and if it is how do i go about it.

A: There are multiple ways of doing this:
First if you are using jQuery this is simple like:
$("#dropdownlist").empty();

Another way can be:
for(i = dropdownlist.options.length - 1 ; i >= 0 ; i--)
{
   dropdownlist.remove(i);
}

Another simplest way can be:
document.getElementById("dropdownlist").innerHTML = "";

Now if you want to repopulate it. You can append the options with jQuery. If you have single value you can achieve it like:
$('#dropdownlist').append($('<option>', {
    value: 1,
    text: 'New option'
}));

And if it's a collection. you need to loop over it like the following snippet:
 $.each(newOptions, function (i, val) {
        $('#dropdownlist').append($('<option>', {
            value: val.value,
            text : val.text
        }));
    });

A: Check this,

$(document).ready(function(){
         $("#test").append($('<option>', {value: 2,text: 'Two'}));
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
          <option value="1">One</option>
 </select>

Give it a try, it should work.