text:
Q: Create user only by admin I am trying to make an application to generate an api token using Lumen for user.
I made login and registration but I want only admin to be able to create create an user. Can anyone point me at the right direction?
Here is my code:
UserController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller {
    /**
     * Register new user
     *
     * @param $request Request
     */
    public function register(Request $request) {
        $hasher = app()->make('hash');
        $username = $request->input('username');
        $email = $request->input('email');
        $password = $hasher->make($request->input('password'));
        $register = User::create([
            'username' => $username,
            'email' => $email,
            'password' => $password,
        ]);
        if ($register) {
            $res['success'] = true;
            $res['message'] = 'Success register!';
            return response($res);
        } else {
            $res['success'] = false;
            $res['message'] = 'Failed to register!';
            return response($res);
        }
    }

    /**
     * Get user by id
     *
     * URL /user/{id}
     */
    public function get_user(Request $request, $id) {
        $user = User::where('id', $id)->get();
        if ($user) {
            $res['success'] = true;
            $res['message'] = $user;

            return response($res);
        } else {
            $res['success'] = false;
            $res['message'] = 'Cannot find user!';

            return response($res);
        }
    }
}

LoginController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class LoginController extends Controller {
    /**
     * Index login controller
     *
     * When user success login will retrive callback as api_token
     */
    public function index(Request $request) {
        $hasher = app()->make('hash');
        $email = $request->input('email');
        $password = $request->input('password');
        $login = User::where('email', $email)->first();
        if (!$login) {
            $res['success'] = false;
            $res['message'] = 'Your email or password incorrect!';
            return response($res);
        } else {
            if ($hasher->check($password, $login->password)) {
                $api_token = sha1(time());
                $create_token = User::where('id', $login->id)->update(['api_token' => $api_token]);
                if ($create_token) {
                    $res['success'] = true;
                    $res['api_token'] = $api_token;
                    $res['message'] = $login;
                    return response($res);
                }
            } else {
                $api_token = sha1(time());
                $create_token = User::where('id', $login->id)->update(['api_token' => $api_token]);
                $res['success'] = true;
                $res['api_token'] = $api_token;
                $res['message'] = $login;
                return response($res);
            }
        }
    }
}

Authenticate Middleware
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate {
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory $auth
     * @return void
     */
    public function __construct(Auth $auth) {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null) {
        if ($this->auth->guard($guard)->guest()) {
            if ($request->has('api_token')) {
                $token = $request->input('api_token');
                $check_token = User::where('api_token', $token)->first();
                if ($check_token == null) {
                    $res['success'] = false;
                    $res['message'] = 'Permission not allowed!';

                    return response($res);
                }
            } else {
                $res['success'] = false;
                $res['message'] = 'Login please!';

                return response($res);
            }
        }
        return $next($request);
    }
}

A: Create a middleware for adminrole authentication

namespace App\Http\Middleware;

use Closure;

class Adminrole
{

    public function handle($request, Closure $next)
    {

        $admin = $this->auth->getUser();

        if(!ADMIN) {
            return response()->json(['success'=> false,'error' => 'Invalid Admin User'])->setStatusCode(400);
        }

        return $next($request);
    }

}

Then register the middleware in routeMiddleware from bootstrap/app.php
$app->routeMiddleware([

    'admin' => App\Http\Middleware\Adminrole::class,

]);

Add you middleware to the registration api-url route
$api->post('YOUR-URL', [
        'uses' => 'UserController@register',
        'middleware' => 'admin'
    ]);


text:
Q: How to get out values from java interface I have a variable inside an interface method and I want it outside the interface:
String responseString;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // i want this value out!
                responseString = response.toString();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println(error.toString());
            }
        });

Of course I can't just assign responseString = response.toString() because they have different scopes. So how can I do this?
Probably this question has already been answered but I couldn't find anything similar online.

A: Try this once as per your JSON  structure Either JSONArray or JSONObject.
//JSON Array
    private JSONArray result;

  //Creating a string request
        StringRequest stringRequest = new StringRequest(URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject j = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            j = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            result = j.getJSONArray("your key");

                //OPTIONAL function
                            functionName(result);//If using function
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

A: The new Response.Listener<String>() {...} that you're doing in that method is called "anonymous" implementation. Indeed you are implementing the interface, but you don't hold any static reference to it in the code.
What you should do, is to have a normal implementation of the interface which of course implements the method required, but also holds a field and a special getter for your field:
public class YourStringListener implements Response.Listener<String> {

    private String responseString; //<-- declare a field

    @Override
    public void onResponse(String response) {
        this.responseString = response.toString(); //<-- set the field
    }

    public String getResponseString() {
        return this.responseString; //<-- get the field from outside
    }

}

Now, you should be able to do this:
String responseString;
YourStringListener listener = new YourStringListener(); //<-- don't implement anonimously, use the concrete implementation
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, listener, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error.toString());
        }
    });
System.out.println(listener.getResponseString()); //<-- access the value of response string from the concrete implementation instance

Of course, be careful you're into a listener. The value will be null until when the method onResponse will have asynchronously been called back.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The "possible spam" banner for suggested edits is misaligned On this banner (seen  here on spam edits):

... the text is aligned to the bottom of the banner, where it should probably be in the middle.
Just putting the text in <p> tags (like the protected and closed banners) seems to fix it (though the text may be larger than desired):

Can this be fixed?

A: This seems to have been fixed without feedback (on this question), I'll add an answer here to mark the question as answered.

There is now a new banner, using its own CSS class (info-box), which has correct padding and centering

.info-box {
    background-color: #FFF1D0;
    margin-top: 1em;
    padding: 0.5em;
    font-size: 14px;
    text-align: center;
}

A: You can use padding top and bottom to fix this problem:
.question-status {
     text-align:center;
     padding:10px 0px;
}


text:
Q: Prettify OS X console by coloring output? OS X terminal is not using colors for highlighting output from different commands, for example ls.
When compared with other systems like Ubuntu, this is a big loss of accessibility/productivity.
What solutions do I have to improve this experience? For the moment I found only this guide for colored ls output under OS X but I am looking for a more complete solution.

A: You can easily change the ls output color by installing "TerminalColors" plugin. I am a big fan of "Solarize" theme which looks terrific on my Mac.

A: *

*you should change the Terminal.app preferences->advanced into xterm-color.

*enter the following into your ~/.profile

for enable colored ls:
export CLICOLOR=1;
export LSCOLORS=exfxcxdxbxegedabagacad;

and from now, you will get colored ls output.


text:
Q: Using outputs terraform files in other terraform files I am new to terraform and have a few questions. Is there a way in terraform, to use the outputs of a module, in another tf file, WITHOUT having a "main" terraform file, or defining both modules in the same file?
For example, this is a project structure:
project/
├── networking
│   ├── init.tf
│   ├── terraform.tfvars
│   ├── variables.tf
│   └── vpc.tf
├── prd-project-1
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── prd-project-2
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── prd-project-3
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── test
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf

vpc.tf would create a VPC and subnets.
instances.tf would create EC2 instances, based on the vpc-id and subnets created previously in vpc.tf. I want to treat/manage these as two seperate actions. ie. First, I would run terraform to create the vpc and subnets, then later I might run terraform to create instances in prod/test for various projects. In this example, I would have only 1 VPC for test and 1 VPC for prod. I would not want a VPC per project (which I am again assuming TF might create if the vpc.tf module is referenced in one of the sub-projects).
Is it best practise to manage terraform code in this way? My concern is if eventually there are many projects needing EC2 instances, I don't want all of these in a single huge main.tf. I am thinking it is safer/cleaner to maintain these all seperately, as long as the vpc outputs can be referenced.  I also don't want my terraform plan/applies being slow and checking each and every resource from every project if I am standing up a new project.
The second part of my question is - consider the following code snippet:
module "main-vpc" {
  source     = "../modules/vpc"
  ENV        = "prod"
  AWS_REGION = var.AWS_REGION
}

module "instances" {
  source         = "../modules/instances"
  ENV            = "prod"
  VPC_ID         = module.main-vpc.vpc_id
  PUBLIC_SUBNETS = module.main-vpc.public_subnets
}

Is terraform smart enough to determine that a VPC was already created with an ENV = prod and would not try to recreate it if I called the same "main-vpc" module in another tf file/project?
I've read a few other posts here on stackoverflow, but they all allude that outputs from a module can only be referenced in another module within the same tf file.
Some other posts I've reviewed:

*

*Using outputs from other tf files in terraform

*Pass terraform output from one file to another

*Terraform module - output variable as input for another module

*Terraform structure for two aws accounts

A: If you want to keep your current folder structure, its best to add main.tf to each project:
project/
├── networking
│   ├── init.tf
│   ├── terraform.tfvars
│   ├── variables.tf
│   └── vpc.tf
├── prd-project-1
│   ├── main.tf
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── prd-project-2
│   ├── main.tf
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── prd-project-3
│   ├── main.tf
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf
├── test
│   ├── init.tf
│   ├── instances.tf
│   ├── terraform.tfvars
│   └── variables.tf

Then each main.tf would be something as follow:
module "main-vpc" {
  source     = "../networking"
  ENV        = "prod"
  AWS_REGION = var.AWS_REGION
}

module "instances" {
  source         = "../instances"
  ENV            = "prod"
  VPC_ID         = module.main-vpc.vpc_id
  PUBLIC_SUBNETS = module.main-vpc.public_subnets
}

This way you keep your project separate and each project will have its own TF state file.

Is terraform smart enough to determine that a VPC was already created with an ENV

No its not. You would have to program your own logic for that. A common way is through a variable
variable "vpc_id" {
  default = ""
}

then if you do not explicitly specify the vpc_id for a given project, it would create new VPC. Otherwise, it would use var.vpc_id that you provide as an input parameter. Using data sources you would then get other information for that VPC, such as its subnets.
Having this setup, you would cd to each project folder first, before deploying it, e.g.
cd ./prd-project-1
terraform apply

