text:
Q: How do I detect a "command + backspace" from an external keyboard in a UITextField I am using the good old add a zero length character solution to detect backspaces in an empty text field (Detect backspace Event in UITextField).
Unfortunately on an iPad if you connect an external keyboard and hit "cmd+backspace" it does not trigger the shouldChangeCharactersInRange method.
I looked around the documentation and the decompiled headers and I don't seem to be able to find a way to prevent that.
So, how do I detect a "command + backspace event"?

A: You can use a UIKeyCommand. I tested on my 10.5" iPad Pro running iOS 12.1.1, using a Bluetooth keyboard and the Swift Playgrounds app version 2.2.
Here's the playground code:
import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    override func loadView() {
        let command = UIKeyCommand(input: "\u{8}", modifierFlags: .command, action: #selector(ViewController.handleKeyCommand), discoverabilityTitle: "Hello")
        addKeyCommand(command)

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        view.contentMode = .topLeft
        view.backgroundColor = .white

        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 8
        stack.alignment = .fill
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            view.leadingAnchor.constraint(equalTo: stack.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: stack.trailingAnchor),
            view.topAnchor.constraint(equalTo: stack.topAnchor)])

        let textField = UITextField(frame: CGRect(x: 20, y: 20, width: 260, height: 30))
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        stack.addArrangedSubview(textField)

        label.translatesAutoresizingMaskIntoConstraints = false
        stack.addArrangedSubview(label)

        self.view = view
    }

    @objc func handleKeyCommand(_ sender: UIKeyCommand) {
        commandCount += 1
        label.text = "\(commandCount)"
    }

    private var commandCount = 0
    private let label = UILabel()
}

let vc = ViewController()
PlaygroundPage.current.liveView = vc

Tap in the text field, then press ⌘⌫. Each time you press it, the count in the label increases by 1.


text:
Q: How to create a global composer command? I've created a composer command locaload, but after requiring it globally, it's not recognized anywhere but in the plugin repo itself. So not very useful.
I don't want to add it to every project/library, and can't even, because some are not mine. I want it to be available everywhere, like all of composer's commands are.
Plugin's composer.json:
{
    "name": "rdx/composer-localoader-plugin",
    "description": "Composer plugin to load some dependencies locally",
    "type": "composer-plugin",
    "require": {
        "composer-plugin-api": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "rdx\\localoader\\": ""
        }
    },
    "scripts": {
        "locaload": "rdx\\localoader\\Plugin::localoadCommand"
    },
    "extra": {
        "class": "rdx\\localoader\\Plugin"
    }
}

The "scripts" defines the command: composer locaload x y. When I run it anywhere else (not the plugin's repo itself):
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "locaload" is not defined.

When I run it like a script (composer run-script locaload -- x y):
[InvalidArgumentException]
Script "locaload" is not defined in this package

It is indeed not defined in THIS package (or when I'm not even IN a package), but it DOES exist in the global composer.json and composer.lock.
How do I make this command globally recognized, so I can use it in any project, or even from any non-project location?
The global install works:
rudie@home:~$ composer global require rdx/composer-localoader-plugin:dev-master
Changed current directory to /home/rudie/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing rdx/composer-localoader-plugin (dev-master d4f5e85)
    Cloning d4f5e8547a4e23c2febc2ed845e76774ea63e61a

Writing lock file
Generating autoload files

and removing it works as well, but doesn't change anything.
When I check the command list globally (composer list | grep locaload), it's empty. When I check it inside the plugin repo itself:
locaload        Run the locaload script as defined in composer.json.

A: Scripts are only available when defined in the root package, so you would have to add this to the package you want to use it in:
"scripts": {
    "locaload": "rdx\\localoader\\Plugin::localoadCommand"
},

But I get that it's not very practical, and one alternative way I guess would be to add a "bin": "locaload" or something to your plugin so that when you install it globally it would make it available a binary script you can just run as locaload ... and it would act upon the composer.json in the current directory, just not as a composer plugin then. You could still have the plugin part be in place globally to listen to the post-autoload-dump.
I hope this is clear enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: My return-result is returning all the correct answers except one, with not errors This is a homework question. I am not asking for the correct answer, I am just looking for help whether I am going in the right direction.
The prompt is that I am to return the first and last name of students who either (OR): (a) Is not currently enrolled (not in Enrollments table) or (b) has the lowest score in any class within their own department.
The database schema is as follows:
My SQL query that I came up with is:
SELECT FIRSTNAME, LASTNAME
FROM STUDENTS
JOIN ENROLLMENTS ON STUDENTS.NETID = ENROLLMENTS.NETID
JOIN COURSES ON COURSES.CRN = ENROLLMENTS.CRN
WHERE STUDENTS.NETID NOT IN (
  SELECT NETID
  FROM ENROLLMENTS
) OR
ENROLLMENTS.SCORE IN (
  SELECT MIN(SCORE)
  FROM ENROLLMENTS
  WHERE COURSES.DEPARTMENT = STUDENTS.DEPARTMENT
  GROUP BY ENROLLMENTS.CRN
);

I tried to use JOIN clauses to combine the three tables where they intersect. The NetId is distinct to each student, identifying them in the Enrollments table. Each class has a unique CRN so I connected them there between Courses table and Enrollments table.
I do not know where the problem lies but the expected outcome is:

Wbixik Yjepuriluwe
Wtoyi Avamijosu
Jheyiresoxo Bsexedoh
Ulerusota Mzuzu

But my outcome is:

Wbixik Yjepuriluwe
Jropop Vduyumi
Jheyiresoxo Bsexedoh
Ulerusota Mzuzu

Looking for any guidance to get me back on track.

A: You can try using left join
SELECT FIRSTNAME, LASTNAME
FROM STUDENTS
left JOIN ENROLLMENTS ON STUDENTS.NETID = ENROLLMENTS.NETID
JOIN COURSES ON COURSES.CRN = ENROLLMENTS.CRN
where ENROLLMENTS.NETID is null OR
ENROLLMENTS.SCORE IN
    (SELECT MIN(SCORE) FROM ENROLLMENTS
        WHERE COURSES.DEPARTMENT = STUDENTS.DEPARTMENT
        GROUP BY ENROLLMENTS.CRN
    )


text:
Q: Verify that $\alpha(a)\neq2$ for all $a$ where $\alpha(x): (2x + 1)/(x + 2)$
If $A=  \mathbb{R} \setminus \{-2\}$ and $B = \mathbb{R} \setminus \{2\}$, let $\alpha: A \to B$ by $\alpha(x): (2x + 1)/(x + 2)$. Verify that $\alpha(a)\neq2$ for all $a \in A$.

As a hint, I was told to use contradiction.
If I use contradiction though, I feel as if I didn't do anything. If I say $\alpha(a) = 2$, it's clear that it's a contradiction since $2 \notin B$. Is that it?

A: As Ilham said, I think the formatting is a bit off. I believe you meant to say that $\alpha(x) = \frac{2x + 1}{x+2} $. If so assume $\alpha(a) = 2$ is true, then:
$$ \frac{2a + 1}{a+2} = 2 $$
Which implies $ 2a+1 = 2a+ 4$ which is not true $\forall a \in \mathbb{R}$

A: By contradiction: Suppose $\alpha(a)=2$. Then
$$
2=\frac{2x+1}{x+2}\Longleftrightarrow 2x+4=2x+1\Longleftrightarrow 4=1,
$$
which is clearly absurd. Hence, $\forall a\in A, \alpha(a)\neq 2$. $\blacksquare$


text:
Q: Split string into list of non-whitespace and whitespace I want to split a string into parts so that
Hello,  what   is up?

becomes
["Hello,", "  ", "what", "   ", "is", " ", "up?"]

A: import re
x="Hello,  what   is up?"
print re.split("(\s+)",x)

You can use re.split for this.
Output:['Hello,', '  ', 'what', '   ', 'is', ' ', 'up?']
We can also use
re.findall(r"\S+|\s+",x)

This will not give empty string is there's a space at start or end.

A: Simply use string.split(" ").If you want to eliminate those white spaces also then string.split()


text: Q: glut game is not capturable by fraps or dxtory I wanted to make some recordings of my game which uses an OpenGL window created by freeglut. The window or its gl-context seems to be unfindable for a recording applications like fraps, taksi or dxtory. How can I fix this?


text:
Q: Estilos en options (Safari) No consigo que el navegador Safari me coja los estilos que le doy a unos options.
Mi código es este:
<select [(ngModel)]="options">
                <option *ngFor="let item of items" [value]="item.nombre" [style.background-color]="item.recomendado ? '#346ba3' : 'black'">{{item.nombre}}
                </option>
              </select>

En el resto de navegadores funciona sin problema, pero en Safari no. ¿Alguna solución?


text:
Q: Google Script copy paste Right now it overwrite same cell in Logs
I need it to write to next cell and not overwrite the same cell.
https://freeimage.host/I/5GIOjs I want to Search for D3=Lumee in the Sheet called Logs in colum A u see all the names. Want it co copy J12 to the specific Name
https://freeimage.host/i/5GTLJI
function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var j12 = s.getRange('J12').getValues();

  var dynamic_cell = s.getRange('D3').getValue();

  var target_s = ss.getSheetByName('Logs');

  for (var i = 2; i<=target_s.getMaxRows();i++){
    var match = target_s.getRange(i, 1).getValue();
    if(dynamic_cell == match){
      var targetrange = target_s.getRange(i,2,1);
      break;
    }
  }

  targetrange.setValues(j12);

}

A: This is how I'd do it.
 function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getActiveSheet();
  const j12 = sh.getRange('J12').getValue();
  const d3 = sh.getRange('D3').getValue();
  const tsh = ss.getSheetByName('Logs');
  const vs = tsh.getRange(2,1,tsh.getLastRow() -1).getValues();
  for( let i = 0;i<vs.length; i++) {
    if(d3 == vs[i][0]){
      tsh.getRange(i + 2,2).setValue(j12);
      break;
    }
  }
}

It's a lot faster than pulling the match value out during each loop. This way I get all of them all at one time and the loop run's much faster.
Demo:

Version 2:
function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('Sheet0');
  const j12 = sh.getRange('J12').getValue();
  const d3 = sh.getRange('D3').getValue();
  const tsh = ss.getSheetByName('Logs');
  const vs = tsh.getRange(2, 1, tsh.getLastRow() - 1).getValues();
  for (let i = 0; i < vs.length; i++) {
    if (d3 == vs[i][0]) {
      tsh.getRange(i + 2, getRowWidth(i + 2, tsh, ss) + 1).setValue(j12);
      break;
    }
  }
}

