text:
Q: A duality with variance I was working on a problem that essentially devolved to this:
Given $n$ successive occurrences of a Bernoulli experiment (say probability of 1 is $p$), find the expected number of runs (consecutive sequences of 1's). For example, 0 1 1 0 1 0 has two runs.
I approached this problem as a recursive idea, if $f(k)$ is the expected number of runs on $k$ occurrences, then $f(k) = (1-p)f(k+1) + \sum_{i=1} p^{i}(1-p)(1 + f(k+i+1))$- i.e. either we get a 0, in which case there's no run, or we get some number of ones followed by a 0, terminating the run. Playing with this recurrence relation got $f(k) = f(k+1) + p(1-p)$, and thus this expected number is $np(1-p)$. (I verified this in simulation)
I noticed this was equivalent to the variance of the binomial distribution, $np(1-p)$. Since this array of Bernoulli experiments is the definition of a binomial distribution, I thought this was too "nice" to be a coincidence, and was wondering if there was a duality/variance-based explanation for this (I couldn't think of one).
Thank you!


text:
Q: how to get current route in react-router-dom v4.2.2 I want to get current route path in meteor based react project and I want to create login page externally..how can i do it?
this is my source code
client/main.jsx
import React from "react";
import {meteor} from "meteor/meteor";
import {render} from "react-dom";
import {
    BrowserRouter as Router,
    Route
} from "react-router-dom"

import "./main.css";
import "../imports/ui/stylesheets/main.scss";

import Main from "../imports/ui/Main";

Meteor.startup(() => {
    return render((
        <Router>

        </Router>
    ), document.getElementById("app-root"));
});

ui/main.jsx
import React, {Component} from "react";
import Link, {withRouter} from "react-router-dom"
import PropTypes from "prop-types";

/*@import Templates*/
import Sidebar from "./components/sidebar";

class Main extends Component {

    render() {

        return (

                <Sidebar/>
                //want current location path for here

        );
    }
}

export default Main;

Used versions:

*

*react v16.2.0

*react-router-dom v4.2.2

*react-router v4.2.0

A: You have to apply the react router HOC to your component (withRouter(Main) at the end of the file) then it'll pass some props to your component, including match and location.
match prop contains url and path to display the component route (path will give you the route with the param name e.g. "user/:id", url give you the real url with the param variable e.g. "user/1d6qsqsd56").
location.pathname will give the actual url wherever you call it (gives "/user/1d6qsqsd56" in your sidebar component).
class Main extends Component {
    render() {
        return (

                <Sidebar/>

 Route path : {this.props.location.pathname}

        );
    }
}

export default withRouter(Main);

Edit : Corrected with actual behaviours of different router props.

A: You need to access the injected property location of the instance of the component like this
let currentLocationPath = this.props.location.pathname

For more information https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dividing fractions with objects I have a class runner that is supposed to do the keep it change it flip it method when doing fractions.
public class Fraction2
{
private int numerator = 0;
private int denominator = 1;
public Fraction2()
{
    numerator = 0;
    denominator = 1;
}
public Fraction2(int num, int denom)
{
    numerator = num;
    denominator = denom;
}

public void show(int num, int denom)
{
    System.out.println(numerator + "/" + denominator);
}
public String toString()
{
    return (numerator + "/" + denominator);
}

public Fraction2 mult(Fraction2 temp)
{
    return new Fraction2(this.numerator * temp.numerator,
                         this.denominator * temp.denominator);
}
public Fraction2 add(Fraction2 sent)
{
   int cmmndenom = sent.denominator * this.denominator;
   int answer = this.numerator * sent.denominator + sent.numerator * this.denominator;
   return new Fraction2(answer, cmmndenom);
}
public Fraction2 divide(Fraction2 sent)
{
    //keep it change it flip it method
    Fraction2 answer = new Fraction2(this.numerator * sent.denominator,
                                     this.denominator * sent.numerator);
    return answer;
}
public Fraction2 reduce()
{
    int ansNumer = numerator;
    int ansDenom = denominator;
    for (int i = 1; ((i <= (numerator)) && i <= (denominator)); i++)
    {
        if (((numerator % i) == 0)  && ((denominator % i) == 0))
        {
            ansNumer = numerator / i;
            ansDenom = denominator / i;
        }
    }
    return new Fraction2(ansNumer, ansDenom);
}

}
When I put in 1/4 and 2/6 and I should be getting 6/8 but I'm getting 8/6. The rest of the methods work except for the dividing part. I'm just stuck on how to get 6/8 instead of 8/6.
import java.util.Scanner;
public class FractionTesterv2
{
    public static void main(String args[])
    {
        System.out.println("\f");
        Scanner input = new Scanner(System.in);
        int numerator;
        int denominator;
        int addCount = 0;
        int multCount = 0;
        int divCount = 0;
        //***************************************
        //Creating future objects
        Fraction2 fraction3 = new Fraction2();
    Fraction2 addAnswer = new Fraction2();
    Fraction2 multAnswer = new Fraction2();
    Fraction2 divAnswer  = new Fraction2();
    //***************************************
    System.out.println("Enter a numerator");
    numerator = input.nextInt();
    System.out.println("Enter a denominator");
    denominator = input.nextInt();
    //creates first fraction
    Fraction2 fraction2 = new Fraction2(numerator, denominator);
    System.out.println("would you like to add another fraction?");
    String choice = input.nextLine();
    choice = input.nextLine();
    // Will only display first fraction entered
    if (choice.equals("no"))
        System.out.println(fraction2);
    else
    {
        while  (!(choice.equals("no")))
        {
            System.out.println("Enter a numerator");
            numerator = input.nextInt();
            System.out.println("Enter a denominator");
            denominator = input.nextInt();
            fraction3 = new Fraction2(numerator, denominator);
            //***************************************
            //Adding Fractions
            if (addCount == 0)
                addAnswer = fraction2;
            addCount = 1;
            addAnswer = fraction3.add(addAnswer);
            System.out.println("add: " + addAnswer);
            //***************************************
            //Multiplying Fractions
            if (multCount == 0)
                 multAnswer = fraction2;
            multCount = 1;
            multAnswer = fraction3.mult(multAnswer);
            System.out.println("Multiply: " + multAnswer);
            //***************************************
            //Dividing Fractions
            if (divCount == 0)
                divAnswer = fraction2;
            divCount = 1;
            divAnswer = fraction3.divide(divAnswer);
            System.out.println("Divide: " + divAnswer);
            //***************************************
            System.out.println("would you like to add another Fraction?");
            choice = input.nextLine();
            choice = input.nextLine();
        }
        Fraction2 addReduced = addAnswer.reduce();
        Fraction2 multReduced = multAnswer.reduce();
        Fraction2 divReduced = divAnswer.reduce();
        System.out.println("Adding Reduced: " + addReduced);
        System.out.println("Multiply Reduced: " + multReduced);
        System.out.println("Dividing Reduced: " + divReduced);
    }
}

}
My code is fairly large to start and I'm sure I can figure out how to simplify it. Just looking for help on the one part.

A: The first two numbers that you enter ("1", "4") are used to build fraction2.
The next two numbers ("2", "6") are used to build fraction3.
And then you calculate:
divAnswer = fraction3.divide(fraction2);

"2/6" divided by "1/4" is "8/6" - if you want "6/8" then you would have to calculate "1/4" divded by "2/6", which would be
divAnswer = fraction2.divide(fraction3);

For chained division operations you could write
// this shows an extract of a larger fraction of your code!
divAnswer = fraction2;
while  (!(choice.equals("no")))
    //...
    // no need for some strange divCount flag here
    divAnwser = divAnswer.divide(fraction3);
    //...
}

or, similar to what your doing now:
while  (!(choice.equals("no")))
    //...
    if (divCount == 0)
        divAnswer = fraction2;
    divCount = 1;
    divAnswer = divAnswer.divide(fraction3);
    //...
}

The basic problem is that your current code has the division operations swapped and that is what I tried to show.


text:
Q: Pandas df.apply does not modify DataFrame I am just starting pandas so please forgive if this is something stupid.
I am trying to apply a function to a column but its not working and i don't see any errors also.
 capitalizer = lambda x: x.upper()
    for df in pd.read_csv(downloaded_file, chunksize=2, compression='gzip', low_memory=False):
        df['level1'].apply(capitalizer)
        print df
        exit(1)

This print shows the level1 column values same as the original csv not doing upper. Am i missing something here ?
Thanks

A: apply is not an inplace function - it does not modify values in the original object, so you need to assign it back:
df['level1'] = df['level1'].apply(capitalizer)

Alternatively, you can use str.upper, it should be much faster.
df['level1'] = df['level1'].str.upper()

A: df['level1'] = map(lambda x: x.upper(), df['level1'])

you can use above code to make your column uppercase


text:
Q: Iterate through Map in ruby How do I rewrite this Java statement in Ruby?
for (Map.Entry<byte[], HServerLoad.RegionLoad> entry : serverLoad.getRegionsLoad().entrySet()){
}

Thanks for your help!

A: If you want to iterate a ruby map(hash) with key and values you could write
h.each { |k, v| puts "Key=#{k}, Value=#{v}" }


text:
Q: Algolia-Error: Cannot find module 'firebase' Im following algolia documents.
https://www.algolia.com/doc/tutorials/indexing/3rd-party-service/firebase-algolia/
I did every step that document tell me to do.But It gives me error.
internal/modules/cjs/loader.js:589
throw err;
^