A: If I understand your question, you want to have independent projects that can still access outputs from one another. So, for example, a project that spins up EC2 instances can refer to the subnets defined in the project that creates a VPC.
There are two ways to do this. First, you can use data sources to query the current deployment environment. For example, the following will look for the VPC with the ENV tag having a value of "prod" (assuming that I haven't made any typos):
data "aws_vpc" "prod" {
  tags = { "ENV": "prod" }
}

Second, you can use remote state (which is a good idea anyway, for security). Each project would write its outputs to a data store (S3 is common, but Terraform offers its own store), and they would be referenced by the others.
And while SO doesn't like links, I can't explain it better than the Terraform docs: https://www.terraform.io/docs/language/state/backends.html


text:
Q: Android SQLite database simple assistance So I am following this tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/    and still seem to produce no result. Could someone please assist me because i have no idea why it won't work. Thanks! It just gives me errors in the logcat!
Also how would i go about posting this data into a textView or ListView in another activity?
public class DatabaseHandler extends SQLiteOpenHelper{

// Database version
private static final int DATABASE_VERSION = 1;
// Database name
private static final String DATABASE_NAME = "athleteProgram";
// Athletes table name
private static final String TABLE_ATHLETES= "athletes";

// Athletes table columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";

DatabaseHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating table
@Override
public void onCreate(SQLiteDatabase db)
{
    String CREATE_ATHLETES_TABLE = "CREATE TABLE " + TABLE_ATHLETES + "(" + KEY_ID +
            " INTEGER PRIMARY KEY," + KEY_NAME + "TEXT," + KEY_AGE + " TEXT" + ")";
    db.execSQL(CREATE_ATHLETES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATHLETES);

    // Create tables again
    onCreate(db);
}
// All CRUD(Create, Read, Update, Delete) Operations

// Adding athlete
void addAthlete(Athlete athlete)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, athlete.getName());
    values.put(KEY_AGE, athlete.getAge());

    // Inserting Row
    db.insert(TABLE_ATHLETES, null, values);
    db.close(); // Closing database connection
}
// Getting single Athlete
public Athlete getAthlete(int id)
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_ATHLETES, new String[] {KEY_ID, KEY_NAME, KEY_AGE}, KEY_ID + "=?",
            new String[] {String.valueOf(id)}, null, null, null, null);
    if(cursor != null)
    {
        cursor.moveToFirst();
    }

    Athlete athlete = new Athlete(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    return athlete;
}
// Getting All Athletes
public List<Athlete> getAllAthletes() {
    List<Athlete> athleteList = new ArrayList<Athlete>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_ATHLETES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Athlete athlete = new Athlete();
            athlete.setID(Integer.parseInt(cursor.getString(0)));
            athlete.setName(cursor.getString(1));
            athlete.setAge(cursor.getString(2));
            // Adding contact to list
            athleteList.add(athlete);
        } while (cursor.moveToNext());
    }

    // return athlete list
    return athleteList;
}
// Updating single athlete
public int updateAthlete(Athlete athlete) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, athlete.getName());
    values.put(KEY_AGE, athlete.getAge());

    // updating row
    return db.update(TABLE_ATHLETES, values, KEY_ID + " = ?",
            new String[] { String.valueOf(athlete.getID()) });
}
// Deleting single athlete
public void deleteAthlete(Athlete athlete) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_ATHLETES, KEY_ID + " = ?",
            new String[] { String.valueOf(athlete.getID()) });
    db.close();
}
// Getting athletes Count
public int getAthletesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_ATHLETES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

}

public class Athlete {

    //private variables
    int _id;
    String _name;
    String _age;

    // Empty constructor
    public Athlete(){

    }
    // constructor
    public Athlete(int id, String name, String age){
        this._id = id;
        this._name = name;
        this._age = age;
    }

    // constructor
    public Athlete(String name, String age){
        this._name = name;
        this._age = age;
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getName(){
        return this._name;
    }

    // setting name
    public void setName(String name){
        this._name = name;
    }

    // getting age
    public String getAge(){
        return this._age;
    }

    // setting age
    public void setAge(String age){
        this._age = age;
}
}

public class StartingActivity extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting);

}

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
    @SuppressWarnings("unchecked")
    EditText editName = (EditText) findViewById(R.id.editName);
    EditText editAge = (EditText) findViewById(R.id.editAge);
    EditText editDate = (EditText) findViewById(R.id.editDate);
    EditText editTier = (EditText) findViewById(R.id.editTier);
    DatabaseHandler db = new DatabaseHandler(this);

    /**
     * CRUD Operations
     * */
    // Inserting Contacts
    Log.d("Insert: ", "Inserting ..");
    db.addAthlete(new Athlete("Joe", "20"));
    db.addAthlete(new Athlete(editName.getText().toString(), editAge.getText().toString()));

    // Reading all contacts
    Log.d("Reading: ", "Reading all contacts..");
    List<Athlete> athletes = db.getAllAthletes();

    for (Athlete ath : athletes) {
        String log = "Id: " + ath.getID() + " ,Name: " + ath.getName() + " ,Phone: " + ath.getAge();
        // Writing Contacts to log
        Log.d("Name: ", log);

    }
}
}

A: try it, maybe you don't insert the primary key. i insert example input.
 db.addAthlete(new Athlete(1,"Joe", "20"));
 //same on this line
 db.addAthlete(new Athlete(2,editName.getText().toString(), editAge.getText().toString()));

maybe it can help
sorry for bad english

A: The create statement below has a problem. Missing space between KEY_NAME and its type.

String CREATE_ATHLETES_TABLE = "CREATE TABLE " + TABLE_ATHLETES + "(" + KEY_ID +
             " INTEGER PRIMARY KEY," + KEY_NAME + "TEXT," + KEY_AGE + " TEXT" + ")";
      db.execSQL(CREATE_ATHLETES_TABLE);


text:
Q: Javascript- swap multiple images First off, I am just starting to learn javascript so your patience is appreciated.  I have a problem that I am trying to figure out.  I am looking for a way to be able to click an image, and then click the image I want to swap it with. To elaborate, I have 9 images labeled 0-9, and 9 blank images.  My goal is to be able to click a numbered image and swap it for one of the blank images. All I have come up with is this, but it absolutely does not work in the way I need.
function swap1() {
    element = document.getElementById('0')
    if (element.src.match("0.jpg")) {
        element.src = "blank.jpg";
        alert(this.id)
    } else {
        element.src = "0.jpg";
    }
}

A: id can't start with a number. Change it to a valid id like image or just get the reference to the element via event.target.
Demo: http://jsfiddle.net/DerekL/b7C3H/

A:

The above code demonstrates two important techniques: a. passing in self-reference to avoid tedious naming; b. storing state variables in the DOM object

A: Try this. Say your html like

function swap1() {
    element = document.getElementById('myimage');
    if (element.src.match("0.jpg")) {
        element.src = "blank.jpg";
    } else {
        element.src = "0.jpg";
    }
}


text:
Q: Multiplying each buffer string in x86 I have a part of code where I need to multiply number from 0-9 and print it out, but I do it by taking one integer at a time and multiplying it by 4 this time, but I don't know what to do when after multiplying I get two digit number. I can only print the mod of it. please help!!!!
Someone said to go to the end of a buffer but I also don't know how to do that...
work:
    MOV dl, [si]

    sub dl,48
    mov bl,dl
    mov al,4 ; this can be changed from 0-9
    mul bl
    mov ah,2
    mov dl,al

    count:
    cmp dl,09H     ;compares with 9
    jbe moveon
    ja ifmorethanten

ifmorethanten:

    mov ax,dx

    mov bl, 10
    div bl         ;al=ax/bl  ah=ax%bl
    mov dl, al

    cmp dl, 09H
    jbe moveon
    ja ifmorethanten

    add dl,48
    push ax

    mov ah,02h
    int 21h

    pop ax
    mov dl, ah

moveon:
    MOV [di], dl
    INC si ;moving on to another buffer's integer
    INC di ;ignore it I put the number into another buffer here
    LOOP    work

Maybe I should do it somehow different please help me!!!


text:
Q: Optimisation of a cost function I'm reading the solution of an optimization problem where i have to optimize the volume of a cylinder according to a specific cost.
The cost is $c_0 = 2\pi r^2c1 + 2\pi rhc_2 = 2\pi r^2c_1 + \pi rhc_2 + \pi rhc_2 = 3(\frac{2\pi r^2c_1 + \pi rhc_2 + \pi rhc_2}{3}) \ge 3(2\pi \pi^2 r^4 h^2 c_1c_2^2)^{1/3}=3(2\pi V^2c_1c_2^2)^{1/3}=3(2\pi)^{1/3}(c_1c_2^2)^{1/3}V^{2/3}$
But i don't understand the part after the inequality, i know that the AG inequality is used but i don't know how,  why does the denominator disappear and how do we get $2\pi \pi^2 r^4 h^2 c_1c_2$ ?


text:
Q: How to inject factory to controller? Hi I am new to angularjs and I am trying to inject some factory to controller but I am facing difficulties. My factory works fine. I am able to set data in factory.
Below is my code where I inject factory.
function () {
    angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
        function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, CONSTANTS, SomeFactory) {

        var OTP = $stateParams.pageList.OTP;
        $scope.EnterOTP = "Please enter this OTP to verify the user " + OTP;
      //RegistrationOTPVerification.$inject = ['SomeFactory'];
      //Facing issues in above line
        alert(1);
        function RegistrationOTPVerification(SomeFactory) {
            var vm = this;
            vm.someVariable = SomeFactory.getData();
            console.log(vm.someVariable);  // logs your data
            alert(vm.someVariable);
        }
});

This is my factory code.
(function () {
    'use strict';
    angular
      .module('RoslpApp')
      .factory('SomeFactory', SomeFactory);

    SomeFactory.$inject = [];

    function SomeFactory() {
        var someData;

        var factory = {
            setData: setData,
            getData: getData
        };
        function setData(data) {

            someData = data;
        }

        function getData() {
            return someData;
        }

        return factory;
    }
})();

I set data in some other controller with SomeFactory.setData("123")
I want to inject someFactory as below:
RegistrationOTPVerification.$inject = ['SomeFactory'];
But whenever I write this, I get error RegistrationOTPVerification is undefined. If I comment that line everything works fine but I want to get some data from factory.
My factory name is SomeFactory and I want to inject in above controller. Any help would be appreciated.

A: You missed CONSTANTS in controller dependency list:
   '$translate', '$state', '$stateParams', 'SomeFactory',