Helper function:
function getRowWidth(row, sh, ss) {
  var ss = ss || SpreadsheetApp.getActive();
  var sh = sh || ss.getActiveSheet();
  var row = row || sh.getActiveCell().getRow();
  var rcA = [];
  if(sh.getLastColumn()){rcA = sh.getRange(row, 1, 1, sh.getLastColumn()).getValues().flat().reverse();}
  let s = 0;
  for (let i = 0; i < rcA.length; i++) {
    if (rcA[i].toString().length == 0) {
      s++;
    } else {[![enter image description here][2]][2]
      break;
    }
  }
  return rcA.length - s;
}

Demo:


text:
Q: What gets called when the screen changes orientation? My app is restarting when I change orientations I have built an app that is a simple question and answer game. A Question is displayed and you can select true or false, and then a toast appears to tell you if you got the question correct. You can then press a button to move to the next question. The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen? I have three classes. The first is the MainActivity which launches the quiz layout. The next is a Question class. The last is the QuizActivity Class. Here is the code:
MainActivity:
package com.example.geoquiz;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Question Class:
package com.example.geoquiz;

public class Question {
    private int mTextResId;
    private boolean mAnswerTrue;
    public Question(int textResId, boolean answerTrue) {
        mTextResId = textResId;
        mAnswerTrue = answerTrue;
    }
    public int getTextResId() {
        return mTextResId;
    }
    public void setTextResId(int textResId) {
        mTextResId = textResId;
    }
    public boolean isAnswerTrue() {
        return mAnswerTrue;
    }
    public void setAnswerTrue(boolean answerTrue) {
        mAnswerTrue = answerTrue;
    }
}

QuizActivity Class:
package com.example.geoquiz;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends AppCompatActivity {
    private Button mTrueButton;
    private Button mFalseButton;
    private Button mNextButton;
    private TextView mQuestionTextView;
    private Question[] mQuestionBank = new Question[] {
            new Question(R.string.question_australia, true),
            new Question(R.string.question_oceans, true),
            new Question(R.string.question_mideast, false),
            new Question(R.string.question_africa, false),
            new Question(R.string.question_americas, true),
            new Question(R.string.question_asia, true),
    };
    private int mCurrentIndex = 0;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);
    mQuestionTextView = (TextView)    findViewById(R.id.question_text_view);
    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { checkAnswer(true); }
    });
    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { checkAnswer(false); }
    });
    mNextButton = (Button) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();
}
    private void updateQuestion() {
        int question = mQuestionBank[mCurrentIndex].getTextResId();
        mQuestionTextView.setText(question);
    }
    private void checkAnswer(boolean userPressedTrue) {
        boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
        int messageResId = 0;
        if (userPressedTrue == answerIsTrue) {
            messageResId = R.string.correct_toast;
        } else {
            messageResId = R.string.incorrect_toast;
        }
        Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
    }

} // to close the entire class

I believe the code to update the question begins in the QuizActivity class. I think the issue is that the counter for which question to be displayed is being set back to 0, but I do not know where to set a breakpoint to check this. Whenever I set a breakpoint none of the UI is updated and I can therefore not test this.
I also have the XML file if you want to test this for yourself:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="vertical">
<TextView
android:id="@+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button" />

    </LinearLayout>
    <Button
    android:id="@+id/next_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/next_button" />
</LinearLayout>

A:
The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen?

Your activity is destroyed and recreated as part of a configuration change. Consider using a ViewModel to hold your activity's state and be able to retain it across configuration changes.

A: You can use ViewModel or override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like as current question number and it will get passed in to onCreate() and also onRestoreInstanceState() where you would then extract the values.


text:
Q: Three.js screen to world position calculation based on browser window size I'm confused about converting screen position to world position in three.js.  I've looked at several answers to questions on Stackoverflow but can't make sense of the formulas and/or extract them from raycasting or mouse testing in the examples (neither of which I'm doing).  I simply want to position a plane in world position according to the width of the scene/window.  For example the bottom right corner of the window minus the width and height of the plane so it's on screen and visible.  Something like this:
//geometry and material of the plane
var geometry = new THREE.PlaneGeometry(50, 50);
var material = new THREE.MeshPhongMaterial( { color: 0xff0000 } );

//create plane
plane = new THREE.Mesh( geometry,  material);

position = new THREE.Vector3();
position.x = ( window.innerWidth / 2 ) - asquare.geometry.parameters.width;
position.y = - ( window.innerHeight / 2 ) - asquare.geometry.parameters.height;
position.z = 0;

plane.position.set( position.x, position.y, position.z );

It's in the right direction but too far, I guess it's the difference between the camera and planes z position that is the issue.  If my camera is at z 500 and the plane is at z 0 how do I adjust the x and y accordingly?


text:
Q: DbContext does not contain a definition for Configuration - EF Core I'm developing a application using EF Core. I want disable proxy creation, but when I try to use the command an error appears.
My Db Context class:
public class BMContext : DbContext
{
     public BMContext()
     {
          this.Configuration.ProxyCreationEnabled = false;
     }
}

And the error:

Severity  Code    Description Project File    Line    Suppression State
  Error   CS1061  'BMContext' does not contain a definition for 'Configuration' and no accessible extension method 'Configuration' accepting a first argument of type 'BeerMakersContext' could be found (are you missing a using directive or an assembly reference?)

Thanks :)

A: As suggested by Gabriel Luci:
You need to install Microsoft.EntityFrameworkCore.Proxies Package.

*

*In Visual studio go to Tools ➤ NuGet Package Manager ➤ Manage NuGet Packages for Solution...

*In opened window go to Browse tab and search for Microsoft.EntityFrameworkCore.Proxies package.

*Click it and on the right choose the project you want to install it in (I suppose it's for server) and press Install


text:
Q: AsyncTask error Android App crashes My oncreate code:
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.board);
    ArrayList<String> passing = new ArrayList<String>();
  new AsyncTaskParseJson().execute();

}

Here is my code:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";
    String yourJsonStringUrl = "my url here";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @SuppressWarnings("null")
    @Override
     public String doInBackground(String... arg0) {

        final String[] values = null;
         try {

             // instantiate our json parser
             JsonParser jParser = new JsonParser();

             // get json string from url
             JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

             // get the array of users
             dataJsonArr = json.getJSONArray("response");

             // loop through all users
             for (int i = 1; i < dataJsonArr.length(); i++) {

                 JSONObject c = dataJsonArr.getJSONObject(i);
                 String text = c.getString("text");
                values[i]=text;
             }
          //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
          //   list1.setAdapter(adapter);

         }
         catch (JSONException e) {
             e.printStackTrace();
         }

         return null;
     }

     @Override
     protected void onPostExecute(String strFromDoInBg) {}

 }

So, it's starts activity when I comment the section values[i] like this:
      //values[i]=text;

BUT when it's not commented, app just crashes. I want to doInBackground to return String[] array, how I do that?

A: you have re declare it again before the for loop
values = new String[dataJsonArr.length()];
for (int i = 1; i < dataJsonArr.length(); i++) {

             JSONObject c = dataJsonArr.getJSONObject(i);
             String text = c.getString("text");
            values[i]=text;
         }

you need to reserve its size in the memory by declaring new

A: You need to have
 values = new String[dataJsonArr.length()];

Also note the commented lines are in doInbackground. But you can't update ui from a background thread. So the below should go to onPostExecute.
 //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
 //   list1.setAdapter(adapter);

Instead of using a String array it is better to use a ArrayList<String>
You need to change the args type also
public class AsyncTaskParseJson extends AsyncTask<String, String, ArrayList<String>> {

Then
 @Override
 public  ArrayList<String> doInBackground(String... arg0) {

    ArrayList<String> values = new ArrayList<String>();
     try {

         // instantiate our json parser
         JsonParser jParser = new JsonParser();

         // get json string from url
         JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

         // get the array of users
         dataJsonArr = json.getJSONArray("response");

         // loop through all users
         for (int i = 1; i < dataJsonArr.length(); i++) {

             JSONObject c = dataJsonArr.getJSONObject(i);
             String text = c.getString("text");
             values.add(text);
         }
     }
     catch (JSONException e) {
         e.printStackTrace();
     }

     return values;
 }

Then
 @Override
 protected void onPostExecute(ArrayList<String> result) {
  super.onPostExecute(result);
   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, result);
   list1.setAdapter(adapter);
 }

Also make sure list1 is initialized before you setAdapter to it coz i do not see the code where list1 is initialized.

A: Just declare String[] array at class level like below,
private static String[] array = null;

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";
    String yourJsonStringUrl = "my url here";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @SuppressWarnings("null")
    @Override
     public String doInBackground(String... arg0) {

        //  final String[] values = null;
         try {

             // instantiate our json parser
             JsonParser jParser = new JsonParser();

             // get json string from url
             JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

             // get the array of users
             dataJsonArr = json.getJSONArray("response");

             // loop through all users
             for (int i = 1; i < dataJsonArr.length(); i++) {

                 JSONObject c = dataJsonArr.getJSONObject(i);
                 String text = c.getString("text");
                values[i]=text;
             }
          //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
          //   list1.setAdapter(adapter);

         }
         catch (JSONException e) {
             e.printStackTrace();
         }

         return null;
     }

     @Override
     protected void onPostExecute(String strFromDoInBg) {}
}

A: Here, you are creating an Array object with to major problem...

*

*creating Array object without defining it's size.

*defining as final which will not allow you to add new element to that object.

You declaring an Array which is null and you defining it as final. When you declare an Array as final then you can't change that Array. That's why you can't insert new value to that Array, as a result, when you are going to access that Array its returning null value. It's the cause to crash your app.
So, what you have to do is, define the values array with a fixed size and don't make it final. These will solve your all problem.
Now, replace the following line...
final String[] values = null;

with these...
String[] values;
values = new String[dataJsonArr.length()];


text:
Q: I'm using NavigationView on a embedded layout, I'm trying to transfert the layout to another layout bu it crash I'm trying to use the NavigationView on a embedded layout and trying to "move" the layout to another contentview, but it crash has soon I remove the View from the parent with:
Attempt to invoke virtual method 'void com.mapbox.services.android.navigation.ui.v5.MultiOnClickListener.clearListeners()' on a null object reference]

