Q: Using Boost asio to receive commands and execute them I'm trying to make a boost server, which will receive commands and do certain things. Now I would like to create a function, that will receive a file and save it to a specific location. The problem is with serialization. I don't know how can I recognize a command in a stream in an efficint way. I tried with boost::asio::read_until. And actually my code works. First file is being sent and received perfectly. But I am getting an error (The file handle supplied is not valid) when client sends second file. I would be very grateful for every advice. Thanks in an advance!
    bool Sync::start_server() {

    boost::asio::streambuf request_buf;
    std::istream request_stream(&request_buf);
    boost::system::error_code error;

    try {

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
        acceptor.accept(socket); //socket is a member of class Sync
        while (true)
        {

            error.clear();

            size_t siz = boost::asio::read_until(socket, request_buf, "\n\n");

            std::cout << "request size:" << request_buf.size() << "\n";

            string command;
            string parameter;
            size_t data_size = 0;

            request_stream >> command;
            request_stream >> parameter;
            request_stream >> data_size;

            request_buf.consume(siz);//And also this

            //cut filename from path below
            size_t pos = parameter.find_last_of('\\');
            if (pos != std::string::npos)
                parameter = parameter.substr(pos + 1);
            //cut filename from path above
            //command = "save";// constant until I make up other functions
             //execute(command, parameter, data_size);

            save(parameter,data_size);//parameter is filename

        }

    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

And function to save file to a hard drive:
bool Sync::save(string filename, size_t filesize) {
    boost::array<char, 1024> buf;
    cout << "filesize is" << filesize;
    size_t data_size = 0;
    boost::system::error_code error;
    std::ofstream output_file(filename.c_str(), std::ios_base::binary);
    if (!output_file)
    {
        std::cout << "failed to open " << filename << std::endl;
        return __LINE__;
    }
    while (true) {

        size_t len = socket.read_some(boost::asio::buffer(buf), error);

        if (len>0)
            output_file.write(buf.c_array(), (std::streamsize)len);
        if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize)
        {

            output_file.close();
            buf.empty();
            break; // file was received
        }

        if (error)
        {
            socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
            socket.close(error);
            output_file.close();
            buf.empty();
            break;//an error occured
        }

    }

}

A: *

*read_until might read beyond the delimiter (therefore request_buf.size() can be more than siz). This is a conceptual problem when you implement save because you read data_size bytes from the socket, which ignores any data already in request_buf

*These things are code smells:
if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize) {

(never use C-style casts). And
return __LINE__; // huh? just `true` then

And
    buf.empty();

(That has no effect whatsoever).
I present here three versions:

*

*First Cleanup

*Simplify (using tcp::iostream)

*Simplify! (assuming more things about the request format)

First Cleanup
Here's a reasonable cleanup:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <fstream>
namespace ba = boost::asio;
using ba::ip::tcp;

struct Conf {
    int def_port = 6767;
} s_config;

struct Request {
    std::string command;
    std::string parameter;
    std::size_t data_size = 0;

    std::string get_filename() const {
        // cut filename from path - TODO use boost::filesystem::path instead
        return parameter.substr(parameter.find_last_of('\\') + 1);
    }

    friend std::istream& operator>>(std::istream& is, Request& req) {
        return is >> req.command >> req.parameter >> req.data_size;
    }
};

struct Sync {
    bool start_server();
    bool save(Request const& req, boost::asio::streambuf& request_buf);

    ba::io_service& io_service;
    tcp::socket socket{ io_service };
    Conf const *conf = &s_config;
};

bool Sync::start_server() {

    boost::asio::streambuf request_buf;
    boost::system::error_code error;

    try {

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
        acceptor.accept(socket); // socket is a member of class Sync
        while (true) {

            error.clear();

            std::string req_txt;

            {
                char const* delim = "\n\n";
                size_t siz = boost::asio::read_until(socket, request_buf, delim, error);

                // correct for actual request siz
                auto b = buffers_begin(request_buf.data()),
                     e = buffers_end(request_buf.data());

                auto where = std::search(b, e, delim, delim+strlen(delim));
                siz = where==e
                    ? std::distance(b,e)
                    : std::distance(b,where)+strlen(delim);

                std::copy_n(b, siz, back_inserter(req_txt));
                request_buf.consume(siz); // consume only the request text bits from the buffer
            }

            std::cout << "request size:" << req_txt.size() << "\n";
            std::cout << "Request text: '" << req_txt << "'\n";
            Request req;

            {
                std::istringstream request_stream(req_txt);
                request_stream.exceptions(std::ios::failbit);
                request_stream >> req;
            }

            save(req, request_buf); // parameter is filename
        }

    } catch (std::exception &e) {
        std::cerr << "Error parsing request: " << e.what() << std::endl;
    }

    return false;
}

bool Sync::save(Request const& req, boost::asio::streambuf& request_buf) {
    auto filesize = req.data_size;
    std::cout << "filesize is: " << filesize << "\n";

    {
        std::ofstream output_file(req.get_filename(), std::ios::binary);
        if (!output_file) {
            std::cout << "failed to open " << req.get_filename() << std::endl;
            return true;
        }

        // deplete request_buf
        if (request_buf.size()) {
            if (request_buf.size() < filesize)
            {
                filesize -= request_buf.size();
                output_file << &request_buf;
            }
            else {
                // copy only filesize already available bytes
                std::copy_n(std::istreambuf_iterator<char>(&request_buf), filesize,
                        std::ostreambuf_iterator<char>(output_file));
                filesize = 0;
            }
        }

        while (filesize) {
            boost::array<char, 1024> buf;
            boost::system::error_code error;

            std::streamsize len = socket.read_some(boost::asio::buffer(buf), error);

            if (len > 0)
            {
                output_file.write(buf.c_array(), len);
                filesize -= len;
            }

            if (error) {
                socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); // ignore error
                socket.close(error);
                break; // an error occured
            }
        }
    } // closes output_file

    return false;
}

int main() {
    ba::io_service svc;

    Sync s{svc};
    s.start_server();

    svc.run();
}

Prints with a client like echo -ne "save test.txt 12\n\nHello world\n" | netcat 127.0.0.1 6767:
request size:18
Request text: 'save test.txt 12

'
filesize is: 12
request size:1
Request text: '
'
Error parsing request: basic_ios::clear: iostream error

SIMPLIFY
However, since everything is synchronous, why not just use tcp::iostream socket;. That would make start_server look like this:
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
acceptor.accept(*socket.rdbuf());

while (socket) {
    std::string req_txt, line;

    while (getline(socket, line) && !line.empty()) {
        req_txt += line + "\n";
    }

    std::cout << "request size:" << req_txt.size() << "\n";
    std::cout << "Request text: '" << req_txt << "'\n";

    Request req;
    if (std::istringstream(req_txt) >> req)
        save(req);
}

And save even simpler:
void Sync::save(Request const& req) {
    char buf[1024];
    size_t remain = req.data_size, n = 0;

    for (std::ofstream of(req.get_filename(), std::ios::binary);
        socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount());
        remain -= n)
    {
        if (!of.write(buf, n))
            break;
    }
}

See it Live On Coliru
When tested with
for f in test{a..z}.txt; do (echo -ne "save $f 12\n\nHello world\n"); done | netcat 127.0.0.1 6767

that prints:
request size:18
Request text: 'save testa.txt 12
'
request size:18
Request text: 'save testb.txt 12
'
[... snip ...]
request size:18
Request text: 'save testz.txt 12
'
request size:0
Request text: ''

Even Simpler
If you know that the request is a single line, or whitespace is not significant:
struct Sync {
    void run_server();
    void save(Request const& req);

  private:
    Conf const *conf = &s_config;
    tcp::iostream socket;
};

void Sync::run_server() {
    ba::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
    acceptor.accept(*socket.rdbuf());

    for (Request req; socket >> std::noskipws >> req; std::cout << req << " handled\n")
        save(req);
}

void Sync::save(Request const& req) {
    char buf[1024];
    size_t remain = req.data_size, n = 0;

    for (std::ofstream of(req.get_filename(), std::ios::binary);
        socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount());
        remain -= n)
    {
        if (!of.write(buf, n)) break;
    }
}

int main() {
    Sync().run_server();
}

That's the entire program in ~33 lines of code. See it Live On Coliru, printing:
Request {"save" "testa.txt"} handled
Request {"save" "testb.txt"} handled
Request {"save" "testc.txt"} handled
[... snip ...]
Request {"save" "testy.txt"} handled
Request {"save" "testz.txt"} handled


Q: change directory with python I coincidentally found out that I cannot change the actual directory from within a python-code. My Test-Program is as follows:
from os import system

def sh(script):
    system("bash -c '%s'" % script)

sh("cd /home")
sh("pwd")

The output of pwd is not /home, but the directory where the code above lives.
Can someone explain why this happens?

A: The problem is that you execute shell commands instead of actually changing the directory using os.chdir()
Each os.system() call executes the given command in a new shell - so the script's working directory is not affected at all.

A: The directory actually is changed, but in another process, the child of your script. There's one simple rule to remember: a child can never affect the environment (PATH, CWD etc) of its parent.

A: sh("cd /home")
sh("pwd")

^ this spawns 2 separate shells, try:
sh("cd /home; pwd")