... $translate,   $state,   $stateParams,   CONSTANTS,    SomeFactory) {

So whatever you inject SomeFactory is available in controller under the name CONSTANTS and symbol SomeFactory is undefined.

A: Firstly, you missed CONSTANTS in your injections.
Next, I think you are mixing two kinds of syntax for controller here. Either use anonymous function or named. Don't mix both together.
Here's how your code should look like.
function () {
    angular.module('RoslpApp').controller('RegistrationOTPVerification', ['$scope', '$http', '$translatePartialLoader', '$translate', '$state', '$stateParams', 'SomeFactory',
        function ($scope, $http, $translatePartialLoader, $translate, $state, $stateParams, SomeFactory) {

        var vm = this;
        var OTP = $stateParams.pageList.OTP;
        vm.EnterOTP = "Please enter this OTP to verify the user " + OTP;
        vm.someVariable = SomeFactory.getData();
        console.log(vm.someVariable);  // logs your data
        alert(vm.someVariable);
});


text:
Q: Is it possible to add an element after a set height interval?
I need to add an element like
 end
 every 100px. Is there any possible solution using Javascript, jQuery or php?
jsfiddle.net/vk4a7pwo/24 This is where my code is. I need the content of class .message-append put inside the .subpage class.

This article examines four new ES6 collections and the benefits they provide.

Most major programming languages have several types of data collections. Python has lists, tuples, and dictionaries. Java has lists, sets, maps, queues. Ruby has hashes and arrays. JavaScript, up until now, had only arrays. Objects and arrays were the workhorses of JavaScript. ES6 introduces four new data structures that will add power and expressiveness to the language:

Searching for the JavaScript HashMap

HashMaps, dictionaries, and hashes are several ways that various programming languages store key/value pairs, and these data structures are optimized for fast retrieval.

In ES5, JavaScript objects — which are just arbitrary collections of properties with keys and values — can simulate hashes, but there are .

Downside #1: Keys must be strings in ES5

JavaScript object property keys must be strings, which limits their ability to serve as a collection of key/value pairs of varying data types. You can, of course, coerce/stringify other data types into strings, but this adds extra work.

Downside #2: Objects are not inherently iterable

Objects weren't designed to be used as collections, and as a result there's no efficient way to determine how many properties an object has. . When you loop over an object's properties, you also get its prototype properties. You could add the  property to all objects, but not all objects are meant to be used as collections. You could use the  method, but this is just a workaround. When you loop over an object's properties, the properties won't necessarily be retrieved in the same order they were inserted.

Downside #3: Challenges with built-in method collisions

Objects have built-in methods like

ES6 includes new collection data types, so there's no longer a need to use objects and live with their drawbacks.

Using ES6 Map Collections

is the first data structure/collection we'll examine. Maps are collections of keys and values of any type. It's easy to create new Maps, add/remove values, loop over keys/values and efficiently determine their size. Here are the crucial methods:


text:
Q: Batch file that will print all files (.pdf's and .docs) in a directory Running Win7, I need a batch file that will print all .doc and .pdf files in a particular directory. Any help greatly appreciated!

A: First you'll need printJS.bat in the same directory:
@echo off
pushd "C:\directory_with_documents"
for %%a in (*.pdf *.doc) do (
   call printjs.bat "%%~fa"
)

and to change the directory at the beginning.
Have on mind that printJS uses invokeverb function which may fail if language on the system is different than English.


text:
Q: Is it possible to update stackdriver logs when a BigQuery job completes? I am using the BigQuery Python library to submit a query job. In stackdriver i can see that the job was submitted, but I would like to see a log entry in Stackdriver when the job is complete. Is this possible to setup?
I know that you can poll the job_id to see the status, but the job runs longer than my cloud function can stay alive.
Thanks

A: StackDriver already shows this information to users:


text:
Q: How to check affected rows before an sql query running? Consider a table with some rows.
by php, I  make a SQL query such as "DELETE * From my_table".
How can I recognize affected rows before running the sql query. On the other words, I want to have the list of affected rows after an sql query and before of its running.
All in all, I want to check somethings before running SQL irreversible queries.
best respects.

A: You can perform a SELECT query with the same JOIN and WHERE criteria as the DELETE would use. This will return the rows that would have been deleted.
If you want perfect safety, you need to use transactions in all the applications that access the tables. The process that's doing the DELETE should perform the SELECT in the same transaction. Otherwise, another process could add rows to the table between the SELECT and DELETE, and they might be deleted if they meet the criteria.
If you're just trying to verify the logic of your DELETE query with an eyeball examination of the results, this may be overkill.

A: Suppose you have a DELETE query like:
DELETE FROM my_table WHERE foo='bar'
To see how many records will be deleted you could first run:
SELECT count(*) from my_table where foo='bar'
The result of that query will be the count of records that meet the same condition.

A: Add the MySQL EXPLAIN keyword before your SQL statement.

A: You can use SELECT and then mysqli_affected_rows to get the number of rows about to get deleted.
If you want data from the rows as well then you fetch it with SELECT.

A: 1) Create a function that analyzes the rows:
function checkRows($table){
    $query = 'SELECT * FROM ' . $table;

    // execute SELECT query
    // get the result
    // using for loop, set $delete boolean based on whether to delete or not

    return $delete;
}

2) Create a function that deletes the stuff:
function deleteFromTable($table){
    $query = 'DELETE FROM ' . $table;

    // execute DELETE query
}

3) Create conditional calls:
$table = 'SomeTable';
$validDelete = checkRows($table);

if($validDelete){
    deleteFromTable($table);
}

This will allow you to perform validation of records prior to deletion.


text:
Q: Eclipse shortcut help (source -> xml & vice versa) I am using Eclipse Juno because of the theme features of this platform. All is well, then I get this difficulty in Android development. When we create a view on the editor there are 2 tabs in the .xml file, "Graphical Layout" and "XML source". But after I've change my theme, I can't find these tabs...
Is there a shortcut in order to switch between the two views?

A: Use AltF7 to switch to the next page in a multi page editor, AltShiftF7 to switch to the previous page.


text:
Q: Clicking routes in Header refreshes page in vuejs with prerender-spa plugin after serving dist The connection in between components gets disrupted. Which shouldnt happen since I am using bootstrap-vue inbuilt router link (using to=" " instead of href="").
The app works perfectly fine when running without dist.

App.vue

<template>

    <app-header></app-header>

        <transition name="slide" mode="out-in">
          <router-view></router-view>
        </transition>

</template>

Header.vue

<template>

      Stock Broker

          Portfolio
          Stocks
          End Day

            Funds: {{ funds }}

</template>

vue.config.js

module.exports = {
  pluginOptions: {
    prerenderSpa: {
      registry: undefined,
      renderRoutes: ["/", "/portfolio", "/stocks"],
      useRenderEvent: true,
      headless: true,
      onlyProduction: true
    }
  }
};

router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/stocks',
    name: 'Stocks',
    component: () => import(/ '../views/Stocks.vue')
  },
  {
    path: '/portfolio',
    name: 'Portfolio',
    component: () => import('../views/Portfolio.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

A: I figured it a minute after making this post haha.
The issue was that in App.vue I had my main div with a class of "container" instead of id of "app".
Corrected below:
<template>

 //correction here
    <app-header></app-header>

        <transition name="slide" mode="out-in">
          <router-view></router-view>
        </transition>

</template>


text:
Q: way to remove global variable in Ruby? I know I can view all global variable through Kernel#global_variables but is there any method for removing them akin to the remove_instance_variable, remove_class_variable, remove_const methods? Or is there a way to use those to accomplish the same thing?

A: I don't believe that it's possible to "unset" a global variable. Your best bet is setting the variable to nil.
Normally, when you try to use a variable you haven't defined yet, Ruby throws an error.
irb > "The following variable has not yet been defined: #{a}"
irb > NameError: undefined local variable or method `a' for main:Object

This behavior is actually different with global variables. Any attempt to call a global variable that hasn't been defined will return nil.
irb > "The following global variable has not yet been defined: #{$a}"
  # => The following global variable has not yet been defined:
irb > $a.class
  # => NilClass

So setting your global variable to nil should have exactly the same behavior that you would expect from "unsetting" it.


text:
Q: MIPS registers preservation So I'm learning MIPS right now and I saw on the MIPS green sheet that there are a total of 12 registers (including the s registers) that are preserved across a call. In my understanding of this, one must stack all such registers and retrieve them later when we want access to them again.
However my question is if there was the trouble of going through this, why bother even using these registers? Is there a point of using these registers other than possibly running out of registers to use?

A: MIPS assembly has a calling convention which specifies that the t registers are caller saved, and the s registers are callee saved.
This means that if you call somebody else's function, say mine, you can gaurantee that the s registers will be the same in your  function after my function exits. You cannot gaurantee this for the t registers, which my function is free to overwrite.
When writing MIPS assembly you should always follow this convention.


text:
Q: Conflicting IF statements in Unity C# , Soccer Game I am a starter in Unity and developing a soccer game. I have a problem ,my IF statements conflict each other. Let me explain it in detail.
In order for a ball to stick to player, I have used IF operator, so whenever the distance between the player and the ball is less than < 0.5 , the ball sticks to player and move together with it. Now when I try to set up shooting the ball (I try with "addforce") it doesnt let me, cause the ball is still attached to player and distance is <0.5.
This one is the balls script.
public bool sticktoplayer;
public transform player;
//gameobject Player is attached
float distancetoplayer;
Rigidbody rb;
//balls rigidbody

void Awake ()
{
rb = getComponent<Rigidbody>();
}

void Update()
{
If (!sticktoplayer)
{
float distancetoplayer = Vector3.Distance (player.position, transform.position);
if(distancetoplayer < 0.5f)
{
sticktoplayer = true;
}
}
else
{
transform.position = player.position;
}

if(Input.GetKeyDown(KeyCode.Space))

{
rb.addforce(20, 0, 0, ForceMode.Impulse);
sticktoplayer = false;
}

When the player is not controlling the ball the force is succesfully applied to the ball, but when the ball is attached (distancetoplayer<0.5) then the other IF statements blocks it from shooting.
Maybe there are some work arounds ? Thanks.
I tried to make another if statement.

A: why dont you try sticking the ball to the player by collision? instead of checking the distance, create a collider with the radius or scale you desire and whenever the ball is inside the collider (when it triggers with the collider) stick it to the player. Because you will not be able to let the ball go since the ball will always be less then 0.5f away from the player once it sticks

A: have you tried it this way?
if(Input.GetKeyDown(KeyCode.Space))
{
 sticktoplayer = false;
 rb.addforce(20, 0, 0, ForceMode.Impulse);
}


text:
Q: Brightway2 - Get LCA scores of immediate exchanges I'm having some problems regarding the post-processing analysis of my LCA results from brightway2. After running a LCA calculation, if, for example, I type top_activities() I get a list of a bunch of activities and their associated scores, however none of the activities/scores are the ones associated directly with my functional unit (they appear to be some exchanges of my exchanges...).
How can I get the LCA scores of the exchanges (both technosphere and biosphere) I defined when constructing my Functional Unit?
Thanks!

A: I've found the best way to get aggregated results for your foreground model in brightway is using the bw2analyzer.traverse_tagged_databases() function rather than top_activities(). Details in the docs are here.
It's designed to calculate upstream impacts of the elements of your foreground model and then aggregate the impacts based on a tag it finds in the activity. e.g. if you add 'tag':'use phase' or 'tag':'processing' to your activities you can aggregate impact results by life cycle stage.
BUT you can change the default label it looks for, so instead of tag you can tell it to look for name - that'll give you the aggregated upstream impact of each of the activities in your foreground model. It returns a dictionary with the names of your tags as keys, and impacts as values. It also returns a graph of your foreground system which you can use to create some cool tree/bullseye charts - see the docs for the format.
Here's the function you need:
results, graph = recurse_tagged_databases(functional_unit, method, label='name')
Here are a couple of examples of the kinds of visualisations you can make using the data recurse_tagged_databases gives you:
Waterfall chart example from the results dictionary

Bullseye chart example from the tagged graph

A: It is pretty easy to traverse the supply chain manually, and everyone wants to do this a slightly different way, so it isn't built in to Brightway yet. Here is a simple example:
from brightway2 import *

func_unit = Database("ecoinvent 3.4 cutoff").random()

lca = LCA({func_unit: 1}, methods.random())
lca.lci()
lca.lcia()

print(func_unit)

for exc in func_unit.technosphere():
    lca.redo_lcia({exc.input: exc['amount']})
    print(exc.input, exc['amount'], lca.score)


text:
Q: godep vendor with docker I'm trying to run a docker container with vendor.
This is my Dockerfile
FROM golang:alpine
EXPOSE 8080

RUN mkdir /app
ADD . /app/
WORKDIR /app
RUN go build -o myapp .
CMD ["/app/myapp"]

and my main.go
package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {

    r := mux.NewRouter()
    r.HandleFunc("/", Hello)

    http.Handle("/", r)
    fmt.Println("Starting up on 8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func Hello(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello world!")
}

I'm using godep for vendoring libs, it's working in my local machine, but when i'm trying to run it with docker with :
docker build -t myapp-img .
docker run -p 8080:8080 --name myapp-cnt myapp-img

I have the following error :
main.go:8:2: cannot find package "github.com/gorilla/mux" in any of:
        /usr/local/go/src/github.com/gorilla/mux (from $GOROOT)
        /go/src/github.com/gorilla/mux (from $GOPATH)

I don't understand what is missing.

A: The error is correct.  It is telling you everything an aspiring Gopher needs.
I am going to assume that you have copied Gorilla Mux to your app's /vendor directory in your local machine, like so:
./main.go # this is your myapp code you are coping
./vendor/github.com/gorilla/mux # for vendoring, this must exist

If you want to learn more about vendoring, see my popular answer here:
How should I use vendor in Go 1.6?
Now, to fix that error assuming you have done the above...
A Gopher needs to set a valid $GOPATH before you can build.  This is missing from your Dockerfile.
FROM golang:1.7-alpine
EXPOSE 8080

# setup GOPATH and friends
#
# TECHNICALLY, you don't have to do these three cmds as the
# golang:alpine image actually uses this same directory structure and
# already has $GOPATH set to this same structure.  You could just
# remove these two lines and everything below should continue to work.
#
# But, I like to do it anyways to ensure my proper build
# path in case I experiment with different Docker build images or in
# case the #latest image changes structure (you should really use
# a tag to lock down what version of Go you are using - note that I
# locked you to the docker image golang:1.7-alpine above, since that is
# the current latest you were using, with bug fixes).
#
RUN  mkdir -p /go/src \
  && mkdir -p /go/bin \
  && mkdir -p /go/pkg
ENV GOPATH=/go
ENV PATH=$GOPATH/bin:$PATH

# now copy your app to the proper build path
RUN mkdir -p $GOPATH/src/app
ADD . $GOPATH/src/app

# should be able to build now
WORKDIR $GOPATH/src/app
RUN go build -o myapp .
CMD ["/go/src/app/myapp"]

Here it is working...
$ tree
.
├── Dockerfile
├── main.go
└── vendor
    └── mydep
        └── runme.go

The source file of my app:
$ cat main.go
package main

import (
        "fmt"

        "mydep"
)

func main() {
        fmt.Println(mydep.RunMe())
}

My dependency in my vendor/ folder:
$ cat vendor/mydep/runme.go
package mydep

// RunMe returns a string that it worked!
func RunMe() string {
        return "Dependency Worked!"
}

Now, build and run the image:
$ docker build --rm -t test . && docker run --rm -it test
(snip)
Step 8 : WORKDIR $GOPATH/src/app
 ---> Using cache
 ---> 954ed8e87ae0
Step 9 : RUN go build -o myapp .
 ---> Using cache
 ---> b4b613f0a939
Step 10 : CMD /go/src/app/myapp
 ---> Using cache
 ---> 3524025080df
Successfully built 3524025080df
Dependency Worked!

Note the last line that prints the output from console, Dependency Worked!.
It works because:

*

*you stated you are using Vendoring, which means you have a local directory called ./vendor in the root of your application code.

*when you ADD . /go/src/app, you are also copying the ./vendor local to your application code.

*you have copied your files into the proper $GOPATH setup structure required by the Go build tools to find packages (and in this case, the ./vendor directory within your source code's root folder).


text:
Q: Hide column while exporting to excel from html table using javascript I have a html table which I have to export to excel , but while doing so, I dont want some of the td elements to be exported. When I apply javascript to hide the td, the changes are being applied only to the view form and not to the the content being exported.
Need help in how to export in this case.
I have included html, css and script all in one page.

                LOB

    <input type="button" id="btnExport"  value="Export" onclick="TableToExcel('metrics');" />

Here I want to hide the td which contains span class "hillbillyForm"
The javascript That I am using is

    function TableToExcel(tableid) {

        var id = $('[id$="' + tableid + '"]');
        var $clonedTable = $("id").clone();
        $clonedTable.find('[style = "display: none"]').remove();
        var strCopy = $('

').html(id.clone()).html();

        window.clipboardData.setData("Text", strCopy);

        var objExcel = new ActiveXObject("Excel.Application");

        objExcel.visible = false; var objWorkbook = objExcel.Workbooks.Add; var objWorksheet = objWorkbook.Worksheets(1); objWorksheet.Paste; objExcel.visible = true;
    }
</script>

A: So what I'm understanding is that you want to remove all TD's which have a direct child with the class hillbillyForm.
You can do something like this:
var form = document.getElementById(tableid),
    exportForm = form.cloneNode(true),
    elementsToRemove = exportForm.querySelectorAll('.hillbillyForm');

for (var i = elementsToRemove.length; i--;){
    var td = elementsToRemove[i].parentElement;
    if (td) td.parentElement.removeChild(td);
}

jsFiddle


text:
Q: Finding something in the TeX document from the PDF I am compiling a PDF (Adobe) using LaTeX (TexWorks) so I have the text document on one side of the screen and the PDF on the other, is there any way to select something on the PDF and it to find that text/command in the TeX document? I know that I could just highlight it and search the TeX document but if it is some symbol then this won't really work.

A: As David Carlisle pointed out, you want synctex in TeXworks for this to work.
If you are on Mac OS you can ⌘-Click (Ctrl-click on other OS's) anywhere in the TeXworks source file or the output and you will be moved to the corresponding point in the other document.


text:
Q: How to check if canvas was updated with Fabric.JS? I am currently working on Auto Save module and I have to perform Auto Save process only if any changes made on canvas So, How can I identify the changes?
I have reach two approaches:

*

*By comparing json

*

*For example, when canvas load then I'll store blank canvas json of default atrributes in a variable and if any object/element is added/modified/removed in canvas then I'll update the canvas json and then compare updated canvas json with stored canvas json from variable.

*Through fabric.js canvas events

*

*For example, If any event is called of fabric.js

I didn't get any idea that which one is better approach or if there is a better way to detect canvas changes.
Can anyone help me please? It would really be appreciated.
Thanks.


text:
Q: how to solve Express.js 404 status? I'm quite new for node.js and express.js.
I'm trying to create a login form using MERN.
when I try to access register route I always jumping to 404 status I don't understand what's wrong with my code please help me on this. I'm following this youtube tutorial -- https://www.youtube.com/watch?v=y7yFXKsMD_U&t=35s
testing these codes using POSTMAN please refer below screenshot.
[![enter image description here][1]][1]
server.js | File
const express = require("express");
const morgon = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

require("dotenv").config({
  path: "./config/config.env",
});

app.use(bodyParser.json());

if (process.env.NODE_ENV === "development") {
  app.use(
    cors({
      origin: process.env.CLIENT_URL
    })
  );

  app.use(morgon("dev"));
}

// Load all routes
const authRouter = require("./routers/auth.route");

// use routes
app.use("/api/", authRouter);

app.use((req, res, next) => {
  res.status(404).json({
    success: false,
    message: "Page Not Founded",
  });
});

const PORT = process.env.PORT;

app.listen(PORT, () => {
  console.log(`App PORT up on port ${PORT}`);
});

config.env | File
PORT = 5000
NODE_ENV = development
CLIENT_URL = http://localhost:3000

auth.route.js | Route File
const express = require("express");

const router = express.Router();

// Load register Controller
const { registerController } = require("../controller/auth.controller.js");

// register Router path
router.post("register", registerController);

module.exports = router;

auth.controller.js | Controller File
exports.registerController = (req, res) => {
    const {name, email, password} = req.body
    console.log(name, email, password)
}

A: In your router path, you need a / in your register route.
router.post("/register", registerController);
You also do not need a trailing slash in your API route.
app.use("/api", authRouter);


text:
Q: Integer sequence that "fills a range in a balanced way" I am writing a piece of software to generate musical sequences, and I would like a way to slowly introduce notes in a chord in a balanced way across the range of the chord. I want it to be more interesting and sonically balanced than top to bottom, or stepwise.
I am looking for a sequence that subdivides a range of integers recursively.
For example, something similar to, or the same as:
For the range 1-8, generate the sequence: 4,8,2,6,3,7,1,5.
For 1-7, generate the sequence: 3,7,1,5,2,6,4
For 1-6, generate the sequence: 3,6,1,4,2,5
For 1-32: 16,32,8,24,12,28,4,20,14,30,6,22,10,26,2,18,15,31,7,23,11,27,3,19,13,29,5,21,9,25,1,17
This sequence cuts the range in half (rounding down) and records the maximum of each subdivision. It repeats, visiting the subdivisions in a balanced way.  An important detail is that it doesn't just visit the subdivisions in a linear way (left to right), but in some form of symmetrical hopping.
Are there any functions or algorithms that are similar to this?


text:
Q: Can K-Means be used to find colour clusters Can K-Means be used to find colour clusters? My objective is to find the most common colours (HSV colour space) that occur in an image.
Can I give the function kmeans() a comparison function to determine 2 colours distance between each other? Ie;
int sameColour(const Vec3b& color1, const Vec3b& color2)
{
    return (abs(color1[0] - color2[0]) +
        abs(color1[1] - color2[1]) +
        abs(color1[2] - color2[2])) < 30;
}

This way I get the 'general' colour clusters in an image.


text:
Q: Avoid cache issues for web application with iframe We have a web application (a single page app backed by a REST API) that is mainly used on smart phones. Users are encouraged to create a homescreen icon so that they have easy access and a full screen experience. This worked fine until we decided to release a new version of our application. Some browsers are caching the old version and refuse to refresh the application, even when the user forces a reload.
This is a serious problem when the REST API is upgraded but the browser is still using an outdated version of the web app. We do need the browser to cache things whenever possible, but we also want a reload when a new version has been released.
Now we are considering to use an iframe to fix this problem. We created an index.html that contains an iframe and a small piece of Javascript that does an XMLHttpRequest to the REST-server to figure out the current version. This version is then used to set the src-attibute of the iframe so that the iframe is loaded with the current version of our web application.
The solution seems to work but I was wondering if there isn't a better solution to this problem. Is it acceptable to use an iframe to solve this problem or will it cause other problems (on some browsers/devices)?
Edit: We can't use server side scripting, so auto-versioning is not a solution for us.

A: Posting the solution to my own question. The index.html looks like this:

<html>
<head>
 <style>
  body {
   margin: 0px;
  }

  iframe {
   overflow: hidden;
   height: 100vh;
   width: 100vw;
   border: none;
  }
 </style>
</head>
<body>

 <iframe id="content"></iframe>

 <script>
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
    var src = xmlHttp.responseText + "/index.html";
    document.getElementById("content").setAttribute("src", src);
   }
  }
  xmlHttp.open("GET", "current-version", true);
  xmlHttp.send(null);
 </script>
</body>
</html>

The file current-version contains the directory name of the current version (like v1.0) and the actual web application resides in that directory.
Even though it feels a bit hackish, this solution does what we need. When we release a new version, we simply put it in a new directory (like v1.1) and change the contents of current-version accordingly.
EDIT
We finally decided to build native wrappers around our web-application. It's a bit more work but gives us full control over the app and the caching behaviour. Besides that, it's much easier to tell people to install the app from the app store than to explain how to create a homescreen icon.

A: You would not be needing an iFrame.
You can achieve it through javascript.
Create a XMLHttpRequest as you are doing from the iframe.
Whenever you request for the image by calling the REST API through the XMLHttpRequest, add a query String parameter in the request url whose value is going to be a random number. Should solve your caching issues.
Example, something like this,
var url = yourexistingurl  + "&randomid=" + Math.random();

Again, I don't know how your REST API is designed, but doing this might not be an issue.


text:
Q: Swift UIDocumentPicker selected document upload into AWS S3 I have done UIDocumentPicker to pick some documents (.pdf,audio or video, etc) and printing the URL path. Now, I don't know how to upload the file in AWS S3 but based on AWS document I have done proper AWS configuration SDK installation within my code.
Now, I have two separate pease of code for pick the document and upload AWS but I don't know how to merge it both.
Here below my code
// File Storage Access
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL)
{
    let myURL = url as URL
    print(myURL)
    print("import result : \(myURL)")
    print(url.lastPathComponent)
    print(url.pathExtension)

    let filename = url.lastPathComponent
    myFiles.append(filename)
    tableView.reloadData()
}

public func documentMenu(
    _ documentMenu: UIDocumentPickerViewController,
    didPickDocumentPicker documentPicker: UIDocumentPickerViewController
) {
    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
}

func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    print("view was cancelled")
    dismiss(animated: true, completion: nil)
}

AWS Upload file code:
func uploadImage(with data: Data) {
    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = progressBlock

    transferUtility.uploadData(
        data,
        bucket: S3BucketName,
        key: S3UploadKeyName,
        contentType: "image/png",
        expression: expression,
        completionHandler: completionHandler
    ).continueWith { (task) -> AnyObject? in
        if let error = task.error {
            print("Error: \(error.localizedDescription)")

            DispatchQueue.main.async {
                //cell.statusLabel.text = "Failed"
            }
        }

        if let _ = task.result {

            DispatchQueue.main.async {
                //cell.statusLabel.text = "Generating Upload File"
                print("Upload Starting!")
            }

            // Do something with uploadTask.
        }

        return nil
    }
}


text:
Q: preceding-sibling [1] is not last I want to thank's to this community for helping me so much lately. You are my saviours :)
I'm trying to verify when a number (x) is different from the previous one
So my list was sorted, first I have:
<xsl:apply-templates select="house">
    <xsl:sort select="./point/x"/>
</xsl:apply-templates>

the important part is:
<xsl:template match="house">

    <xsl:if test="./point/x != preceding-sibling::house[1]/point/x">

        <xsl:value-of select="preceding-sibling::house[1]/point/x"/>
             value changed to <xsl:value-of select="./point/x"/>
    </xsl:if>

    <xsl:value-of select="./point/x"/>
    <xsl:value-of select="./point/y"/>

</xsl:template>

Note I have 2 values in print, x and y, but Im only working with x
I want output to be something like:
xy
00
01
0 value change to 1

10
11
somehow my result goes get the wrong previous number
00
1 value change to 0
01
0 value change to 1
10
0 value change to 1
11
Progress:
I found out that by removing the sort the output is correct
00
0 value change to 1
10
1 value change to 0
01
0 value change to 1
11
So my question now is... how can I do this procedure?

A: Not very nice, but if you must know "the previous value of x according to a certain order", then you must order the nodes again and fetch the right one:
<xsl:template match="house">
    <xsl:variable name="current-position" select="position()" />
    <xsl:variable name="preceding-x-ordered">
      <xsl:for-each select="../house">
        <xsl:sort select="point/x" />
        <xsl:if test="position() = $current-position - 1">
          <xsl:value-of select="point/x" />
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>

    <xsl:if test="position() > 1 and point/x != $preceding-x-ordered">

        <xsl:value-of select="$preceding-x-ordered"/>
        <xsl:text> value changed to </xsl:text>
        <xsl:value-of select="point/x"/>
    </xsl:if>

    <xsl:value-of select="point/x"/>
    <xsl:value-of select="point/y"/>
</xsl:template>

XSLT is supposed to be side-effects free, which means that the processor can process templates in any order it wishes without changing the overall result. Not "knowing" what it did in the last iteration of a loop is a consequence of that requirement. Hence there is no way that the preceding-sibling axis can know what node was processed earlier.

A: Here is a much more efficient (linear vs O(N^2*log(N)) XSLT 1.0 solution:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:key name="kHouseById" match="house" use="generate-id()"/>

 <xsl:variable name="vIdsOfSorted">
  <xsl:for-each select="/*/house">
    <xsl:sort select="point/x" data-type="number"/>
    <xsl:copy-of select="concat(generate-id(), ' ')"/>
  </xsl:for-each>
 </xsl:variable>

 <xsl:template match="/*">
  <xsl:call-template name="traverseIds">
   <xsl:with-param name="pIds" select="concat($vIdsOfSorted, ' ')"/>
   <xsl:with-param name="pLength" select="count(house)"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="traverseIds">
   <xsl:param name="pIds"/>
   <xsl:param name="pLength"/>
   <xsl:param name="pPos" select="1"/>
   <xsl:param name="pPrevId" select="''"/>

   <xsl:if test="not($pPos > $pLength)">
     <xsl:variable name="vId" select="substring-before($pIds, ' ')"/>
     <xsl:variable name="vHouse" select="key('kHouseById', $vId)"/>

     <xsl:value-of select=
      "concat('
(', $vHouse/point/x, ',', $vHouse/point/y, ')')"/>
       <xsl:if test="not($pPos >= $pLength)">
        <xsl:variable name="vNextId" select=
         "substring-before(substring-after($pIds, ' '), ' ')"/>

        <xsl:variable name="vNextHouse" select="key('kHouseById', $vNextId)"/>

        <xsl:if test="not($vHouse/point/x = $vNextHouse/point/x)">
         <xsl:value-of select=
           "concat('
value changed to ', $vNextHouse/point/x)"/>
        </xsl:if>

        <xsl:call-template name="traverseIds">
          <xsl:with-param name="pIds" select="substring-after($pIds, ' ')"/>
          <xsl:with-param name="pLength" select="$pLength"/>
                <xsl:with-param name="pPos" select="$pPos+1"/>
                <xsl:with-param name="pPrevId" select="$vId"/>
        </xsl:call-template>
       </xsl:if>
     </xsl:if>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:
<t>
  <house>
    <point>
      <x>1</x><y>0</y>
    </point>
  </house>
  <house>
    <point>
      <x>0</x><y>1</y>
    </point>
  </house>
  <house>
    <point>
      <x>0</x><y>0</y>
    </point>
  </house>
  <house>
    <point>
      <x>1</x><y>1</y>
    </point>
  </house>
</t>

the wanted, correct result is produced:
(0,1)
(0,0)
value changed to 1
(1,0)
(1,1)

In case you don't love recursion, here is a non-recursive XSLT 1.0 solution that uses the xxx:node-set() extension function:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common">
 <xsl:output method="text"/>
 <xsl:variable name="vrtfSorted">
        <xsl:for-each select="/*/house">
            <xsl:sort select="point/x" data-type="number"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
 </xsl:variable>

 <xsl:variable name="vSorted" select="ext:node-set($vrtfSorted)/*"/>

    <xsl:template match="/*">
        <xsl:for-each select="$vSorted">
            <xsl:variable name="vPos" select="position()"/>
            <xsl:if test=
              "$vPos > 1
             and
               not(point/x = $vSorted[position()=$vPos -1]/point/x)">
                <xsl:text>
</xsl:text>
                <xsl:value-of select="concat('value changed to ', point/x)"/>
            </xsl:if>
            <xsl:text>
</xsl:text>
            <xsl:value-of select="concat('(',point/x,',',point/y, ')')"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

produces exactly the same, correct result.

II. XSLT 2.0 solution
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output method="text"/>

 <xsl:template match="/*">
  <xsl:variable name="vSorted">
   <xsl:perform-sort select="house">
     <xsl:sort select="xs:integer(point/x)"/>
   </xsl:perform-sort>
  </xsl:variable>

  <xsl:sequence select=
   "(for $n   in 2 to count($vSorted/*),
        $n-1 in $n -1,
        $vNewX in $vSorted/*[$n]/point/x,
        $vOldX in $vSorted/*[$n-1]/point/x,
        $vNewY in $vSorted/*[$n]/point/y,
        $vOldY in $vSorted/*[$n-1]/point/y,
        $remark in
              if($vNewX ne $vOldX)
                then concat('
value changed to ', $vNewX, '
')
                else '
'
     return
       concat('(',$vOldX,',',$vOldY, ')', $remark)
     ),
     concat('(',$vSorted/*[last()]/point/x,',',
                $vSorted/*[last()]/point/y, ')'
            )
   "/>
 </xsl:template>
</xsl:stylesheet>

When applied to the same XML document (above), the same correct result is produced:
 (0,1)
 (0,0)
value changed to 1
 (1,0)
 (1,1)

A: Here is an alternate approach. You might want to think in terms of groups. As you have tagged the question xslt 2.0, this does come with some useful grouping functions (In xslt 1.0 you would have to make use of the Meunchian Grouping technique)
Effectively you are grouping houses by the point/x value, so you get each distinct group like so:
<xsl:for-each-group select="house" group-by="point/x">
   <xsl:sort select="point/x"/>

Then you could iterate over the houses within the group like so:
<xsl:for-each select="current-group()">
    <xsl:sort select="point/y"/>

Here is the full XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output method="text"/>

   <xsl:template match="houses">
      <xsl:text>xy
</xsl:text>
      <xsl:for-each-group select="house" group-by="point/x">
         <xsl:sort select="point/x"/>
         <xsl:if test="position() > 1">
            <xsl:value-of select="concat(' value changed to ', point/x, '
')" />
         </xsl:if>
         <xsl:for-each select="current-group()">
            <xsl:sort select="point/y"/>
            <xsl:value-of select="concat(point/x, point/y, '
')" />
         </xsl:for-each>
         <xsl:if test="position() < last()">
            <xsl:value-of select="point/x" />
         </xsl:if>
      </xsl:for-each-group>
   </xsl:template>
</xsl:stylesheet>

When applied to the following XML....
<houses>
    <house><point><x>1</x><y>0</y></point></house>
    <house><point><x>2</x><y>1</y></point></house>
    <house><point><x>0</x><y>1</y></point></house>
    <house><point><x>1</x><y>1</y></point></house>
    <house><point><x>0</x><y>0</y></point></house>
    <house><point><x>2</x><y>0</y></point></house>
</houses>

The following is output:
xy
00
01
0 value changed to 1
10
11
1 value changed to 2
20
21


text:
Q: PowerShell: calculate delta between successive values of the rawvalue property for each counter 'evening,
I'm brand new at PowerShell scripting (and to this site) and need to write a script that:

*

*gathers performance counters (in this case, TCP) several times

*calculates the difference between successive values of the rawvalue property of each counter

Stipulating that every interval T the script iterates through the performance counters N times, and said performance counters are "A" and "B", and we're counting from 0, it needs to perform the following calculations:
A[1st] - A[0th],
A[2nd] - A[1st],
A[3rd] - A[2nd]
...

At present, the script only iterates through the counters, twice (i.e. N = 2 in this case). The goal is to be able to be able to iterate through these counters "many" (e.g. a couple hundred) times.
Currently the script reads the raw value of each counter into a single array. Here it is:
$cntr = (get-counter -listset tcpv4).paths
$arry = @()

for ($i=0; $i -lt 2; $i++) {
    write-host "`nThis is iteration $i`n"
    foreach ($elmt in $cntr) {
        $z = (get-counter -counter $elmt).countersamples[0].rawvalue
        $arry = $arry + $z
        write-host "$elmt is: $z`n"
    }
}