I have a simple class with:
public class clsNavigationView extends CoordinatorLayout implements OnNavigationReadyCallback, MapboxMap.OnMapLongClickListener,
        NavigationListener, ProgressChangeListener, InstructionListListener, SpeechAnnouncementListener,
        BannerInstructionsListener, OnTrackingModeChangedListener
...
        inflate(getContext(), R.layout.mapbox_activity_embedded_navigation, this);
...

The layout have
    <com.mapbox.services.android.navigation.ui.v5.NavigationView
    android:id="@+id/navigationView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:navigationDarkTheme="@style/NavigationViewDark"
    app:navigationLightTheme="@style/NavigationViewLight"/>

I put the clsNavigationView on a static FrameLayout, I add it to my mainView on another FrameLayout.
When I change view, I remove the view with:
((FrameLayout) objFrameMap.getParent()).removeView(objFrameMap);

Do my new setContentview on my main Activity.
Then I add back my Frame into my new FrameLayout on the new Content
((FrameLayout) findViewById(R.id.layer_mapview)).addView(objFrameMap);

It crash at the removeView, what can I do for fixing that?
What is the best way for "move" a NavigationView without crashing?
** I'm not using fragment.


text:
Q: Testing react component that is dependent on Stateful Context Providers chain in React Testing Library I'm aware of this, but it's not my case.
Example:
<AuthProvider>
  <SessionProvider>
    <AnotherProvider>
      <OneMoreProvider>
        <MyComponent />

All of these providers are actually regular React Components with state and effects, that fetch some data via GraphQL and pass that data as a 'value' prop to MyContext.Provider in return statement.
This enforces me to create lots of mocks for modules that are being used in all of these providers, just to render my own component in testing env.
Any thoughts about what can be done to avoid creating so many mocks?

A: You can create a helper test lib with a custom render function that wrap your component with the contexts then export all react testing library methods from there
- test/lib.jsx
import React from 'react';
import { render as reactRender } from '@testing-library/react';
export * from '@testing-library/react';

export const render = (MyComponent, options) => {
    return reactRender(
        <AuthProvider>
            <SessionProvider>
                <AnotherProvider>
                    <OneMoreProvider>
                        {MyComponent}
                    </OneMoreProvider>
                </AnotherProvider>
            </SessionProvider>
        </AuthProvider>,
        options
    )
}

Then use this helper lib to import test functions instead of using @testing-library/react directly

import { render } from 'test/lib'
import MyComponent from './MyComponent';

test("My component", () => {
    const { getByTestId, ... } = render(<MyComponent>);
    ...
});


text:
Q: How do you identify if a domain in Freebase is either a commons/base? I see that the relationship between topics in Freebase start as follows:
/user/foo/...
/music/album/...
/base/talships/...
Should I just check if the relationship starts with the word "base" or "user" in which case the domain is not a commons domain? Thus, if it starts with any word other than "base" or "user" then it is a commons domain.
Is my understanding correct?

A: Yes, in general you can tell that something is a user domain or a base just from looking at the ID. However the most reliable way to do it is in MQL like this:
{
  "id": "/music/album",
  "/type/type/domain": {
    "/freebase/domain_profile/category": [{
      "id": null
    }]
  }
}

Any domain that has the category /category/commons is a Freebase commons domain.


text:
Q: factorial recursion "visualized" in java So I have this basic factorial calculator in java but I am having trouble modifying it to fit the exercise. It says: Modify the factorial
method to print its local variable and recursive-call parameter. For each recursive call,display the outputs on a separate line and add a level of indentation. I think Im having trouble understanding where the print statements should go. So does local variable = number and recursion call parameter = number-1. Here is my code so far.
public class Factorial {
    private static String s1="";
    public static long factorial(long number,long save) {

    if (number <= 1) { //test for base case
        System.out.printf("%s%d! = %d*%d!=  ",s1,save,save,save-1);
        s1 = s1 +" ";
        return 1;
    }
    else{ //recursion step
        return number * factorial(number - 1,save);
    }
}

//output factorial for values 0-21
public static void main(String[] args) {
    //calculate factorials 0-21
            for (int counter = 0; counter <= 21; counter++){
                long x = factorial(counter,counter);
        System.out.printf("%d%n",x);
    }
}

}

A:
I think Im having trouble understanding where the print statements should go.

Yes, indeed. As you can see, the exercise states

Modify the factorial method to print its local variable and recursive-call parameter.

So, modify factorial instead of main. This way, each time factorial is invoked, you get a new line printed out, just as the exercise asks.


text:
Q: How to set default values for RadioGroupFieldEditor I have a RadioGroupFieldEditor field in my class. I want to set the defualt values. Is it possible.

A: As far as I understand, you can load the default value from the preference store with doLoadDefault(). You can set the preference store with setPreferenceStore() - see Javadoc