Error: Cannot find module 'firebase'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:587:15)
    at Function.Module._load (internal/modules/cjs/loader.js:513:25)
    at Module.require (internal/modules/cjs/loader.js:643:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/home/ali/Desktop/algolia/index.js:3:18)
    at Module._compile (internal/modules/cjs/loader.js:707:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
    at Module.load (internal/modules/cjs/loader.js:605:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
    at Function.Module._load (internal/modules/cjs/loader.js:536:3)

How to fix it?
this is what i got when i tried to install firebase module with npm.
error:
   node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://node-precompiled-binaries.grpc.io/grpc/v1.16.0/node-v67-linux-x64-glibc.tar.gz
node-pre-gyp WARN Pre-built binaries not found for grpc@1.16.0 and node@11.1.0 (node-v67 ABI, glibc) (falling back to source compile with node-gyp)
gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack     at getNotFoundError (/usr/lib/node_modules/node-gyp/node_modules/which/which.js:13:12)
gyp ERR! stack     at F (/usr/lib/node_modules/node-gyp/node_modules/which/which.js:68:19)
gyp ERR! stack     at E (/usr/lib/node_modules/node-gyp/node_modules/which/which.js:80:29)
gyp ERR! stack     at /usr/lib/node_modules/node-gyp/node_modules/which/which.js:89:16
gyp ERR! stack     at /usr/lib/node_modules/node-gyp/node_modules/isexe/index.js:42:5
gyp ERR! stack     at /usr/lib/node_modules/node-gyp/node_modules/isexe/mode.js:8:5
gyp ERR! stack     at FSReqCallback.oncomplete (fs.js:161:21)
gyp ERR! System Linux 4.19.2-1-MANJARO
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--library=static_library" "--module=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc/grpc_node.node" "--module_name=grpc_node" "--module_path=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc" "--napi_version=3" "--node_abi_napi=napi"
gyp ERR! cwd /home/ali/Desktop/algolia/node_modules/grpc
gyp ERR! node -v v11.1.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/bin/node /usr/lib/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --library=static_library --module=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc/grpc_node.node --module_name=grpc_node --module_path=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc --napi_version=3 --node_abi_napi=napi' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/ali/Desktop/algolia/node_modules/grpc/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:257:5)
node-pre-gyp ERR! System Linux 4.19.2-1-MANJARO
node-pre-gyp ERR! command "/usr/bin/node" "/home/ali/Desktop/algolia/node_modules/grpc/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build" "--library=static_library"
node-pre-gyp ERR! cwd /home/ali/Desktop/algolia/node_modules/grpc
node-pre-gyp ERR! node -v v11.1.0
node-pre-gyp ERR! node-pre-gyp -v v0.10.3
node-pre-gyp ERR! not ok
Failed to execute '/usr/bin/node /usr/lib/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --library=static_library --module=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc/grpc_node.node --module_name=grpc_node --module_path=/home/ali/Desktop/algolia/node_modules/grpc/src/node/extension_binary/node-v67-linux-x64-glibc --napi_version=3 --node_abi_napi=napi' (1)
npm WARN algolia@1.0.0 No description
npm WARN algolia@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! grpc@1.16.0 install: `node-pre-gyp install --fallback-to-build --library=static_library`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the grpc@1.16.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ali/.npm/_logs/2018-11-23T17_32_22_514Z-debug.log

A: Try using command npm-install firebase.
It will come up with message firebase install with version.
After that go to package.Json under dependencies add "firebase":"version number". This will solve your issue.


text:
Q: how to make the html div responsive to the screen resolution All, new to web development, I am trying to create a login page. It works correctly for 1400*765 but how to make to responsive for all screen. Please help me on this.. Sorry for the basic question here again.
I have three images login.png, bck.png and icon.png. So bck.png is background image, login.png is designed box and icon.png is icon which along with login.png.

.login-wrapper {
  top: 154px;
  left: 528px;
  width: 385px;
  height: 509px;
  background: url('../../assets/login.png') 0% 0% no-repeat padding-box;
  position: relative;
  opacity: 1;
}

.background {
  width: 100%;
  height: 100%;
  background: url('../../assets/bck.png') 0% 0% no-repeat padding-box;
  background-size: 100% 100%;
  color: white;
  top: -0.000244140625px;
  left: 0.0009765625px;
  position: fixed;
}

.icon {
  background: url('../../assets/icon.png') 0% 0% no-repeat padding-box;
  opacity: 1;
  top: 90px;
  left: 656px;
  width: 128px;
  height: 128px;
  position: fixed;
}

.example-full-width {
  top: 328px;
  left: 568px;
  width: 304px;
  height: 52px;
  background: #FFFFFF 0% 0% no-repeat padding-box;
  border: 1px solid #979797;
  border-radius: 4px;
  opacity: 1;
  position: fixed;
}

.example-full-width1 {
  top: 409px;
  left: 568px;
  width: 304px;
  height: 52px;
  background: #FFFFFF 0% 0% no-repeat padding-box;
  border: 1px solid #979797;
  border-radius: 4px;
  opacity: 1;
  position: fixed;
}

.btn-block {
  top: 516px;
  left: 569px;
  width: 304px;
  height: 60px;
  background: transparent linear-gradient(180deg, #FF80A9 0%, #C93C6A 100%) 0% 0% no-repeat padding-box;
  border-radius: 4px;
  opacity: 1;
  position: fixed;
}

.h1 {
  top: 228px;
  left: 652px;
  width: 139px;
  height: 34px;
  text-align: left;
  font: Heavy 25px/34px Avenir;
  letter-spacing: 8.05px;
  color: #000000;
  opacity: 1;
  position: fixed;
}

.h2 {
  top: 264px;
  left: 670px;
  width: 104px;
  height: 25px;
  text-align: left;
  font: Black 18px/25px Avenir;
  letter-spacing: 2.63px;
  color: #000000;
  opacity: 0.5;
  position: fixed;
}

    <mat-card-header>

CONFIG

SERVICES

    </mat-card-header>

    <form class="example-form">
      <mat-card-content>
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Email">
        </mat-form-field>

        <mat-form-field class="example-full-width1">
          <input matInput placeholder="Password">
        </mat-form-field>
      </mat-card-content>
      <button mat-stroked-button color=#C93C6A class="btn-block">Log in</button>
    </form>

A: You can use CSS media queries to make your website responsive to all screens
For example:
@media (max-width: 1600px) {
// your CSS codes
}

A: There really are tons of ways for you to make a website more responsive.
You may want to read into
CSS media queries. They let you define style rules only applicable for a certain screen size.
Something like this:
/* normal styling (e.g. mobile) */
@media screen and (min-width: 992px) {
  /* extra styling for desktop */
}


text:
Q: Laravel 5 Validation - Return as json / ajax I am trying to post the values into validation and return the response as json rather than return view as given in the documentation.
    $validator = Validator::make($request->all(), [
        'about' => 'min:1'
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => ?, 'status' => 400], 200);
    }

The post is made by ajax so I need to receive the response in the ajax as well.
I figured out that in order to prevent refresh of the page in the returning response, I have to give it a status code of 200 outside the array. But I couldn't figure out what to give the 'errors' part. What should I write in there?

A: You can use $validator->messages() that returns an array which contains all the information about the validator, including errors. The json function takes the array and encodes it as a json string.
if ($validator->fails()) {
    return response()->json($validator->messages(), Response::HTTP_BAD_REQUEST);
}

Note: In case of validation errors, It's better not to return response code 200. You can use other status codes like 400 or Response::HTTP_BAD_REQUEST

A: I use below this code for API in my existing project.
$validator = Validator::make($request->all(), [
      'ride_id' => 'required',
      'rider_rating' => 'required',
  ]);

  if ($validator->fails()) {
    return response()->json($validator->errors(), 400);
  }

A: in case you are using a request class.
you may use failedValidation to handle you failed
    /**
     * Returns validations errors.
     *
     * @param Validator $validator
     * @throws  HttpResponseException
     */
    protected function failedValidation(Validator $validator)
    {
        if ($this->wantsJson() || $this->ajax()) {
            throw new HttpResponseException(response()->json($validator->errors(), 422));
        }
        parent::failedValidation($validator);
    }

A: You can also tell Laravel you want a JSON response. Add this header to your request:
'Accept: application/json'

And Laravel will return a JSON response.

A: In Laravel 5.4 the validate() method can automatically detect if your request is an AJAX request, and send the validator response accordingly.
See the documentation here

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

So you could simply do the following:
Validator::make($request->all(), [
    'about' => 'min:1'
])->validate();

A: For those who have created a custom request class can override the public function response(array $errors) method and return a modified response without Validator explicitly.
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;

class CustomRequest extends FormRequest
{

    public function rules()
    {
        $rules = [
            //custom rules
        ];

        return $rules;
    }

    public function response(array $errors)
    {
        return new JsonResponse(['error' => $errors], 400);
    }
}

A: My solution is to make my own FormRequest class which I put in the root API namespace namespace App\Http\Requests\Api.
Hope this helps someone
https://jamesmills.co.uk/2019/06/05/how-to-return-json-from-laravel-form-request-validation-errors/

A: Actually I used @Soura solution but with a little change. You need to import the Validator package as well.
$validator = \Validator::make($request->all(), [
      'ride_id' => 'required',
      'rider_rating' => 'required',
  ]);

  if ($validator->fails()) {
    return response()->json($validator->errors(), 400);
  }


text:
Q: std::emplace_back invoking constructor of other objects in vector? I am really confused about std::vector::emplace_back. I run the following code:
struct Thing {
    explicit Thing(std::string name) : name_{std::move(name)} {
        std::cout << "Constructed a thing called " << name_ << std::endl;
    }

    ~Thing() {
        std::cout << "Deconstructed a thing called " << name_ << std::endl;
    };
    std::string name_;
};

int main() {
    std::vector<Thing> things{Thing("A")};
    std::cout << "Size: " << things.size() << std::endl;
    things.emplace_back("B");
    std::cout << "Size: " << things.size() << std::endl;
}

and get this output:
Constructed a thing called A
Deconstructed a thing called A
Size: 1
Constructed a thing called B
Deconstructed a thing called A
Size: 2
Deconstructed a thing called A
Deconstructed a thing called B

Why on earth does things.emplace_back("B") invoke the deconstructor of the thing called A?

A: std::vector stores the objects continuously in an allocated memory block. When that block's size becomes too small to add new elements into it, it must allocate a new, larger, memory block and copy/move the currently present elements in the vector into that new allocation. After that, the objects in the previous allocation are destroyed, involving the destructor call.
You are not seeing the copies being made, because you didn't define a custom copy constructor. If you did, you would see that a copy of A is copy constructed before the original A is destructed. If you define a noexcept move constructor, you will see that a copy of A is move constructed before the original A is destructed.

A: What's happening is that when you add B to the vector, the vector probably only had capacity for 1 element, so had to move it's existing element into another vector (destructing the one in the original storage)
Let's add some more logging to see what happens:
#include <iostream>
#include <string>
#include <vector>

struct Thing {
    explicit Thing(std::string name) : name_{std::move(name)} {
        std::cout << "Constructed a thing called " << name_ << " at " << this << std::endl;
    }
    Thing(Thing&& t) noexcept : name_{std::move(t.name_)} {
        std::cout << "Moved a thing called " << name_ << " from " << &t << " to " << this << std::endl;
    }
    Thing(const Thing& t) : name_{t.name_} {
        std::cout << "Copied a thing called " << name_ << " from " << &t << " to " << this << std::endl;
    }

    ~Thing() {
        std::cout << "Deconstructed a thing called " << name_ << " at " << this << std::endl;
    };
    std::string name_;
};

int main() {
    std::vector<Thing> things{Thing("A")};
    std::cout << "Size: " << things.size() << " Capacity: " << things.capacity() << std::endl;
    things.emplace_back("B");
    std::cout << "Size: " << things.size() << " Capacity: " << things.capacity() << std::endl;
}

Example output:
Constructed a thing called A at 0x1111
Copied a thing called A from 0x1111 to 0x2222
Deconstructed a thing called A at 0x1111
Size: 1 Capacity: 1
Constructed a thing called B at 0x3333
Moved a thing called A from 0x2222 to 0x4444
Deconstructed a thing called A at 0x2222
Size: 2 Capacity: 2
Deconstructed a thing called A at 0x4444
Deconstructed a thing called B at 0x3333


text:
Q: Gulp replace files with minified I have the following tree structure
|-src
|--assets
|---script.js

and I want to replace the contents of script.js with their minified version of it WITHOUT renaming it into script-min.js.
The code right now is:
gulp.task('minifyjs',['movejs'],function(){
    return gulp.src('src/assets/sample.js',{base:'./'})
        .pipe(gulp_requires.minify())
        .pipe(gulp.dest('src/assets/'))
});

How should be modified in order to acheive that?

A: Try to use gulp-uglify package instead of minify one.
https://www.npmjs.com/package/gulp-uglify


text:
Q: Storing model or collection-specific views inside model or collection constructors I realize there is many solutions to this but I was wondering what the community's opinion is.
I have a series of models and collections. Each model has a number of views like details, edit, print, aside, help, etc. Collections have views that often have the same names (ie: aside, help, etc).
One requirement I have is that I need to structure my code in modules. The application should have no trace of a module's functionality if the module is NOT loaded. This may happen if, say, a user has no permissions to view, edit, etc other users. So the "Users" module would not even be loaded.
So...
I thought a good place to store view definitions for a model could be the model's constructor and for a collection in the collection's constructor. For example:
var User = (function(){ // module definition

    // model definition
    var Model = Backbone.Model.extend({
        initialize: function() {
            // ...
        }
    },{
        Views: {
            Details: Backbone.View.extend({
                // ...
            }),
            Aside: Backbone.View.extend({
                // ...
            }),
            Help: Backbone.View.extend({
                // ...
            })
        }
    });

    // collection definition
    var Collection = Backbone.Collection.extend({
        model: Model,
        initialize: function() {
            // ...
        }
    },{
        Views: {
            Aside: Backbone.View.extend({
                // ...
            }),
            Help: Backbone.View.extend({
                // ...
            })
        }
    });

    // add more code here

    return { // make model and collection public
        Model: Model,
        Collection: Collection
    };

})(); // end module definition

I realize I could have my views live elsewhere but would this approach have any considerable drawbacks that I may not be aware of? Perhaps memory leaks or something less obvious?
Thank you!

A: Have a look at require.js. With it you should be able to add logic that deals with module loading. In general you should still have a look at it, works great for organising backbone applications, especially with the text plugin.

A: I think you would be better off not adding your views as "class methods" onto your models and collections. Because of the nature of JavaScript's prototypical inheritance, you aren't really adding class methods so much as properties to the constructor functions for your model types. As to whether or not this is going to cause you issues like memory leaks, I can't say.
I would instead say that, unless you have an unlisted compelling reason for using this structure, you are better off just grouping your views on simple objects.
If the goal is to modularize your code I would take advantage of something like require.js or Marionette modules or just grouping "related" code in an IIFE.
If you are interested in knowing more about what exactly happens to the classProperties that are passed into the Backbone.Model.extend method then I would recommend looking directly at the annotated source.


text:
Q: My code to capture a video from the default camera works fine on every device except the Galaxy S2 when specifying MediaStore.EXTRA_OUTPUT path I have code that gives me back a path to store my video file which basically produces a path that looks like this:
/storage/sdcard0/Pictures/MyApp/MyApp20130816_144111_1131938614.mp4

When I try to capture the video on my S2, I take the video and press stop the camera my camera app does not display the normal save screen, it just puts itself back into the beginning of capture mode and onActivityResult is never called. I've found that if I do not pass a path to MediaStore.EXTRA_OUTPUT it functions correctly.
I've tested my code on Note II, GS3, GS4, Nexus and they all seem to be able to capture the video and save it to the correct path with no problems. Why would the S2 be behaving this way?

A:
Something about the galaxy s2 doesn't like /storage/ maybe?

Never hardcode paths. Always use methods like Environment.getExternalStoragePublicDirectory() to get the root of where to store files on external storage. Different devices, and even different users on the same device (Android 4.2+ tablets) will have different paths for external storage.
However, the point in my initial comment still holds. You as a developer are not "using the default camera app as installed on the galaxy devices". You as a user may be using that particular app. There are nearly a billion Android device users; you are not all of them. They are welcome to use whatever camera app they want to, including third-party ones. And, they will be using thousands of Android device models. None of them will necessarily honor your request to take a picture. It's certainly worthwhile for you to do testing to try to work more faithfully on more devices (such as not hardcoding paths), but you need to bear in mind that any time you ask another developer's app to do work for you, the other developer is control of what happens, much more than you are.


text:
Q: Issues while sending emails using Laravel… When sending the email, it is not formatting it correctly, it is displaying it in plain text and not using the HTML my view has in it.
The way I send it:
Mail::to($request->user()->mail)->send(new AccountLocked(Auth::user()));

AccountLocked.php:
class AccountLocked extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.user.account_locked');
    }
}