When I run this script, I get output just like the following:
This is iteration 0

\TCPv4\Segments/sec is: 24723

\TCPv4\Connections Established is: 27

\TCPv4\Connections Active is: 796

\TCPv4\Connections Passive is: 47

\TCPv4\Connection Failures is: 158

\TCPv4\Connections Reset is: 412

\TCPv4\Segments Received/sec is: 14902

\TCPv4\Segments Sent/sec is: 9822

\TCPv4\Segments Retransmitted/sec is: 199

This is iteration 1

\TCPv4\Segments/sec is: 24727

\TCPv4\Connections Established is: 27

\TCPv4\Connections Active is: 798

\TCPv4\Connections Passive is: 47

\TCPv4\Connection Failures is: 159

\TCPv4\Connections Reset is: 412

\TCPv4\Segments Received/sec is: 14903

\TCPv4\Segments Sent/sec is: 9824

\TCPv4\Segments Retransmitted/sec is: 200

e.g. The two values for the rawvalue property for the "\TCPv4\Segments Retransmitted/sec" counter are $arry[8] and $arry[17] respectively. To derive the difference between the two I'm using:
write-host "The difference between the successive counters for $($cntr[-1]) is $($($arry[17]) - $($arry[8]))."

Any help would be greatly appreciated.

A: I poked at it some, and this fell out:
$cntr = (get-counter -listset tcpv4).paths
$LastValue = @{}