text:
Q: What is the effect of merging categories on logistic regression estimates? I have a logistic regression with a number of predictors variables including a factor with, say, 5 categories. The estimates for that factor compare categories 2-5 in turn to the reference category zero.
If I merge 2 of the non-reference categories (say merge 2 and 3) then the estimates for the other change slightly. I think this is because estimates will be correlated in a non-orthognal design but I'd like confirmation or a more thorough explanation please.
Edit
to be honest my colleague has such a problem with conditional logistic regression but the same issue occurs with ordinary logistic regression and I suspect in regressoin generally.
for myself I'd like to know for general knowledge what the issue is (as well as to reassure my colleague
I hope it is OK to post code (I hope it doesn't get too scrambled - I indented the code) but this illustrates the occurence with the generally available (e.g. in R package MASS from the Venables and Ripley book) dataset birthwt where binary outcome "low birthweight" is modelled by logistic regression - I have a factor ftv (which I make groups 0-4 by merging then I create s copy fvt2 where groups 1 and 2 are merged to be "2".
The estimates in both analyses compare group zero to the other groups and you can see below the comparison of group 4 to 0 changes (slightly - I've put them in bold). Why? the data for those 2 groups in unaltered but I can see there is an issue of correlated estimates here.
Many thanks for any advice.
library(MASS)
data(birthwt)
birthwt$ftv<-ifelse(birthwt$ftv>3,4,birthwt$ftv)
# change 4 or more to 4
birthwt$ftv2<-birthwt$ftv
# create duplicate
birthwt$ftv2<-ifelse(birthwt$ftv==1,2,birthwt$ftv)
# then merge categories in duplicate
table(birthwt$ftv,birthwt$ftv2)
# 1 and 2 for ftv become 2 in ftv2

    0   2   3   4
0 100   0   0   0
1   0  47   0   0
2   0  30   0   0
3   0   0   7   0
4   0   0   0   5

low_log<-glm(low ~  ht + ui + lwt +as.factor(ftv), data= birthwt,family = binomial)
coef(summary(low_log))

               Estimate  Std. Error    z value    Pr(>|z|)
(Intercept)      1.15892582 0.852443200  1.3595344 0.173977321
ht               1.87181914 0.710991788  2.6326874 0.008471227
ui               0.90472684 0.442643299  2.0439185 0.040961597
lwt             -0.01627838 0.006638716 -2.4520372 0.014204999
as.factor(ftv)1 -0.55718506 0.419152552 -1.3293133 0.183744632
as.factor(ftv)2 -0.39179846 0.501082892 -0.7819035 0.434271296
as.factor(ftv)3  0.76139653 0.837278585  0.9093706 0.363154537
as.factor(ftv)4 **-0.17724595** 1.183684076 -0.1497409 0.880969020

low_log<-glm(low ~  ht + ui + lwt +as.factor(ftv2), data= birthwt,family = binomial)
coef(summary(low_log))

                Estimate  Std. Error    z value    Pr(>|z|)
(Intercept)       1.14052105 0.850496353  1.3410064 0.179918375
ht                1.84783639 0.704472332  2.6230078 0.008715729
ui                0.91241494 0.441875434  2.0648691 0.038935385
lwt              -0.01612754 0.006620628 -2.4359530 0.014852614
as.factor(ftv2)2 -0.49476082 0.354944684 -1.3939097 0.163344887
as.factor(ftv2)3  0.76274256 0.836785227  0.9115153 0.362023910
as.factor(ftv2)4 **-0.17931225** 1.183211033 -0.1515471 0.879544125

Actually if you remove the other variables - ht, ui and lwt, then the estimates/contrasts for groups 4 and 3 vs 0 are unaffected!
The estimates are always the difference in log odds between the 2 groups
I am uneasy this is well understood (at least by others).


text:
Q: SQL: Finding/Deleting entries for each member based on timestamp difference I have a MySQL table of actions with the following key fields (all of them are integers):
Actions
id | member_id | timestamp (seconds)

This table keeps all the actions that every member does.
My problem:  there are entries that were inserted by error. I need to find (eventually delete) all actions per member where the timestamp difference is less than 1 day (86400 seconds)
So for example, taking the following 4 actions for one member:
id | member_id | timestamp  | (difference)
---|-----------|------------|----------
1  |     1     | 1499500834 |
2  |     1     | 1499580834 | 80000 (22 hours)
3  |     1     | 1499640834 | 60000 (16 hours)
4  |     1     | 1499700834 | 60000 (16 hours)

I would need to determine that:

*

*the 1st is valid (because it's the 1st action registered)

*the 2nd is invalid (< 24 hours compared to last valid: 1st)

*the 3rd is valid (> 24 hours compared to last valid: 1st)

*the 4th is invalid (< 24 hours compared to last valid: 3rd)

And thus delete the 2nd and 4th.
How would I go about this in SQL ?


text:
Q: VLC setting volume from command line/bash With the risk of feeling really really stupid here, but I seem not to be able to set the volume of VLC from command line??
vlc file.mp3 --vol 0

I have read the man pages as well as googled but I can not get the above to work. Also tried --volume 0, -vol 0, -volume 0 (as well as putting the volume option before the file name).
No matter, VLC starts with its preset volume. Using VLC 1.1.5 on Ubuntu. (I intend to use the line in a bash script therefore I can not use the VLC GUI)
/J

Update
I have tried different values. I now run vlc with very verbose. This section looks a bit suspicious (but I have no idea how to interpret it!):

[0xb7108d14] main audio output warning: PTS is out of range (-9483), dropping buffer
[0xb7108d14] main audio output warning: PTS is out of range (-35533), dropping buffer
[0x94384ac] mpgatofixed32 audio filter debug: libmad error: bad main_data_begin pointer
[0xb7108d14] pulse audio output debug: Pulse stream started
[0xb7108d14] main audio output warning: output date isn't PTS date, requesting resampling (86708)
Warning: call to rand()
[0xb7108d14] main audio output warning: buffer is 86706 late, triggering upsampling
[0xb7104654] qt4 interface debug: IM: Setting an input
[0xb7108d14] main audio output warning: output date isn't PTS date, requesting resampling (44448)
[0xb7108d14] main audio output warning: audio drift is too big (130928), dropping buffer
[0x94384ac] mpgatofixed32 audio filter debug: libmad error: bad main_data_begin pointer
[0xb7108d14] main audio output debug: audio output is starving (20040), playing silence
[0xb7108d14] main audio output warning: resampling stopped after 16895748 usec (drift: 19049)

A: Seems to be a known bug.  Volume option doesn't have any effect

A: For anyone that comes by this later, I had to disable the "Save audio" option under the audio settings for this to work.  I also had to use one of the other audio settings.  Mine was:
--mmdevice-volume=<float [0.000000 .. 1.250000]>

Other options are
--directx-volume=<float [0.000000 .. 2.000000]>
--waveout-volume=<float [0.000000 .. 2.000000]>

A: From the documentation:

*

*--volume <integer> sets the level of audio output (between 0 and 1024). Also only applies to local playback (like --noaudio).

Have you tried using any other values besides 0? What about other files (from a source different from the ones you've tried)?
Try using the very verbose (-vv) option to see if it tells you anything.

A: Further to Jason Wisely's answer, I used the following on VLC version 3.0.6 and it worked to play a song with VLC at 35% volume. The device really matters because neither directx of waveout worked for me.
start "" "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" --mmdevice-volume=0.35 "F:\Beastmode.mp3"

However, it's somewhat moot because your system volume will determine the apparent volume anyway. So to control the system volume I downloaded nircmd and put it into system32. nircmd uses 65535 as 100% volume, so a 50% volume is 65535 ÷ 2 = 32767.5, and I round to 32767. After that, the following is how I keep a consistent volume of 14% system volume and 80% VLC volume when starting VLC:
nircmd.exe setsysvolume 9200
start "" "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" --mmdevice-volume=0.35 "F:\Beastmode.mp3"


text:
Q: More Windows 10 Bluetooth Audio Problems I've been trying to get my Dell XPS 13 (Windows 10 Pro, version 10.0.18363, build 18363) to communicate with a JBL Flip 4, or some very expensive Bose Quiet Comfort 35 II's for about nine months off and and on, but although the problem seems very common I still can't make them work, and most of the answers I can find elsewhere are pretty much "update the drivers" and that's it.
Today I found this site, and then the following question, and thought I'd discovered the Holy Grail of answers :-
Windows 10 computer paired w/ bluetooth speaker, but doesn't send music to speaker
Ask Question Asked 4 years, 2 months ago Active 11 months ago Viewed 242k times
Response 6 was very promising, thank you whoever wrote it, everything worked all the way down to where it said:
This time you should see two entries: "Bluetooth AV" and "Bluetooth Stereo", choose "Bluetooth Stereo", click Next and click Yes if asked anything -
But I only get Bluetooth AV, NO Bluetooth Stereo !
I also tried going back to the beginning and trying the "Headset Audio Gateway Service" option, but that also failed.
I'm presuming something in Windows has been changed since this response was given. Just to be incredibly annoying both the JBL speaker and Bose headphones work with my iPhone and a recently purchased Samsung Tablet, so I've presumed it must be a windows issue.
Can anybody help and tell me the best course of action please?

A: In my experience Bluetooth simply isn't handled very well by Windows unless you are on a desktop computer and your system doesn't have to deal with lid/dock events changing aspects of multiple audio devices.  Most of these experiences were on older Dell hardware.
Some things you can try:

*

*Bypass the Bluetooth hardware in the laptop: try getting a Bluetooth USB adapter and see if you have better luck with that.

*Bring up the Run dialog, type mmsys.cpl and press Enter, and disable every audio device but your Bluetooth devices.

*If you only care about hearing the audio and not using any mic as a headset: Bypass the Windows Bluetooth stack entirely and look for a device that accepts headphone jack inputs and converts to Bluetooth (search for "aux to Bluetooth adapter" for examples).


text:
Q: Organizing csv export with scrapy For exporting my data to a CSV file, I'm currently using (mainly because I never understood pipelines that well):
custom_settings = {

    'FEED_FORMAT': 'csv',
    'FEED_URI' : 'datosAmazon.csv'

}

This custom settings are inside my spider.
Right now, I'm scraping different categories of items, for example, laptops and cell phones.
Problem is that, when I go check out my data, things are not organized, maybe a laptop appears, then a cell phone, then 2 laptops, cellphone and so on.
I'm currently going into different categories this way
def start_requests(self):

    keywords = ['laptop', 'cellphone']

    for keyword in keywords:

        yield Request(self.search_url.format(keyword))

Is it there a way for the data to be more organized (2 files would be even better), or an easy pipeline solution.

A: There is no settings-only way to achieve what you want.
That said, exporting to multiple files from a custom pipeline is pretty straight-forward:

*

*Create multiple exporters (scrapy.exporters.CSVItemExporter) in the open_spider method (probably store them in a dict)

*Select the correct exporter (based on the item) in the process_item method and call its export_item

*Close the files in the close_spider method

Don't forget to activate your pipeline :)


text:
Q: find the range of $f(x)=\sqrt{x^2−9}$ $$f(x)=\sqrt{x^2−9}$$
I know that the domain of square root is greater than or equal to zero. I solve for when $x^2−9\ge 0$ and get $x^2\ge9$. Now I get $x\ge 3$ and x≤−3. So that the domain would be (−∞,−3]∪[3,∞).
But how can i find its range? Would anybody please show me the process of find the range of $f(x)=\sqrt{x^2−9}$.

A: In $\mathcal D =(- \infty, -3] \cup [3, +\infty)$, the range of $x \rightarrow x^2-9$ is $[0, +\infty)$.

This is because :

*

*$\forall x \in \mathcal D, x^2-9 \ge 0 $

*$\exists x \in \mathcal D, x^2-9 = 0 $. Indeed, $3$ and $-3$ work

*$x \rightarrow x^2-9$ is continuous on $[3, +\infty)$, as well as on $(- \infty, -3]$, and $\lim_{x \rightarrow \infty}x^2-9 = +\infty$

Furthermore, $\sqrt{[0, +\infty)} = [0, +\infty)$
Then the range is $[0, +\infty)$

A: Let's investigate what happens on the interval $[3,+\infty)$. We note that the function $f(x)=\sqrt{x^2-9}$ is symmetric around $x=0$, so we can justify not needing to look at the cases when $x\in(-\infty,-3]$ to find the range.
For $x\in[3,+\infty)$, we have the following:

*

*$f(x)$ is a (strictly increasing) continuous function on this interval

*$f(3)=0$

*$f(x)\rightarrow +\infty$ as $x\rightarrow +\infty$

Thus we can conclude that the range for $f(x)$ will be all nonnegative real numbers, namely the interval $[0,+\infty)$


text:
Q: Строковый буфер Си Какой есть на Си строковый буфер вроде stringstream на C++, и как им пользоваться?

A: В стандарте POSIX 2008 есть весьма удобная функция: open_memstream(). Вы можете сделать так:
// здесь в итоге появятся записанные значения и размер текста:
char* buffer = NULL;
size_t bufferSize = 0;

// создаём поток с указателями для выходных значений:
FILE* myStream = open_memstream(&buffer, &bufferSize);

// можно записывать в поток как в обычный вывод:
fprintf(myStream, "You can output anything to myStream, just as you can with stdout.\n");

// можно добавить что-либо ещё с неизвестным размером в других функциях:
myComplexPrintFunction(myStream);

// закрытие потока перенесёт данные и размер в buffer и bufferSize:
fclose(myStream);

// теперь можно делать что угодно с полученной строкой:
printf("I can do anything with the resulting string now. It is: \"%s\"\n", buffer);

// ну и не забывайте чистить память:
free(buffer);

Перевод ответа: String Stream in C.


text:
Q: Turning .py file into an executable? I have an extremely basic text based game that I have been coding and want to turn into an executable for both Windows and Mac. I am an extreme beginner and am not quite sure how this works.
Thus far, in the coding process, I've been running the game in terminal (I have a Mac), in order to test it and debug.
I've installed PyInstaller to my computer, tried to follow the directions to make it work, yet when I finally get the Game.app (again, for a Mac because I was testing the process), it does not open.
The game is all contained between two files, ChanceGame.py (the one with the actual game), and ChanceGameSetup.py (one that contains a command to setup the game.) ChanceGame.py imports ChanceGameSetup.py at the start so that it can use the functions in ChanceGameSetup.py where needed. My point in this is that I don't actually have to be able to run ChanceGameSetup.py, it only needs to be able to be imported by ChanceGame.py.
Is there a way to turn ChanceGame.py into an executable? Or is it just too simple of a file? I'm an extreme beginner, therefore I have no experience on the subject.
Thanks in advance for any help!
P.S. I just want to be able to email the game to some friends to try out, and I assume this is the only way of doing so without them having their own compiler, etc. If there is actually an easier way, I would appreciate hearing that as well. Thanks!

A: py2exe is what you need for windows.


text:
Q: How change color of a selected item? I have a collection view, where each of item is selected with the same brown color, this is my item

this is my code:
<CollectionView SelectionMode="Single"  ItemsSource="{Binding CeLLs}">
<CollectionView.ItemTemplate>
    <DataTemplate>
      <StackLayout>
          <Label TextColor="Black"  background="Black"/>

i want to change the color brown

A: In the document, there is a section shows you how to change color of a selected item.
CollectionView has a Selected VisualState that can be used to initiate a visual change to the selected item in the CollectionView:
In your case, change the backgroundColor of stacklayout would work:
<ContentPage.Resources>
    <Style TargetType="StackLayout">
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Selected">
                        <VisualState.Setters>
                            <Setter Property="BackgroundColor"
                                    Value="LightSkyBlue" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>
</ContentPage.Resources>

<CollectionView SelectionMode="Single">
    <CollectionView.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Baboon</x:String>
            <x:String>Capuchin Monkey</x:String>
            <x:String>Blue Monkey</x:String>
            <x:String>Squirrel Monkey</x:String>
            <x:String>Golden Lion Tamarin</x:String>
            <x:String>Howler Monkey</x:String>
            <x:String>Japanese Macaque</x:String>
        </x:Array>
    </CollectionView.ItemsSource>

    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Label Text="{Binding .}" TextColor="Black"/>
            </StackLayout>
        </DataTemplate>

    </CollectionView.ItemTemplate>

</CollectionView>

Another way is binding the BackgroundColor with the property in your ViewModel and change it when the item is selected:
 <Label Text="{Binding .}" TextColor="Black" BackgroundColor="{Binding backColor}"/>


text:
Q: AutoComplete with JSON data using jQuery I'm trying add an autocomplete input textbox which will retrieve the data using Pipedrive API.
The JSON response I get from Pipedrive is as follows:-
{
  "success": true,
  "data": [{
    "id": 1671,
    "title": "Queens Park Tyres deal"
  }, {
    "id": 1672,
    "title": "Wildman Craft Lager deal"
  }, {
    "id": 1673,
    "title": "General Store deal"
  }, {
    "id": 1674,
    "title": "Deluxe Off Licence deal"
  }, {
    "id": 1675,
    "title": "Ahmed Halal Bazaar deal"
  }],
  "additional_data": {
    "pagination": {
      "start": 0,
      "limit": 5,
      "more_items_in_collection": true,
      "next_start": 5
    }
  }
}

I basically need to return the title and id of the value they select.
At the moment my jQuery code is as follows:-
$('#search-deal').autocomplete({
    source: function (request, response) {
        $.getJSON("https://api.pipedrive.com/v1/searchResults/field?term=deal&field_type=dealField&field_key=title&start=0&api_token=<my_token>", function (data) {
            response($.map(data.title, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

A: You could use Array.map to map the data to label, value & desc properties.
var datamap = data.data.map(function(i) {
  return {
    label: i.id + ' - ' + i.title,
    value: i.id + ' - ' + i.title,
    desc: i.title
  }
});

The property you set against value during data.map is used to set the input's value.
Then using the Array.filter you could filter those values as per the input:
var key = request.term;

datamap = datamap.filter(function(i) {
  return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});

$('#search-deal').autocomplete({
  source: function(request, response) {
    var data = {
      "success": true,
      "data": [{
        "id": 1671,
        "title": "Queens Park Tyres deal"
      }, {
        "id": 1672,
        "title": "Wildman Craft Lager deal"
      }, {
        "id": 1673,
        "title": "General Store deal"
      }, {
        "id": 1674,
        "title": "Deluxe Off Licence deal"
      }, {
        "id": 1675,
        "title": "Ahmed Halal Bazaar deal"
      }],
      "additional_data": {
        "pagination": {
          "start": 0,
          "limit": 5,
          "more_items_in_collection": true,
          "next_start": 5
        }
      }
    };

    var datamap = data.data.map(function(i) {
      return {
        label: i.id + ' - ' + i.title,
        value: i.id + ' - ' + i.title,
        desc: i.title
      }
    });

    var key = request.term;

    datamap = datamap.filter(function(i) {
      return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
    });

    response(datamap);
  },
  minLength: 1,
  delay: 100
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>

<input type="text" id="search-deal" />


text:
Q: Angular Component: How Ensure Callback Defined? I'm using Angular Components which were introduced with v1.5.
GOAL: If & bindings callbacks aren't specified by a parent view html template, I'd like to display a warning in the browser console, alerting the developer that the expected and necessary properties haven't been specified in the component they are using.
QUESTION: How do I ensure that & bindings (which function as callbacks to component events) are defined, so that I can aid future developers toward quick debugging?

A: I know this is old but if you specify the binding as '&?' then you can use typeof to check it is a function.

A: Simply check in the component controller if the type of the property is a function.
angular
    .module('moduleName')
    .component('compName', {
        controller: function() {
            if (typeof this.myFunc !== 'function') {
                console.warn('myFunc not defined!');
            }
        },
        bindings: {
            myFunc: '&'
        }
    });


text:
Q: include sp.core.js in spfx webpart How do I include sp.core.js in my webpart? I tried this in the config
 "externals": {
    "@microsoft/sp-client-base": "node_modules/@microsoft/sp-client-base/dist/sp-client-base.js",
    "@microsoft/sp-client-preview": "node_modules/@microsoft/sp-client-preview/dist/sp-client-preview.js",
    "@microsoft/sp-lodash-subset": "node_modules/@microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",
    "office-ui-fabric-react": "node_modules/office-ui-fabric-react/dist/office-ui-fabric-react.js",
    "react": "node_modules/react/dist/react.min.js",
    "react-dom": "node_modules/react-dom/dist/react-dom.min.js",
    "react-dom/server": "node_modules/react-dom/dist/react-dom-server.min.js",
    "spcore":"https://static.sharepointonline.com/bld/_layouts/15/16.0.5708.1207/sp.core.js"

},
and in my webpart I put

import {sp}  from "spcore";

but it says spcore could not be found. I am trying to get access to the sp.permissionkind enum.
thanks


text:
Q: Trying to concatenate a string with what I think is an unicode suffix I have this app of mine that reads datamatrix barcodes from drugs using the camera.
When it does for a particular drug, I receive this string from the detector, as seen on Xcode console:
0100000000D272671721123110700XXXX\U0000001d91D1

my problem is that \U0000001d91D1 part.
This code can be decomposed on the following:
01 00000000D27267 17 211231 10 700XXXX \U0000001d 91D1"

01 = drug code
17 = expiring date DMY
10 = batch number
The last part is the dosage rate

Now on another part of the application I am on the simulator, with no camera, so I need to pass this string to the module that decomposes the code.
I have tried to store the code as a string using
let code = "0100000000D272671721123110700XXXX\U0000001d91D1"

it complains about the inverted bar, so I change it to double bar
let code = "0100000000D272671721123110700XXXX\\U0000001d91D1"

the detector analyzes this string and concludes that the batch number is 700XXXX\U0000001d91D1, instead of just 700XXXX, so the information contained from the \ forward is lost.
I think this is unicode or something.
How do I create this string correctly.

A: You can use string transform to decode your hex unicode characters:
let str1 = #"0100000000D272671721123110700XXXX\U00000DF491D1"#
let str2 = #"0100000000D272671721123110700XXXX\U0000001d91D1"#
let decoded1 = str1.applyingTransform(.init("Hex-Any"), reverse: false)!  // "0100000000D272671721123110700XXXX෴91D1"
let decoded2 = str2.applyingTransform(.init("Hex-Any"), reverse: false)!  // "0100000000D272671721123110700XXXX91D1"

You can also get rid of the verbosity extending StringTransform and StringProtocol:
extension StringTransform {
    static let hexToAny: Self = .init("Hex-Any")
    static let anyToHex: Self = .init("Any-Hex")
}

extension StringProtocol {
    var decodingHex: String {
        applyingTransform(.hexToAny, reverse: false)!
    }
    var encodingHex: String {
        applyingTransform(.anyToHex, reverse: false)!
    }
}

Usage:
let str1 = #"0100000000D272671721123110700XXXX\U00000DF491D1"#
let str2 = #"0100000000D272671721123110700XXXX\U0000001d91D1"#
let decoded1 = str1.decodingHex  // "0100000000D272671721123110700XXXX෴91D1"
let decoded2 = str2.decodingHex // "0100000000D272671721123110700XXXX91D1"

A: The \U0000001d substring probably represents code point U+001D INFORMATION SEPARATOR THREE, which is also the ASCII code point GS (group separator).
In a Swift string literal, we can write that code point using a Unicode escape sequence: \u{1d}. Try writing your string literal like this:
let code = "0100000000D272671721123110700XXXX\u{1d}91D1"


text:
Q: How do I use a variable outside the for loop in batch file? I have a list "A.txt" that has a list of remote servers.
I need to do a net time in all of them and then echo the result with the remote server name.
Example : "server 10/10/2018 19:00"
This is my code :
FOR /f %%G IN (D:\A.txt) DO (
    net time \\%%G
)>> B.txt

FOR  /f "tokens=5,7,8" %%H IN (D:\B.txt) DO (echo %%H %%I %%J >> nettime.csv)

The result of this is :

"\\Server1 10/10/2018 10:40:09

 com

 \\Server2 10/10/2018 10:40:09

 com

It reads the token of the "command successful" line(I have Portuguese language on OS)
Is there a way to put the %%G in the echo? or can I hide the "command successful"?
Thanks

A: Just pipe the output of the NET command to the FIND command to search for the string Current or whatever it is in your language.  You can capture all of this with a FOR /F command.
@ECHO off
FOR /f "delims=" %%G IN (D:\A.txt) DO (
    FOR  /f "tokens=5,7,8" %%H IN ('net time \\%%G ^| find "Current"') DO echo %%H %%I %%J
)>> nettime.csv


text:
Q: Storyboard doesn't contain a view controller with identifier I keep getting the following error:
Storyboard (<UIStoryboard: 0x7ebdd20>) doesn't contain a view controller with identifier 'drivingDetails'

This is the code:
- (void)tableView:(UITableView *)tableView
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   UIViewController *controller =  [self.storyboard instantiateViewControllerWithIdentifier:@"drivingDetails"];
   controller.title = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"name"];
   [self.navigationController pushViewController:controller animated:YES];
}

I have already set the identifier on the UIStoryboard but I'm still getting this error.

A: Just had this issue after adding a new VC to the storyboard but only on the device, not on the simulator.  Turns out it was due to having multiple storyboard localizations - the VC was only added to the primary one.  I tried removing the other localizations (one of which is the one my iPhone uses) but still had the error.  In the end I had to recreate the other localizations with the new VC in each of them.

A: Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''

Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as
Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

Here storyboardWithName is the name of the storyboard file we are working with and bundle specifies the bundle in which our storyboard is (i.e. mainBundle).

A: let storyboard = UIStoryboard(name: "StoryboardFileName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "StoryboardID")
self.present(controller, animated: true, completion: nil)

Note:

*

*"StoryboardFileName" is the filename of the Storyboard and not the ID of the storyboard!

*"StoryboardID" is the ID you have manually set in the identity inspector for that storyboard (see screenshot below).

Sometimes people believe that the first one is the Storyboard ID and the second one the View Controller class name, so note the difference.

A: For those with the same issue as @Ravi Bhanushali, here is a Swift 4 solution:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

A: Fixed! Not only the identifier in the segue must be set, in my case DrivingDetails, but also the identifier in my tableViewController must be set as DrivingDetails...check my picture:

I also removed the navigation view controller so now the 2 table view controllers are connected directly with a "push" animation.
*****EDIT for XCODE 7.0*****
you have to set the storyboardId(in this case the viewController is embedded in a Navigation controller:
let lastMinVc  = mainStoryBoard.instantiateViewControllerWithIdentifier("lastMinuteNavController") as! UINavigationController

A: I found it ...
click on the view controller in storyboard,
click the third icon from left on the vc attributes inspectors - the one where you set the call name
on that scereen it says 'identity' - mine was hidden , i had to click on the word identity
it then shows storyboardID - add the identifier from the code, done

A: Modifying "Storyboard ID" in the identity inspector (the 3rd icon to the left) should work.
If not and you're sure there's no typo, try cleaning up the project ("Product"->"Clean", or simply command + shift + K).

A: Just for future reference:
I'm developing on iOS 6 using Storyboards.
I was having the same issue, but I could not find the "Identifier" field in the inspector.
Instead, just set the field named "Storyboard ID" to what you would name the Identifier. This field can be found under the "Show the Identity inspector" tab in the inspector.
[Note - comments below indicate that some people have found that they need to (also?) set the field "Restoration ID" just below the Storyboard ID in the inspector. Clicking on "Use Storyboard ID" does not seem to be enough.]
There's an image below for reference: (in this instance I've named my identifier the same as my class)

A: In Xcode 7 - 13,
when you change storyboard IDs and you get errors like this,
just CLEAN your project (CMD+SHIFT+K)

A: Identity located in Identity Inspector tab named Storyboard ID for Xcode 6.3.2 and checked Use Storyboard ID option.

A: While entering the identifier u have not selected proper view controller, just check once if done repeat the procedure once more.

A: A few of my view controllers were missing the storyboardIdentifier attribute.
Before:
<viewController
    id="pka-il-u5E"
    customClass="YourViewControllerName"
    customModule="ModuleName"
    customModuleProvider="target"
    sceneMemberID="viewController">

After:
<viewController
    storyboardIdentifier="YourViewControllerName"   <----
    id="pka-il-u5E"
    customClass="YourViewControllerName"
    customModule="ModuleName"
    customModuleProvider="target"
    sceneMemberID="viewController">

A: I was facing the same issue. I had given the identifier but the compiler was giving the issue, so I made the new controller and gave that controller a new ID and added it and it's working perfectly! I have added pods as well but don't know why the error was coming but now its gone! Plus also try to clean your project by pressing CMD+SHIFT+K keys. Lemme know if it worked.

A: I got same error and I could fix this by changing the following changes in my project. I have mentioned my class name in the inspector panel then the problem is solved.
Goto->right panel there Identity Inspector
In the custom class section
class:your class name(ViewController)
In the Identity section
storyboard ID:your storyboard ID(viewController Name)
After this click on Use storyboard ID option over there.That's it the problem is finished. I hope it will help you....

A: Use your identifier(@"drivingDetails") as Storyboard ID.

A: I tried all of the above solutions and none worked.
What I did was:

*

*Project clean

*Delete derived data

*Restart Xcode

*Re-enter the StoryboardID shown in previous answers (inside IB).

And then it worked. The shocking thing was that I had entered the Storyboar ID in interface builder and it got removed/deleted after opening Xcode again.
Hope this helps someone.

A: it is very simple select the respective view controller in the main story board and check the storyboardID if its present use it in the identidier of give a name and use it.
here my firstone is the storyboardID
let vc = self.storyboard?.instantiateViewController(withIdentifier: "firstone") as! tabBarViewController

A: Cleaning all things and closing Xcode doesn't solved the issue for me.
I had to delete the viewController and create a new one with new identifier.

A: Note: If you use cocoapods in your project, then first run pod deintegrate and rm Podfile.lock
Then open your project folder in any third party code editor like VSCode and do a global search for the ViewController name throwing the error.

*

*Rename/fix any wrong names which you find.

*Save all changes.

*Clean and build your project.

Everything should work fine now.
This is most often caused when you rename files from within Xcode.

A: check your language, may be the (base) have your controller, but may be specific storyboard does not have it

A: XCODE DRAG N DROP PANE IS GONE!!!


text:
Q: MobileFirst 7.1 build all environment is not creating android folder i have created the sample app 0n mobilefirst 7.1 with mac 10.12.5 java 1.8 eclipse mars, once i have created project added the android and ios environment after done build all environment ,ideally it should create separate android folder for that but its not creating any separate android folder , please any solution really appreciated

A: The most likely cause of the issue is missing "Android Developer Tools" Plugin in your Eclipse. This is required to create the Android native project, when you add Android environment.
Verify its installation.


text:
Q: Is it my application causing freezing and restarting the phone? Recently some users of my application complaining that their phone freezes and restarts while using my app. My question is how can an App freeze Android OS? Is there a chance for that? If yes, what are the possible causes behind it? How can I isolate the issue?
(one of the user uses device SM-G900V, Android OS 5.0)

A: In debug mode i ran the my app and continuously used it, and found that thead count was not coming down and it was gradually increasing ,I noted the thread names. Then i used DDMS in that i used update Thread option and checked from where the thread was getting created. Actually in my case media related thread was not getting released(Its was system thread). Then i made sure that it gets released all time . Boom problem solved :)


text:
Q: Can we use variable as a function? I'm learning Destructuring Assignment in JS and encountered this code which I don't understand.
Isn't half a variable, why could we use it as a function and pass an argument in console.log?
What would it look like if we write the same code in a basic way?
Thank you!
const stats = {
 max: 56.78,
 min: -0.75
};

const half = ({max,min}) => (max+min)/2.0;

console.log(half(stats));

const stats = {
  max: 56.78,
  min: -0.75
};

const half = ({max,min}) => (max+min)/2.0;

console.log(half(stats));

A: JavaScript allows you to use function definition and function assignment.
function myFunction() {}

On top of this, you can also assign your function to another variable (like an alias)
const myAlias = myFunction

You can also define this all in one line
const myAlias = function myFunction() {}

Since you would like to re-assign / rename your function, you can define an anonymous function (omit the function name) and assign it to a variable
const myAlias = () => {}

A: First of all, in JavaScript functions are Objects that implement the [[runnable]] interface. As with any other object, this can be assigned to a variable, passed around as an argument to other functions etc. The latter is commonly referred to as JavaScript functions being first-class citizens:

In programming language design, a first-class citizen [...] in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable.

JavaScript has the concept of named functions, but this feature is not available for ES6 "arrow" functions (as the one you're showing).
Hence the only way to give such an anonymous arrow function a name  (and thus, make it available for calling later) is to assign (always) anonymous arrow functions to a variable, which then acts as a pointer to that anonymous function.
That is exactly what is happening in your line
const half          = ({max,min}) => (max+min)/2.0;
//    ^^^ variable    ^^^ anonymous arrow function

Also note that only arrow functions allow to omit the return keyword and the {} block markers around it, if all that follows is a single expression.
With "old" ES5 functions, you could outright declare a named function:

const stats = {
  max: 56.78,
  min: -0.75
};

console.log(half(stats));

// ES 5 function declarations are "hoisted"
// meaning you can call them in your code before
// declaring the function
function half({max,min}) {
  return (max+min)/2;
}

Please also note that compared to your code, there are minor additional technical differences. Named ES5 function declarations are hoisted, which means the JS interpreter pulls them right to the top of your code, making the function available for calling even before declaring it.

A: Yes, you can store functions as variables in JS.
// Arrow style
const myFunction = () => { console.log('hi!') };

// 'Function' keyword style
const anotherFunction = function() { console.log('hi!') };

Take in consideration this is going to work differently than a common function based on the code placement due to hositing. var functionName = function() {} vs function functionName() {}

A: Yes. JavaScript has first-class functions. Cool, huh?

This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures

A: There is not a massive difference between the const and function version.  So the question is why is const version becoming popular,.
I think it's mainly down to scope, a pure function declaration scope is similar to how var works, were it gets hoisted to the function scope, were const / let are block scoped.  Also the arrow function () => {} assigned to a const seems to create slightly less code too.
Below is a simple example were initially they look like they might do the same thing, but you will notice the function version returns OUTER/inner/inner, but the const version does OUTER/inner/OUTER, so seems more logical..

function test1() {
  function log() {
    console.log('OUTER');
  }
  log();
  {
    function log() {
      console.log('inner');
    }
    log();
  }
  log();
}

function test2() {
  const log = () => console.log('OUTER');
  log();
  {
    const log = () => console.log('inner');
    log();
  }
  log();
}

console.log('simple function');
test1();

console.log('const function');
test2();

A: Sure. Javascript natively supports first class functions.
https://en.wikipedia.org/wiki/First-class_function
Therefore, that you can pass function as argument of another function, or return function as result of calculating of another function.
Also, functions can be anonymous.
In your case, you creating constant variable half, and assigning  arrow (anonymous) function as value ({max,min}) => (max+min)/2.0. So calling half with () operator will execute it. I'ts very common practice.
// in imperative scenario, assigning as variable allows you to tweak some behavior. But am not recommend to use this way in production, because i'ts much harder to controll app state while debugging

var SomeBehaviour;
SomeBehaviour = ({max,min}) => (max + min)/2.0;
SomeBehaviour();
SomeBehaviour = ({max,min}) => (max - min)/4.0;
SomeBehaviour();

// just common anonimous function
[ { min: 1, max: 2 } , { min: 3, max: 4 } ].map( ({max,min}) => (max + min)/2.0 )

// classic function
function half({max,min})
{
   return (max+min)/2.0
};

Main difference of using one of thouse scenarious would be in behaviour of this keyword in context.
Basically, if you don't use this in your module - you can don't worry.
Else - i advice you to read Kyle Simpsons book "This and Object prorotypes"


text:
Q: Кто может помочь с JUnit тестированием легкой программки? public class Matrix_Multiplication {
Scanner scan;
int matrix1[][], matrix2[][], multi[][];
int row, column;

void create()
{
    scan = new Scanner(System.in);
System.out.println("Matrix Multiplication");

    // First Matrix Creation..

    System.out.println("\nEnter number of rows & columns");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1 = new int[row][column];
matrix2 = new int[row][column];
multi = new int[row][column];
    System.out.println("Enter the data for first matrix :");
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
    matrix1[i][j] = scan.nextInt();
        }
}

    // Second Matrix Creation..

System.out.println("Enter the data for second matrix :");
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
    matrix2[i][j] = scan.nextInt();
        }
}
}

void display()
{
    System.out.println("\nThe First Matrix is :");
for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
    System.out.print("\t" + matrix1[i][j]);
        }
    System.out.println();
}

System.out.println("\n\nThe Second Matrix is :");
for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
    System.out.print("\t" + matrix2[i][j]);
        }
    System.out.println();
}
}

void multi()
{
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
    multi[i][j] = matrix1[i][j] * matrix2[i][j];
        }
}
    System.out.println("\n\nThe Multiplication is :");
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
            System.out.print("\t" + multi[i][j]);
        }
        System.out.println();
}
}}