A: This isn't an issue with Laravel, if you actually view the data being sent in the request you'll see Laravel will format the email properly, with a valid HTML code.
This issue is probably the targets email provider blocking the HTML, I know a few email providers that do this, you may want to check that before thinking its Laravel.


text:
Q: solclient send request resulting success and fail at the same time I'm starting a new project with Solace as the load balancer. As I follow the guideline on the official doc to build a service that can send requests to Solace, I encounter a weird issue where my request is successful and fails simultaneously. Here's my code
function initSolace(pass: string) {
  var factoryProps = new solace.SolclientFactoryProperties();
  factoryProps.profile = solace.SolclientFactoryProfiles.version10;
  solace.SolclientFactory.init(factoryProps);

  session = solace.SolclientFactory.createSession({
    "url": "ws://localhost:8008",
    "userName": "tech_core",
    "vpnName": "testing",
    "password": pass
  }, new solace.MessageRxCBInfo(messageRxCb));

  session.on(solace.SessionEventCode.UP_NOTICE, function (sessionEvent: any) {
    requestData(10000).subscribe();
  });

  session.connect();
}

async function messageRxCb(session: any, message: any) {
  message = Parser.decodeBinaryAttachmentToPb(message, pnlPb.RespPnl);
  console.log('result from RxCb', message); // I got the correct response here
}

function requestData(timeout = 10000) {
  return new Observable(subscriber => {
    const parsedPayload = Parser.createPb({displayCurrency: 'USD'}, pnlPb.ReqPnl);
    const msg = Parser.encodePbToBinaryAttachment(parsedPayload, pnlPb.ReqPnl);
    const request = solace.SolclientFactory.createMessage();

    request.setDestination(solace.SolclientFactory.createTopicDestination('my/testing/topic'));
    request.setDeliveryMode(solace.MessageDeliveryModeType.DIRECT);
    request.setDeliverToOne(true);
    request.setBinaryAttachment(msg);
    session.sendRequest(request, timeout,
      (ses: any, message: any) => {
        console.log('SUCCESS', message);
        subscriber.next(message);
      },
      (ses: any, event: any) => {
        console.error('FAIL', event); // I got a timeout error here
        subscriber.error(event);
      },
      'correlation test'
    )
  });
}

As I run the code, I gets the timeout error from the requestData function AND the correct data from the messageRxCb function as well.

How does this happening? Did I miss any config here?

A: The Request-Reply pattern is a closely coupled communication pattern.
Every request that is posted by the requestor requires a response from the replier within the timeout specified.
I see from your code sample that you have configured a timeout of 10000ms. What it means is that every request that is posted should receive an incoming reply within 10000ms. If this response is not received, then it would result in the timeout error that you see in the console.
The reason why you see that the request is successfull and the error is because while the request has been successfully posted, a reply was not received within the specified timeout.
Do you already have a replier setup for this interaction? If not then I would suggesting setting up a simple boilerplate replier listening on this and testing the flow again.
Additionally, it would be good coding practise to handle the timeout error in a functionally appropriate manner.
Regards
Hari


text:
Q: I'm trying to use a functional IIF statement within a JOIN statment I want to blend these two commands into one…

*

*This statement joins all agency.value that have been selected and works fine:
="Includes: " & Chr(10) & JOIN(Parameters!Agency.Value, ", ")
Reports like this -
Includes:
Lots Of Other Stuff (LOOS), Many More Things Done (MMTD)

*This statement abbreviates each of the Agency.value that have been identified (otherwise, it goes as original value):
=iif(Parameters!Agency.Value = "Lots Of Other Stuff (LOOS)", "LOOS",
iif(Parameters!Agency.Value = "Many More Things Done (MMTD)", "MMTD", Parameters!Agency.Value)))
Report looks like this -
LOOS, MMTD

*Not sure it's possible to combine them, but I've tried (with error) this statement:
="Includes: " & Chr(10) & JOIN(Parameters!Agency.Value, iif(Parameters!Agency.Value = "Lots Of Other Stuff (LOOS)", "LOOS", iif(Parameters!Agency.Value = "Many More Things Done (MMTD)", "MMTD", Parameters!Agency.Value))), ")
Want it to look like this -
Includes:
LOOS, MMTD
not this -
Includes:
Lots Of Other Stuff (LOOS), Many More Things Done (MMTD)

A: Untested but try this..
   ="Includes: " & Chr(10) &
        JOIN(
             IIF(Parameters!Agency.Value = "Lots Of Other Stuff (LOOS)", "LOOS",
                 IIF(Parameters!Agency.Value = "Many More Things Done (MMTD)", "MMTD",
                     Parameters!Agency.Value)),
              ", ")

In your attempt you were trying to check is the the JOIN result was a specific value. In the version above we JOIN the list after it has been updated (after the IIF)