Get-Counter $cntr -SampleInterval 2 -MaxSamples 5 |
foreach {
  foreach ($Sample in $_.CounterSamples)
   {
     $ht = [Ordered]@{
        Counter   = $Sample.path.split('\')[-1]
        TimeStamp = $_.TimeStamp
        RawValue  = $Sample.RawValue
        LastValue = $LastValue[$Sample.Path]
        Change    = $Sample.RawValue - $LastValue[$Sample.Path]
        }
     if ($LastValue.ContainsKey($Sample.path))
       { [PSCustomObject]$ht }
     $LastValue[$Sample.Path] = $Sample.RawValue
   }
 }

Edit:
This should work on V2:
$cntr = (get-counter -listset tcpv4).paths
$LastValue = @{}

Get-Counter $cntr -SampleInterval 10 -MaxSamples 3 |
foreach {
  foreach ($Sample in $_.CounterSamples)
   {
     $Object = '' |
      Select-Object Counter,TimeStamp,RawValue,LastValue,Change
      $Object.Counter   = $Sample.path.split('\')[-1]
      $Object.TimeStamp = $_.TimeStamp
      $Object.RawValue  = $Sample.RawValue
      $Object.LastValue = $LastValue[$Sample.Path]
      $Object.Change    = $Sample.RawValue - $LastValue[$Sample.Path]

     if ($LastValue.ContainsKey($Sample.path))
       { $Object }

     $LastValue[$Sample.Path] = $Sample.RawValue
   }
 }

A: Ok. Well lets work with this then
$cntr = (get-counter -listset tcpv4).paths
$arry = @()
$maximumIterations = 2  # Variable based since you intended to change this.

# Cycle the counters while recording the values. Once completed we will calculate change.
for ($i=1; $i -le $maximumIterations; $i++) {
    foreach ($elmt in $cntr) {
        $arry += New-Object -TypeName PsCustomObject -Property @{
            Iteration = $i
            Counter = $elmt
            RawValue = (get-counter -counter $elmt).countersamples[0].rawvalue
            Change = $null
        }
    }
}

# Now that we have all the values lets calculate the rate of change over each iteration.
$arry | Where-Object{$_.Iteration -gt 1} | ForEach-Object{
    $previousIteration = $_.Iteration - 1
    $thisCounter = $_.Counter
    $thisValue = $_.RawValue
    $previousValue = ($arry | Where-Object{$_.Counter -eq $thisCounter -and $_.Iteration -eq $previousIteration}).RawValue
    $_.Change = $thisValue - $previousValue
}

$arry | Select Iteration,Counter,RawValue,Change

Not that we have to but I collected all of the counters data along with their iteration value like you were putting against Write-Host. You will notice that I create a placeholder for Change but do not populate it. Before the calculations $arry would have data like the following. Note: the output is truncated
Iteration Change Counter                           RawValue
--------- ------ -------                           --------
        1        \TCPv4\Segments/sec               28324837
        1        \TCPv4\Connections Established         120
        .        ..............................       .....
        2        \TCPv4\Segments/sec               28325441
        2        \TCPv4\Connections Established         125

Once all of that data is collected into $arry we get all the iterations that are not the first and process each item individually. Using the data of the current item in the pipeline we match it up with the previous iterations value. Using the same values as above we get the changes you were hoping to monitor
Iteration Counter                           RawValue Change
--------- -------                           -------- ------
        1 \TCPv4\Segments/sec               28324837
        1 \TCPv4\Connections Established         120
        . ..............................       .....
        2 \TCPv4\Segments/sec               28325441 604
        2 \TCPv4\Connections Established         125 5


text:
Q: Resolve domain names in QEMU VDE setup I have re-built QEMU with VDE support. For the uninitiated, VDE attaches a virtual switch program (vde_switch) to a TAP device which allows multiple VDE-enabled programs to utilize a single TAP device.
My ultimate goal here is to be able to resolve my virtual machines by hostname such as "test1.qemu" "machineb.qemu", etc from my host -- this will ease configuration for me in many circumstances since I use DHCP via dnsmasq on the TAP interfaces.
Really this is probably a matter of not fully understanding how name resolution works, so I'm hoping to learn something out of this =)
Firstly, my dnsmasq configuration file:
user=nobody
interface=tap0
except-interface=lo
listen-address=192.168.1.1
#Assign IP's 192.168.1.2-192.168.1.253 for 8 hrs
dhcp-range=192.168.1.2,192.168.1.253,255.255.255.0,192.168.1.255,8h
pid-file=/var/run/dnsmasq_tap0.pid
dhcp-leasefile=/var/lib/misc/dnsmasq.vde.leases
domain=qemu
server=/qemu/
#Only really run on tap0, needed so there is no confliction with
#NetworkManager's dnsmasq
bind-interfaces
dhcp-authoritative
dhcp-no-override
strict-order

As you can see, I have configured dnsmasq to answer for "*.qemu" names. I can ping 192.168.1.1 properly, but as is stands, 'ping qemu' doesn't work. I assumed this was because my host machine didn't know how to resolve 'qemu', so I added it to the /etc/hosts file. Though, I'm not sure this is the proper way to do this. Of course, after adding the entry to /etc/hosts, qemu resolves but not i386.qemu (one of my VM's).
I guess a good starting point would be: how do I tell my machine to forward all *.qemu requests to the dnsmasq running on 192.168.1.1 (local interface tap0)?
Also, if it's any help, here is my /etc/network/interfaces entry for tap0:
auto tap0
iface tap0 inet static
    address 192.168.1.1
    netmask 255.255.255.0
    vde2-switch -
    pre-up /sbin/sysctl net.ipv4.ip_forward=1
    pre-up /sbin/iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
    up /usr/sbin/dnsmasq -C /etc/dnsmasq.d/vde-network --pid-file=/var/run/dnsmasq_tap0.pid --bind-interfaces
    post-down /bin/bash -c "kill -9 $(cat /var/run/dnsmasq_tap0.pid)"
    post-down /sbin/sysctl net.ipv4.ip_forward=0
    post-down /sbin/iptables -t nat -D POSTROUTING -o wlan0 -j MASQUERADE

A: So, I figured out the answer, and it was a bit of a facepalm moment.
I had a file called /etc/NetworkManager/dnsmasq.d/qemu which contained an incorrect DNS IP for my qemu dnsmasq instance (192.168.100.1 rather than 192.168.1.1). So, I think what was happening was that when I queried qemu, the default NetworkManager instance of netmask attempted to pass the query to 192.168.100.1 which didn't work for obvious reasons.
Once I changed the address to 192.168.1.1 in the config file and restarted NetworkManager (and thus its instance of dnamasq), everything works great! The /etc/hosts entry was not required as I had thought.
Now I just have to figure out how to resolve my VM host's hostname to my LAN address within my VM's rather than returning 127.0.1.1 which is incorrect from my VMs' perspective.


text:
Q: whats the difference between cloning and extending backbone events object? after a tutorial I've followed recently,  I've been using the following for custom events in my very small backbone app..
window.vent = _.extend({}, Backbone.Events);

which is mirrored in backbone documentation, http://backbonejs.org/#Events
the documentation then goes on to state,

For example, to make a handy event dispatcher that can coordinate
  events among different areas of your application: var dispatcher =
  _.clone(Backbone.Events)

this is maybe a newb question but what exactly is an event dispatcher?, and how is extending or cloning the events object different ?
EDIT: I've read that cloning performs only a shallow copy passing the existing values by reference, but to be honest I'm not entirely clear what that means.

A: Well cloning (http://underscorejs.org/#clone) creates a shallow copy of the object, but extending (http://underscorejs.org/#extend) takes all properties from the second object, puts them in the first, and returns the first object.
In other words, when you clone you start with 1 object and finish with 2, when you extend you start and finish with 2 objects (but the extended objects will have all of the second object's properties in addition to the ones it had before extension).
An event dispatcher allows for a pub sub pattern (http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern): some bits of the application "announce" things, and other bits of the app can listen and respond to them.


text:
Q: Undeclared identifier for nested types from ancestor I don't understand why the descendant class TChild can't see the ancestor nested type TLNested and the compiler still reports an error that it cannot find it.

E2003 Undeclared identifier: 'TLNested'

The original simplified hierarchy looks like this.
  TAncestor = class abstract
  public
    type
      TLNested = class
      end;
  strict protected
    procedure DoSometing(AParam: TLNested); virtual; abstract;
  end;

  TChild = class(TAncestor)
  strict protected
    procedure DoSometing(AParam: TLNested); override;
  end;

Unfortunately, even if I simplify it even more, it still doesn't work. Does anyone know what I'm missing?
  TAncestor = class
  public
    type
      TLNested = class
      end;
  end;

  TChild = class(TAncestor)
  public
    procedure DoSometing(AParam: TLNested);
  end;

A: You need to use fully qualified name.
  TChild = class(TAncestor)
  public
    procedure DoSometing(AParam: TAncestor.TLNested);
  end;


text:
Q: Flutter Textfield in separate widget onChanged: (value) {if (value.length == 2) focus.requestFocus(nextFocusNode);} does not work I try to make a separate TextField widget to use repeatedly. Because there is a lot of code that I would otherwise duplicate
And I want to make the cursor jump to the next TextField when there are 2 numbers in onchanged. So I use the value to see whether there are already 2 numbers inputted. And I use context to focus on the next focus node.
It works if I put it in te same widget, but when I extract the widget. It won't work.
Could you please help me?
Is it possible?
import 'package:flutter/material.dart';
import 'package:careapp/widgets/layout/time_input.dart';

class newInput extends StatefulWidget {
  const newInput({Key? key}) : super(key: key);

  @override
  _newInputState createState() => _newInputState();
}

class _newInputState extends State<newInput> {
  final hoursController = TextEditingController();
  final minutesController = TextEditingController();

  final nextFocusNode = FocusNode();

  @override
  void dispose() {
    hoursController.dispose();
    minutesController.dispose();
    nextFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final focus = FocusScope.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Add input'),
        actions: [
          IconButton(
            onPressed: _addEvent,
            icon: Icon(Icons.save),
          ),
        ],
      ),
      body: Card(
        elevation: 6,
        child: Container(
          padding: EdgeInsets.only(top: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                //height: 100,
                padding: EdgeInsets.symmetric(
                  horizontal: 15,
                  vertical: 20,
                ),
                child: Row(
                  children: [
                    Container(
                      child: Text('Time:'),
                    ),
                    timeInput(
                      labelText: 'Hour',
                      onSubmitted: () {},
                      controller: hoursController,
                      onChanged: (value) {
                        if (value.length == 2)
                          focus.requestFocus(nextFocusNode);
                      },
                      //textInputAction: TextInputAction.next,
                      // onEditingComplete: () => focus.nextFocus(),
                    ),
                    Container(
                      child: Text(
                        ':',
                        style: TextStyle(
                          fontSize: 20,
                          //fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    timeInput(
                      labelText: 'Min',
                      onSubmitted: () {},
                      controller: minutesController,
                      focusNode: nextFocusNode,
                    ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ElevatedButton(
                    onPressed: () {},
                    child: Text('Add Event'),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

import 'package:flutter/material.dart';

class timeInput extends StatelessWidget {
  final String labelText;
  final VoidCallback onSubmitted;
  final Function? onChanged;
  final VoidCallback? onEditingComplete;
  FocusNode? focusNode;
  final TextInputAction textInputAction;
  final TextEditingController controller;
  // final String lastname;
  // final String birthday;
  // final String id;

  timeInput(
      {required this.labelText,
      required this.onSubmitted,
      this.focusNode,
      this.textInputAction = TextInputAction.done,
      this.onChanged,
      this.onEditingComplete = _onEditingComplete,
      required this.controller});

  static _onEditingComplete() {}

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Container(
        padding: EdgeInsets.all(10),
        height: 50,
        width: 70,
        child: TextField(
          // onChanged: (_) => onChanged!(),
          onChanged: (_) => onChanged!(),
          textInputAction: textInputAction,
          // onEditingComplete: onEditingComplete,
          maxLength: 2,
          //style: ,
          decoration: InputDecoration(
            //labelText: 'Uur',
            labelText: labelText,
            border: OutlineInputBorder(),
            counterText: '',
          ),
          controller: controller,
          keyboardType: TextInputType.numberWithOptions(decimal: false),
          onSubmitted: (_) =>
              onSubmitted(), //You must add an input but underscore indicates that you are not using it
          // onChanged: (val) => amountInput = val,
        ),
      ),
    );
  }
}

A: please try this
import 'package:flutter/material.dart';
import 'package:careapp/widgets/layout/time_input.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

class newInput extends StatefulWidget {
  const newInput({Key? key}) : super(key: key);

  @override
  _newInputState createState() => _newInputState();
}

class _newInputState extends State<newInput> {
  final hoursController = TextEditingController();
  final minutesController = TextEditingController();

  final nextFocusNode = FocusNode();

  @override
  void dispose() {
    hoursController.dispose();
    minutesController.dispose();
    nextFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final focus = FocusScope.of(context);

    return Scaffold(
        appBar: AppBar(
          title: Text('Add input'),
          actions: [
            IconButton(
              onPressed: (){
              },
              icon: Icon(Icons.save),
            ),
          ],
        ),
        body: Card(
            elevation: 6,
            child: Container(
              padding: EdgeInsets.only(top: 15),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      //height: 100,
                      padding: EdgeInsets.symmetric(
                        horizontal: 15,
                        vertical: 20,
                      ),
                      child: Row(
                        children: [
                          Container(
                            child: Text('Time:'),
                          ),
                          timeInput(
                            labelText: 'Hour',
                            onSubmitted: () {},
                            controller: hoursController,
                            onChanged: (v) {
                              if (v.length == 2){
                                print("ok");
                                FocusScope.of(context).nextFocus();
                              }
                              //focus.requestFocus(nextFocusNode);
                            },
                            //textInputAction: TextInputAction.next,
                          ),
                          Container(
                            child: Text(':',
                              style: TextStyle(
                                fontSize: 20,
                                //fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          timeInput(
                            labelText: 'Min',
                            onSubmitted: () {},
                            controller: minutesController,
                            focusNode: nextFocusNode,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              ElevatedButton(
                                onPressed: () {},
                                child: Text('Add Event'),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  ]),
            )
        )
    );
  }
}

class timeInput extends StatelessWidget {
  final String labelText;
  final VoidCallback onSubmitted;
  final  Function? onChanged;
  final VoidCallback? onEditingComplete;
  FocusNode? focusNode;
  final TextInputAction textInputAction;
  final TextEditingController controller;
  // final String lastname;
  // final String birthday;
  // final String id;

  timeInput(
      {required this.labelText,
        required this.onSubmitted,
        this.focusNode,
        this.textInputAction = TextInputAction.done,
        this.onChanged,
        this.onEditingComplete = _onEditingComplete,
        required this.controller});

  static _onEditingComplete() {}

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Container(
        padding: EdgeInsets.all(10),
        height: 50,
        width: 70,
        child: TextField(
          // onChanged: (_) => onChanged!(),
          onChanged: (v)=>onChanged!(v),
          textInputAction: textInputAction,
          // onEditingComplete: onEditingComplete,
          maxLength: 2,
          //style: ,
          decoration: InputDecoration(
            //labelText: 'Uur',
            labelText: labelText,
            border: OutlineInputBorder(),
            counterText: '',
          ),
          controller: controller,
          keyboardType: TextInputType.numberWithOptions(decimal: false),
          onSubmitted: (_) =>
              onSubmitted(), //You must add an input but underscore indicates that you are not using it
          // onChanged: (val) => amountInput = val,
        ),
      ),
    );
  }
}


text:
Q: Correct syntax for setUp function for JSTestDriver Eclipse Juno Service Release 1
Example of a working Unit Test ...
InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.test01 = function()
{
    var ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
    assertTrue(ir.isInRange(0.3));
};

But, to do more than one test I believe I should be using setUp. Unless I am mistaken, the advantage of setUp is that I would not have to instantiate var ir in every unit test. So, I tried the following ...
InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.setUp = function()
{
    var ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
};

InRangeTest.prototype.test01 = function()
{
    assertTrue(ir.isInRange(0.3));
};

Only, I get the error message

ReferenceError: ir is not defined

Replacing var ir with this.ir did not get it working.
What's wrong?
Thanks for any help in advance.

A: If you use this.ir in both functions it should work:
InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.setUp = function()
{
    this.ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
};

InRangeTest.prototype.test01 = function()
{
    assertTrue(this.ir.isInRange(0.3));
};


text:
Q: What happens if a monitor's refresh rate is different to X's refresh rate? I have a dual-screen system running on CentOS Linux using two industrial grade LCD touch screens. I currently have the following line set in my xorg.conf under the "Display" subsection of the Screen section:

Modes     "1280x1024_60.00"

The Xorg.log also has the following:

(II) IEGD(1): Keeping user defined mode: 1280x1024_60.00

This all seems well and good, but I recently noticed in the screen's menu that it is running at 1280x1024 at 75Hz.
I have yet to dig up the documentation on the touch screen to work out if 75Hz is in fact its minimum refresh rate, but I was wondering - does this cause an issue? All signs point to Xorg and the graphics driver considering the refresh rate of the screen to be 60Hz. What happens if there is a discrepancy between the graphics driver's assumed refresh rate and the screen's actual refresh rate?
I can find plenty of stuff online that talks about differences between video game FPS and screen refresh rates. Does that apply in this instance too (i.e. is the effect of app : screen ratio the same as driver : screen ratio) ?

A: Just because Xorg keeps a user-supplied modeline doesn't mean that it will necessarily be used. If there is a better fit that is not overridden, Xorg will use it instead.


text:
Q: How to dynamically chose DB user among multiple users I have been experiencing "database connection exceeds(max: 30)" problem in my website in shared hosting. In order to avoid this, I have created 10 DB users and want to distribute the load among them. Would you please help me with an efficient way to achieve this? Mine is a web application based on PHP-MySQL platform. My user base is also defined (nearly 550 users).
I am using following simple script to connect DB.
$dbhost = 'localhost';
$dbuser = 'MYDBUSER';
$dbpass = 'MYPASS';
$dbname = 'MYAPPLICATIONDB';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
    die('Could not connect database.');
}

A: Well, you better change your hosting account then.
A solution (which I don't really like) might be:
$dbhost = 'localhost';
$dbusers = ['MYDBUSER1', 'MYDBUSER2', 'MYDBUSER3', 'MYDBUSER4', 'MYDBUSER5'];
$dbpass = 'MYPASS';
$dbname = 'MYAPPLICATIONDB';
$conn = mysqli_connect($dbhost, array_rand($dbusers), $dbpass, $dbname);
if (!$conn) {
    die('Could not connect database.');
}

A: Instead of creating a new connection for every CRUD operation, create just a single connection with one database user and share that one connection with all of the CRUD operations for the script.
Some hosting plans on some hosts might well limit you to a single database user.
Creating new connections for every CRUD operation is very inefficient. In the past I've seen an example of when someone done that, it meant that page loads took ages. Once it was altered to use a single database connection which was passed around the script, it made a huge difference to page load times, which then loaded a million times faster.


text:
Q: Using SWIG for Java, how can I selectively swig certain parts of a huge C/C++ header file? I have some legacy C/C++ header files that I need to work with.  These header files are huge and I do not want to swig all of the elements.  Is it possible to swig only certain parts of that header file and if so, how would I go about it?
For example, here is a C header file called BigHeaderFile.h, with enum declarations:
#ifndef __HEADER_GUARD__
#define __HEADER_GUARD__

typedef enum _MYSTATUS {
    OK, NG, NONE
} MYSTATUS;

typedef enum _NOTINTERESTED {
    AVAL, BVAL, CVAL
} NOTINTERESTED;

#endif __HEADER_GUARD__

Below is my swig file:
%module MyNativeClass
%include "enums.swg"
%javaconst(1);

%include "BigHeaderFile.h"

When I run swig on the above, it generates two java classes MYSTATUS and NOTINTERESTED.  Is there a way to tell swig to only generate java enums for MYSTATUS only?

A: You're almost certainly looking for SWIG's advanced renaming feature.
You can start to solve this by using:
%rename("$ignore") "";

To cause SWIG to ignore all the declarations within your header file. Once you've done that you can then selectively re-enable wrapping of anything you see fit.
So your .i file becomes:
%module MyNativeClass
%include <enums.swg>
%javaconst(1);

%rename("$ignore") ""; // ignore all
%rename("%s") "MYSTATUS"; // except MYSTATUS

%include "BigHeaderFile.h"

You can specify what to un-ignore based on more than simple name matching, e.g. regex, namespace, type (class/template/enum/constness/...)
It turns out that my basic example above is almost identical to an example in the docs.

A: I can think of two ways to do this:

*

*Make a copy of the file BigHeaderFile.h, rename it to say BigHeaderFile.i, remove the parts for which you do not want swig wrappers, and in the swig file %include "BigHeaderFile.i" instead.

*Before including the file BigHeaderFile.h in the swig file, use %ignore NOTINTERESTED; to tell swig to ignore NOTINTERESTED. Swig will then not generate wrappers for that class.
Note that in either case you probably need to add
%{
#include "BigHeaderFile.h"
%}

to the top of your swig file so that this line gets put in the wrapper code. Otherwise, it should not compile.


text:
Q: Nested Accordion opens and closes immidiately I have the following fiddle: http://jsfiddle.net/bgejtbyk/2/
When the second title opens, there are 2 sub titles under it. When i try to open any one of those two sub, they open and quickly the main accordion closes.
What am i doing wrong?
Cheers.

$( "#accordion" ).accordion({
heightStyle: "content",
collapsible: true,
active: 'none',
});

Agri Business Division

                TEXT TEXT TEXT

Consumer Business Division

SUB1

   SUB1 TEXT

SUB2

   SUB2 TEXT

A: Updated your fiddle. The problem is that you have two elements with the same ID, so changing "id" to "class" will fix the issue:

$(".accordion").accordion({
    heightStyle: "content",
    collapsible: true,
    active: 'none',
});


text:
Q: Check if # exist in URL then remove it When the URL has #id-name-here I want to apply a CSS class to the parent of that target on the page.
So given this URL...
domain.com/#Domain
Then the page will jump to this location in the page

I want to find the PARENT of
So using javaScript I want to find the Parent of this Node like this...
$('a[name="Domain"]').parent('.module-box').addClass('active-cat');
which will add the class active-cat to the Parent of my target Node.
So I need help making this more Dynamic, so Domain could be any value...
I am able to get the Domain portion from the URL with location.hash.
Then do this....
var activeCat = location.hash;
$('a[name="' + activeCat + '"]').parent('.module-box').addClass('active-cat');

This almost works except my activeCat contains the # and I need to remove that.
So if someone can help me....

*

*Remove # from var activeCat = location.hash;

*Check to make sure var activeCat = location.hash; even exist before running the other code?

My end result...

A: Just remove that #:
 var activeCat = location.hash.replace('#', '');


text:
Q: How many batches can be created in a JOB via Bulk API? I went through limitations about Bulk API but could not get explanation on the limit of Batches created per job in Salesforce. I can read Batch limitation but no limitation in Job. Your help is appreciated.
-Thanks
Ankur

A: Daily limit, not per job:

You can submit up to 5,000 batches per rolling 24 hour period

Source: http://sforce.co/1avfW6t
A job can be active for 24 hours, so the amount of batches created for a job is at most 5000.