A: Добрый день,
Такой код действительно очень сложно протестировать:)
Есть предложение сделать методы болeе общими и выделить параметры от которых они зависят в аргументы, а результаты алгоритма в возвращаемые значения.
Так же пытайтесь избегать дублирования кода.
Например:
public class Matrix_Multiplication {
Scanner scan;

public Matrix_Multiplication() {
    scan =  new Scanner(System.in);
}

public int askForInt(String message){
    System.out.println(message);
    return Integer.parseInt(scan.nextLine());
}

public int[][] createMatrix(int rows, int columns) {
    int matrix[][] = new int[rows][columns];
    System.out.println("Enter the data for matrix :");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            matrix[i][j] = scan.nextInt();
        }
    }
    return matrix;
}

public void display(int[][] matrix) {
    System.out.println("\nMatrix is :");
    for (int i = 0; i < matrix[0].length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            System.out.print("\t" + matrix[i][j]);
        }
        System.out.println();
    }
}

public int[][] multi(int[][] matrix1, int[][] matrix2) {
    int row = matrix1.length;
    int column = matrix1[0].length;
    int result[][] = new int[row][column];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            result[i][j] = matrix1[i][j] * matrix2[i][j];
        }
    }
   return result;
}

public void closeResourses(){
    scan.close();
}
}