text:
Q: хорош ли такой подход в архитектуре проекта? В своих проектах API - я использую паттерн Controller -> Service -> Model. В простых проектах достаточно описать все функций в одном файле.
user.controller.js
const ApiError = require('../error/ApiError');
const yup = require('yup');
...

exports.login = (req, res, next) => {...}
exports.signup = (req, res, next) => {...}
exports.getInfo = (req, res, next) => {...}
exports.changePassword = (req, res, next) => {...}

Но когда проект развивается, то соответственно растет код, и хранить все в 1 файле становится неудобно. Например когда файл состоит из 500 строк кода и нужно изменить где то 1 строчку кода, то приходится скроллить вниз, что очень неудобно.
Я решил, а что если каждую функцию разделить на под файлы и подключать в итоге все в index.js
controllers/user/
- index.js (Единая точка входа для всех функций);
- login.js;
- signup.js
...

и получается что то вроде
controllers/user/login.js
const ApiError = require('../error/ApiError');
const yup = require('yup');
...

module.exports = (req, res, next) => {...}

controllers/user/index.js
const login = require('./login');
const signup = require('./signup');
...

module.exports = {
 login,
 signup
};

Теперь намного удобней редактировать функций, и все они хранятся в одной точке.
Как вы считаете мой подход к проектированию нормальный или есть что то похожее?

A: Я пришел к такому выводу, что все таки лучше использовать архитектуру, которая была описана мною в вопросе.
Пример, когда это вам поможет:

*

*Удобно работать с кодом. Понятно что и где находится.

*Ваш проект всегда должен иметь возможность расширяться. Соответственно хранить код все в 1 файле уже неправильно. Если это Rest Api ? - то часто бывает, что меняется бизнес логика и появляются роутеры вида /api/v1/users, /api/v2/users.

*С большим кол-ом кода другие программисты не будут мучаться.


text:
Q: Facebook Checkins on Website I have a website that has users regularly checking in to with Facebook. I want to display the currently checked in users (name & avatar) on the homepage. I've managed to achieve this for people checking in with foursquare but can't work out how to do it with Facebook.
As far as I can tell checkins are extended permissions and require an access token. I've managed to generate an Access token using...
echo $token = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=[-APP ID-]&client_secret=[-APP SECRET-]&grant_type=client_credentials');

and appending the result to a checking request...
echo file_get_contents('https://graph.facebook.com/[-PAGE ID-]/checkins/?'.$token);

but all I get from that is:
400 Bad Request
I don't want visitors to the site to have to login to facebook & grant permissions to see checked in users... I just want to list account names and pictures.
Is this possible or am I dreaming?

A: Facebook does not allow you to see the checkins to a place unless the current user is friends with the person checked in.
https://graph.facebook.com/[-PAGE ID-]/checkins/?access_token=$token

will give you all the current users friends who have checked into [-PAGE ID-].

A: Did you mean:
echo file_get_contents('https://graph.facebook.com/[-PAGE ID-]/checkins/?access_token='.$token);

You forgot ?access_token=


text:
Q: How to create a vector of missing values of certain length in julia? In R I can create a vector length 5 with all NA_real_ values:
x <- 1:5
length(x)
## [1] 5
rep(NA_real_, times = length(x))
## [1] NA NA NA NA NA

How can I do the same in julia? I can create a vector containing zeros, but I don't know how to put missing values in there:
v = Vector{Float64}(undef, 5)
## 5-element Array{Float64,1}:
 0.0
 0.0
 0.0
 0.0
 0.0

A: The missing value in Julia is called missing. It is a singleton of type Missing. You can create a vector of missing values like this:
v = Vector{Missing}(undef, 5)
# 5-element Array{Missing,1}:
#  missing
#  missing
#  missing
#  missing
#  missing

Or, more conveniently using fill:
v = fill(missing, 5)

Be warned, though, that unlike in R, Missing does not share a type with other numeric types: it is its own type. Notice what happens when you try to put a Float64 into a vector of Missings:
v = fill(missing, 5)
# 5-element Array{Missing,1}:
#  missing
#  missing
#  missing
#  missing
#  missing

v[1] = 3.14
# ERROR: MethodError: convert(::Type{Union{}}, ::Float64) is ambiguous.

This means if you want to create a vector containing only missing values, but you want it to also be able to contain a numeric value like a Float64, you should be explicit:
v = convert(Array{Union{Float64,Missing}}, v)
# 5-element Array{Union{Missing, Float64},1}:
#  missing
#  missing
#  missing
#  missing
#  missing

v[1] = 3.14;
v
# 5-element Array{Union{Missing, Float64},1}:
#  3.14
#   missing
#   missing
#   missing
#   missing

A: Vector{Union{Float64,Missing}}(missing, 5) should do what you want.


text:
Q: Copy instance of View - zoom doesn't work I'd would pass copy of instance ol.View to map constructor. When I do that zoom stop working and I wonder why?
I have to write some text to create post eh..

<!doctype html>

  <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/css/ol.css" type="text/css">

  <title>OpenLayers example</title>

My Map

Openlayers v5.2.0


text:
Q: String Containing only Vowels Suppose I have a vector of string and it contains strings (aei,ou,a). I want to concatenate them in O(n). After concatination it will become (aeiou,aeia,oua). I want to do concatination in one for loop. How to do it?

A: Mind you, I haven't checked this, i just made this on the fly. but this sounds like its what you want.
public void variableStrings(arr[] strings) {
List<string> newList = new List<string>();
   for(int i = 0; i+1 < strings.Length -1; i++)
   {
      newList.add(string.Format("{0}{1}",strings[i],strings[i+1]));
   }
}


text:
Q: Android image can't convert to drawable I am not able to add image. I downloaded the image and added it to res directory under drawable-mdpi. Then when I try to add the image on the view using imageView, it gives me this error
Couldn't resolve resource @drawable/ball01
Failed to convert @drawable/ball01 into a drawable

Here is my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_gravity="center"
        android:textSize="32sp"
        android:layout_above="@+id/button"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enlighten Me"
        android:id="@+id/button"

        android:layout_centerVertical="true"
        android:layout_alignParentRight="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_above="@+id/textView"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ball01" />

</RelativeLayout>

What am I doing wrong here.

A: The directory name should be 'drawable-mdpi'. Using a hyphen instead of an underscore.

A: image  name must   Digital or  lowercase 。   ide only identification.

A: I had this same problem, I had this image which I named Barcode and then saved it into my drawable folder, then I decided it would be better to have it named barcode with a small b, so I renamed it.
Then I checked if it would work, and I got the same errors as you, after changing the name in my xml to 'Barcode' with a big B, it worked.
solution for me: delete barcode image from drawable and add it again with the name I'm going to use for it, don't change the name while it is in drawable folder.

A: I had this problem on android studio.
if you close and open project and it continues, all you need to do is RIGHT CLICK on the particular image you put in your "res" folder (that's giving the problem) and refactor-RENAME. Remove spaces in the name of the file. that should do it.


text:
Q: Nested Group by LINQ to Nested object I am unable to solve this problem with the LINQ Query.
So we have the table structure of Book as follows:
LibraryId || LibraryName || ShelveId || ShelveName || Cost || Name || ForeName || Stuff

I want to group by Library first, then by Shelve of Book. A Library is a list of Shelve and a Shelve is a list of book. Performance matters. This is a fragment of real data.
var table = new[] {
    new Book (1, "Green", 42, "A", 10, "Gra", "Bar", "etc."),
    new Book (1, "Green", 43, "B", 21, "Grb", "Bar", "etc."),
    new Book (2, "Blue", 652, "C", 10, "Blc", "Bar", "etc."),
    new Book (2, "Blue", 652, "C", 01, "Bl2", "Bar", "etc."),
    new Book (2, "Blue", 123, "D", 12, "Bld", "Bar", "etc."),
    new Book (8, "White", 94, "E", 14, "Foo", "Bar", "etc."),
    new Book (9, "Grey", 142, "F", 11, "Foo", "Bar", "etc."),
    new Book (9, "Grey", 142, "F", 12, "Bar", "Bar", "etc.")
};

Class:
class Book
{
    public int LibraryId {get;set;}
    public string LibraryName {get;set;}

    public int ShelveId {get;set;}
    public string ShelveName {get;set;}

    public int Cost {get;set;}
    public string Name {get;set;}
    public string ForeName {get;set;}
    public string Stuff {get;set;}

    public Book(int libraryId, string libraryName, int shelveId, string shelveName
                , int cost, string name, string foreName, string stuff)
    {
        LibraryId = libraryId;
        LibraryName = libraryName;
        ShelveId = shelveId;
        ShelveName = shelveName;
        Cost = cost;
        Name = name;
        ForeName = foreName;
        Stuff = stuff;
    }
}

class Library
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Cost {get;set;}
    public List<Shelve> Shelves {get;set;}

    public Library (Shelve shelve)
    {
        Id = shelve.Books[0].LibraryId;
        Name = shelve.Books[0].LibraryName;
        Cost = shelve.Cost;
        Shelves = new List<Shelve> {shelve};
    }
}

class Shelve
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Cost {get;set;}
    public List<Book> Books {get;set;}

    public Shelve (Book book)
    {
        Id = book.ShelveId;
        Name = book.ShelveName;
        Cost = book.Cost;
        Books = new List<Book> {book};
    }
}

I achieve my behavior with a good old foreach:
var libraries = new List<Library> { new Library (new Shelve(table[0])) };
foreach (var item in table.Skip(1))
{
    if (item.LibraryId != libraries.Last().Id)
    {
        libraries.Add(new Library(new Shelve(item)));
        continue;
    }

    if (item.ShelveId != libraries.Last().Shelves.Last().Id)
    {
        libraries.Last().Cost += item.Cost;
        libraries.Last().Shelves.Add(new Shelve(item));
        continue;
    }

    libraries.Last().Cost += item.Cost;
    libraries.Last().Shelves.Last().Cost += item.Cost;
    libraries.Last().Shelves.Last().Books.Add(item);
}
var total = libraries.Sum(x => x.Cost);

As far as I know, this is a O(n) solution.
Now, I would like to refactor it. I think we can do something with GroupBy. I tried this:
var grouped = table
    .GroupBy(l => new { l.ShelveId, l.LibraryId})
    .GroupBy(l => l.Key.LibraryId);

foreach(var country in grouped)
{
    foreach(var state in country)
    {
        foreach(var personInState in state)
        {
            Console.WriteLine(personInState.Name);
        }
    }
}

But I don't know how to Sum the cost and add LibraryName and ShelveName into each Library and Shelve.
Try it Online! (with basic tests)