A: When you run sh function you spawn a new bash process which then changes current directory and exits.  Then you spawn a new process which knows nothing about what happened to the first bash process.  Its current directory is, again, set to the home directory of the current user.
To change Python process' current working directory use
os.chdir("blah")`

A: Each sh( ) call is generating a different shell, so you are affecting the shell's working directory, not python's.  To change pythons working directory, use chdir()


Q: Delete link for user isn't showing up I am new to web development (I have been coding for about 6/7 months now) in hopes of building my own app. I have been reading and working of the Ruby on Rails tutorial by Michael Hartl.  I am on the chapter 9 section deleting users and am stuck. Everything works for the most part  except that the user link. It just doesn't show on the display page. The users and their avatars fine. I just can't figure out a way to get the user delete link to show.  Below is the code for the user model, the user controller, the session controller where the code current user lives and the view.
Also, when ever i take out the if statement from the user partial the delete link shows. I am not sure whats wrong since I already defined admin, and the current_user.
I would be entirely grateful for any kind of guidance. My project is also on github if the information below isn't sufficient enough
https://github.com/krischery2150/Try2150-master/tree/updating-users
class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile Updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def index
    @users = User.paginate(page: params[:page])
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "Your profile was deleted"
    redirect_to users_url
  end

  private

  def user_params
      params.require(:user).permit(:username, :email, :password,
                                  :password_confirmation, :user_about_me,
                                  :birthday, :avatar, :gender)

  end

  ##Before filters method
  # Confirms that a given user is logged in. Only when these conditions are met the user will
  # be able to update or edit their page

  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger]= "Please Log In"
      redirect_to login_url
    end
  end

# Confirms the correct user.
  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_url) unless current_user?(@user)
  end

  # Confirms an admin user.
  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

end

.
class User < ActiveRecord::Base
    before_save {self.email = email.downcase}
    attr_accessor :remember_token

    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "50x50>" }, default_url: "/images/:thumb/missing.png"
    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
    # this before_save is a callback method. What it does is before it saves the email
    #address it calls back and transforms all the letters into lower case. Had to do the indexing
    #in active record in order for the method to work
    validates :username , presence: true, length: {maximum: 250}
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      #code that ensures that a user  puts the right format for emails in signup
      #fields
    validates :email, presence: true, length:{maximum: 50},
                                      format:{with: VALID_EMAIL_REGEX },
                                      uniqueness:{ case_sensitive: false }
                                      #rails still assumes that uniquess is true
                                      #whether the user types CAMELcase or lowercase
    validates :password, presence: true, length:{maximum: 50}, allow_nil: true
    validates :user_about_me, presence: true
    validates :birthday, presence:true
    has_secure_password

    # Returns the hash digest of the given string.
    def User.digest(string)
      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                    BCrypt::Engine.cost
      BCrypt::Password.create(string, cost: cost)
    end

    ## returns a random user token
    def User.new_token
      SecureRandom.urlsafe_base64
    end

    # Remember a given user to the database for use of persistent sessions

    def remember
      self.remember_token = User.new_token
      update_attribute(:remember_digest, User.digest(remember_token))
    end

    ##returns true if given token matches the digest
    def authenticated?(remember_token)
      return false if remember_digest.nil?
      BCrypt::Password.new(remember_digest).is_password?(remember_token)
    end

    def forget
      update_attribute(:remember_digest, nil)
    end

    def log_out
      forget(current_user)
      session.delete(:user_id)
      @current_user = nil
    end
  end

This is the code in the partial rendering on the index page where all users show up.

      <%= image_tag user.avatar.url %>

    <%= link_to user.username, user %>
    <% if current_user.admin? && !current_user?(user) %>
     | <%= link_to "delete", user, method: :delete,
                                   data: { confirm: "You sure?" } %>
      <% end %>

A: The delete link in your partial has two conditions that are required to be true. The user must be an admin, and the profile must not be their own profile. So if the admin user is the only user, then no delete link will show up.
Try creating a second user and see if the delete link shows up for that user.


Q: Shell script getting 'permission denied' despite using umask 000 before command I have a shell script (build.sh) that ends by attempting to copy some files into a new directory. However it says:

mkdir: cannot create directory
  ‘/files/ondisk/shared//comp/auto/bleeding-1169-b28d31a’: Permission
  denied

when running the script.
The command is:
( umask 000; mkdir -p "${BASE}/${TARGET}" ) || exit -1
( umask 000; cp -r ${STORE} "${BASE}/${TARGET}" ) || exit -1

Does umask 000 not ensure that I am able to write to this location?

A: That double-slash in the pathname looks odd.  Perhaps you have no permission to write the ${BASE}, which might be /files/ondisk/shared.  The umask value is irrelevant, because it only affects the permissions of the directories and files which mkdir and cp create — not the permissions of the existing directory into which you are copying.


Q: What's the best way to update some properties of an object immutably in JavaScript? Say we have an object like:
const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}

Now I want to update all properties' baz to 5 if the type of the property in foo is foo. And I would like to modify it in an immutable way, that means it would not modify the origin object but returns a new object.

A: I normally write Object.create() for shallow copy ,but deep copy (nested object) I do with JSON.parse(JSON.stringify(nestedObject))
const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}
var temp = JSON.parse(JSON.stringify(obj))

for(var i in temp.foo) {
  if(temp.foo[i].type == "foo") {
    temp.foo[i].baz = 5;
  }
}
console.log(temp);
console.log(obj);

A: Object.assign is perfect for this, from the docs:

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

And you can use it like this :
Object.assign(
    {},
    obj,
    {
        foo: {
            a: {
                baz: obj.foo.a.type === 'foo' ? 5 : obj.foo.a
            }
        }
    }
);

A: You can use Object.entries(), Array.prototype.map(), spread element, computed property, Object.assign()

const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}

let key = Object.keys(obj).pop();

let res = {[key]: Object.assign({},
          ...Object.entries(obj[key])
          .map(([prop, {type,baz}]) =>
            ({[prop]: {type,baz:type === "foo" ? 5 : baz}})
          ))};

console.log(res, obj);


Q: How do certain variables/equations affect lists? def list(a, b):
  for k in range(len(a)):
    a[k] = a[k] + b[len(b)-1-k]
  return a

When it comes to manipulating lists, how does python execute a function like this one from a line by line basis. Specifically when i'm presented with an len() or [k] in this code how does it affect a list presented by a user? An example could be
when a = [1,3,5,7,9], b = [1,4,9,8,6] the returned (a) value is [7, 11, 14, 11, 10] I'm unsure how this process is completed in Python.

A:
I am mostly confused by the introduction of [k] in the equation as I don't know how it changes the list.

someList[k] is an item accessor for the kth item of the list. So for a list a = [2, 3, 5, 7], a[k] will return the kth number. For example:
>>> a = [2, 3, 5, 7]
>>> a[0]
2
>>> a[1]
3
>>> k = 3
>>> a[k]
7

Using the accessor alone will just read the value without affecting the list. Python however does allow you to also assign a value to it. Doing so will change the list’s item at that index:
>>> a = [2, 3, 5, 7]
>>> a[2]
5
>>> a[2] = 13 # we change the value
>>> a[2]
13
>>> a # the original list was modified
[2, 3, 13, 7]

So in your loop, when you have a[k] = a[k] + something, you get the value at the kth index, add something to it, and then update the original list at the same index. Since function parameters are passed by references, this updates your original list (and you later return the identical list object from your function).
As for the “something” part, you are doing this: b[len(b)-1-k]. Again, you are using an index to access a single item of the list b. But this time, the index is not a constant or a single variable, but a more complex expression: len(b) - 1 - k. len(b) will return the length of the list b, so ultimaltely, as you iterate through the a list from the beginning, you are iterating b from the end (assuming the same length for both lists). Python will execute the expression first, so in the end it will access b’s item at the index that results from that expression.


Q: How to write numeric expressions in Makefile? I want to write statements about Podman in Makefile. A UID mapping is used here.  But I found that I was always unable to do numerical calculations.
Below is my Makefile. But here ${uid}+1 and similar operations will become empty strings. How should I solve this problem?
Thanks!
HOST_GEM5 := /mnt/disk/cuiyujie/workspace/workGem5/gem5
SIM := ${HOST_GEM5}/X86/gem5.opt
SHELL := /bin/bash
DOCKER_GEM5 := /usr/local/src/gem5

subuidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.UIDMap }}+{{.Size }}{{end }}" ) - 1 )))
subgidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.GIDMap }}+{{.Size }}{{end }}" ) - 1 )))
uid := $(shell id -u)
gid := $(shell id -g)

DOCKER_DIRS_MAP := \
    -v ${HOST_GEM5}/runScripts:${DOCKER_GEM5}/runScripts

MAP_CMD := \
    --user ${uid}:${gid} \
    --uidmap ${uid}:0:1 \
    --uidmap 0:1:${uid} \
    --uidmap $(($uid+1)):$(($uid+1)):$(($subuidSize-$uid)) \
    --gidmap ${gid}:0:1 \
    --gidmap 0:1:${gid} \
    --gidmap $(($gid+1)):$(($gid+1)):$(($subgidSize-$gid))

.PHONY: default clean run build

default: build

build:
    podman run  -it --rm  ${DOCKER_DIRS_MAP} --security-opt seccomp=unconfined  \
    ${MAP_CMD}  \
    gerrie/gem5:v1  "/bin/bash"

clean:
    rm -rf ${HOST_GEM5}/build/*

A: Make always uses /bin/sh as the shell it invokes, both for recipes and for $(shell ...) functions.  /bin/sh is a POSIX-conforming shell.  The syntax you're using is not POSIX shell syntax: it's special enhanced syntax that is only available in the bash shell.
You can either rewrite your scripting to work in POSIX shells (probably by using the expr program to do the math), or add this to your makefile to tell it you want to use bash instead of /bin/sh:
SHELL := /bin/bash

Note, of course, that your makefile will now no longer work on any system that doesn't have a /bin/bash shell.


Q: How can I refer to what called a function in C++? I was wondering if there is a way in C++ to know what called a function? Like the this keyword in Java or JavaScript.
For example, I have a function called insert, which inserts an item into a linked list, I want the linked-list that called those the function insert to call two other functions. How would I do that?
I have this right now, is this valid?
bool linked_list::insert( int i )
{
    bool inserted = false;

    if( this.is_present(i) ) /* function is_present is defined earlier checks if an int is already in the linked-list. */
    {
        inserted = true // already inside the linked-list
    }
    else
    {
        this.Put( 0, i ); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */
        inserted = true; // it was put it.

    }
return inserted;
}

A: For historical reasons, this is a pointer. Use -> instead of ..
bool linked_list::insert(int i) {
    bool inserted = false;

    if(this->is_present(i)) {
        inserted = true; // fixed syntax error while I was at it.
    } else {
        this->put(0, i); // fixed inconsistent naming while I was at it.
        inserted = true;
    }
    return inserted;
}

Usually it is not needed to use this-> at all; you can just do if(is_present(i)).

A: this works in c++ the same as it does in Java. The only difference is that you need to use this-> instead of this. this is a pointer than therefor you cannot use the dot operator to access it's members.

A: why don't you just call the other functions in linked_list::insert(int)? And no, it is not valid, you should put this -> something instead of this.something


Q: Split the string at the word before the next colon? I am trying to split this string between the first colon entry and the next word that includes a colon. The string is a long text. It can have a period or comma between the colons.
For example, if I have the following string.
String s       = "Description: This is the description. Observation: This is the description.";
String[] parts = s.split("REGULAR_EXPRESSION");

The result would be:
This is the description.

For example if the string is
"Description: This is. The, description. Words: words words"

The result would be:
This is. The, description.

A: If you want what you ask, you need a regex that splits by colon and period.
Something like this?
:.+\.

EDIT: Here is a breakdown of this regular expression (as requested by Roman C)
: matches the colon character (:) literally
.+ matches any character one and unlimited times, greedy (except newline)
\. matches the period character (.) literally

A: This splits the string on both the colon or period. Element index 1 (the second element) is what you want. Just trim it.
String description = "Description: This is the description. Observation: This is the description.".
   split("[\\.:]")[1].trim();

You could also pre-trim it:
String description = "Description: This is the description. Observation: This is the description.".
   split("[\\.:] +")[1];

Use "[\\.:]\\s+" if there might be non-space whitespace.

A: Split is not the best method to use. This code gets you the part you want:
String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1");

This also trims the part extracted.

Some test code:
String string = "Description: This is the description. Observation: This is the description.";
String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1");
System.out.println(part);

Output:
This is the description.

A: What about the next?:
String string = "Description: This is the description. Observation: This is the description.";
String str = string.replaceFirst(".*:\\s+(.*)", "$1");


Q: BPEL Apache ODE .deployed file I have created a basic helloworld.bpel process file in eclipse in BPEL project and tried to deploy it Apache ODE. So I followed the steps in this link
   Apache ODE Eclipse BPEL guide.
But in the later stages, after putting the relevant files in WEB-INF folder and running the APACHE ODE the expected .deployed file was not created. And Apache ODE is not detecting the same in ODE browser when I use localhost:8080/ode/processes.
When I tried to launch ODE server in eclipse, I am getting the following errors.
Firstly, this was the error that I got.
"Another instance of derby may have booted into the database"
 Then I restarted Apache Tomcat in services.msc. Then that error stopped showing.
Now this is the error I am stuck with.
"Schema SA does not exist"
Database Class Loader started - derby.database.classpath=''
13:54:26,099 WARN  [GeronimoConnectionEventListener] connectionErrorOccurred called with null
  java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist
  at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown     Source)
  at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
  at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)

A: Looks like there are some problems with the embedded derby database. I'd try to completely redeploy ODE so that the database is extracted from the .war again.

A: You have to execute Eclipse or NetBeans as Administrator.


Q: Django assign user to group during registration based on choice in another field I would like to automatically assign users to a group based on their choice in another field in the user registration field. I am new to Django and I am not sure of the best way to achieve this.
I want to assign the group based on the choice of the "business_location_county" field in the model. In simple terms the group should be the group id where the group "forum_id" equals the id of the business_location_county choice. The group "forum_id" is a custom column added to the Group model.
The models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
from machina.core.db.models import get_model
from django.db.models import Q
from django.contrib.auth.models import Group

Forum = get_model("forum", "Forum")

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    business_location_state = models.ForeignKey(Forum, null=True,  on_delete=models.SET_NULL, limit_choices_to={"lft":1})
    business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2))))

Group.add_to_class('forum_id', models.PositiveIntegerField(null=True, blank=True))

views.py:
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.shortcuts import render
from machina.core.db.models import get_model
from django.db.models import Q

Forum = get_model("forum", "Forum")

class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

def load_counties(request):
    parent_id = request.GET.get('business_location_state')
    counties = Forum.objects.filter(parent_id=parent_id).order_by('name')
    return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties})

forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county')

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['business_location_county'].queryset = CustomUser.objects.none()

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'age','business_location_state', 'business_location_county')

I am attempting to use post_save signal to accomplish this. However before I tackle trying to save the user to the group, I need to figure out how to get the Group id where business_location_state id is equal to Group forum_id.
I tried (unsuccessfully) adding this to the models.py
from django.db.models.signals import (
    post_save
)

def user_addgroup_handler(sender, instance, created, *args, **kwargs):
    g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county)))
    print (g)

post_save.connect(user_addgroup_handler, sender=CustomUser)

Any suggestions on how to achieve this?

A: With help from an expert the following works:
def user_addgroup_handler(sender, instance, created, *args, **kwargs):
    # g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county)))
    # group = Group.objects.get(name=instance.business_location_county.name)

    # for g in CustomUser.objects.all():
    #     print(g.business_location_county_id)

    if created:
        # Get or create group
        new_group, created = Group.objects.get_or_create(
            name=instance.business_location_county.name, forum_id=instance.business_location_county.id)

        # add new group to user
        instance.groups.add(new_group)

post_save.connect(user_addgroup_handler, sender=CustomUser)


Q: NodeJS, ExpressJS & Jade - passing model to knockout? I'm trying to get my expressJS-Model to my .jade-template, but the way I can access the Model with JS on the client-machine.
The idea is simple:
I want to use the Model with Knockout - so I need to give the Model-Object as it is to the client.
If I do the obvious - var t = #{customer} - I ending up with the rendered output var t = [object Object]
So how can I use the object on the client-side?
Thanks!

A: JSON.stringify the object on the server, and JSON.parse it on the client (will only work in IE >= 8, if you need to support older i3-browsers you could provide json-js from douglas crockford: https://github.com/douglascrockford/JSON-js


Q: How to get Bootstrap timepicker date object? Currently using bootstrap timepicker with Angularjs
http://jdewit.github.com/bootstrap-timepicker
The control is displaying well but when i set the ng-model and get the startTime

           <input type="text" class="form-control timepicker" ng-disabled="!useTime" data-template="dropdown" data-show-seconds="true" data-default-time="11:25 AM" data-show-meridian="true" data-minute-step="5" ng-model="startTime" />

The startTime assigned is a string like "11:25 AM" instead of a date object i can manipulate in javascript.
How can i get date object? Do i need to convert it manually?

A: Think this answer seems to be similar to your question.Hope it provides some insight.
Time Binding issue in Bootstrap timepicker


Q: Nested filters in angular for hierarchical data model I have an hierarchical data model with lines of products and then sublines, and then sublines of sublines etc. What I am trying to do is isolate only the sublines that are directly descendants (sons not grandchildren) of a particular line or subline.
Here is my existing data model:
items:[
  {
    "_id": "1",
    "description": "sth1",
    "name": "smname1",
    "level_type": "line",
    "ancestor": "",
    "descendant": "smname2"
   }
  },
  {
    "_id": "2",
    "description": "sth2",
    "name": "smname1",
    "level_type": "subline",
    "ancestor": "smname1",
    "descendant": ""
    }
  },
]

Also for the example above another thing I'm trying to accomplish is to get the children of all the product lines. What I have tried but is not working so far is:
Controller
$scope.prodClassIsALine = function(item) {
        return item.level_type=='line';
    };

    $scope.prodClassIsASubLineof = function(item) {
        return item.ancestor==$scope.prodClassIsALine.name;
};

Tragic proposal just to show you that I need all children of all lines i.e. all items with ancestor names of items that are lines.
Html

{[{item.name}]}

Is this the way we are nesting filters in AngularJS? It seems that filters are iterating over the list that are given as attribute but further than that I can't understand in detail how they work. Please help.
Solution
In script.js
//product is my ng-module
//filter to get all product classes that are lines
product.filter('prodClassIsALine', function() {
    return function(input) {
      var out = [];
      for (var i = 0; i < input.length; i++) {
        if (input[i].level_type=='line') {
            out.push(input[i])
        };
      };
      return out;
    };
});

//filter to get all children of product classes that are lines
product.filter('prodClassLineChild', function() {
    return function(input) {
      var out = [];
      var out2 = [];
      for (var i = 0; i < input.length; i++) {
        if (input[i].level_type=='line') {
            out2.push(input[i])
        };
      };
      for (var i = 0; i < out2.length; i++) {
        for (var j = 0; j < input.length; j++) {
            if (input[j].ancestor==out2[i].name) {
                out.push(input[j])
            };
        };
      };
      return out;
    };
});

Html

{[{item.name}]}

A: do u mean this?

more info here
http://docs.angularjs.org/guide/dev_guide.templates.filters.using_filters
EDIT:
now i got that u didnt wrote filters but scope function, u need something like this
myModule.filter('iif', function () {
    return function (input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
    };
});

my use is class="{{ catalogItem.IS_FINAL | iif : 'IsFinalCatalogItem' : '' }}"
should look like this
myModule.filter('prodClassIsALine', function() {
    return function(item) {
        return item.level_type=='line';
    };
});

p.s. in angular 1.2 they added the standard iif syntax


Q: How do I save my resized image to my Azure Blob Storage in my ASP.NET Core Application? I'm using the ImageSharp library to rescale my images before they are uploaded to Azure, the application hangs with no errors when it reaches the UploadBlob action and I think it's the stream causing it.  When the image is uploaded the information is gathered from the image stream, I create an empty MemoryStream, resize the image using ImageSharp, stuff the MemoryStream with my newly scaled image and try to upload that MemoryStream to Azure and I don't think it likes it as that is where it hangs.
Is MemoryStream the correct thing to use in this instance or is it something else?
CarController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    // Define the cancellation token.
    CancellationTokenSource source = new CancellationTokenSource();
    CancellationToken token = source.Token;

    if (ModelState.IsValid)
    {
        //Access the car record
        _carService.InsertCar(car);

        //Get the newly created ID
        int id = car.Id;

        //Give it a name with some virtual directories within the container
        string fileName = "car/" + id + "/car-image.jpg";
        string strContainerName = "uploads";

        //I create a memory stream ready for the rescaled image, not sure this is right.
        Stream outStream = new MemoryStream();

        //Access my storage account
        BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey);
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName);

        //Open the image read stream
        var carImage = car.ImageFile.OpenReadStream();

        //Rescale the image, save as jpeg.
        using (Image image = Image.Load(carImage))
        {
            int width = 250;
            int height = 0;
            image.Mutate(x => x.Resize(width, height));
            image.SaveAsJpeg(outStream);
        }

        var blobs = containerClient.UploadBlob(fileName, outStream);
        return RedirectToAction(nameof(Index));
    }
    return View(car);
}

A: It's not got anything to do with the ImageSharp library.
You need to reset your outStream position after saving. BlobContainerClient is trying to read from the end of the stream.


Q: How can an untrusted client prove that an ID isn't human meaningful? I have a situation where an untrusted client is generating string IDs, but I don't want them to be human readable.
They don't need to be crytographically random or even unique, I just don't want IDs like "idiot" to be accepted.
How can I go about preventing this?
EDIT: It would be nice if the IDs were "aspirationally-unique", like GUIDs.

A: Here are some ideas:

*

*Convert the supplied ID to a hash or encrypt it. This will result in meaningless strings

*Create a dictionary of words you don't want used, and when the supplied ID contains one of those words, reject it... a PHP example can be found at https://scvinodkumar.wordpress.com/2009/06/17/bad-word-filter-and-replace/

*Require that the IDs not contain sequences where two (or however many) alpha characters are next to each other

If you have any additional info/preference/requirements, let me know.


Q: Fill List with strings from Regex.Matches I'm writing a WPF client for an online browser game as a learning project for C#. I want to import the data that is shown on the website, store it in a model and display it through binding. Usually, i go about it this way:
Retreive data with HttpWebRequest, perform Regex to receive the wanted data, and then store it for further use in the Models. With this particular item, a list of cars and their properties in a table, i need 6 properties of the cars, which i can retrieve with 1 Regex query:
var carInfos = Regex.Matches(HTMLBody, @"(?<== }"">).*(?=</td>)");

I get 42 matches from that string, which means there are 7 CarModels to be filled. Now, if i want to fill the models i would go about it this way:
            Cars.AllCars.Add(new CarModel{
                                             Plate = carInfos[0].Value,
                                             Type = carInfos[1].Value,
                                             NetWorth = int.Parse(carInfos[3].Value,
                                             etc, etc..

                                         });

This is my CarModel:
  public class CarModel : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;
    private string _plate;

    public string Plate{
        get { return _plate; }
        set{
            if (value == _plate) return;
            _plate = value;
            OnPropertyChanged();
        }
    public string Type { get; set; }
    public int NetWorth { get; set; }
    public State CurrentWorth { get; set; }
    public State Location { get; set; }
    public int Condition { get; set; }
    public int Issues { get; set; }

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

How can i do this dynamically? Every 6th property is the car type, location etc. I want to be able to bind hundreds of cars eventually.
Let's say, for instance, i get 12 matches from the Regex, i.e. two cars. the carInfos[0].value would be a Plate, and the carInfos[6].value would also contain a plate. How can i loop through the results in such a manner that these models will be filled accordingly?

A: This should work for you then -
for (int index = 0; index < carInfos.Count/6; index++)
{
    int offest = index * 6;
    Cars.AllCars.Add(new CarModel{
                                 Plate = carInfos[0 + offest].Value,
                                 Type = carInfos[1 + offest].Value,
                                 NetWorth = int.Parse(carInfos[3 + offest].Value,
                                 etc, etc..
                                 });
}

Since you have total of 7 items that's why (42/6) = 7 and item is at offset of multiple of 6 hence the logic for calculation of offset (offest = index * 6)


Q: overpass-turbo.eu find all cities on maps maybe someone can help me with a overpass-turbo.eu-query.
I'd like to highlight (center of it) all cities of a country or region (or current map).
Is there maybe an "simple" example on web?
(Google was not a good friend with this special request, yet. But I am sure someone must tried to search this way already.)
Many thanks for every idea.

A: Here is an example for finding all cities, towns, villages and hamlets in the country Andorra:
[out:json][timeout:25];
// fetch area “Andorra” to search in
{{geocodeArea:Andorra}}->.searchArea;
// gather results
(
  node[place~"city|town|village|hamlet"](area.searchArea);
);
// print results
out body;
>;
out skel qt;

You can view the result at overpass-turbo.eu after clicking the run button.
Note: When running this query for larger countries you might need to increase the timeout value. Also rendering the result in the browser might not be possible due to performance reasons. In this case use the export button and download the raw data instead.


Q: Download multiple MP3 files in the background in Android LEVEL: Beginner
Language: Java
IDE: Android Studio
CASE: Downloading multiple MP3 files from multiple URL's in a row in the background.
ISSUE: download task in the loop to download all the urls.
the songs did download in the following path but aren't fully downloaded (every song is downloaded for 3 seconds/4 seconds basically very less).
don't know what's the problem, It'll be great if i can get any help

*

*receive mp3 url's from API

*download them using the following code. (ISSUE)

*get the path of all and store them in the Database

*fetch the path and play one by one continuously.
private class DownloadTask extends AsyncTask<SongDetails, Integer, String> {
Context context;

public DownloadTask(Context context) {
    this.context = context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    Utilities.showProgressDialog(getActivity(), getFragmentManager());
}

@Override
protected String doInBackground(SongDetails... songDetails) {
    for (SongDetails songs : songDetails
    ) {
        donwloadsong(songs);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Utilities.dismissProgressDialog();
}
}

 for (SongDetails songs : songDetails
    ) {
        downloadTask(songs);
    }

 public void downloadTask(SongDetails songs){
   HttpURLConnection httpURLConnection = null;
   try {
     URL url = new URL(songs.getUrl());
     httpURLConnection = (HttpURLConnection) url.openConnection();
     httpURLConnection.setRequestMethod("GET");
     httpURLConnection.connect();

    int fileLength = httpURLConnection.getContentLength();
         InputStream inputStream = new
    BufferedInputStream(url.openStream(), 8192);
    OutputStream outputStream1;
    outputStream1 = new
    FileOutputStream(Environment.getExternalStorageDirectory() + "/gbeduwarssongs/" + songDetails.getTitle().trim() + ".mp3");
    int count = 0;
         byte data[] = new byte[1024];
    int buffer_length;

    while ((buffer_length = inputStream.read(data)) != -1) {
        outputStream1.write(data, 0, count);
          count += buffer_length;
    }
    outputStream1.flush();
    outputStream1.close();
    inputStream.close();

} catch (Exception e) {
    e.printStackTrace();
    Log.e("Error", "Download Error Exception " + e.getMessage());
} finally {
    if (httpURLConnection != null)
        httpURLConnection.disconnect();
  }
}

A: Rather calling iteration inside a new thread, use iteration first and then start new thread in every iteration. I hope it will help you. I am posting code for your help.
for (SongDetails songs : songDetails) {
        new DownloadTask(pass your song object in constructor).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

and in doInBackground call your downloading method stuff.

A: I offer to use DownloadManager or workmanager for it. AsyncTask has used a bad idea. It has a problem with a memory leak.
The asyncTask use only one thread
The same question


Q: Accessing Shared Calendars with Exchange Web Services I'm trying to access shared calendars from exchange using exchange web services, can someone provide me with info on how I can do this?
I have tried:
ExchangeService myService = new ExchangeService (ExchangeVersion.Exchange2007_SP1);
myService.Credentials = new NetworkCredential ("user@domain.com", "12345");

But I may not always have the passwords for these accounts and the account I'm logged into does has shared calendar access.

A: I have managed to get it working now
Dim _cal As New Microsoft.Exchange.WebServices.Data.FolderId(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Calendar, New Microsoft.Exchange.WebServices.Data.Mailbox(_otherAddress))
Dim _calendarView As New Microsoft.Exchange.WebServices.Data.CalendarView(_startTime.Date, _endTime.Date.AddDays(1))

For Each appointmentItem As Microsoft.Exchange.WebServices.Data.Appointment In _
    service.FindAppointments( _
    _cal, _
    _calendarView)
Next


Q: Access WPF Treeview selected index through a TreeViewItem object I have a treeview with checkboxes for each item using a DataTemplate.
<TreeView ItemsSource="{Binding}">
<DataTemplate DataType="{x:Type local:MatchDataLeaf}">
    <Grid Margin="3">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="240"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="150"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="60"/>
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="0" Orientation="Horizontal">
            <CheckBox x:Name="selectCheckBtn" Grid.Column="0" IsChecked="True" Click="select_Click"
                      Tag="{Binding}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"/>
            <TextBlock Grid.Column="1" Margin="5,0,0,0" Text="{Binding Path=Name}" FontFamily="Arial" FontSize="12" FontWeight="Bold" Foreground="Black" VerticalAlignment="Center"/>
    </StackPanel>
 </Grid>
</DataTemplate>

In the checkbox click event, I'm trying to figure out the selected index in the main tree's binded list. The closest I got is passing the TreeViewItem object along in the CommandParameter, but I can't do anything with it. I was able to the the parent ItemsControl using:
ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(selectedItem);
int s = parent.Items.IndexOf(selectedItem);

But s = -1 here.
I also have the Tag on the checkbox that has the underlying object in it. Sure, I can do a Find on my list for the object, but it just seems like there must be a simpler way to find the index.

A: The ItemsControl you are fetching might be the StackPanel, or the Grid.  You should be able to access the Checkbox through the event sender, and navigate up to the TreeViewItem and TreeView and use IndexOf.
 private void CheckBox_Click(object sender, RoutedEventArgs e)
 {
        CheckBox cb = (CheckBox)sender;
        StackPanel sp = (StackPanel)cb.Parent;
        Grid g = (Grid)sp.Parent;
        ContentPresenter cp = (ContentPresenter)VisualTreeHelper.GetParent(g);
        IList l = (IList)myTreeView.ItemsSource;
        object o = cp.Content;
        MessageBox.Show(l.IndexOf(o).ToString());
 }


Q: iOS 9 simulator can't show the whole screen For some reason, when I run some old projects, the simulator can't load the full screen:

Any suggestion?


Q: Azure FreeRtos middleware and DPS, on ESP32 I am working on a project, where I am using the Azure FreeRTOS Middleware Stack on ESP32.
I would like to introduce DPS to provision all my 3K upcoming devices.
The Stack has got a DPS option, but I would like some advice as I would like to generate one global bin file, for all 3K devices. I would like DPS to create the device on IoT Hub and also provide the necessary keys to the device so it can generate the SAS token for each device id.
The device ID will be either the serial number or mac number of the ESP32 device.
What i want to avoid is creating a seperate bin file for each device.
Can this be possible? or am i miss understanding DPS?

A: DPS will not provide you neccessary keys for each device. To work with Azure IoT (either DPS or Hub), you must have per-device credential flash to your device, this is usually done during manufacturing phase.
When you use DPS group enrollment, you get a group key from DPS and use a formula to generate per-device key (hash the group key and enrollment/device id), you need a method to flash 3k keys to 3k devices on production line.

A: DPS do actually provision a device AUTOMATICALLY. You don't extra step.
Let me explain how.
Step 1: Things you have to do once from the Azure portal:

*

*You create/you have an Azure IoT Hub up and running;

*Your create/you have azure DPS up and running;

*You create/you have a group enrolment with symmetric key from within DPS;

*You keep the primary key of your group enrolment for use in a bit. Let’s call the primary key “KEY”

Step 2: programming
From your firmware source code:

*

*Write a code function that returns a device ID that’s unique for a device. You can use a string followed by the device MAC address, that you usually get from the Wifi interface (or Ethernet interface). For example: “3Kdevice-3454e210228c” the prefix will be the same for all devices you’ll have, but the hex numeric suffix will be different for each device. Let’s call this string REG_ID.

*Write a code function that creates for the device it runs on, the symmetric key from both the primary key (aka KEY) of your enrolment and the registration ID (aka REG_ID). You do that by doing a SHA256 (see DPS doc for that). Let’s call the computed symmetric key “SYM_KEY”;

*Use the azure SDK to  get the credentials from DPS by presenting the registration ID (aka REG_ID) and the computed symmetric key (SYM_KEY) to it;

*You can connect to the IoT Hub with the credentials you got at point 3.


Q: Reading multiple cookie I would like to know how do I detect multiple cookies. I have two button with class- .attack_enabled and .restore_enabled, both create cookie called attackcompletecookie and restorecompletecookie, respectively.
How do I detect both cookies and add a class to .territory_middle_complete
Here's my code:
$(".attack_enabled").click(function(){

   createCookie('attackcompletecookie','attack_cookie');

});

$(".restore_enabled").click(function(){

   createCookie('attackcompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');

});

if(atkcomplete){
   console.log(atkcomplete);
   $(".territory_middle_complete").addClass("displayblockzindex2");
}

A: Try to use id instead class to refer in jQuery, leave the classes for CSS.
Check it here http://jsfiddle.net/hbzqnrm8/5/
I hope it helps you.
<button id="attack_enabled">ATTACK</button>
<button id="restore_enabled">RESTORE</button>

ADD A CLASS HERE

I've edited your jQuery code, and add what I think you want to achieve. Of course if you want to check the existance of the cookie when clicking the "restore" button, if not, just move the if condition wherever you needed, but not outside the click function, because it will be executed only on loading the file.
$("#attack_enabled").click(function(){
   createCookie('attackcompletecookie','attack_cookie');
});

$("#restore_enabled").click(function(){
   createCookie('restorecompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');
   if(atkcomplete)
   {
       alert(atkcomplete);
       $(".territory_middle_complete").addClass("displayblockzindex2");
    }
});

function createCookie(cookieName, cookieId) {
    document.cookie = cookieName + '=' + cookieId;
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}


Q: Error Code:1262 when loading to mySQL I have a little bit of an issue when trying to load tsv file 2gb to mysql database. Error Code:1262
As this is quite big file how can i open/change so i can load it into the system?

A: this will be csv file and as you aware that it is to big.
if you are in local server you can change in .ini file and increase the limit for uploading file and if you are using web server add in .htaccess file
in the .htcaccess file add the following:
php_value upload_max_filesize 500M
php_value post_max_size 500M

in php.ini add:
upload_max_filesize = 500M
post_max_size = 500M

or you can split your csv file


Q: Putting regex into a variable REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g
(echo "1.2.3" | grep -Eq "$REG" ) && echo "matched" || echo "did not match"

I get the error:
test.sh: line 2: syntax error near unexpected token `('
test.sh: line 2: `REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g'

Not very much to go on here. Trying to see if 1.2.3 meets the regex expression.
The expression I got from here: https://github.com/mojombo/semver/issues/232

A: Use quotes so the shell doesn't barf on special characters.
REG='/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g'

Note that this regex will not work with grep. POSIX regex syntax is different and more limited than Perl syntax, which is what you've got.

A: You ran into two major problems

*

*Bash handling special characters, escapes, and anything else it found in your string before storing it. This is solved by single quoting your string to prevent bash expansion/interpretation.

*The Regex was written in Perl syntax, which grep does not support, it uses POSIX which is slightly different from Perl even though the two are similar. This is solved by removing the surrounding / /g and replacing all instances of \d which is not recognized by POSIX with [0-9].
Result:
REG='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$'


Q: C# tableAdapter.Update() won't change the database record I want my program to be able to change one row in my Access database with the data from my form.
The problem is that the update-function doesn't do anything.
There are no error messages and the program compiles correct. Nothing changes in the database.
Here is the code:
private void btnTallenna_Click(object sender, EventArgs e)
{
    string[] vanhat = new string[9];
    lueVanhatTiedot(vanhat);

    hevosetTableAdapter.Connection.Close();
    hevosetTableAdapter.Connection.Open();
    try
    {
        hevosetTableAdapter.Update(txtNimi.Text, txtIka.Text, cmbPaino.Text, cmbKaytto.Text, cmbRotu.Text, cmbSukupuoli.Text, cmbKunto.Text, cmbRehunkayttokyky.Text, int.Parse(vanhat[0]), vanhat[1], vanhat[2],vanhat[3], vanhat[4], vanhat[5], vanhat[6], vanhat[7], vanhat[8]);
        this.hevosetBindingSource.EndEdit();
        hevosetTableAdapter.Update(this.dsHevonen.Hevoset);
        hevosetTableAdapter.Connection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
    hevosetTableAdapter.Connection.Close();
}

lueVanhatTiedot() function gets the original data for the record.
Still learning to program so there may be stupid mistakes which I just can't notice. :)

A: Have you called the "AcceptChanges" method on the DataSet?


Q: Mongoose ignores $ne while updating document I'm building a persistent html fields framework using Node, Mongoose, and Socket.io for the backend. I've run into what seems like a bug in Mongoose's update method.
The documents in mongo look like this:
{
    "_id" : "pickable_qty",
    "currently_connected" : [ ],
    "locks" : [
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.1,
                product_item_id: 5555
            }
        },
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.2,
                product_item_id: 5555
            }
        },
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.1,
                product_item_id: 1234
            }
        }
    ],
    "definition" : {
        "ajax_url" : "/persistent-fields/pickable_qty",
        "unique_keys" : [
            "product_item_id",
            "merchant_warehouse_id"
        ],
        "max_idle_seconds" : 30,
        "field_type" : "text"
    },
    "__v" : 0
}

The problem arises when I start inserting subdocuments into the locks array.
I insert them using Mongoose's update method like so:
FieldSchema.update(
    {
        _id: 'pickable_qty',
        'locks.unique_values': {
            '$ne': {
                merchant_warehouse_id: 11.1,
                product_item_id: 5334
            }
        },
        'definition.unique_keys': {
            '$all': [
                'merchant_warehouse_id',
                'product_item_id'
            ]
        }
    },
    {
        '$push': {
            locks: {
                socket_id: 'eQYVyz1z28rJZRPpAAAB',
                unique_values: {
                    merchant_warehouse_id: 11.1,
                    product_item_id: 5334
                }
            }
        }
    },
    function(err, count, res){
        console.log('err:', err, 'count:', count, 'res:', res);
        //err: null count: 1 res: { ok: true, n: 1, updatedExisting: true }
    }
);

The first insert works exactly as expected, there were no locks in the array containing the unique values {merchant_warehouse_id: 11.1,product_item_id: 5334} so the document was found and the lock subdocument was inserted.
However running this same update the second time should not insert a new locks subdocument because one already exists with the same unique_values and the $ne part of the query should cause it to return no matches to update.
I have confirmed that doing a find with the same query returns no documents both on the MongoDB command line and using Mongoose's own Schema.find method, but the Schema.update method still finds a document and inserts a duplicate lock subdoc.
Am I just going crazy or is there a reason why Mongoose's find method won't retrieve the document while update will?

A: The problem is that you are querying whether or not an object matches a subdocument, and this can be tricky. What you want to do use a combination of $elemMatch and $ne in your query.
var query = {
    _id: 'pickable_qty',
    'locks': {
        $elemMatch: {
            merchant_warehouse_id: {
                $ne: 11.1
            },
            product_item_id: {
                $ne: 5334
            }
        }
    },
    'definition.unique_keys': {
        '$all': [
            'merchant_warehouse_id',
            'product_item_id'
        ]
    }
}

It's basically a query for a document inside of an array.

A: After using MongoDB's query profiler, I figured out that Mongoose was switching the order of the keys in the lock's unique_values object while doing the update query. Then it was inserting the duplicate subdocuments with the keys in the correct order. So apparently MongoDB's $ne operator will match nested subdocument arrays only if the keys in the subdocument are in the same order as your query.


Q: Why does my SURF.detectAndCompute returns none before the array? I am trying to extract key point and descriptors but my SURF.detectAndCompute returns None in front of the array and because of that I cannot do the clustering. Below is my code:
image_paths = []
image_group_id = []
image_group_names = os.listdir(train_path)
descriptors = []
SURF = cv2.xfeatures2d.SURF_create()
SURF.setHessianThreshold(5000)
for group_id, train_group_path in enumerate(os.listdir(train_path)):
    image_path = train_path + '/' + train_group_path
    for path in os.listdir(image_path):
        full_image_path = image_path + '/' + path
        image_paths.append(full_image_path)
        image_group_id.append(group_id)
        _, des = SURF.detectAndCompute(cv2.imread(full_image_path), None)
        descriptors.append(des)

And this is the  of the descriptors that I tried to print:
[None, array([[ 0.00140431,  0.00414569,  0.00156097,  0.00508978, -0.01072729,
         0.03109567,  0.01673188,  0.04477221, -0.04659119,  0.0652261 ,
         0.04661125,  0.08301401, -0.00103816,  0.0069982 ,  0.00168295,
         0.00876924,  0.01606237, -0.00151245,  0.01966742,  0.01294267,
        -0.2951115 , -0.14716513,  0.32090443,  0.18698329,  0.21934257,
        -0.02404423,  0.29070902,  0.17538053, -0.03951943,  0.02635496,
         0.04406727,  0.02923489,  0.03092461, -0.04000381,  0.03236163,
         0.04539306, -0.26897454, -0.112547  ,  0.33476326,  0.29709056,
         0.2916087 , -0.01106649,  0.351532  ,  0.19272245, -0.07418256,
        -0.04663706,  0.07452377,  0.04671762,  0.00109221,  0.00404389,
         0.0019812 ,  0.0101865 ,  0.00381939, -0.01452297,  0.05944061,
         0.05199388,  0.0035292 , -0.04607308,  0.03296318,  0.04701661,
        -0.00757545, -0.00286426,  0.00760168,  0.00306828]],
      dtype=float32)

The None isn't supposed to be there. What can I do to fix this? I am new in this field, any advice is very appreciated. Thank you!


Q: Two accounts need new SSH keys I've got two accounts which are used for automated file uploads on a server and company policy requires that they are updated after 3 years. I wasn't here 3 years ago and I've not done this before.
I don't understand how to create the SSH keys for two separate accounts. The .ssh directory has the id_rsa keys, but there's no specifying which user account is needed. From what I've read, I believe the keys would need to go into the .ssh folder for the associated account but I've been informed that the keys are under a further account, different to the two above.
I hope this isn't too confusing, I can't really give specific details without potentially compromising our security.

A: Usually key creation can be done by the following steps. Perhaps this will help you achieve your goal.

*

*Create new keys with
ssh-keygen -t rsa

*Insert the content of id_rsa.pub into the authorized_keys file under /home/user/.ssh/authorized_keys - might be called authorized_keys2
cat id_rsa.pub > /home/user/.ssh/authorized_keys (this will overwrite the current content of authorized_keys

*copy/download id_rsa to your client and connect to your account using the key.
In case you need ppk keys, you can use PuTTYgen in order to convert your key above.


Q: Reset scrollbar state on switching content I have a sample code with one button and 2 images that are shown conditionally. I need to scroll to the top of the content div, where images are shown but it stays in the same position as the previous content.
I tried to separate buttons and content between separate divs but it didn't help. Is there a way to achieve this with only CSS.
Here is the code and working example in codesandbox:
https://codesandbox.io/s/upbeat-sutherland-9r0kh?file=/src/styles.css:0-206
The page:
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [isOpen, setIsOpen] = useState(true);

  return (

        <button onClick={() => setIsOpen(!isOpen)}>switch</button>

        {isOpen ? (

        ) : (

        )}

  );
}

CSS:
.App {
  font-family: sans-serif;
  text-align: center;
  display: flex;
  align-items: center;
}

.buttonContainer {
  position: fixed;
  height: 100vh;
}

button {
  position: absolute;
  height: 100px;
}


Q: Xpath - Extracting multiple specific differnt parts of text strings from one text node I have three samples of text nodes that and I want to extract three different parts of the text, using a universal x-path.
First

                This is an amazing game from the company Midway Games. Excellent gameplay. Very good game.

Second

                New Line Cinema distributed this movie in 1995.

Third

                New game from 2011, with new 3D graphics. This game was made by NetherRealm Studios.

The extraction should be either Midway Games or New Line Cinema or NetherRealm Studios
Note that the text node allways include just one company, never two or three (just one).
My try is from this question but the problem is that it dosen't work nor include all three companies.
substring('Midway Games',1,12*contains(//p[@class='product-summary']/following-sibling::text()[1], 'Midway Games'))

A: As the input will only contain one of them, you can use concat to join the results.
concat(
  substring('Midway Games', 1,
      12*contains(//p[@class='product-summary'], 'Midway Games')),
  substring('Line Cinema', 1,
      11*contains(//p[@class='product-summary'], 'Line Cinema')),
  substring('NetherRealm Studios', 1,
      19*contains(//p[@class='product-summary'], 'NetherRealm Studios'))
)

You can remove the line breaks that I added for readability as you want.
I had to fix the query you provided: the text nodes are no following-siblings, but children. Your XPath processor will query the (concatenated) text nodes below that element anyway as contains works on strings.


Q: How do you create a read-only user in PostgreSQL? I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be:
GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy';

What is the equivalent command or series of commands in PostgreSQL?
I tried...
postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy';
postgres=# GRANT SELECT ON DATABASE mydb TO xxx;

But it appears that the only things you can grant on a database are CREATE, CONNECT, TEMPORARY, and TEMP.

A: Grant usage/select to a single table
If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so:
GRANT CONNECT ON DATABASE mydb TO xxx;
-- This assumes you're actually connected to mydb..
GRANT USAGE ON SCHEMA public TO xxx;
GRANT SELECT ON mytable TO xxx;

Multiple tables/views (PostgreSQL 9.0+)
In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one:
GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx;

This only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future:
ALTER DEFAULT PRIVILEGES IN SCHEMA public
   GRANT SELECT ON TABLES TO xxx;

Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow.
Multiple tables/views (PostgreSQL versions before 9.0)
To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view:
SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;'
FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE nspname = 'public' AND relkind IN ('r', 'v', 'S');

This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created.

A: From PostgreSQL v14 on, you can do that simply by granting the predefined pg_read_all_data role:
GRANT pg_read_all_data TO xxx;

A: Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:
test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;

A: If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser)
db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser;
GRANT
db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser;
GRANT
db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser;
GRANT

If your database is using customschema, execute the above but add one more command:
db=> ALTER USER readonlyuser SET search_path=customschema, public;
ALTER ROLE

A: The not straightforward way of doing it would be granting select on each table of the database:
postgres=# grant select on db_name.table_name to read_only_user;

You could automate that by generating your grant statements from the database metadata.

A: Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):
$ sudo -upostgres psql postgres
postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE';
postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run:
$ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf
$ sudo service postgresql reload

A: By default new users will have permission to create tables. If you are planning to create a read-only user, this is probably not what you want.
To create a true read-only user with PostgreSQL 9.0+, run the following steps:
# This will prevent default users from creating tables
REVOKE CREATE ON SCHEMA public FROM public;

# If you want to grant a write user permission to create tables
# note that superusers will always be able to create tables anyway
GRANT CREATE ON SCHEMA public to writeuser;

# Now create the read-only user
CREATE ROLE readonlyuser WITH LOGIN ENCRYPTED PASSWORD 'strongpassword';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonlyuser;

If your read-only user doesn't have permission to list tables (i.e. \d returns no results), it's probably because you don't have USAGE permissions for the schema. USAGE is a permission that allows users to actually use the permissions they have been assigned. What's the point of this? I'm not sure. To fix:
# You can either grant USAGE to everyone
GRANT USAGE ON SCHEMA public TO public;

# Or grant it just to your read only user
GRANT USAGE ON SCHEMA public TO readonlyuser;

A: Reference taken from this blog:
Script to Create Read-Only user:
CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234'
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';
\connect YourDatabaseName;

Assign permission to this read-only user:
GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User;
GRANT USAGE ON SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Assign permissions to read all newly tables created in the future
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User;

A: I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

A: I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!
user@server:~$ sudo su - postgres

create psql user:
postgres@server:~$ createuser --interactive
Enter name of role to add: readonly
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

start psql cli and set a password for the created user:
postgres@server:~$ psql
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
Type "help" for help.

postgres=# alter user readonly with password 'readonly';
ALTER ROLE

connect to the target database:
postgres=# \c target_database
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
You are now connected to database "target_database" as user "postgres".

grant all the needed privileges:
target_database=# GRANT CONNECT ON DATABASE target_database TO readonly;
GRANT

target_database=# GRANT USAGE ON SCHEMA public TO readonly ;
GRANT

target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;
GRANT

alter default privileges for targets db public shema:
target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
ALTER DEFAULT PRIVILEGES

A: Taken from a link posted in response to despesz' link.
Postgres 9.x appears to have the capability to do what is requested.  See the Grant On Database Objects paragraph of:
http://www.postgresql.org/docs/current/interactive/sql-grant.html
Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)."
This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES".
Also present is information about how GRANT functionalities compare to SQL standards.

A: CREATE USER username SUPERUSER  password 'userpass';
ALTER USER username set default_transaction_read_only = on;


Q: MongoDB Conditional Projection based on existence of query of subdocument in Array I have a schema in which properties can have respective "override" documents stored in an Array("overrides")
E.g.
{
    foo:'original foo',
    overrides: [
        {property:'foo', value:'foo override'},
        {property:'bar', value:'bar override'},
    ]
}

I want to project a field for the override value if it exists, otherwise, the original property.
So something like this
project: { overrideOrOriginal: {$cond: fooOverrideExists ? fooOverrideValue : originalFooValue }

So in this example, I would expect overrideOrOriginal to equal 'foo override' . If -  {property:'foo', value:'foo override'} subDoc didn't exist in the overrides array (or if overrides array itself didn't even exist)...then I'd expect overrideOrOriginal = 'original foo'
How can I do this?
I was thinking I'd need $exists in tandem with $cond. But the complication here is that I'm searching for a subDoc in an Array based on a query
Thanks!

A: *

*$ifNull to check if field is null then return empty array

*$in to check "foo" is in overrides.property array

*$indexOfArray to get index of array element in overrides.property array

*$arrayElemAt to get element by specific index return from above operator

let fooOverrideExists = "foo";
db.collection.find({},
{
  overrideOrOriginal: {
    $cond: [
      {
        $in: [
          fooOverrideExists,
          { $ifNull: ["$overrides.property", []] }
        ]
      },
      {
        $arrayElemAt: [
          "$overrides.value",
          { $indexOfArray: ["$overrides.property", fooOverrideExists] }
        ]
      },
      "$foo"
    ]
  }
})

Playground

A: Query

*

*find the property , key-value(kv) (it works for all property names)
(assumes your schema with only string value the value of that   property)

*checks if that it exists in the overrides array

*if it exists, takes the value from the array

*else keeps the original

*checks also cases where override doesnt exists, or its empty array, or property doesn't exist
*in case you want to do it only for a specific "foo" ignore the big first $set and use this code
Test code here
db.collection.aggregate([
  {
    "$set": {
      "kv": {
        "$arrayElemAt": [
          {
            "$filter": {
              "input": {
                "$objectToArray": "$$ROOT"
              },
              "cond": {
                "$eq": [
                  {
                    "$type": "$$this.v"
                  },
                  "string"
                ]
              }
            }
          },
          0
        ]
      }
    }
  },
  {
    "$set": {
      "index": {
        "$indexOfArray": [
          "$overrides.property",
          "$kv.k"
        ]
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "overrideOrOriginal": {
        "$cond": [
          {
            "$or": [
              {
                "$eq": [
                  "$index",
                  -1
                ]
              },
              {
                "$not": [
                  "$overrides"
                ]
              }
            ]
          },
          "$kv.v",
          {
            "$arrayElemAt": [
              "$overrides.value",
              "$index"
            ]
          }
        ]
      }
    }
  }
])


Q: Using OpenCV to take a particular amount of images without pressing any key I wish to write a program for face recognition. I want my program to automatically take a specific number of images(say,5). Here is what I am currently doing:
import cv2

cam=cv2.VideoCapture(0)
a=0
count=0
for a in range(5):
    ret,img=cam.read()

    cv2.imshow("Test",img)

    if not ret:
        break

    k=cv2.waitKey(1)

    print("Image"+str(count)+"saved")
    file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg'
    cv2.imwrite(file,img)
    a+=1

cam.release()
cv2.destroyAllWindows()

cam.release()
cv2.destroyAllWindows()

It shows "Image 0 saved" five times but in the folder(ad2), there is only a single image. Need some guidance.
Thank you

A: Lets start interpreting the code line-by-line:

*

*

*

*Variable initialization

*

*
import cv2

cam=cv2.VideoCapture(0)
a=0
count=0

*You load the opencv library and initialize the cam variable for webcam display. Then both a and count are intialized to 0. Now count variable is understandable, most probably count count the frames. What does a do?

*

*Display and save frames

*

*First-part

*
for a in range(0, 5):
    ret,img=cam.read()
    cv2.imshow("Test",img)

    if not ret:
        break

*variable a declared again so we don't need to intialize at the beginning. Then current web-frame is being fetched. The frame is given as an input to imshow without even the current frame returned or not. The correct logic should be:

*
for a in range(5):
    ret,img=cam.read()

    if ret:
        cv2.imshow("Test",img)

*Second-part

*
k=cv2.waitKey(1)

print("Image"+str(count)+"saved")
file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg'
cv2.imwrite(file,img)
a+=1

*Now, the k variable is initialized as a key for quiting the program when a key is pressed. Say, when q is pressed program terminates.

*
k=cv2.waitKey(1) & 0xFF

if k == ord('q'):
     break

*But if you break during the process, then you can't save the images. Therefore break should be at the end of the line.

*For the rest of the code, you can use a as a counter. If you specify the start and end values. For each value a is increased by one. Then you can use it to discriminate the frames.

Code:
# Load the library
import cv2

# Initialize webcam
cam = cv2.VideoCapture(0)

# Save the frames
for a in range(0, 5):

    # Get current frame
    ret, img=cam.read()

    # If frame is returned
    if ret:

        # Set the file-name
        file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2' + str(a) + '.jpg'

        # Write the frame
        cv2.imwrite(file, img)

        # Inform the user
        print("Image" + str(a) + "saved")

        # Display the frame
        cv2.imshow("Test", img)

        # If q is pressed quit
        k=cv2.waitKey(1) & 0xFF
        if k == ord('q'):
            break

# Release the object
cam.release()

# Close the window
cv2.destroyAllWindows()


Q: Gradle Script To call a REST Web service without any 3rd party plugins, any pointers? Hi I need to call a REST service as part of the buildscript (Gradle) without any 3rd party plugins, how could I use Groovy to do that?
(My first attempt)
repositories {
    mavenCentral()
}
      dependencies {
            complie "org.codehaus.groovy.modules.http-builder:http-builder:0.5.2"
    }

task hello {
    def http = new HTTPBuilder("http://myserver.com:8983/solr/select?q=*&wt=json")
    http.auth.basic 'username', 'password'
    http.request(GET, JSON ) { req ->
    }
}

A: I'm using the JsonSlurper it looks quite simple and OS independent:
import groovy.json.JsonSlurper

String url = "http://<SONAR_URL>/api/qualitygates/project_status?projectKey=first"
def json = new JsonSlurper().parseText(url.toURL().text)
print json['projectStatus']['status']

A: Can't you just do
new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text

A: Java has had a proper HTTP Client in the standard library since Java 9.
Here's how you can use that from a Gradle script (Groovy):
import groovy.json.JsonSlurper

import java.net.http.*
import static java.nio.charset.StandardCharsets.UTF_8

tasks.register('hello') {
    def url = new URL("http://myserver.com:8983/solr/select?q=*&wt=json")
    def req = HttpRequest.newBuilder(url.toURI()).GET().build()
    def res = HttpClient.newHttpClient()
       .send(req, HttpResponse.BodyHandlers.ofString(UTF_8))
    def parsedJson = new JsonSlurper().parseText(res.body())
    println parsedJson
}

A: this is working guys
import java.io.*
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.EncoderRegistry
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2'
    }
}

task hello {
    def http = new groovyx.net.http.HTTPBuilder("http://local.com:8983/solr/update/json")

    http.request(POST, JSON ) { req ->
        req.body{

        }
        response.success = { resp, reader ->
            println "$resp.statusLine   Respond rec"

        }
    }
}

A: This question is ranking so well on search engines that I keep stumbling on it.
However, as others commented, I don't really like the accepted answer because it relies on curl.
So here is a complete example w/o any prerequisite (no plugin, no curl, ...):
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
task getExample {
    doLast {
        def req = new URL('https://jsonplaceholder.typicode.com/posts/1').openConnection()
        logger.quiet "Status code: ${req.getResponseCode()}"
        def resp = new JsonSlurper().parseText(req.getInputStream().getText())
        logger.quiet "Response: ${resp}"
    }
}
task postExample {
    doLast {
        def body = [title: "foo", body: "bar", userId: 1]
        def req = new URL('https://jsonplaceholder.typicode.com/posts').openConnection()
        req.setRequestMethod("POST")
        req.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
        req.setDoOutput(true)
        req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8"))
        logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done on first read
        def resp = new JsonSlurper().parseText(req.getInputStream().getText())
        logger.quiet "Response: ${resp}"
    }
}

You can run this on your box as they use a public development API.

A: The easiest way to call REST from groovy without external libraries is executing CURL. Here's an example of calling Artifactory, getting JSON back and parsing it:
import groovy.json.JsonSlurper

task hello {
    def p = ['curl', '-u', '"admin:password"', "\"http://localhost:8081/api/storage/libs-release-local?list&deep=1\""].execute()
    def json = new JsonSlurper().parseText(p.text)
}

A: The solution using Kotlin DSL and Fuel HTTP Client:
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result

buildscript {
    dependencies {
        "classpath"("com.github.kittinunf.fuel:fuel:2.3.1")
    }
}

tasks {
    register("post") {
        val (request, response, result) = "https://httpbin.org/post".httpPost().responseString()
        if (result is Result.Success) {
            println(result.get())
        }
    }
}


Q: Quickly finding custom class in xib file I am in a kind of situation to check if any of components (say UILabel) in my nib file specified custom class in identity inspector.
Currently the only way to find out is to go and check each component in every xib, is there any way we can search for it, similar to way where we can search for the occurrence of particular class in the Xcode, and the Xcode will quickly tell us which xib file contains the UILabel of that specific custom classes.

A: Currently I would suggest to use command grep in terminal(Xcode could not search .xib file):
grep -i -r --include=*.xib "TextToFindHere" /PathToSearchHere

Another way is to right click your .xib file and Open As Source Code and use Command+F to search. But this method can only search one file a time.


Q: TypeError: Cannot read property 'quote' of undefined React js Just to summarise, I'm creating a quote-generator using React js. The data is getting fetched from a mock API using React axios.
However, when I'm trying to display the quote it gives me that above error
line where I get error: {quotes[quoteIndex].quote}
(quotes) gets populated with the data
(quoteIndex) is basically an index in an array
(.quote) is the attribute from the data
Please find the relevant code
// sample from .json file data
"quotes": [
    {
    "id":0,
    "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "id":1,
    "quote": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  }
 ]
}

const [quotes, setQuotes] = useState([]);
const [quoteIndex, setQuoteIndex] = useState(0);

// fetching the data
const getData = async() =>{
        try{
            const response = await Axios.get("/quotes");

            if(response && response.data){
                setQuotes(response.data);
                console.log(response.data);
            }

        }catch(error){
            console.log(error);
        }

    }

//this inside the return statement

{quotes[quoteIndex].quote}

A: This is a very common problem when dealing with data that is loaded asynchronously.
Here's how I would suggest debugging this to understand your problem:

*

*Remove the offending code so that you can observe what's happening.

*Add console.log(quotes) in your component. You will see that it logs [] and then again with your array.

*Next add console.log(quotes[quoteIndex]). Notice that it logs undefined and then an object.
Consider that while the value is undefined, you cannot treat it like an object and attempt to access properties on it.

*Add a check to make sure the value is an object before using it:

// Nullsafe operator
quotes[quoteIndex]?.quote
// Or ternary
quotes[quoteIndex] ? quotes[quoteIndex].quote : null

Here is a simulated example:

const async_quotes = [
  {
    "id":0,
    "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "id":1,
    "quote": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  }
 ]

const {useState, useEffect} = React;

const index = 1;

const Example = () => {
  const [quotes, setQuotes] = useState([]);

   useEffect(() => {
     setTimeout(() => {
       setQuotes(async_quotes);
     }, 3000);
   }, []);

   console.log("quotes:", quotes);
   console.log("single quote:", quotes[index]);

   return
{quotes[index] ? quotes[index].quote : ''}

}

ReactDOM.render(<Example />, document.getElementById('root'));


Q: I can’t connect to my Azure VM After I used this command:
ifdown eth0

can't connect to my VM (CentOS 6) with ssh on cloud Microsoft azure.
How can I fix it?

A: Well, of course if you brought down the network you can't reach the VM anymore. What else were you expecting? :)
Just reboot the VM from the Azure management portal; the network should start automatically.


Q: What does the "box" mean in "don't block the box"? I see other similar signs saying "don't block the intersection", but what does "box" here mean?

A: The "box" is the intersection.  When viewed from above, most intersections look like a square, or "box".


Q: How can I create Macros for games on Linux? I am searching for a free software to create macros for games on Linux, that could work on any keyboard with a GUI.
I want it to do successive keystrokes and tweak the delay between each key.

A: You must install the software Autokey, you can type this in the terminal:
sudo apt-get install autokey-gtk

Open it and click on New then Script and name it (you can also create a folder with the name of your game).
Keyboard
There is two important lines, here is the code for pressing the key "x":
keyboard.send_keys("x")

And here is how to add a delay, 1/10 of a second (try lower values until the game doesn't allow it, also keep in mind than an high ping can make some keys doesn't input if the delay is too low):

time.sleep(0.1)

Then repeat the code by adding a delay between each keys, for the last key you don't need to add a delay after it.
To hold a key type that, for example to hold then release Shift and typing x in between:
keyboard.press_key("<shift>")
keyboard.send_keys("x")
keyboard.release_key("<shift>")

Mouse
To click use this two commands:
mouse.click_relative_self(x, y, button)

mouse.click_absolute(x, y, button)

The first command is relative (to click near the mouse's current location) the second is absolute (from the entire screen).
The button takes 3 arguments:
1: left click
2: middle click
3: right click
This script work best if you add a minimum of 0.1 second of sleep. Here an example to click at the center of the screen:
time.sleep(0.1)
mouse.click_absolute(1920/2, 1080/2, 1)

Comment
You can add a comment with "#":

keyboard.send_keys("x") # use a potion

Once your script is finished you can bind it to a key, bellow your script you will see script settings, at the line Hotkey click on Set and define a key. I recommend you to use the key F# to attach it or the key.
You can test if your macro is working by opening a text editor like gedit.
For Dota it is better to use the in game queue feature, for example to use 3 items and one spell:
keyboard.send_keys("s")
time.sleep(0.01)
keyboard.press_key("")
keyboard.send_keys("zxcq") # edit this line
keyboard.release_key("")


Q: Stop the Banner and Profile picture get change on MouseOver I have a MVC project which has a Banner in _Layout.cshtml

and a Img tag to get the Profile Pic according to the currect logges user

and I have implemented Rating with Jason

My Issue Is whe I run the Program My Banner and Profile picture also get changed into Empty or Filled Starts when it runs over/Out mouse pointer..
Please help me to stop the Banner and Profile picture get change on MouseOver

A: Short Answer :
Add a class to the images for rating, say a class "rating" and then replace $("img") with  $("img.rating")
Long Answer :
Ok, the jquery selector you are using is this $("img") which says select all images from the page. Hence the problem.
Now what you should do,
As you want to have the jquery run only for the 5 Rating images, you can have all the images have a common class like as shown below..

and Now you can use your code like this...

A: Brilliant..... Thanks a lot Yasser... Code required a bit fixes but thanks to u now its working. Bellow I have given the working code.. its almost the same code u hv corrected for me but with capital letters in necessary places.

Yahooo .. Thanks a lot


Q: Webdings are different on V10 vs V9. Why? Bug introduced in 10.0 or earlier and persisting through 10.2 or later

I use FontFamily->"Webdings" in interfaces in several places, but among other things for custom opener icons, for example I use the following "icons" for open and closed openers:

In version 10 this is what happens:

Both screen grabs are taken on the same computer. Webdings is installed. I open V9 and evaluate and take a grab. I close V9 and open V10 and do the same.
I knew the Mathematica fonts were different in V10 compared to V9 but I don't understand why Webdings would be being rendered differently. I've tested a hand full of other fonts, including Wingdings, and have not observed any difference between V9 and V10. Can anyone enlighten me why Webdings is now different?
I'm on OS X 10.9.4 but my interfaces have worked on both Windows and Mac with V9.
Edit
I always use OS X. On my current machine I am running OS X 10.9.4. I have V8, V9, and V10 installed. None of these have a /SystemFiles/CharacterEncodings/Webdings.m
Regarding the error message that @m_goldberg gets when using FromCharacterCode. The same message occurs in V8 and V9 so I think that is irrelevant to the present issue.
V8

V9

So the same error message occurs for FromCharacterCode in previous versions but it clearly has no bearing on the using of Style[6,FontFamily->"Webdings"].
The present issue is that you could use Webdings as a font in V8 and V9 on OS X and now you can't.

A: Wolfram has confirmed this is a bug

A: I'm running of OS X, and if I try
 Style[FromCharacterCode[6, "Webdings"], 24]

I get

Get::noopen: "Cannot open /Applications/Mathematica.10.app/SystemFiles/CharacterEncodings/Webdings.m. >>"

On the other hand
Style[FromCharacterCode[Range[33, 255], "ZapfDingbats"], 24]

gives

So it appears that the Webdings font is not supported in V10. A hint that this was true was given when I typed "Webdings" into the above code -- no completion was offered for it. On the other hand, completion was offered for the supported
ZapfDingbats font.
Another verification
 MemberQ[$CharacterEncodings, "Webdings"]

False

MemberQ[$CharacterEncodings, "ZapfDingbats"]

True