Тогда main будет примерно таким:
  public static void main(String[] args) {
    Matrix_Multiplication matrixMultiplication = new Matrix_Multiplication();
    int rows = matrixMultiplication.askForInt("\nEnter number of rows");
    int columns = matrixMultiplication.askForInt("\nEnter number of columns");

    int[][] matrix1 = matrixMultiplication.createMatrix(rows, columns);
    int[][] matrix2 = matrixMultiplication.createMatrix(rows, columns);

    int[][] result = matrixMultiplication.multi(matrix1, matrix2);

    matrixMultiplication.display(result);
    matrixMultiplication.closeResourses();

}

и тесты написать будет намного проще, достаточно вызвать метод с параметрами и сравнить с ожидаемым результатом:
 @Test
public void testMultiiple() {
    int[][] m1 = new int[][]{
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };
    int[][] m2 = new int[][]{
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };

    int[][] expectedResult = new int[][]{
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };
   assertArrayEquals(expectedResult,matrix_multiplication.multi(m1,m2));

}


text:
Q: Партицирование таблицы по дате Есть таблица с 40+ млн записей, и для быстродействия возникла необходимость ее партицировать по дате. Партицирование требует PRIMARY ключ на поле, по которому будем разбивать таблицу, поэтому PRIMARY получился по полям (id, date), потому что в таблицу очень часто вставляются записи, и поле date может дублироваться. В итоге получилась таблица вида
CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `date` int(11)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `orders` ADD PRIMARY KEY (`id`, `date`);
ALTER TABLE `orders` MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;