A: Maybe you can simplify it by using calculated properties as below
class Shelve
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<Book> Books {get;set;} = List<Book>();
    public int Cost
    {
        get{ return this.Books.Sum(x => x.Cost); }
    }
}

and you can do the same with the Library class...
class Library
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<Shelve> Shelves {get;set;} = new List<Shelve>();
    public int Cost
    {
        get{ return this.Shelves.Sum(x => x.Cost); }
    }
}

I think it'd add clarity to your business logic code and you won't need to bang your head with complex group by expressions


text:
Q: Column in field list is ambiguous MYSQL, PHP, SEARCH, SELECT i am trying to select information from my mysql database with this statement after making a successful connection to the database:
$query = "SELECT * FROM `users`, `markers`,`imagemarkers`
    WHERE username LIKE '%$s%'
    OR email LIKE '%$s%'
    OR location LIKE '%$s%'
    OR author LIKE '%$s%'
    OR bike LIKE '%$s%'
    OR id LIKE '%$s%'
    OR title LIKE '%$s%'";

and i am getting this error: Column 'author' in where clause is ambiguous. Which i understand to be because i have multiple tables with the same field name.
I want to extract the information from these tables, and from these fields:
 -markers:
    author
    title
    bike
    id
    date

 -imagemarkers:
   -author
   -title
   -id
   -date

 -users:
   -loction
   -email
   -username
   -id

I have searched for the solution and have so far come to the conclusion that each table field should be refered to as something like:
  markers.title
  imagemarkers.title

  markers.author
  imagemarkers.author

  markers.date
  imagemarkers.date

  markers.id
  imagemarkers.id
  users.id

And that the statement might look something like:
  SELECT markers.author
    FROM markers JOIN imagemarkers ON markers.author = imagemarkers.author

But i'm not sure how to make this work with the amount of information I need to retrieve.
The whole code i have at the moment looks like this:
        if (isset($_POST['submit'])) {
    if ($_POST['search'] !="") {
    require("connection.php");

    $s = mysql_real_escape_string($_POST['search']);
    $query = "SELECT * FROM `users`, `markers`,`imagemarkers` WHERE username LIKE '%$s%' OR email LIKE '%$s%' OR location LIKE '%$s%' OR author LIKE '%$s%' OR bike LIKE '%$s%' OR id LIKE '%$s%' OR title LIKE '%$s%'";
    $result = mysql_query($query, $connect)
        or die(mysql_error());

    $num = mysql_num_rows($result);

    echo "
you searched for: " . $s . "..
";
    echo "
there are " . $num . " results
";

while ($row = mysql_fetch_assoc($result)) {
    echo "
username: " . $row['username'] . "
";
    echo "location: " . $row['location'] . "
";
    echo "author: " . $row['author'] . "
";//error: Column 'author' in where clause is ambiguous, same with date.
    echo "date: " . $row['date'] . "
";
    echo "id: " . $row['id'] . "
";
    echo "title: " . $row['title'] . "
";
    echo "
";

    }
} else {
        echo "
 you must type something in the box
";
}  }

Can anyone offer me any help?
Thanks very much.

A: thats because fields are named the same way
try:
$query = "SELECT * FROM `users` u, `markers` m,`imagemarkers` im
    WHERE u.username LIKE '%$s%'
    OR u.email LIKE '%$s%'
    OR u.location LIKE '%$s%'
    OR m.author LIKE '%$s%'
    OR m.bike LIKE '%$s%'
    OR m.title LIKE '%$s%'";

and so on

A: That's a lot of code for a simple question.. Ambiguous means that an identifier in either your select case or where case is present in more than one table.. If you're saying "Select authors", you need to specifiy from which table.. so markers.authors. If you're doing "where authors.." you need "where markers.authors"
I would suggestion UNIONing your tables.

A: quick and dirty
$query = "SELECT * FROM `users` u
INNER JOIN `markers` m ON (m.author = u.id)
INNER JOIN``imagemarkers` im ON (im.author = u.id)
 WHERE u.username LIKE '%$s%'
  OR u.email LIKE '%$s%'
  OR u.location LIKE '%$s%'
  OR m.author LIKE '%$s%'
  OR m.bike LIKE '%$s%'
  OR m.title LIKE '%$s%'";

This will link the results together, so that only markers and imagemarkers related to users are shown.
Note that I don't know if markers.author is an integer field linking to users.id or a char field linking to users.name this query assumes the former, please adjust the join condition accordingly is this does not match your tables.
If you leave out the join conditions, you will end up with a cross join, which is 99% likely not what you want.
See: http://en.wikipedia.org/wiki/Join_(SQL)
Listing the columns explicitly
If you want to limit the columns you'll have to name them explicitly (recommended).
$query = "SELECT u.location, u.email, u.username as author, u.id as user_id
   ,m.title as marker_title, m.bike, m.date as marker_date, m.id as marker_id
   ,im.title as imagemarker_title, im.date as imagemarker_date, im.id as imagemarker_id
FROM `users` u
INNER JOIN `markers` m ON (m.author = u.id)
INNER JOIN``imagemarkers` im ON (im.author = u.id)
 WHERE u.username LIKE '%$s%'
  OR u.email LIKE '%$s%'
  OR u.location LIKE '%$s%'
  OR m.author LIKE '%$s%'
  OR m.bike LIKE '%$s%'
  OR m.title LIKE '%$s%'";

Note that as everything is linked on author, you need to only list that field once, because otherwise you'd get 3 authorfields with exactly the same content, which would be silly.


text:
Q: Rails model validation: How to make sure a attribute is in a list Hi I have a job model which has an string attribute called category. In the front end, I have a form with a dropbox where a user can fill out the category attribute with the selected value from the list. This is good enough front end validation for me, but now how will I do backend validation for the model?
I have dont other validations in the past for example:
validates :name, :presence => true

But is there anyway I can do something like
validates :category, :in => {"Food", "Drink", "Rental"}

A: You can do it like this:
validates :category, :inclusion => { :in => %w(Food Drink Rental) }

Or shorter:
validates :category, :inclusion => %w(Food Drink Rental)

Everything is in the documentation.


text:
Q: C++ Calling a function that returns template type value I am trying to understand if it is possible to call a function that returns a template type value without explicitly specifying it in call statement?
Function I am trying to call is like this,
template <typename T>
std::unique_ptr<SomeClass<T>> createObjectInstance(InputData data) {
  if(data.type_str == "abc") {
    return createObjectInstanceImpl<ABC>(data);
  } else if(data.type_str == "def") {
    return createObjectInstanceImpl<DEF>(data);
  } else {
    // throw error
  }
}

calling statement
const auto objectPtr = createObjectInstance(data);
// Do something with objectPtr

This does not compile, compiler complains it couldn't infer template argument.
Does the calling function need to resolve the type each time this is needed? Seems very cluttered to do that. Are there known design workarounds?

A: It is not possible to define the return type of a function at runtime, as your example tries to do.
When you define a function with a templated return value, the returned value can only be of one type.  And that type MUST be defined at compile time.
The only way your function may compile, is to have the type of the returned pointer be a base class of both ABC and DEF.  But then, you would not need a template function to achieve that goal.


text:
Q: Initialization of an interface of Strings in Groovy interface PRINT {
  def LN = '\n\n'
  def BREAK = '='*80
}
println PRINT.BREAK

I'm getting this error while trying to initialize BREAK:

java.lang.NoClassDefFoundError: PRINT$1

There's an issue with  '='*80, what could be the reason and what would be a better approach for this?
It works without the multiplication.
Thanks for helping out.


text:
Q: Avoiding method with multiple identical typed parameters I want to avoid passing multiple identically typed parameters into my method to avoid the potential to misorder the parameters. For example:
void createBook(String publisher, String illustrator, String author)

My instinct is to create 3 new types extending String, so that I can have parameters Publisher, Illustrator, and Author, which can be constructed and used as Strings. However, this isn't possible since String is final.
How can I achieve the Clean Code that I desire in the simplest manner? It seems like overkill to have to implement a base class that provides a constructor and .toString for each of these.

A: Create a Book class and make the method accept an instance of Book :
void createBook(Book book)

To avoid the same problem of parameters with the same type in the Book constructor, you could use a builder or a setter approach.
Setter approach :
Book book = new Book();
book.setPublisher(...);
book.setIllustrator(...);
book.setAuthor(...);

Builder approach :
Book book = new BookBuilder().withPublisher(...)
                             .withIllustrator(...)
                             .withAuthor(...)
                             .build();

The Builder approach is more verbose to achieve but note that it also provides clearer client code and  make completely sense if the object is designed to be immutable. It makes it always consistent and thread safe.

A: Named parameters are not supported in Java but you can either use a little trick or make a builder-type class like below.
1-Little trick;
String publisher; String illustrator; String author;
createBook(publisher="...", illustrator="...", author="...");

2-Builder class;
Based on your method name I named class as Book
public class Book {
  public static class Builder {
    public Book build() {
      return new Book(this);
    }

    public Builder setPublisher(String publisher) {
      this.publisher = publisher;
      return this;
    }

    public Builder setIllustrator(String illustrator) {
      this. illustrator = illustrator;
      return this;
    }

    public Builder setAuthor(String author) {
      this.author = author;
      return this;
    }

     private String publisher;
     private String illustrator;
     private String author;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Book(Builder builder) {
    publisher = builder.publisher;
    illustrator = builder.illustrator;
    author = builder.author;
  }

  private String publisher;
  private String illustrator;
  private String author;
}

Then you can use it like this
Book book = Book.builder()
    .setPublisher("JohnThePublisher")
    .setIllustrator("JohnTheIllustrator")
    .setAuthor("JohnTheAuthor")
    .build();


text:
Q: Rails does not propagate Java exception to ApplicationController I have a rails website, and the models will cause some backend service.  I have a rescue_from StandardError in the ApplicationController, which can capture rails exception, but cannot capture exceptions from the backend service.
ApplicationController:
class ApplicationController < ActionController::Base

 rescue_from StandardError do |exception|
   # do something
 end
end

Actual controller:
class StatementsController < ApplicationController

  def show
    # get statement
    respond_to :js
  end
end

If I do "raise 'error message'" inside the show method, then the ApplicationController's rescue method can capture this error. But if the get statement encounters a service exception from the backend service, then the ApplicationController cannot catch it. However, if I do
class StatementsController < ApplicationController

  def show
    # get statement
    respond_to :js