Далее создаем партиции
ALTER TABLE `orders`
PARTITION BY RANGE (`date`) PARTITIONS 6 (
PARTITION p0 VALUES LESS THAN (1420059600) ENGINE = InnoDB COMMENT = '< 01.01.2015',
PARTITION p1 VALUES LESS THAN (1483218000) ENGINE = InnoDB COMMENT = '< 01.01.2017',
PARTITION p2 VALUES LESS THAN (1496264400) ENGINE = InnoDB COMMENT = '< 01.06.2017',
PARTITION p3 VALUES LESS THAN (1514764800) ENGINE = InnoDB COMMENT = '< 01.01.2018',
PARTITION p4 VALUES LESS THAN (1527811200) ENGINE = InnoDB COMMENT = '< 01.06.2018',
PARTITION p5 VALUES LESS THAN MAXVALUE ENGINE = InnoDB COMMENT = 'Current part')

Получается, что у нас составной PRIMARY. И если выполнить запрос
SELECT * FROM `orders` WHERE `id`=1 AND `date` = UNIX_TIMESTAMP();

то задействуется составной PRIMARY и выборка будет максимально быстрой. А если сделать
SELECT * FROM `orders` WHERE `id`=1;

или
SELECT * FROM `orders` WHERE `date` = UNIX_TIMESTAMP();