    rescue StandardError => e
        # Don't even need to write code here
  end
end

Then the applicationController can catch the java exception.
I am very new to rails. Can someone help me with this? Thanks


text:
Q: Turning certain rows into columns in SQL Server Please see table below:

For each CustomerID + PaymentID + ClaimNum, there are 3 NULL values for the ItemID & Qty.
I want to take these 3 NULL values and put them as COLUMNS.
DeductionID 1085 = Service Fee (Column Name)
DeductionID 486 = Freight Charge (Column Name)
DeductionID 559 = Handling Charge (Column Name)
For example, let's take the ClaimNum for the highlighted NULLs:
Doing what I want to do, it would end up with the following columns:
CustomerID, PaymentID, ClaimNum, ItemID, Qty, Amount, Service Fee, Freight Charge, Handling Charge
I'm not sure if I need to do a CROSS JOIN, PIVOT or UNPIVOT here. I've never done this in the past and reading Microsoft's website on this isn't really helping. Can anyone give me a hand?
Let me know if you need more info. I appreciate all the help!!

A: You can pivot, then join back to your original data.
ie:
select
    yourtable.* , Service, handling, freight
from yourtable
    inner join
(
    select CustomerID, PaymentID, ClaimNum,
            [1085] as Service, [486] as freight, [559] as handling
    from
            (select customerid, paymentid, claimnum, DeductionID, Amount from yourtable) t
                pivot
        (sum (amount) for DeductionID in ([1085],[486],[559]))p
        ) pt
    on yourtable.CustomerID = pt.CustomerID
    and yourtable.PaymentID = pt.PaymentID
    and yourtable.ClaimNum = pt.ClaimNum
where ItemID is not null


text:
Q: More efficient way of writing this function Is there a more efficient way of writing this?
I try to archive a terser code. Something like:
value: { Angebotsmappen, Angebotsordner, Abheftmappen, Außendienstmappen ...  },
$(function(){
  var tags = [
    { value: 'Angebotsmappen' },
    { value: 'Angebotsordner' },
    { value: 'Abheftmappen' },
    { value: 'Außendienstmappen' },
    { value: 'Firmenmappen' },
    { value: 'Flipcharts' },
    { value: 'Grafikmappen' },
    { value: 'Geschenkschachteln' },
    { value: 'Hotelmappen' },
    { value: 'Infomappen' },
    { value: 'Konferenzmappen' },
    { value: 'Klemmbretter' },
    { value: 'Klemmmappen' }
  ];

  $('#autocomplete').autocomplete({
    lookup: tags,
    width: "auto",
    onSelect: function (suggestion) {
    document.location.href = "/search?q=" + $(this).val()
    }
  });

});

A: var names = ['Angebotsmappen', 'Angebotsordner', 'Abheftmappen', 'Außendienstmappen']; //until whatever
var tags = [];

for(var i = 0; i < tags.length; i++){
    tags.push({'value': tags[i]});
}

Just create an array of names, and use a loop to create a key/value pair.
If you're comfortable with functional programming (maps), this is even shorter:
 ['Angebotsmappen',
'Angebotsordner',
'Abheftmappen',
'Außendienstmappen'].map(function(i){return {value: i}});


text:
Q: About the general context for Markov processes Following the book about Markov Processes from Ethier and Kurtz I understood that the most general requirements for the infinitesimal generator point of view for defining a Markov process from a given operator (which satisfies some hypothesis) in some space $E$, is that this space must be locally compact and separable. My question arises after reading some articles where the space used is only a Polish space, which is the usual setting for probabilities, and I would like to know how can i apply this theory in the given context. What happen if I'm missing the locally compact requisite?
Any enlightenment will be appreciated.


text:
Q: C# Regex performance pure relative JS I had a good experience at the speed of regex in JS.
And I decided to make a small comparison. I ran the following code:
var str = "A regular expression is a pattern that the regular expression engine attempts to match in input text.";

var re = new RegExp("t", "g");

console.time();

for(var i = 0; i < 10e6; i++)
   str.replace(re, "1");

console.timeEnd();

The result: 3888.731ms.
Now in C#:
var stopwatch = new Stopwatch();

var str = "A regular expression is a pattern that the regular expression engine attempts to match in input text.";

var re = new Regex("t", RegexOptions.Compiled);

stopwatch.Start();

for (int i = 0; i < 10e6; i++)
    re.Replace(str, "1");

stopwatch.Stop();

Console.WriteLine( stopwatch.Elapsed.TotalMilliseconds);

Result: 32798.8756ms !!
Now, I tried re.exec(str); vs Regex.Match(str, "t");: 1205.791ms VS 7352.532ms in favor of JS.
Is massive text processing "Not suitable" subject to be done in .net?
UPDATE 1 same test with [ta] pattern (instead t literal):
3336.063ms in js VS 64534.4766!!! in c#.
another example:
console.time();

var str = "A regular expression is a pattern that the regular expression engine attempts 123 to match in input text.";

var re = new RegExp("\\d+", "g");
var result;
for(var i = 0; i < 10e6; i++)
    result = str.replace(str, "$0");

console.timeEnd();

3350.230ms in js, vs 32582.405ms in c#.

A: String in C# is a dangerous beast and you really can shoot yourself in the foot if you use it carelessly, but I don't think given test is representative enough to warrant any generalizations.
First, I did reproduce similar performance for your test case. Adding RegexOptions.Compiled reduced the required time to 30-ish seconds, but this is still significant difference.
The specific test case is probably not a too realistic one, as who would use regex for single char replace? Should you use a dedicated API for this task, you would get comparable results str.Replace('t', '1'); was 1600ms on my machine.
This means for this specific task C# performance is comparable to JS. Whether the C# Regex.Replace() is internally somehow not suitable for single-char replaces or if JS regex version is optimizing the regex away - some JS guru should answer that.
Would a more realistic complex regex have a notable difference - would be interesting to know.
Edit:
I verified that the performance gap remains when the replace results are actually used and when input strings differ in each run (10s vs 35s in my tests). So gap is less, but still there.
Possible reasons
According to hints from this SO question browser implementations delegate some string operations to optimized c++ code. If they do this for string concat, they probably do that for Regex as well. AFAIK, C# Regex ans String classes stay in managed world and that brings some baggage.

A: One of the reasons for the big difference between JS regex and .NET regex is that JS lacks quite a number of advanced features, however .NET is very feature-rich.
Here's two quotes from regular-expressions.info:
JavaScript:

JavaScript implements Perl-style regular expressions. However, it
lacks quite a number of advanced features available in Perl and other
modern regular expression flavors:
No \A or \Z anchors to match the start or end of the string. Use a
caret or dollar instead.
No atomic grouping or possessive quantifiers.
No Unicode support, except for matching single characters with \uFFFF.
No named capturing groups. Use numbered capturing groups instead.
No mode modifiers to set matching options within the regular expression.
No conditionals.
No regular expression comments. Describe your regular
expression with JavaScript // comments instead, outside the regular
expression string.

.NET Framework:

The Microsoft .NET Framework, which you can use with any .NET
programming language such as C# (C sharp) or Visual Basic.NET, has
solid support for regular expressions. .NET's regex flavor is very
feature-rich. The only noteworthy feature that's lacking are
possessive quantifiers.


text:
Q: how to change interface ip in ifconfig with /etc/network/interfaces Hi everybody when modifiying /etc/network/interfaces, saving it and then executing ifconfig i can't see the modification i made..for example here is part of my
/etc/network/interfaces:
auto wlan1
iface wlan1 inet static
address 192.168.0.60
netmask 255.255.255.0
gateway 192.168.0.61

you can see that the IP address of my wlan1 is 192.168.0.60 but when typing ifconfig i have this:
wlan1     Link encap:Ethernet  HWaddr 00:19:70:0f:c2:9c
          inet adr:192.168.0.1  Bcast:192.168.0.255  Masque:255.255.255.0
          adr inet6: fe80::219:70ff:fe0f:c29c/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Packets reçus:758 erreurs:0 :0 overruns:0 frame:0
          TX packets:610 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000
          Octets reçus:73490 (73.4 KB) Octets transmis:127883 (127.8 KB)

(the inet adr:192.168.0.1 and not 198.168.0.60)..if someone can help me I'll be very thankful :)

A: You need to restart networking, or at the very least take the interface down and back up again.
Restart networking (DON'T do this if you're logged in via SSH!):
/etc/init.d/networking restart

Or to 'bounce' the interface (DON'T do this if you're logged in via SSH, via this interface!):
ifdown wlan1
ifup wlan1

A: Merely editing the init configuration for the interface isn't adequate to change it at runtime.  The interface will be configured like you specified at the next boot.
To change it right away, you could restart the init script for the interface.  Additionally, you could simply issue ifconfig wlan1 192.168.0.60 255.255.255.0.  If the gateway has also changed you would need to change the route (something like ip route change default via 192.168.0.61 dev wlan0).


text:
Q: c++ passing subclass as parameter I got a superclass named Obje
#ifndef OBJE_H
#define OBJE_H

#include <QString>

class Obje
{
    public:
    Obje();
    QString name="";
    int id;
    int itemid=0;
    void setItemid(int i);
    virtual void update(){};
};

#endif // OBJE_H

and I got a subclass named Npc
#ifndef NPC_H
#define NPC_H

#include "obje.h"
#include "QString"
#include "QPixmap"
class Npc : public Obje
{
public:

    Npc(QString dir="left");
    QString direction="left";

    QPixmap* spriteSheet = nullptr;
    QPixmap face;
    QPixmap sprites[3];
    void update(int nid);
    QPixmap* getCurrentSprite();
    int currentFrame;
    QString frameDirection;

};

#endif // NPC_H

I also got a class to manage listWidgets
class ListUpdate
{
public:
    ListUpdate();
    static void update(QListWidget *q, vector<Obje>& i);

    private:
    static struct item{
        QString id;
        QString name;
        QPixmap px;
    };

    static QListWidgetItem* newItem(ListUpdate::item &i, int c);
};

#endif // LISTUPDATE_H

When I try to pass object named "npcs" which is type vector"Npc" to ListUpdate::update , it gives this error
Passing the vector:
ListUpdate::update(ui->listWidget,npcs);

error:
C:\Qt Projects\RpgEditor\npcscreen.cpp:64: error: C2665: 'ListUpdate::update': none of the 3 overloads could convert all the argument types

Note: I also got 2 other overload functions and I didn't write them here to prevent unnecessary confusion(that's why it says , "none of the 3 overloads")
Why doesn't it accept my subclass ?

A: The relationship between a base class and a derived class does not extend to containers (except for a few special cases). std::vector<Npc> is not convertible to std::vector<Obje>. Perhaps you can template the update method like this :
template<class T>
static void update(QListWidget *q, vector<T>& i);

This solution will work for vectors of any type that matches the expected interface of Obje including, but not limited to, types that publicly derive from Obje.


text:
Q: Difference between pyclean and py3clean Both pyclean and py3clean seem to have to same purpose:
From pyclean man page: pyclean - removes .pyc and .pyo files
From py3clean man page: py3clean - removes .pyc and .pyo files
The former doesn't seem to remove my __pycache__ files however, while the latter works just fine.
Does anyone know why this might be the case, and what the difference is between these two programs?


text:
Q: returning each DOM elements in an array I used 3 ways in my experiment in returning each HTML elements in an array:

*

*elementsArray.forEach(function(elem) {})

*[].forEach(elementsArray, function(elem) {})

*Array.prototype.forEach.call(elementsArray, function(elem) {})

In my HTML, I have the following elements:

First example:
var query = document.querySelector.bind(document);

query('#example').children.forEach(function(elem) {
  console.log(elem);
})

Uncaught TypeError: query(...).children.forEach is not a function

Second example:
var query = document.querySelector.bind(document);

[].forEach(query('#example').children, function(elem) {
  console.log(elem);
})

Uncaught TypeError: #<HTMLCollection> is not a function

Third example:
var query = document.querySelector.bind(document);

Array.prototype.forEach.call(query('#example').children, function(elem) {
  console.log(elem)
})

My question is, what is it that makes these three different from each other in terms of returning DOM elements? And when should I use each?