то произойдет фулл скан таблицы (согласно этой статье)
Правильно ли будет создать обычные индексы на поля id и date, чтобы делать выборку только по ним
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`, `date`),
  ADD KEY `id` (`id`),
  ADD KEY `date` (`date`);

Или составной PRIMARY работает как-то иначе, чем обычный составной ключ?


text:
Q: Rule-based rendering in qgis2web client is not working I made a simple map with polygons of the staates of africa and used the rule-based renderer for different colors to tint them. When I tried to load or export this map with qqis2web I didn't get displayed any colors but only the contours. I tried several very simple rules but in every case the result was always the same. If I used the categorized renderer for that everything worked fine.
Isn't the qqis2web able to display rule- based rendering or what could be the matter in that case?

A: It all depends on your rules. Can you post (some of) them? The rule-based renderer is tied heavily to QGIS expressions, and only a small subset of QGIS expression functions are so far supported in qgis2web. Some missing functions will be easy to add, others less so, and some pretty much impossible.
So, if you can edit your question to put in some or all of the expressions used, I can give a more definitive answer.


text:
Q: почему E_ACCESSDENIED от VBoxManage? не работает genymotion
выбираю virtual device из списка, долго висит экран эмулятора, а потом окно исчезает без сообщений
в логе такая запись:
Jul 20 11:46:42 [Genymotion] [debug] [VBox] VM engine version: "5.0.40_Ubuntur115130"
Jul 20 11:46:42 [Genymotion] [debug] VMX/SVM CPU availability: true
Jul 20 11:46:42 [Genymotion] [debug] VM engine version: "5.0.40_Ubuntur115130"
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Call: ("list", "vms")
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Return code: 0
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Call: ("guestproperty", "enumerate", "4a9cc299-cc77-4b58-8934-4877293a450c")
Jul 20 11:46:42 [Genymotion] [critical] [VBox] Return code: 1
Jul 20 11:46:42 [Genymotion] [critical] [VBox] Output command: "VBoxManage: error: The object functionality is limited
VBoxManage: error: Details: code E_ACCESSDENIED (0x80070005), component MachineWrap, interface IMachine, callee nsISupports
VBoxManage: error: Context: "LockMachine(a->session, LockType_Shared)" at line 253 of file VBoxManageGuestProp.cpp"
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Call: ("guestproperty", "enumerate", "968add45-3d41-444a-ae0f-b48a59ef89e3")
Jul 20 11:46:42 [Genymotion] [critical] [VBox] Return code: 1
Jul 20 11:46:42 [Genymotion] [critical] [VBox] Output command: "VBoxManage: error: The object functionality is limited
VBoxManage: error: Details: code E_ACCESSDENIED (0x80070005), component MachineWrap, interface IMachine, callee nsISupports
VBoxManage: error: Context: "LockMachine(a->session, LockType_Shared)" at line 253 of file VBoxManageGuestProp.cpp"
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Call: ("guestproperty", "enumerate", "2e84bc6c-c1d7-44e9-98f9-950b783f8cd9")
Jul 20 11:46:42 [Genymotion] [debug] [VBox] Return code: 0

как исправить ошибку?

A: оказалось проблема в драйверах видеокарты


text:
Q: Freeswitch verto performance is low This is my first question, thanks in advance for all your help!
I setup a freeswitch server, and call it from a web page, I found freeswitch server costs more than 13 percent cpu, when it's idle it costs less than 1 percent, if I use a sip client call it, it costs about 4 percent cpu, anyone know why it costs 9 percent more cpu if use verto? Below is some detailed information.
Freeswitch version: 1.7.0+git~20151231T160311Z~de5bbefdf0~64bit (git de5bbef 2015-12-31 16:03:11Z 64bit).
I use ubuntu 14.04 on intel i5 cpu with 16G ram.
Sip client used is Zoiper on windows.

A: You did not tell anything about the codecs that you're using. If you use OPUS in your WebRTC client, and it needs to be transcoded by the FreeSWITCH, then the workload looks quite relevant. OPUS is a quite expensive codec in terms of CPU effort needed for transcoding.
The same applies to the SIP client. The CPU load depends significantly on the codec encoding/decoding job during the call. In ideal situation, both legs of a call use the same codec, and then your FreeSWITCH server would only be busy with sending and receiving RTP frames, without heavy processing of the payload.
Keep in mind that the primary platform for FreeSWITCH is Debian Jessie, and there may also be issues with the kernel or libraries in Ubuntu, as nobody took care to analyze and optimize for this platform.


text:
Q: Marionette Layout doesn't exist I'm going through the docs and trying to set up a Backbone.Marionette.Layout in my application, but I keep getting a Cannot read property 'extend' of undefined error.
So I went through the source of the Marionette library on my server and couldn't find a definition for Layout anywhere. Which is odd since it's all over the docs. The layoutView works just fine and I can see the definition for that in the source.
I updated Maionette again, just to be sure I had the latest version, it's at 2.3.0 right now.
Here are some places where Layout is discussed as existing:
The Marionette.js docs site
Derick Baily's blog
I'm wondering if just a plain Layout has been deprecated, or if the docs are maybe using some sort of short hand and layoutView is actually what's being defined. Or if I'm just missing something.

A: As of version 2.0.0, Layout has been renamed to LayoutView and here's the current docs


text:
Q: Using jQuery function if element width is valid I'm new to jQuery and I found this code to use in my site:
$(function() {
  elemWidth = parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
  halfWidth = parseInt(window.innerWidth / 2, 10);
  alert("Your browser " + ((elemWidth == halfWidth) ? "" : "does not ") + "support VW and VH");
});

The code check if my element have the size that I define in css, returning if users browser support my size unit (viewport).
What I need is load a script if elemWidth value is not the same as halfWidth, but I don't know how to change this alert to a conditioning function.
Thanks!

A: The expression ((elemWidth == halfWidth) ? "" : "does not " makes use of the conditional ternary operator.
It is short for:
if (elemWidth == halfWidth) {
  // ""
} else {
  // "does not"
}

Therefore if you want to load a script if the elemWidth value is not the same as halfWidth, then you could simply use the $.getScript function or whatever you are using the load the script.
if (elemWidth !== halfWidth) {
  $.getScript('...');
}

A: Pretty straight forward, place the comparison of the two values in a condition, and lot a script if they are not equal.
$(function () {
    var elemWidth = parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
    var halfWidth = parseInt(window.innerWidth / 2, 10);

    if ( elemWidth !== halfWidth ) {

        $.getScript('whatever.js');

    }
});

A: var elemWidth =    parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
var halfWidth = parseInt(window.innerWidth / 2, 10);
elementWidth !== halfWidth ? alert("Your browser " + ((elemWidth == halfWidth) ? "" : "does not ") + "support VW and VH");


text:
Q: Fail2ban for nginx post flood ignores time intervals I'm trying to create a fail2ban filter that is going to ban the host when it sends over 100 POST requests over 30 seconds interval.
jail.local:
[nginx-postflood]

enabled = false
filter = nginx-postflood
action = myaction
logpath = /var/log/nginx/access.log
findtime = 30
bantime = 100
maxretry = 100

nginx-postflood.conf
[Definition]
failregex = ^<HOST>.*"POST.*
ignoreregex =

Using GREP i was able to test the regular expressions and indeed it matches Host and POST requests.
Problem is that it bans any Host that performs at least one POST request. This means likely that it's not taking findttime or maxretry options into consideration. In my opinion it's timestamp issue.
Sample line of nginx log:
5.5.5.5 - user [05/Aug/2014:00:00:09 +0200] "POST /auth HTTP/1.1" 200 6714 "http://referer.com" "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"

Any help?


text:
Q: c# OpenFileDialog Location Not Available I have a very simple C# code not sure what I am missing, I need to open OpenFileDialog and select file but when I open it by clicking of a button on Documents, Desktop and Downloads short cuts in windows 10 it says Location is not available, but when I go to any of these folders directly from C drive and users directory it works fine.
Here is my code
var FD = new OpenFileDialog();
string dir = Path.GetDirectoryName(Environment.CurrentDirectory);
if (!Directory.Exists(dir))
{
      dir = "defaultdirectory";
}

FD.InitialDirectory = dir;
if (FD.ShowDialog() == DialogResult.OK)
{
    string fileToOpen = FD.FileName;
    uploadFile(fileToOpen);
}

And here is the screeshot
enter image description here


text:
Q: I want to calculate session_id for my list of events with T-SQL query The following is a list of events.
I want to calculate the session_id column in my list of events.
After that I try to calculate time between events in each session.
Each session_id should be started from event_name = "app_open", ordered by timestamp. In the bellow table you can see data that I have (3 first columns) and the last one that I want to calculate.
How can I do it with T-SQL?

event_name	event_number	timestamp	session_id

app_open	1	2015-09-10 02:54:04	1

crashlytics_init	2	2015-09-10 02:54:38	1

parse_init	3	2015-09-10 02:55:13	1

appsflyer_init	4	2015-09-10 02:56:10	1

googleanalytics_init	5	2015-09-10 02:56:54	1

login_popup	6	2015-09-10 02:57:25	1

login_get	7	2015-09-10 03:01:27	1

login_success	8	2015-09-10 03:02:01	1

lobby_displayed	9	2015-09-10 03:02:44	1

app_open	1	2015-09-10 03:04:21	2

crashlytics_init	2	2015-09-10 03:06:07	2

parse_init	3	2015-09-10 03:07:27	2

login_get	4	2015-09-10 03:07:27	2

login_success	5	2015-09-10 03:08:40	2

lobby_displayed	6	2015-09-10 03:09:49	2

app_open	1	2015-09-10 03:10:07	3

googleanalytics_init	2	2015-09-10 03:10:28	3

login_popup	3	2015-09-10 03:11:35	3

login_get	4	2015-09-10 03:13:40	3

login_success	5	2015-09-10 03:17:46	3

lobby_displayed	6	2015-09-10 03:25:02	3

A: As Jony said, you will have to explain better what you're trying to do. The posted data is the input data or the expected result? If it's the input data, you already have a session_id there; do you simply need to calculate the interval between events? If yes, try something like this (in SQL Server 2012 or later):
DECLARE @X XML='

event_name	event_number	timestamp	session_id

app_open	1	2015-09-10 02:54:04	1

crashlytics_init	2	2015-09-10 02:54:38	1

parse_init	3	2015-09-10 02:55:13	1

appsflyer_init	4	2015-09-10 02:56:10	1

googleanalytics_init	5	2015-09-10 02:56:54	1

login_popup	6	2015-09-10 02:57:25	1

login_get	7	2015-09-10 03:01:27	1

login_success	8	2015-09-10 03:02:01	1

lobby_displayed	9	2015-09-10 03:02:44	1

app_open	1	2015-09-10 03:04:21	2

crashlytics_init	2	2015-09-10 03:06:07	2

parse_init	3	2015-09-10 03:07:27	2

login_get	4	2015-09-10 03:07:27	2

login_success	5	2015-09-10 03:08:40	2

lobby_displayed	6	2015-09-10 03:09:49	2

app_open	1	2015-09-10 03:10:07	3

googleanalytics_init	2	2015-09-10 03:10:28	3

login_popup	3	2015-09-10 03:11:35	3

login_get	4	2015-09-10 03:13:40	3

login_success	5	2015-09-10 03:17:46	3

lobby_displayed	6	2015-09-10 03:25:02	3

'
--SELECT @x
SELECT *, CONVERT(time,timestamp-LAG(timestamp) OVER (PARTITION BY session_id ORDER BY event_number)) as interval
FROM (
    SELECT  c.value('td[1]','varchar(100)') as event_name,
            c.value('td[2]','int') as event_number,
            c.value('td[3]','datetime') as timestamp,
            c.value('td[4]','int') as session_id
    FROM @x.nodes('/table/tbody/tr[td!=""]') t(c)
) q

If the posted data is the expected result, then please post the input data.
Later edit:
If you want to compute the session_id based on the event_number, you can use something like this:
DECLARE @X XML='

event_name	event_number	timestamp	session_id

app_open	1	2015-09-10 02:54:04	1

crashlytics_init	2	2015-09-10 02:54:38	1

parse_init	3	2015-09-10 02:55:13	1

appsflyer_init	4	2015-09-10 02:56:10	1

googleanalytics_init	5	2015-09-10 02:56:54	1

login_popup	6	2015-09-10 02:57:25	1

login_get	7	2015-09-10 03:01:27	1

login_success	8	2015-09-10 03:02:01	1

lobby_displayed	9	2015-09-10 03:02:44	1

app_open	1	2015-09-10 03:04:21	2

crashlytics_init	2	2015-09-10 03:06:07	2

parse_init	3	2015-09-10 03:07:27	2

login_get	4	2015-09-10 03:07:27	2

login_success	5	2015-09-10 03:08:40	2

lobby_displayed	6	2015-09-10 03:09:49	2

app_open	1	2015-09-10 03:10:07	3

googleanalytics_init	2	2015-09-10 03:10:28	3

login_popup	3	2015-09-10 03:11:35	3

login_get	4	2015-09-10 03:13:40	3

login_success	5	2015-09-10 03:17:46	3

lobby_displayed	6	2015-09-10 03:25:02	3

'
--SELECT @x
SELECT *, CONVERT(time,timestamp-LAG(timestamp) OVER (PARTITION BY session_id ORDER BY event_number)) as interval
FROM (
    SELECT *, DENSE_RANK() OVER (ORDER BY row_num-event_number) AS session_id
    FROM (
        SELECT *, ROW_NUMBER() OVER (ORDER BY timestamp) AS row_num
        FROM (
            SELECT  c.value('td[1]','varchar(100)') as event_name,
                    c.value('td[2]','int') as event_number,
                    c.value('td[3]','datetime') as timestamp
            FROM @x.nodes('/table/tbody/tr[td!=""]') t(c)
        ) q1
    ) q2
) q3


text:
Q: Diagnosing Blue Screen (IRQL_not_less_or_equal) Windows 7 64bit I've searched high and low for an answer to this one. I recently removed my nVidia graphics card and the crashes are now less frequent. Here's the info from my latest mini dump. Can anybody shed any light on this?
Thanks!
==================================================
Dump File         : 032413-14320-01.dmp
Crash Time        : 24/03/2013 22:55:22
Bug Check String  : IRQL_NOT_LESS_OR_EQUAL
Bug Check Code    : 0x0000000a
Parameter 1       : fffffd8004695fe8
Parameter 2       : 0000000000000002
Parameter 3       : 0000000000000000
Parameter 4       : fffff800029669d5
Caused By Driver  : ntoskrnl.exe
Caused By Address : ntoskrnl.exe+75c40
File Description  : NT Kernel & System
Product Name      : Microsoft® Windows® Operating System
Company           : Microsoft Corporation
File Version      : 6.1.7601.18044 (win7sp1_gdr.130104-1431)
Processor         : x64
Crash Address     : ntoskrnl.exe+75c40
Stack Address 1   :
Stack Address 2   :
Stack Address 3   :
Computer Name     :
Full Path         : C:\Windows\Minidump\032413-14320-01.dmp
Processors Count  : 4
Major Version     : 15
Minor Version     : 7601
Dump File Size    : 280,944

A: I would start at the very beginning in scenario like this because these BSOD messages can sometimes be misleading and can easily send you down the wrong path.
Test your hard drive for bad sectors as well as the RAM in your system for errors.
There are a variety of bootable disk utilities you can use to test the health of Hard Drives. One simple but effective tool to use is Drive Fitness Test. This will tool will essentially go through the drive checking for bad sectors as well as performing a number of other checks in the process.
The second thing to test for would be faulty RAM, with something like Memtest86+.
Once you have established that there is no faulty hardware it will be much easier to diagnose other, OS related issues, such as faulty drivers or bad patches/processes.