A: First example:
The children property of an element is an HTMLCollection, which does not have a forEach method. So this option does not work.
Second example:
[].forEach(query('#example').children, function(elem) {

This attempts to use the children HTMLCollection as a callback function. It's not a function, so this does not work.
You could do:
[].forEach.call(query('#example').children, function(elem) {

Third example:
Array.prototype.forEach.call is roughly equivalent to the [].forEach.call method, except it does not create a new array object. This one will work.
Another Option:
Another slightly-different option would be to use querySelectorAll, which returns a NodeList, which does have a forEach method.
var queryAll = document.querySelectorAll.bind(document);

queryAll('#example > *').forEach(function(elem) {
  console.log(elem);
})

However, the forEach method of NodeList is a newer addition, and browser support is still lacking. You could polyfill it though.

A: You should use querySelectorAll.

Foo

Foo

Foo

var section = document.querySelector('section');
section.querySelectorAll('.foo').forEach(function(e) {
    console.log(e);
})

Here's a JSFiddle


text:
Q: Inbound Windows Firewall Core Networking Rules I've just purchase a Windows Server 2008 R2 VPS plan and I was alarmed to see the default configuration had Windows firewall disabled. I've enabled the firewall and disabled most of the inbound rules, but I have some uncertainty about the rules in the Core Networking category. I know that I don't want DHCP in, so I've disabled both the IP4 and IP6 versions, but I'm at a loss for the other entries in this category:
IGMP
IPHTTPS
IPv6
Multicast Listener Done, Query, Report and Report v2
Neighbor Discovery Advertisement and Solicitation
Packet Too Big
Parameter Problem
Router Advertisement
Router Solicitation
Teredo
Time Exceeded

The only planned inbound connections for this server are HTTP, HTTPS, and RDP, so my preference is to disable all of these rules. However, I want to make sure this isn't going to cause any unexpected problems.

A: You absolutely should leave these on ...

*

*Packet Too Big

*Parameter Problem

*Time Exceeded
You absolutely should leave these on if you are going do be doing any IPv6

*

*IPv6

*Multicast Listener Done, Query, Report and Report v2

*Neighbor Discovery Advertisement and Solicitation

*Router Advertisement

*Router Solicitation
And I would disable these ...

*

*IPHTTPS

*Teredo

*IGMP (unless your doing IPv4 multicasting)

A: You're good in blocking the others as they are mainly internetworking protocols with other networking equipment.


text:
Q: Using Probabilistic argument to show an inequality Question:-Use Chebychev's inequality to show that for any $k>1$, $e^{k+1}\ge k^2$
Chebychev's inequality states that for any random variable $X$ with finite mean, and for $k>0$ $$P(|X-\mu|\le k\sigma)\ge 1-\frac {1}{k^2}$$
Or $$P(|X-\mu|\ge k\sigma)\le \frac {1}{k^2}$$
A general for of the inequality is given in the book of Casella-Berger,
                    $$P(h(X)\ge\epsilon)\le\frac{Eh(X)}{\epsilon}$$
I tried to do it using the argument that for $k>1$ we have to show $P(k^2\le e^{k+1})\ge$ a no. quite close to $1$.
However,I am getting problem in thinking a random variable which will serve the work. I can't even consider the function as $h(k)$ because both the function on either side of the inequality contains $k$.
Hoping to get a hint by my fellow mates.

A: Set $X\sim \exp(1)$. Then you have for $k>1$ \begin{align}
e^{-(k+1)}=P(X>1+k) = P(|X-1|>k)\leq \frac{1}{k^2}
\end{align}
And now it is easy to finish.


text:
Q: How to validate a date is in the format yyyy-MM-dd using kendo validator? I have a kendo date picker that is constructed as follows:
$("#date").kendoDatePicker({
    format: "yyyy-MM-dd",
    footer: " ",
    parseFormats: ["MM/dd/yyyy", "dd/MM/yyyy"]
  });

I would like to use the kendo validator to validate that the date contains a valid date in the format of yyyy-MM-dd. I have tried this:
<input type="date" id="date" placeholder="yyyy-mm-dd" name="date" required data-required-msg="Please enter a date." data-date-msg="Please enter a valid date."/>

While the validator does correctly validate the "required" condition, it does not seem to validate that the date is in the correct format or is a valid date. For instance, "abc" passes as a valid date as does 2013-18-85. How can I use the validator to ensure a valid date in the correct format?

A: The answer is:
<script src="@Url.Content("~/Scripts/kendo/2015.2.805/kendo.aspnetmvc.min.js")"></script>
<script type="text/javascript">
    kendo.ui.validator.rules.mvcdate = function (input) {
        //use the custom date format here
        //kendo.parseDate - http://docs.telerik.com/kendo-ui/api/javascript/kendo#methods-parseDate
        return !input.is("[data-val-date]") || input.val() === "" || kendo.parseDate(input.val(), "@(MvcApplication.AppCulture.DateTimeFormat.ShortDatePattern)") !== null;
    };
</script>

Here is more information: http://docs.telerik.com/kendo-ui/aspnet-mvc/validation
Cheers

A: If you want to validate a date you need to define a rule (no built-in rule).
Try defining:
$("#date").kendoValidator({
    rules: {
        date: function (input) {
            var d = kendo.parseDate(input.val(), "yyyy-MM-dd");
            return d instanceof Date;
        }
    }
});

NOTE: Remember that KendoUI first uses parseFormats option for parsing the date, then converts it to the format option and finally run validations. That's why I use in validation yyyy-MM-dd and not ["MM/dd/yyyy", "dd/MM/yyyy"].


text:
Q: Html sidebar function Is it possible to implement my code by changing only the check box to a button in the same way as the function?And how do I make js code onclick instead of css? Could you tell me both?

<input type="checkbox" id="menuicon">

I tried to implement the onclick function by changing the check box to a button and using javascript, but the function did not work I want to make it with JavaScript only

A: Look at the code below...
First in HTML
In the markup, we have a sidebar open button class="opened", a sidebar close button button class="closed" and the sidebar itself div class="sidebar" inside the aside semantic tag. Note that the close button for the panel is inside the panel itself. Those. it appears on the user's screen only when the panel is open, which is logical.
Now take a look at the CSS
The visual styles of the buttons are not particularly interesting. Interesting sidebar styles. It is positioned fixedly relative to the browser window. In order for the panel to occupy the entire height of the screen, the top: 0 and bottom: 0 properties are set. In addition, by default, we hide the panel outside the visible area using our transform: translateX(-100%) property. The percentage sizes for this property are calculated based on the size of the block to which it is applied. Those. -100% shifts the panel to the left by its full width.
Notice the .sidebar.active selector. It will take effect when the sidebar has both the .sidebar class and the .active class. In this selector, we remove the shift of the sidebar outside the visible area. This means that the sidebar with the .active class is visible to the user.
Now let's take a look at JS
First, we define the identifiers of the elements we need - the open, close and sidebar buttons. This will be needed for what follows. Obviously, when the open button is clicked, we need to add the active class to the sidebar. We defined the function of adding this class for the click event in the addEventListener method.
On the close button we hang a click listener and a deletion function of the .active class for the sidebar.
Here's a simple technique.

const open = document.querySelector('.opened');
const close = document.querySelector('.closed');
const sidebar = document.querySelector('.sidebar');

open.addEventListener('click', () => {
  sidebar.classList.add('active');
});
close.addEventListener('click', () => {
  sidebar.classList.remove('active');
});
body {
  margin: 0;
}

.opened,
.closed {
  border: none;
  padding: 0;
  width: 48px;
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 250px;
  background-color: #e9e9ed;
  transform: translateX(-100%);
  transition: .2s;
}

.closed {
  position: absolute;
  top: 0;
  right: 0;
}

.sidebar.active {
  transform: translateX(0);
}
<button class="opened"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 6h-24v-4h24v4zm0 4h-24v4h24v-4zm0 8h-24v4h24v-4z"/></svg></button>

    <button class="closed"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M23 20.168l-8.185-8.187 8.185-8.174-2.832-2.807-8.182 8.179-8.176-8.179-2.81 2.81 8.186 8.196-8.186 8.184 2.81 2.81 8.203-8.192 8.18 8.192z"/></svg></button>


text:
Q: Is there known URI scheme or URN namespace for Unicode characters? I need to reference to a Unicode character with a URI. Following IANA references list multiple schemes and namespaces but do not mention anything about identifiers for the Unicode characters. Does anyone know if something like this exists already?

*

*http://www.iana.org/assignments/uri-schemes.html

*http://www.iana.org/assignments/urn-namespaces/urn-namespaces.xml
I hoped to find something like

*

*unicode://U+0394

*urn:unicode://0394

*http://unicode.org/unicode/0394
for the greek capital letter delta Δ.
If someone wonders, this is for a semantic web like application that uses URIs as identifiers for concepts, including concepts of the Unicode characters.

A: I'm afraid there is no URL or URN for referring authoritative information on a Unicode character in general. In the Unicode Standard, information about individual characters is partly in the so-called character database (mostly plain text files in specific formats), partly in the Code Charts (PDF files). Neither of them offers a way to point at an individual character. Moreover, the information there is not exhaustive: there are important remarks on individual characters information scattered around the standard.
The Decodeunicode site has individually addressable items, such as
http://www.decodeunicode.org/en/u+0394
but its information content varies a lot and is generally very limited. It is not official, and it currently contains Unicode 5.0 only.
The Fileformat.info site is much more systematic, but it, too, is unofficial. It is basically limited to formal properties and data derivable from them, plus comments extracted from the Code Charts, plus instructions on typing the character in Windows, plus information about support in fonts—but that's quite a lot! Example:
http://www.fileformat.info/info/unicode/char/0394/

A: [ EDIT ] : found this URL matching your needs : http://unicode.org/cldr/utility/character.jsp?a=1F40F
.
Well, there is an URL referencing the authoritative information on the Unicode database, even though it does not describe (as said in the other answer) all the information on one specific character.
You have the following URL, pointing to the latest Unicode database. This is a simple list of existing valid Unicode characters. Some upcoming characters are missing (㋿), and you should expect it to be mutable.

*

*https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
The contents looks like the following, which isn't so practical to use as-is.
$ grep -ai kangaroo UnicodeData.txt -C 7
1F991;SQUID;So;0;ON;;;;;N;;;;;
1F992;GIRAFFE FACE;So;0;ON;;;;;N;;;;;
1F993;ZEBRA FACE;So;0;ON;;;;;N;;;;;
1F994;HEDGEHOG;So;0;ON;;;;;N;;;;;
1F995;SAUROPOD;So;0;ON;;;;;N;;;;;
1F996;T-REX;So;0;ON;;;;;N;;;;;
1F997;CRICKET;So;0;ON;;;;;N;;;;;
1F998;KANGAROO;So;0;ON;;;;;N;;;;;
1F999;LLAMA;So;0;ON;;;;;N;;;;;
1F99A;PEACOCK;So;0;ON;;;;;N;;;;;
1F99B;HIPPOPOTAMUS;So;0;ON;;;;;N;;;;;
1F99C;PARROT;So;0;ON;;;;;N;;;;;
1F99D;RACCOON;So;0;ON;;;;;N;;;;;
1F99E;LOBSTER;So;0;ON;;;;;N;;;;;
1F99F;MOSQUITO;So;0;ON;;;;;N;;;;;

You could build up a hacky « hash-based » namespace with a suffix like this, but that's definitely non-standard.

*

*https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt#1F998

A: Since this is also tagged semantic-web, I will try to pick URIs that are easily (and permanently) dereferenceable and cannot be mistaken for a document describing that character: the data: scheme. Not only can that refer to a character in Unicode, but any encoding, and also any string thereof.
data:;charset=utf-8,%CE%94
Attempting to open this URI should result in a text/plain file with the single character as its content.
If the system accepts IRIs (as many semantic web applications do), the character can be included directly:
data:;charset=utf-8,Δ
This is mapped to the same URI as shown above, and your browser may convert it directly. Specifying UTF-8 is necessary in this case, since the mapping is not defined for other encodings.


text:
Q: Using git subtree merging, while also merging in all branches of all merged subtrees I'd like to use a popular, open source issue tracker (Redmine) that offers git integration. Unfortunately, each project in the tracker can only be associated with one git repo. Creating multiple projects in the tracker is not my ideal setup.
With that in mind, I've attempted to use git subtree merging (explained here, and here). I've created an "umbrella" repo which has merged in each of the numerous other repos that I'm working with.
Unfortunately, the examples given only pull in the master branch of each subtree. Since I have development going on in multiple branches of each subtree, I need to learn how to have this umbrella repo reflect each branch of each subtree.
Is this possible?
Extra Credit: What if 2 subtrees each have a branch with the same name?

A: For those of us not familiar with Redmine, please extend your description to include answers to the following questions: What kind of access into the repository does the tracker need? Will it need to make its own commits? Or, does it just need certain kinds of read access (perhaps to validate commit hashes and scan commit logs for keywords)?
If your tracker only needs read access, you may not need any subtree merging at all. It is perfectly acceptable to have multiple initial commits (allowing multiple, independent histories) in a single repository. The Git project itself does this for some 'extras' (man, html, todo) that share no (commit) history with, but are published alongside the main set of branches for the source code (maint, master, next, pu). For your purpose, it may be enough to setup a remote for each sub-repository and fetch their branch tips into your aggregating repository. Maybe the automatic 'remote tracking branches' would be enough, or maybe you need to take the extra step to create (and update) local branches based on the remote tracking branches.
The subtree merging scheme you describe is probably not meaningful in the general situation where the branches in the source repositories are unrelated or only semi-related. But, if all the source repositories share a set of branches where each branch has a given purpose that is the same across all the repositories, you could probably meaningfully merge them into a kind of super-repository.
But the interesting question is not "what if two repositories have branches with the same name?", but "how do you handle the case where a repository is missing a branch from the shared, 'global' set?".
If all the sub-repositories have the same set of branches, you just do what you did with master, but once for each branch. The problem comes when a particular branch is missing from a repository. You could substitute its master, but that may not always be the right answer. It depends on why you are aggregating the repositories together in the first place and what you expect to 'see' in that subtree of that branch in the super-repository.
If the sub-repositories are not closely related, then I really have my doubts about the reasonableness of this subtree approach. Such an approach for unrelated repositories feels like it would be 'going against the grain'. It is probably still possible, but I doubt there is any tool to help, and you will need to spend some time planning out the corner cases.
If you end up sticking with subtree merges, you might look at the third-party git subtree command. It might help in keeping your myriad repositories synchronized.

Collecting Branches, Without Merging
If Redmine specifies --mirror clone, the implication is that it expects local branches and may not be able to directly read the 'remote tracking braches', so you will probably need to create and update some local branches.

Local Branches Updated From 'Remote Tracking Branches'

*

*Initial Setup
mkdir $COLLECTION_REPO && cd $COLLECTION_REPO &&
git init
git remote add alpha <url/path-to-alpha-repo>
git remote add bravo <url/path-to-bravo-repo>
git remote add charlie <url/path-to-charlie-repo>
for r in $(git remote); do
    git config --add remote.$r.fetch \
      "$(git config remote.$r.fetch | sed -e 's.heads.tags.;s.remotes.tags/all.')"
    git config remote.$r.tagopt --no-tags
done

*Periodic Update
git remote update
git for-each-ref --shell --format \
  'git branch --force --track -l all/%(refname:short) %(refname:short)' refs/remotes \
  | sh

Local Branches That Directly Receive Fetched Branch Tips

*

*Initial Setup
mkdir $COLLECTION_REPO && cd $COLLECTION_REPO &&
git init
git remote add alpha <url/path-to-alpha-repo>
git remote add bravo <url/path-to-bravo-repo>
git remote add charlie <url/path-to-charlie-repo>
for r in $(git remote); do
    git config remote.$r.fetch \
      "$(git config remote.$r.fetch | sed -e 's.remotes.heads/all.')"
    git config --add remote.$r.fetch \
      "$(git config remote.$r.fetch | sed -e 's.heads.tags.g')"
    git config remote.$r.tagopt --no-tags
done

*Periodic Update
git remote update

Both methods end up collecting branches under refs/heads/all/<remote-name>/<branch-name-on-remote>, but the first also has a duplicate set of refs under refs/remotes/<remote-name>/<branch-name-on-remote>. The first uses a normal fetch refspec and uses git branch to duplicate the 'remote tracking branches' (refs/remotes/…) into normal, local branches (refs/heads/all/…). The second one uses a custom refspec to store the fetched refs directly into the destination ref hierarchy.
Because of the way updates are blindly fetched into this combined repository, no one should ever try to directly use it: no commits made directly on its branches, no pushes from outside. If someone were to make commits locally or to push onto one of the branches those commits would be wiped out when the next update is done.
If Redmine can handle a bare repository, I would recommend using one. Use git init --bare and a repo name that ends with .git. Also git config core.logAllRefUpdates true might be a good idea (since this defaults to false in a bare repository).
Besides the all/ prefix in the namespaces, another difference between this approach and a full --mirror clone is that refs outside refs/heads and refs/tags will not be collected. Most of the other common refs are considered 'local' to a repository (which is why they are not copied by a normal clone). Some of the other refs are 'remote tracking branches' (refs/remotes), some 'bisect' record keeping (refs/bisect), git filter-branch 'original' ref backups (refs/original), et cetera. Probably none of these other things are important for Redmine. If they are, they can also be included with additional refspecs.
Creating Extra Initial Commits
To arrange for a branch with an new initial commit, see GitTips page under How to create a new branch that has no ancestor. Two of the recipes involve another repository from which you push or fetch a branch after going through the usual init/add/commit step (exactly what the above recipes do in an automated way).


text:
Q: Cannot unhide a button except in ViewDidLayoutSubviews() I have a UIButton that should only be appearing sometimes. In the viewDidLayoutSubviews I did the following:
 override func viewDidLayoutSubviews() {
    super.viewWillLayoutSubviews()
    clearButtonOutlet.hidden = true

However, when I try to do clearButtonOutlet.hidden = false in other places, the button will not reappear.
At first I thought maybe my constraints were messed up but this makes the button reappear:
override func viewDidLayoutSubviews() {
    super.viewWillLayoutSubviews()
    clearButtonOutlet.hidden = true
    clearButtonOutlet.hidden = false

Why can I not make the button reappear in other places?
EDIT 1: Where I am trying to make the button reappear:
func textFieldDidBeginEditing(textField: UITextField) {

    //some stuff
    switch textField.tag {

        //tag = 3 is the when I want the clear button to show
    case 3:
        //launch the date picker
        launchDatePicker(textField)

        //once DatePicker is launched, show the clear button
        clearButtonOutlet.hidden = false
    default: break
    }

A: Just setting it hidden won't do everything, you need to get the view to redraw. I would set clearButton.hidden = true when you create the button not in viewDidLayout or it will always hide when the view lays out again (resize on iPad or landscape orientation). Then in your textFieldDidBeginEditing method I would set the clearButton.hidden = false like you have and then call view.setNeedsLayout() to force it to relayout and draw.