Q:

Populate grouped tables from php and filtered by jquery using ajax json

I have two php files. fetch.php creates the filtered array (filter from leagueboxes.php) and passes it back to the leagueboxes.php through ajax json.
fetch.php
<?php

include_once 'dbconfig.php';

if(isset($_GET['filter'])){

    $filter = $_GET['filter'];

    $query ="SELECT box_id, league_id, position, ";
    $query .="(SELECT GROUP_CONCAT(DISTINCT CONCAT(U.first_name, '
',U.last_name) SEPARATOR ' & ')FROM reg_players RP,users U ";
    $query .="WHERE RP.id = LE.reg_num AND U.id = RP.user)AS player, ";
    $query .="points, place ";
    $query .="FROM league_entries LE ";
    $query .="JOIN round_league_boxes2 RLB ON RLB.id =
LE.round_league_box_id ";
    $query .="JOIN leagues L ON L.id = RLB.league_id ";
    $query .="JOIN boxes B ON B.id = RLB.box_id ";
    $query .="WHERE league_id =:league ";
    $query .="ORDER BY round_league_box_id, position";

    $stmnt = $DB_con->prepare($query);
    $stmnt->bindParam(":league",$filter);
    $stmnt->execute();

    $final=$stmnt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($final);
}
?>

leagueboxes.php
<?php
include_once 'dbconfig.php';
include_once 'header.php';
?>

 League Tables

            <button type="button" class="filter btn-primary" value=1>Singles</button>
            <button type="button" class="filter btn-primary" value=2>Ladies Doubles</button>
            <button type="button" class="filter btn-primary" value=3>Mens Doubles</button>
            <button type="button" class="filter btn-primary" value=4>Mixed Doubles</button>

Singles

<?php include_once 'footer.php'; ?>

I wouldd like to populate the table caption with the box_id, and have a table for each box within the filtered league.
My problem is that I do not think I can loop through the array that I have produced to put each position, player, points & place in a box.  I think maybe I need to create a nested array. Perhaps before I encode it to json?
I have used (PDO::FETCH_GROUP|PDO::FETCH_ASSOC) to create a nested array and then use php foreach to populate html using php, so that I have data grouped by box_id. However this does not seem to work using json, or I cannot work our how to do it?
This is the ungrouped array:-
[{
    "box_id": "1",
    "league_id": "1",
    "position": "1",
    "player": "Caroline Hogan",
    "points": "27",
    "place": "0"
}, {
    "box_id": "1",
    "league_id": "1",
    "position": "2",
    "player": "Fran Gordon",
    "points": "11",
    "place": "0"
}, {
    "box_id": "1",
    "league_id": "1",
    "position": "3",
    "player": "Josh Handley",
    "points": "39",
    "place": "0"
}, {
    "box_id": "2",
    "league_id": "1",
    "position": "1",
    "player": "Gillian Shaw",
    "points": "0",
    "place": "0"
}, {
    "box_id": "2",
    "league_id": "1",
    "position": "2",
    "player": "Sally Westwood",
    "points": "0",
    "place": "0"
}, {
    "box_id": "2",
    "league_id": "1",
    "position": "3",
    "player": "Sandy Eley",
    "points": "0",
    "place": "0"
}]

This is the grouped array, where I cannot work out how to define box_id, etc.
{
    "1": [{
        "league_id": "1",
        "position": "1",
        "player": "Caroline Hogan",
        "points": "27",
        "place": "0"
    }, {
        "league_id": "1",
        "position": "2",
        "player": "Fran Gordon",
        "points": "11",
        "place": "0"
    }, {
        "league_id": "1",
        "position": "3",
        "player": "Josh Handley",
        "points": "39",
        "place": "0"
    }],
    "2": [{
        "league_id": "1",
        "position": "1",
        "player": "Gillian Shaw",
        "points": "0",
        "place": "0"
    }, {
        "league_id": "1",
        "position": "2",
        "player": "Sally Westwood",
        "points": "0",
        "place": "0"
    }, {
        "league_id": "1",
        "position": "3",
        "player": "Sandy Eley",
        "points": "0",
        "place": "0"
    }]
}

Thank you

A:

Is this what are you looking for? It simply loops through the query result and put it into map by box_id:
$grouped = [];
foreach ($final as $m) {
  $box_id = $m['box_id'];
  if (empty($grouped[$box_id])) {
    $grouped[$box_id] = [];
  }
  unset($m['box_id']);
  array_push($grouped[$box_id], $m);
}
echo json_encode($grouped);

Result:
{
  "1": [
    {
      "league_id": "1",
      "position": "1",
      "player": "Caroline Hogan",
      "points": "27",
      "place": "0"
    },
    {
      "league_id": "1",
      "position": "2",
      "player": "Fran Gordon",
      "points": "11",
      "place": "0"
    },
    {
      "league_id": "1",
      "position": "3",
      "player": "Josh Handley",
      "points": "39",
      "place": "0"
    }
  ],
  "2": [
    {
      "league_id": "1",
      "position": "1",
      "player": "Gillian Shaw",
      "points": "0",
      "place": "0"
    },
    {
      "league_id": "1",
      "position": "2",
      "player": "Sally Westwood",
      "points": "0",
      "place": "0"
    },
    {
      "league_id": "1",
      "position": "3",
      "player": "Sandy Eley",
      "points": "0",
      "place": "0"
    }
  ]
}

To display the result as tables with caption in js:

const data = {"1":[{"league_id":"1","position":"1","player":"Caroline Hogan","points":"27","place":"0"},{"league_id":"1","position":"2","player":"Fran Gordon","points":"11","place":"0"},{"league_id":"1","position":"3","player":"Josh Handley","points":"39","place":"0"}],"2":[{"league_id":"1","position":"1","player":"Gillian Shaw","points":"0","place":"0"},{"league_id":"1","position":"2","player":"Sally Westwood","points":"0","place":"0"},{"league_id":"1","position":"3","player":"Sandy Eley","points":"0","place":"0"}]};

function create_list(data, container){
  Object.keys(data).forEach((boxId) => {
   container.append(create_table(boxId, data[boxId]));
  });
}

function create_table(boxId, data) {
    var table = $('
');
    table.append($('
').text(boxId));
    var table_head = $('
');
    table_head.append($('').text('Position'))
    table_head.append($('').text('Player'))
    table_head.append($('').text('Points'))
    table_head.append($('').text('Place'))
    table.append(table_head);
    for(let x in data){
        let tr = $('
');
        tr.append($('').text(data[x].position));
        tr.append($('').text(data[x].player));
        tr.append($('').text(data[x].points));
  tr.append($('').text(data[x].place));
        table.append(tr);
    }
    return table;
}

create_list(data, $('#container'))
table {
  margin: 2em 0;
  font-family: "Trebuchet MS";
  border-collapse: collapse;
}

caption {
  margin: 2px 0;
}

caption, th, td {
  border: 1px solid #ddd;
  padding: 8px;
}


Q:

Why are observable dictionaries implemented by implementing interfaces?

Okay, so I've been looking for a dictionary which throws an event when a piece of data is changed. One of the links I kept coming across is : http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx
After inspecting IDictionary interface and Dictionary Class I can clearly see the CRUD (create read update delete). All dictionaries in theory should build on this functionality.
As far as I see it implementing an observable dictionary should be as simple as
public class test<K,V> : Dictionary<K,V>, INotifyCollectionChanged, INotifyPropertyChanging
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;
    public event PropertyChangedEventHandler PropertyChanged;

    private const string pCount = "Count";
    private const string pKeys = "Keys";
    private const string pValues = "Values";

    public V this[K key]
    {
        get
        {
            return base[key];
        }
        set
        {
            object old = base[key];
            base[key] = value;
            if (CollectionChanged != null)
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, new KeyValuePair<K, V>(key, value), new KeyValuePair<K, V>(key, (V)old)));
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(pValues));
        }
    }

    public override void Add(K key, V value)
    {
        base.Add(key, value);
        if(CollectionChanged!=null)
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new KeyValuePair<K,V>(key, value)));
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(pCount));
            PropertyChanged(this, new PropertyChangedEventArgs(pKeys));
            PropertyChanged(this, new PropertyChangedEventArgs(pValues));
        }
    }

    public override void Remove(K key)
    {
        object removed = base[key];
        base.Remove(key);
        if (CollectionChanged != null)
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(pCount));
            PropertyChanged(this, new PropertyChangedEventArgs(pKeys));
            PropertyChanged(this, new PropertyChangedEventArgs(pValues));
        }
    }
}

EDIT : Added more to make it more like the sample and to help clarify the question
I don't understand why all these elaborate dictionaries are being made, Is there something I'm missing? Can someone please explain this to me?
It feels like they're all reinventing the wheel which as far as I see goes against the reusable code which is the point of OO. I really feel like I must be missing something.

A:

There are several reasons why you can't do what you're trying to do:
The indexer, Add, and Remove methods are not virtual.  You cannot override the Add or Remove methods because they aren't virtual.
Because you aren't overriding these methods, you can at best shadow them, anytime the object is typed as an IDictionary or Dictionary the events won't be triggered.
By using composition instead of inheritance, as is shown in the example you linked to, there is no way for someone given an object of the dictionary to add items without triggering the event, since direct access to the dictionary isn't possible.


Q:

Google App Engine - YouTube Python Client Library Error

I am using the YouTube Data API client Library for Python. I have deployed my application on Google App Engine, the App Engine is able to import the library but following error is shown
SyntaxError: Non-ASCII character '\xe2' in file /Users/adityaborde/Python-projects/Gujarati Rasoi Bot/gujaratirasoi-bot/lib/httplib2/__init__.py on line 134, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
httplib2 file is part of the google-api-python-client library

A:

Did you replace or copy paste some code that caused a replacement of single quotation mark with apostrophe? Please see this article for some background information.
You could simply go to the _ init _.py file in question and see why line 134 is misread and see if you can fix it from there. If it's not incorrect in the file and it's just not being encoded properly, then adding this to the top of the .py file should work:
# -*- coding: utf-8 -*-


Q:

Не могу сделать русский язык для pyowm

Хотел сделать программу, на основе PyOwm. Вроде всё работало, но я не могу сделать русский язык, хотя всё сделал правильно.
Вот код:
from pyowm import OWM

owm = OWM('[token]', language = 'ru')

place = input("Укажите город/страну: ")

mgr = owm.weather_manager()
observation = mgr.weather_at_place(place)
w = observation.weather

print(w)

Что это выдаёт:
owm = OWM('[token]', language = "ru")  # You MUST provide a valid API key
TypeError: __init__() got an unexpected keyword argument 'language'

Пишет что-то связанное с аргументом language, но я не понимаю

A:

Язык в OWM переехал в конфиг.
Попробуйте так:
from pyowm import OWM
from pyowm.utils import config as cfg

config = cfg.get_default_config()
config['language'] = 'ru'

owm = OWM('<TOKEN>', config)


Q:

display input text as span, width trouble

I'm trying to make an input text look like exactly like a span. I want my user to be able to type text without noticing he's in a field.
I've almost succeeded, the last problem I've got is about the width of the input.
The input text is wider than the text it's replacing.
Here's the jsfiddle. (You may click on "Texte" to type yours).
Here's the interesting css part :
input {
    background-color: transparent;
    padding: 0px;
    border: initial;
    font: inherit;
    margin: 0px;
}

A:

Here is the idea try fixed width for the inputs
Demo : http://jsfiddle.net/nyitsol/eotd8p4n/17/
also you may try use the same width of the span for the input
$('span.width').width(); // returns a width value

using this get the width of the span and put it into the input box using JavaScript.
EDIT:
try this, if you want to grow the input based on text limit then you have to increase the size as well.
http://jsfiddle.net/nyitsol/eotd8p4n/25/
 var input = $('<input onkeypress=\"this.style.width = ((this.value.length + 1) * 8) + \'px\';\" type=text>');


Q:

Jest & Enzyme - SyntaxError: Unexpected token import

Writing tests for my React App with Jest & Enzyme has hit me hard as I'm unable to setup Enzyme along with Jest.
Below is the error I get whenever I use this line in my test file import React from 'react';
FAIL  src\App.test.js
  ● Test suite failed to run

    D:\experiements\react\my-app\src\App.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.049s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

package.json
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap-daterangepicker": "^2.1.30",
    "history": "^4.7.2",
    "jquery": "^3.3.1",
    "moment": "^2.21.0",
    "npm": "^5.7.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-bootstrap-daterangepicker": "^4.1.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "react-toastify": "^3.3.4",
    "redux": "^3.7.2",
    "redux-form": "^7.2.3",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "homepage": "http://localhost/my-app",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-jest": "^23.0.0-alpha.0",
    "enzyme": "^3.3.0",
    "jest": "20.0.4",
    "jest-cli": "20.0.4",
    "jest-config": "20.0.4",
    "jest-environment-node": "20.0.3",
    "react-scripts": "1.1.0"
  }
}

App.test.js
import React from 'react';

describe("<App />", () => {
    it("renders App Component", () => {
        expect(true).toBe(true);
    })
})

But, if I remove the import statement and just run 'npm test' it works fine.
Any help very much appreciated!

A:

It seems like you're not compiling with Babel.
If you install or update babel-jest, that should fix your issue:
npm install --save-dev babel-jest

Here's the yarn version:
yarn add -D babel-jest


Q:

Would data in vertex buffer change after translation?

If I load an X file and store vertex data in vertex buffer.  Then, Do translation on object, Would it change data in vertex buffer?

A:

Of course not. You store the translation in a matrix right? So in the vertex shader you transform the vertex position by the matrix to calculate the vertex position in world space but it doesnt affect the vertex buffer


Q:

What is the meaning of wizard words here?

SOURCE (Script of the film August Rush)
Wizard is trying to put a new name to his boy Evan who is already has a name.

We're gonna need to get you a new name. Something with a little more pop.
  I mean, in the whole world, what do you want to be? Close your eyes and
  think about that. Found. Doesn't have enough "yin". Little more
  "yang", you know?

A:

Sorry, but those aren't really "wizard words." Yin and yang are Chinese terms related to balancing forces in nature. From the Wikipedia article on the concept:

In Chinese philosophy, yin and yang (also yin–yang or yin yang, 陰陽 yīnyáng "dark–bright") describe how seemingly opposite or contrary forces may actually be complementary, interconnected, and interdependent in the natural world, and how they may give rise to each other as they interrelate to one another.

Whoever is speaking in your passage is appropriating the concept into folksy English, which is intended to have a somewhat humorous effect.


Q:

"Unhandled Exception: Creating default object from empty value"

I'm trying to show a snippet of code and in the same time display comments that you can make to the snippets (I call the snippets code). But I'm having troubles to view the username of the user who made each and every comment. I expect to have each user when I'm calling with(array('user', 'comments', 'comments.user')) but I just get an unhandled exception.
//Models
class Code extends Eloquent
{
    public function user() {
        return $this->belongs_to('User');
    }

    public function comments() {
        return $this->has_many('Comment');
    }
}

class Comment extends Eloquent
{
    public function user() {
        $this->belongs_to('User');
    }

    public function code() {
        $this->belongs_to('Code');
    }
}

class User extends Eloquent
{
    public function codes() {
        return $this->has_many('Code');
    }

    public function comments() {
        return $this->has_many('Comment');
    }
}
//Controller
    public function get_show($id)
    {
        //$code = Code::with(array('user', 'comments'))->where_slug($id)->first();
        //$comments = Comment::with(array('user'))->where_code_id($id)->get();
        $code = Code::with(array('user', 'comments', 'comments.user'))->where_slug($id)->first();
        dd($code);
        //return View::make('code.show')->with(array('code' => $code));
    }

//View

{{ $code->title }}

    @include('code.controls')

Syntax: {{ $code->syntax}}

syntax }}">{{ $code->content }}

    @foreach($code->comments as $comment)

#{{ $comment->id }}

        {{ User::find($comment->user_id)->first()->name }}

{{ $comment->body }}

    @endforeach

//Message when trying to view
Unhandled Exception
Message:

Creating default object from empty value

Location:

/home/victor/Projects/check-my-code/laravel/database/eloquent/query.php on line 167

Stack Trace:

#0 /home/victor/Projects/check-my-code/laravel/laravel.php(40): Laravel\Error::native(2, 'Creating defaul...', '/home/victor/Pr...', 167)
#1 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(167): Laravel\{closure}(2, 'Creating defaul...', '/home/victor/Pr...', 167, Array)
#2 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(140): Laravel\Database\Eloquent\Query->load(Array, 'user', NULL)
#3 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(74): Laravel\Database\Eloquent\Query->hydrate(Object(Comment), Array)
#4 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(186): Laravel\Database\Eloquent\Query->get()
#5 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(140): Laravel\Database\Eloquent\Query->load(Array, 'comments', NULL)
#6 /home/victor/Projects/check-my-code/laravel/database/eloquent/query.php(74): Laravel\Database\Eloquent\Query->hydrate(Object(Code), Array)
#7 /home/victor/Projects/check-my-code/application/controllers/codes.php(31): Laravel\Database\Eloquent\Query->get()
#8 [internal function]: Codes_Controller->get_show('testar-snippets')
#9 /home/victor/Projects/check-my-code/laravel/routing/controller.php(325): call_user_func_array(Array, Array)
#10 /home/victor/Projects/check-my-code/laravel/routing/controller.php(285): Laravel\Routing\Controller->response('show', Array)
#11 /home/victor/Projects/check-my-code/laravel/routing/controller.php(165): Laravel\Routing\Controller->execute('show', Array)
#12 /home/victor/Projects/check-my-code/laravel/routing/route.php(153): Laravel\Routing\Controller::call('codes@show', Array)
#13 /home/victor/Projects/check-my-code/laravel/routing/route.php(124): Laravel\Routing\Route->response()
#14 /home/victor/Projects/check-my-code/laravel/laravel.php(125): Laravel\Routing\Route->call()
#15 /home/victor/Projects/check-my-code/public/index.php(34): require('/home/victor/Pr...')
#16 {main}

A:

The methods in the class Comment is missing return statements.
class Comment extends Eloquent
{
    public function user() {
        $this->belongs_to('User');
    }

    public function code() {
        $this->belongs_to('Code');
    }
}

Should be
class Comment extends Eloquent
{
    public function user() {
        return $this->belongs_to('User');
    }

    public function code() {
        return $this->belongs_to('Code');
    }
}

Got help from a thread on the Laravel forums: http://forums.laravel.io/viewtopic.php?id=6266


Q:

HashDoS: how can worst case complexity of Hashtable be O(n^2)?

By now many of you must have heard about HashDoS. The researchers who found this, claim in their video that the worst case complexity of Hastable is O(n^2). How can this be?

A:

The question is worded in an incorrect way. The researchers do not claim that "the worst case complexity of Hashtables is O(n^2)".
What they claim is that "The [...] complexity of inserting n elements into the table [...] goes to O(n^2)." So, the complexity of a single operation is O(n). Which makes sense: if all keys have the same hash, then they all go into the same bucket, which is just an array or a linked list, so it needs to be searched linearly.


Q:

Split 1 Column of CSV Into 3 Lists/Columns

I have a CSV file with one column with the following data type of 500 emails:
[['Lindsey Jessica <xyz@icloud.com>'],
['Jonathan Bob <a@xyz.edu>'],
['Homer Simpson <b@xyz.edu>']

I need it to be put in a new CSV file with 3 columns separated by
**FirstName** **LastName** **Email**

I managed to separate the one column of the CSV into a list of 3 elements each:
["['Lindsey", 'M', "<lindsey@icloud.com>']", "['Jonathan", 'Andre', "<andre@xyz.edu>']", "['Greg", 'Kohl', "<kohls@gmail.com>']",...etc]

But now I need it to write to a CSV to look like this:
      Col 1    Col 2   Col 3
Row 1 John     Doe     <mail-noreply@google.com>
Row 2 Joe      Doe     <mail-noreply@google.com>
Row 3 Jacob    Doe     <mail-noreply@google.com>

And preferably get rid of those "< >" signs on the emails so I can import them into mailchimp. I can't figure out how to write my list into 3 columns however..
My code:
import csv

filename = ('email_list1.csv')

with open(filename, 'rt', encoding="utf-8") as f:
    reader = csv.reader(f)
    email_list = list(reader)
    email_list = (' '.join(str(v) for v in email_list)) ## Convert to string
    email_list = email_list.split() #Split into seperate elements in a list: first, last, email

## Trying to print out in columns instead of rows
out = open('email_list2.csv', 'w')
for element in email_list:
    out.write(element)
    #print (element)
    out.write('\n')
out.close()

I tried using the zip function to no avail so I'm not sure if the best way is to separate into three lists like
firstname = []
lastname = []
email = []

or to just write them to 3 columns. Thanks

A:

import csv

a=[['Lindsey Jessica <xyz@icloud.com>'],
['Jonathan Bob <a@xyz.edu>'],
['Homer Simpson <b@xyz.edu>']]

mylist=[elem[0].split() for elem in a ]

"""Output[['Lindsey', 'Jessica', '<xyz@icloud.com>'], ['Jonathan', 'Bob', '<a@xyz.edu>'], ['Homer', 'Simpson', '<b@xyz.edu>']]"""

mylist1=[]
#removing '<' and'>' and creating a new list name mylist1
for elem in mylist:
    elem[2] = elem[2][1:len(elem[2])-1]
    mylist1.append(elem)
#writing to a csv file
with open('out.csv', 'wb') as fp:
    myf = csv.writer(fp, delimiter=',')
    myf.writerows(mylist1)


Q:

AS3: Detect long key presses

I have an interface that needs to react to "long key presses". That means 2 different actions for the same key based on how long the key has been down:
PRESS LEFT CURSOR: action A
PRESS & HOLD LEFT CURSOR: action B
Well, it's proving harder that I thought. The main problem is that both Keyboard.KEY-DOWN and Keyboard.KEY-UP fire continuously if you hold the key down. This looks weird to me although might make sense if you think about imputing text (if you are entering text and hold down a key it starts to fill the space).
When I was trying to tackle the problem I thought about starting a counter on the KEY-DOWN and resetting it on KEY-UP. Then if it reached certain threshold fire an event. The problem is the counter resets straight away because they KEY-UP event fires all the time.
I'm aware of the keyboard polling classes such as BigRoom's and Senocular's but they don't solve the problem because they base their status on the same events.
I could go for timers starting a timer on KEY-DOWN and after x milliseconds check if the key is still down but that would assume that the key has been down all the time. I don't think it would be reliable.
And this is the point I'm starting to run out of ideas. Is there a much simpler method I've overlooked? I hope there is!
Thanks,
Juan

A:

Sorry that took me so long to come back, but was on the middle of the project and really didn't have time to look deeper into this. Now I have and I've found that there's no such problem. Read below for the long answer.
This is only hapenning under very specific circumstances and probably none to blame Adobe.
I have an iMac running Ubuntu and develop Flash on a virtual machine running Windows XP. This problem only appears on the virtual XP, the same application running natively on Ubuntu (and probably other systems) doesn't show the problem.
And because I have some other keyboard quirks when using the VM, I think the problem is on VirtualBox's keyboard driver.
Thanks to everybody that took the time to look into this. I hope this helps for other people!
Juan


Q:

Are there any mods available to prevent the pause menu from appearing when tabbing out of the game?

I'm wanting to keep windows open of Minecraft for some live streaming, and have considered using multiple copies of Minecraft for multiple camera angles. However, if I alt-tab out of the game, the pause menu appears.
Are there any mods out there to prevent this from occurring?
This question is similar to this one, with the exception that I simply want nothing to be obstructing the view of the game during SMP.
Edit: The point is I want to stream the screen without having to be active in-game, so opening the crafting screen is out of the question.

A:

If you open a crafting/inventory/smelting window it will not pause the game when you ALT-TAB out of the game.
Try opening Chat window instead. (press T) The chat window is transperant, and the game is essentially "paused" (you can't move and use items) while it waits for you to type something. Obviously don't type anything and when you are done you can press T again to make it go away.


Q:

Volley request with headers and body params

I need to make an api request which.
Two headers :

Accept
Authorization

Five body params.

Number
Make
Model
Description
Plates

Through postman everything works great.
But when i try through android app i can't get through.
Note: Login through the same host works great so the setup its not the problem i think my main problem is in api call.
public void add(View view) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String URL = "http://10.0.2.2:8000/api/trucks";
        StringRequest request = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObj = new JSONObject(response);
                            // parse response
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse response = error.networkResponse;
                        String errorMsg = "";
                        if (response != null && response.data != null) {
                            String errorString = new String(response.data);
                        }
                    }
                }
        ) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Accept", "application/json");
                headers.put("Authorization", "Bearer " + myToken);
                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
                TextInputEditText make = findViewById(R.id.textInputEditTextMake);
                TextInputEditText model = findViewById(R.id.textInputEditTextModel);
                TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
                TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);

                params.put("number", number.getText().toString());
                params.put("make", make.getText().toString());
                params.put("model", model.getText().toString());
                params.put("description", description.getText().toString());
                params.put("plates", plates.getText().toString());
                return params;
            }
        };
        queue.add(request);
    }

Edit: by Solution #1.
public void add(View view) throws JSONException {
    RequestQueue queue = Volley.newRequestQueue(this);
    TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
    TextInputEditText make = findViewById(R.id.textInputEditTextMake);
    TextInputEditText model = findViewById(R.id.textInputEditTextModel);
    TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
    TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("Number", number.getText().toString());
    jsonObject.put("Make", make.getText().toString());
    jsonObject.put("Model", model.getText().toString());
    jsonObject.put("Description", description.getText().toString());
    jsonObject.put("Plates", plates.getText().toString());
    final String requestBody = jsonObject.toString();

    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://10.0.2.2:8000/api/trucks", jsonObject,
            new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            //now handle the response
            Toast.makeText(truck_add.this, response.toString(), Toast.LENGTH_SHORT).show();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //handle the error
            Toast.makeText(truck_add.this, "An error occurred", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    }) {    //this is the part, that adds the header to the request
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Accept", "application/json");
            params.put("Authorization", myToken);
            return params;
        }
    };
    queue.add(jsonRequest);
}

Postman :

A:

When you want to pass the data through the body, you need to create a json object before string request.
try this way,
1. create a string url for request.
2. create json object for body data and pass data to it. Like,
JSONObject jsonObject= new JSONObject();
jsonObject.put("Number", address.getNumber());
jsonObject.put("Make", address.getMake());
jsonObject.put("Model", address.getModel());
jsonObject.put("Description", address.getDescription());
jsonObject.put("Plates", address.getPlates());
final String requestBody=jsonObject.toString();

3. After this, apply stringRequest.
4. Now, add below lines before header method and after error method.
@Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }

5. In your getHeaders() method, use Content-Type for "application/json" and for Authorization you must use only token without (Bearer).
Done.


Q:

different way of importing

Now what I am doing is:
import numpy as np
x = np.arange(100)

is there anyway to import such that I could directly do:
x = arange(100)

A:

if you want to use all the numpy possibilities without prefix (np) :
from numpy import *

if you just want to use arange() :
from numpy import arange


Q:

Qt Layouts Spacers Size

I have created 2 Push-Buttons in a horizontal layout. Then I added a spacer but it's almost invisible. I also cannot change the size of this spacer.
I cannot change ANY size in any layouts! I tried everything, changed the size policy etc. but nothing worked. I watched this video where this guy created two push buttons and put them together in a horizontal layout.
He added a spacer, just like me, and he was able to change the size it! :
Qt Layout Tutorial
What am I doing wrong? I did exactly what he did but it won't work >.< So how can I change the size of the items in a layout (particularly the spacer's size)?

A:

Try using QBoxLayout::addStretch() instead of addSpacerItem() or addSpacing().


Q:

Increase string array value +1?

How would I increase the value of this array +1?
I have some code but its not getting +1 the value of that array.
By +1 I mean the array value 1 above that one, so if my array contains the words: Hi, Hey Hello, instead of it displaying Hi I want it so display Hey.
Heres the code I have but its not moving it +1 up:
string[] u = getBetweenAll(vid, "</id><published>", "</published><updated>");
                for (int i = 0; i < listView1.Items.Count; i++)
                {

                    string input = u[i] + 1;
                    int index = input.IndexOf("T");
                    if (index > 0)
                        input = input.Substring(0, index);
                    listView1.Items[i].SubItems.Add(input);
                }

A:

Did you mean:
string input = u[i + 1];


Q:

pass string varialbe to placeholder for attribute in infoWindow (ArcGIS Javascript)

I am working on a Javascript-based webapp that uses an ArcGIS map service, which has several attribute columns containing URLs to photos.  The user will be able to open photos by clicking on a link in the infoWindow, accessed with an IdentifyTask.   I would like to use a variable in the placeholder.  My problem is I can't find a way to pass a string variable into the placeholder position.  Below is an example:
In my code, I have onclick=\"javascript:showPicture('${PrePic1}
where HTTP is the name of a column containing photo links.
I would like to use a variable, such as 'testString' so that I may vary the attribute in the placeholder (for instance, PrePic2, PrePic3 etc..)
I have tried setting a var to just 'PrePic1" and placing this in the brackets, and have tried '${PrePic1}' (with and without escape characters)..but these attempts didn't work..
any ideas? I hope I am explaining the problem well // Jason

A:

Looks Like you are using the Dojo syntax (${key}), which identifies the field that will be used in the parameter substitution.
In this case you have something like
link here
where ${HTTP} is a substitution for the value in the attribute field of HTTP from your feature (another attribute example is ${OBJECTID}).
I am not entirely certain of your intent, but if you have 3 different fields all storing image URLs you may want to access them like this.
link 1
link 2
link 3
If you are looking to do something more dynamic and less hard-coded... you could try something like
var urlFieldName = 'HTTP';
var htmlContent = "link 4"
your comment earlier was:
I tried things like; ('${' + HTTP + '}') but no luck
I think here you used single quotes where you needed double:
I tried things like; ('${" + HTTP + "}') but no luck
The one piece to keep in mind is... getting the substitution is only part of the solution, the field name must also be correct (and I think it is case-sensitive).


Q:

Waiting for a TThread to finish with WaitForSingleObject()

I am creating a thread, and then say want to wait for it to terminate with a WFSO call (simplified pseudo-code below, obviously no one wants to wait on a thread right after creating it).
constructor TFileScannerThread.Create(Parameters)
begin
/// assign parameters to private variables, and call
inherited Create(true);  //Create Suspended
FreeOnTerminate := true;
Start;
end;

In the main thread
fst := TFileScannerThread.Create(BaseFolder, ScanMode, AbortEvent);

///  I presume, the next call would block the main thread until the child thread is done
///  but, it seems to create a deadlock & WFSO never returns
///  I get a WAIT_TIMEOUT if I use a finite wait time
WaitForsingleObject(fst.Handle, INFINITE);

What am I doing wrong/missing?  If I do not have the WFSO the thread completes in about 10 seconds.
Edit: Creating with FreeOnTerminate=false does not create this issue.

A:

Waiting on a TThread object that uses FreeOnTerminate=true is a race condition, as the object could be freed at any moment once its Execute() method has exited.  So unless you can guarantee that you are calling WaitForSingleObject() before the thread's OnTerminate event is fired, then you are not guaranteed to have a valid object on which to read its Handle property.  Basically, once the thread's constructor exits, all bets are off when using FreeOnTerminate=true, unless you use an OnTerminate event handler. FreeOnTerminate=true is meant for "create and forget" kind of threads. If you need to refer to a thread for any reason, using FreeOnTerminate=true becomes dangerous if you are not very careful.
If you are going to wait on a TThread object, there is no point on using FreeOnTerminate=true on that object, since you can just free the object yourself once the wait is complete.  Doing so ensures the object remains valid until you manually free it, thus you can use its Handle at any time:
constructor TFileScannerThread.Create(Parameters)
begin
  inherited Create(False);
  FreeOnTerminate := false;
  // assign parameters to private variables
end;

fst := TFileScannerThread.Create(BaseFolder, ScanMode, AbortEvent);
...
WaitForSingleObject(fst.Handle, INFINITE);
fst.Free;

(you don't need to call Start() inside the constructor, use CreateSuspended=False instead, the thread will not actually begin running until after the constructor exits)
That being said, it is impossible for WaitForSingleObject() to return WAIT_TIMEOUT on an INFINITE timeout.  But it is possible for it to return WAIT_FAILED, such as when the TThread object is freed before WaitForSingleObject() is called, or even while it is still waiting on the Handle, thus closing the Handle while it is being used.
With regard to a deadlock, if you have an OnTerminate event handler assigned to the TThread object, that handler gets called via the TThread::Synchronize() method so that the handler runs in the main thread.  But, if the main thread is blocked on WaitForSingleObject(), then it can't service any TThread::Synchronize() (or TThread::Queue()) requests.  Thus, you end up with the worker thread waiting on the main thread while the main thread is waiting on the worker thread - deadlock.
To avoid that, you can call WaitForSingleObject() in a loop with a short timeout so that you can call the RTL's CheckSynchronize() function periodically while you are waiting:
var h: THandle;

h := fst.Handle;
while WaitForSingleObject(h, 500) = WAIT_TIMEOUT do
  CheckSynchronize;

fst.Free;

There are other issues to deal with when using a blocking wait, like SendMessage() calls from other threads to the main thread.  So you would need to service those requests as well:
var
  h: THandle;
  ret: DWORD;
  msg: TMsg;

h := fst.Handle;
repeat
  case MsgWaitForMultipleObjects(1, h, False, 1000, QS_SENDMESSAGE) of
    WAIT_OBJECT_0, WAIT_FAILED: Break;
    WAIT_OBJECT_0 + 1: PeekMessage(msg, 0, 0, 0, PM_NOREMOVE);
    WAIT_TIMEOUT: CheckSynchronize;
  end;
until False;

fst.Free;

Alternatively, add the Classes.SyncEvent handle to the wait as well (TThread::Synchronize() and TThread::Queue() signal it internally when there are requests pending):
var
  h: array[0..1] of THandle;
  ret: DWORD;
  msg: TMsg;

h[0] := fst.Handle;
h[1] := SyncEvent;
repeat
  case MsgWaitForMultipleObjects(2, h, False, INFINITE, QS_SENDMESSAGE) of
    WAIT_OBJECT_0, WAIT_FAILED: Break;
    WAIT_OBJECT_0 + 1: CheckSynchronize;
    WAIT_OBJECT_0 + 2: PeekMessage(msg, 0, 0, 0, PM_NOREMOVE);
  end;
until False;

fst.Free;

FYI, TThread has its own WaitFor() method that performs a blocking wait on the thread to terminate, while servicing TThread::Synchronize()/TThread::Queue() and SendMessage() requests, similar to above:
fst := TFileScannerThread.Create(BaseFolder, ScanMode, AbortEvent);
...
fst.WaitFor;
fst.Free;

Just note that calling TThread::WaitFor() on a TThread object that uses FreeOnTerminate=true is not safe, either.  It will either fail with an EThread or EOSError exception when the Handle is closed between internal loop iterations, or it will likely just crash outright when it tries to access the Handle of a TThread object that has already been freed.


Q:

How to deactivate pdf preview in files

I have a large folder of pdfs. Every time I open it with files it has to load these little preview icons which takes pretty much time. How can I disable this?

A:

Pantheon-files uses a thumbnailer daemon called tumbler . You can disable generation of thumbnails for PDFs by opening a terminal and editing the config file.
sudo nano /etc/xdg/tumbler/tumbler.rc

Search for the section listed below-
# PDF/PS thumbnailer
[PopplerThumbnailer]
Disabled=false
Priority=1
Locations=
MaxFileSize=0

Change Disabled=false to Disabled=true (Ctrl+O,Enter to save the file, Ctrl+X to exit nano)
Then reset your thumbnail cache  with rm -r ~/.cache/thumbnails
Note: Rather than disabling thumbnails for all PDFs, you could set the Locations or MaxFileSize options to your liking. Unfortunately though, as far as I can tell the Locations setting only allows you to whitelist rather than blacklist folders.


Q:

ReactJS: Reloading component after function is executed?

In the quest to make a to-do application in order to get more familar with API's, CRUD and React, I've encountered a slight roadblock on reloading the component(s) after executing a function.
The case is as following:

Tasks get displayed
User can press button to mark task as finished
Task is marked as finished (This is already working)
Button gets changed to "Mark unfinished" (This doesn't fire)

At the moment I use window.location.reload() to force each component to update after pressing the "mark finished" button, however I know that refreshing the entire page upon this is rather unnecessary, and to my understanding voids the whole reason of using javascript and react.
As such, I should be using this.setState() to do this instead, but it is not working without any explanation why. Neither would this.forceUpdate() which is discouraged to begin with.
The code is as following:
constructor(){
  super();
  this.state = {
    tasks: [],
    update: false
  };

  this.markFinished = this.markFinished.bind(this);
  this.update = this.update.bind(this);
}

markFinished(id, title, content){
  axios.put('/api/tasks/'+id, querystring.stringify({
    task_id: id,
    title: title,
    content: content,
    state: 'finished'
  }),{
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
  })
  .catch(function(err){
    console.log(err)
  })
  this.setState({update: true});
}

Is there something that I would be missing in this implementation of setState?
Oddly enough if I replace update: true with tasks: [] it will update, but remove the entire tasks array as result. prompting me that it -does- function as it should.

A:

You are running an async function with axios.put, so your update: true is executed before axios.put returns the promise, you likely want to do a .then(//set the state here) on success.
So, something along this line:
let that = this;
axios.put('/api/tasks/'+id, querystring.stringify({
    task_id: id,
    title: title,
    content: content,
    state: 'finished'
  }),{
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
  })
  .then(function(success) {
    that.setState({update: true})
   }
  .catch(function(err){
    console.log(err)
  })

On success of your axios.put the state will be updated and your page should re-render.


Q:

How to pass String paramaters in jsp?

Below code is an output.jsp to display the data submitted from submit.jsp in a  format. I am fairly new to JSP and would like some guidance in how to pass paramaters firstname/lastname into html tags. Please advise . I have tried couple of approcahes with no success.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>

<h>The first and last name are</h>
<%
String firstname = (String) request.getAttribute("firstname");
String lastname  = (String) request.getAttribute("lastname");

//out.println(firstname  + "                     " + lastname);
%>

First Name : 	<% firstname  %>

Last Name : 	<% lastname %>

Here is the error that are thrown when running output.jsp.
An error occurred at line: 20 in the jsp file: /output.jsp
firstname cannot be resolved to a type
17: %>
18:

19:

20: First Name : 	<% firstname  %>
21:

22:

23: Last Name : 	<% lastname %>

An error occurred at line: 23 in the jsp file: /output.jsp
lastname cannot be resolved to a type
20: First Name : 	<% firstname  %>
21:

22:

23: Last Name : 	<% lastname %>
24:

25:

26:

A:

instead of <% firstname  %>	 and <% lastname  %>
try <%= firstname  %>	 and <%= lastname  %>


Q:

Редирект url в подпапку

Задача в следующем:
Нужно чтобы при переходе на site.com, подгружался index.php из папки subdir, которая находится в корне. При этом сайт не должен быть доступен по адресу site.com/subdir/.
Вопрос:
Возможно ли сделать подобное через .htaccess, или виртуальные хосты? В данный момент используется связка Apache+Nginx.

A:

Отвечу на свой вопрос сам.
Моё решение:
Options +FollowSymLinks -MultiViews -Indexes

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+subdir/(\S*)\s [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_URI} !^/subdir/ [NC]
RewriteRule ^(.*)$ /subdir/$1 [L]


Q:

Learning Java 8 streams

I have an existing code and i am looking to convert into streams provided by Java8:
    for(Person details: modList){

                   if (null != details &&null!=details.getPersonChild()) {
                                  Child mod= details.getPersonChild();

                                  if (mod.isAB() ||
                                          mod.isBC() ||
                                          mod.isCD() ||
                                          mod.idDE() ||
                                          mod.isEF()) {
                                      childeligible = true;
                                                 break;
                                  }
                   }
    }

i have so far done:
return details.stream()
                .filter( p -> null != p && null != p.getPersonChild())
                .map(Person::getPersonChild)
                .anyMatch(mi -> (mod.isAB() || mod.isBC() || mod.isCD() || mod.idDE() || mod.isEF()));

is there a more optimised way to achieve this
Thanks for the help

A:

The way I might write it is
return Details.stream()
            .filter(p -> null != p)
            .map(Person::getPersonChild)
            .filter(pc -> null != pc)
            .anyMatch(pc -> pc.isABCEDF());

Where isABCDEF checks all the conditions.

no that method cannot be added

Or you can add this method with a better description of what it is checking.
 .anyMatch(pc -> isABCEDF(pc));

If you don't want to add a method you can do what you suggested
.anyMatch(c -> c.isAB() || c.isBC() || c.isCD() || c.idDE() ||  c.isEF());

As @WanderNauta points out you can also use .filter(Objects::nonNull) for null checks if you feel this is clearer.

A:

Other solution is:
 Details.stream()
    .filter(Objects::nonNull)
    .map(Person::getPersonChild)
    .filter(Objects::nonNull)
    .anyMatch(
      ((Predicate<String>) Child::isAB).
         or(Child::isBC).
         or(Child::isDE).
         or(Child::isEF)
     );

We are combining a few Predicates here using Predicate.or method:
((Predicate<String>) Child::isAB).or(Child::isBC).or(Child::isDE).or(Child::isEF)


Q:

Why use an Objective-C protocol when all methods are optional?

I always had the impression a protocol should help me implement certain methods so my object will responds to certain messages. If I forget a method or type it wrong the compiler will tell me.
But what is the use of setting a protocol for a class when all methods are optional? Like in the NSSpeechSynthesizerDelegate-protocol. The compiler doesn't remind me to implement some methods and he doesn't tell me if I wrote a method name the wrong way. And the program works fine even without the protocol.

A:

If you implement a delegate protocol of your own, you will get compiler warnings if you try to call the methods without them being declared somewhere (x may not respond to selector...).
It also helps with documentation and code completion to define a protocol. If you want to know which delegate methods are supported, you can simply look at the corresponding header file (or a documentation page that is generated from it).
When you start typing a new method in your class, Xcode is also smart enough to suggest method signatures from protocols your class conforms to.


Q:

Открыть видео в mxplayer через intent

Вопрос в заголовке. Как?
Пытался
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim()));
                intent.setDataAndType(Uri.parse(url.trim()),
                        "application/com.mxtech.videoplayer.pro|application/com.mxtech.videoplayer.ad");
                PackageManager packageManager = getContext().getPackageManager();
                List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);

                if (activities.size() > 0) {
                    getContext().startActivity(intent);
                }else {
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim()));
                    List<ResolveInfo> a = packageManager.queryIntentActivities(i, 0);
                    Log.d("download", title + " " + url);
                    if (a.size() > 0)
                        getContext().startActivity(intent);
                }

Помимо mx так же предлагает dvget даже если нажимаю запомнить

A:

Просто указание миме-типа не поможет - приложения подписываются на всё.
Нужно указать явно пакет и активити цели.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim()));
intent.setDataAndType(Uri.parse(url.trim()),
                    "application/com.mxtech.videoplayer.pro|application/com.mxtech.videoplayer.ad");
PackageManager packageManager = getContext().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);

if (activities.size() > 0) {
    boolean started = false;
    for (ResolveInfo info : activities) {
        ActivityInfo activityInfo = info.activityInfo;

        if (activityInfo.packageName.startsWith("com.mxtech.videoplayer")) {
            getContext().startActivity(intent.setClassName(activityInfo.packageName, activityInfo.name));
            started = true;
            break;
        }
    }

    if (!started)
        getContext().startActivity(intent);
}


Q:

Insert data from staging table into multiple, related tables?

I'm working on an application that imports data from Access to SQL Server 2008. Currently, I'm using a stored procedure to import the data individually by record. I can't go with a bulk insert or anything like that because the data is inserted into two related tables...I have a bunch of fields that go into the Account table (first name, last name, etc.) and three fields that will each have a record in an Insurance table, linked back to the Account table by the auto-incrementing AccountID that's selected with SCOPE_IDENTITY in the stored procedure.
Performance isn't very good due to the number of round trips to the database from the application. For this and some other reasons I'm planning to instead use a staging table and import the data from there. Reading up on my options for approaching this, a cursor that executes the same insert stored procedure on the data in the staging table would make sense. However it appears that cursors are evil incarnate and should be avoided.
Is there any way to insert data into one table, retrieve the auto-generated IDs, then insert data for the same records into another table using the corresponding ID, in a set-based operation? Or is a cursor my only option here?

A:

Look at the OUTPUT clause. You should be able to add it to your INSERT statement to do what you want.
BTW, if you need to output columns into the second table that weren't inserted into the first one, then use MERGE instead of INSERT (as suggested in the comment to the original question) as its OUTPUT clause supports referencing other columns from the source table(s).  Otherwise, keeping it with an INSERT is more straightforward, and it does give you access to the inserted identity column.


Q:

連鎖決済にてPENDDINGになっている支払の返金

連鎖決済にてPENDDINGになっている支払に対して返金処理(Refund API) もしくは決済の取消の処理を行うことができるか？
可能な場合、通常の返金処理と同様にRefund API を実行すればよい認識で問題ないか？

A:

Refund API を使用して全額返金は可能ですが一部返金はできないと思いますよ。


Q:

Play framework 1.x 'hibernate.properties not found' issue

I have deployed my play framework 1.2.5 app on amazon ec2 ubuntu instance. And I did configuration according to what play.1.2.5 production tutorial says. After starting my app it throws exception for hibernate configuration. I am really struggling with deploying and configuring my app on production. The Information trace is like that.
    2014-02-09 16:51:41,531 - Precompiling ...
2014-02-09 16:52:36,885 - Connected to jdbc:mysql://127.0.0.1/emirbazaridb?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci
2014-02-09 16:52:37,194 - Hibernate Commons Annotations 3.2.0.Final
2014-02-09 16:52:37,202 - Hibernate 3.6.10.Final
2014-02-09 16:52:37,203 - hibernate.properties not found
2014-02-09 16:52:37,206 - Bytecode provider name : javassist
2014-02-09 16:52:37,212 - using JDK 1.4 java.sql.Timestamp handling
2014-02-09 16:52:37,325 - Hibernate EntityManager 3.6.10.Final
2014-02-09 16:52:37,426 - Binding entity from annotated class: models.Comments
2014-02-09 16:52:37,463 - Bind entity models.Comments on table Comments
2014-02-09 16:52:37,583 - Binding entity from annotated class: models.Prod
2014-02-09 16:52:37,663 - Binding entity from annotated class: models.CommentDetail
2014-02-09 16:52:37,663 - Bind entity models.CommentDetail on table commentdetail
2014-02-09 16:52:37,667 - Binding entity from annotated class: models.UserMetaData
2014-02-09 16:52:37,668 - Bind entity models.UserMetaData on table usermetadata
2014-02-09 16:52:37,683 - Binding entity from annotated class: models.Messages
2014-02-09 16:52:37,683 - Bind entity models.Messages on table messages
2014-02-09 16:52:38,636 - Database ->
       name : MySQL
    version : 5.5.35-0ubuntu0.12.04.2
      major : 5
      minor : 5
2014-02-09 16:52:38,636 - Driver ->
       name : MySQL-AB JDBC Driver
    version : mysql-connector-java-5.1.20 ( Revision: tonci.grgin@oracle.com-20111003110438-qfydx066wsbydkbw )
      major : 5
      minor : 1
2014-02-09 16:52:38,646 - Using default transaction strategy (direct JDBC transactions)
2014-02-09 16:52:38,649 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
2014-02-09 16:52:38,649 - Automatic flush during beforeCompletion(): disabled
2014-02-09 16:52:38,649 - Automatic session close at end of transaction: disabled
2014-02-09 16:52:38,649 - JDBC batch size: 15
2014-02-09 16:52:38,649 - JDBC batch updates for versioned data: disabled
2014-02-09 16:52:38,650 - Scrollable result sets: enabled
2014-02-09 16:52:38,650 - JDBC3 getGeneratedKeys(): enabled
2014-02-09 16:52:38,650 - Connection release mode: auto
2014-02-09 16:52:38,650 - Maximum outer join fetch depth: 2
2014-02-09 16:52:38,650 - Default batch fetch size: 1
2014-02-09 16:52:38,650 - Generate SQL with comments: disabled
2014-02-09 16:52:38,651 - Order SQL updates by primary key: disabled
2014-02-09 16:52:38,651 - Order SQL inserts for batching: disabled
2014-02-09 16:52:38,651 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
2014-02-09 16:52:38,657 - Using ASTQueryTranslatorFactory
2014-02-09 16:52:38,657 - Query language substitutions: {}
2014-02-09 16:52:38,658 - JPA-QL strict compliance: enabled
2014-02-09 16:52:38,658 - Second-level cache: enabled
2014-02-09 16:52:38,658 - Query cache: disabled
2014-02-09 16:52:38,658 - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
2014-02-09 16:52:38,659 - Optimize cache for minimal puts: disabled
2014-02-09 16:52:38,659 - Structured second-level cache entries: disabled
2014-02-09 16:52:38,671 - Statistics: disabled
2014-02-09 16:52:38,671 - Deleted entity synthetic identifier rollback: disabled
2014-02-09 16:52:38,671 - Default entity-mode: pojo
2014-02-09 16:52:38,671 - Named query checking : enabled
2014-02-09 16:52:38,671 - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
2014-02-09 16:52:38,704 - building session factory
2014-02-09 16:52:38,714 - Type registration [clob] overrides previous : org.hibernate.type.ClobType@5df7b6e1
2014-02-09 16:52:38,714 - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType@5df7b6e1
2014-02-09 16:52:38,714 - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType@32079df9
2014-02-09 16:52:38,714 - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType@12146018
2014-02-09 16:52:38,714 - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType@77b0d0ed
2014-02-09 16:52:38,714 - Type registration [blob] overrides previous : org.hibernate.type.BlobType@7964b4fe
2014-02-09 16:52:38,714 - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType@7964b4fe
2014-02-09 16:52:38,714 - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType@42a6cdf5
2014-02-09 16:52:38,715 - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@551bb202
2014-02-09 16:52:39,801 - Not binding factory to JNDI, no JNDI name configured
2014-02-09 16:52:40,421 - Application 'EB' is now started !
2014-02-09 16:52:41,196 - Listening for HTTP on port 9000 ...

End Error Trace :
@6h7p4k2lk
Internal Server Error (500) for request GET /

Execution exception (In /app/controllers/ControllerUtility.java around line 33)
PersistenceException occured : org.hibernate.exception.SQLGrammarException: could not execute query

play.exceptions.JavaExecutionException: org.hibernate.exception.SQLGrammarException: could not execute query
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:237)
    at Invocation.HTTP Request(Play!)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1389)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:255)
    at play.db.jpa.JPQL.findAll(JPQL.java:32)
    at models.Categories.findAll(Categories.java)
    at controllers.ControllerUtility.checkPopUp(ControllerUtility.java:33)
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:510)
    at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484)
    at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479)
    at play.mvc.ActionInvoker.handleBefores(ActionInvoker.java:328)
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:142)
    ... 1 more
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.doList(Loader.java:2545)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
    at org.hibernate.loader.Loader.list(Loader.java:2271)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:459)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:365)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:246)
    ... 9 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'emirbazaridb.CATEGORIES' doesn't exist
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2310)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
    at org.hibernate.loader.Loader.doQuery(Loader.java:802)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.doList(Loader.java:2542)
    ... 17 more
2014-02-09 16:53:33,457 - Table 'emirbazaridb.CATEGORIES' doesn't exist

A:

I think the hibernate.properties not found message is possibly a red herring. The last line of your stacktrace might be where the problem lies:
Table 'emirbazaridb.CATEGORIES' doesn't exist

Does the CATEGORIES table exist?


Q:

Ansible string concat before filter

I was having an issue in my Ansible template where I wanted to create an HTTP basic auth credential out of two different variables a user inputs into the play.
The first thing I tried to do was:
basic_auth: "{{ user + ':' + pass | b64encode }}"

However I ended up with:
basic_auth: "user:<BASE64_ENCODED>"

How can I have Jinja concatenate these strings and then pass it through my filter?

A:

Pretty basic solution: group with parenthesis.
basic_auth: "{{ (user + ':' + pass) | b64encode }}"

I assume that this will allow me to nest several layers of filters.
complex: "{{ ((user + ':' + pass) | b64encode) | complex_filter}}"


Q:

Set property method in grails could not change the instance globally

I have a domain class DbUserSchemaServer with a transient property unassign
class DbUserSchemaServer {
    static transients = ["unassign"]

    DbUser user
    String schema
    DbServer server
    BigInteger objects
    Date creationDate
    String schemaStatus //for dropping
    Boolean protect

    //Transients
    Boolean unassign

    static constraints = {
        user unique:false, nullable: false, blank:false
        schema unique:'server', nullable: false, blank:false
        server unique: false, nullable: false, blank:false
        objects blank:false, nullable:false
        creationDate blank:false, nullable:false
        schemaStatus nullable:true, blank: false
    }

    static mapping = {
        protect defaultValue: false
        unassign defaultValue: false
    }
}

In a service, I tried to change the value of protect property of a DbUserSchemaServer instance. The method as folows
public Boolean protectSchema(DbUserSchemaServer usrSchSrvInst) {
    println "protectSchema: "+usrSchSrvInst.schema
    if(!usrSchSrvInst.protect) { // If unprotected
        if(usrSchSrvInst.schemaStatus.equals("drop")) // If schema status is drop
            usrSchSrvInst.setSchemaStatus(null)
        usrSchSrvInst.setProtect(true)
        println "-->"+usrSchSrvInst.getProtect()
        return true
    }
    else {  // If already protected
        return true
    }

    return false
}

When I tried to change the status of a schema TEST_SCHEMA_1 by setProtect(true) call, it changes in the local view (prints true on std println), but doesn't change in the  database entry. I tried to save the instance by instance.save() bu no change in the behavior.
I am using grails 2.4.4 now. Previously, I used version 2.2.4 and it worked as expected. I have this issue when I migrated the application to version 2.4.4. What could be the reason, and how could it be resolved.

A:

At what point in your service are you checking the state of the instance in the database?  When is your instance created?  Your method sets the protect variable but doesn't save the instance.
If you call save() then the instance isn't actually saved to the db, it's only saved to the DB when the session is flushed.  Try using:
save(flush: true, failOnError: false)


Q:

How to read blender API manual?

I can't understand some type definitions like

bones
  Type:   ArmatureBones bpy_prop_collection of Bone, (readonly)

link:
https://docs.blender.org/api/current/bpy.types.Armature.html#bpy.types.Armature.bones
What is this type?  Type should be simply one word. Why this one?

ArmatureBones bpy_prop_collection of Bone

We suppose to get data based on the reference section like this one, but I can't find bpy.context.armature.
Can you shed a light one this?

C.armature

Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
AttributeError: 'Context' object has no attribute 'armature'

Here are some variables also shown in manual, but I can't get them from my context. I find difficult to understand this manual. I want to show you, but
(I can't pose another picture. " You need at least 10 reputation to post more than 2 links?!" I just want to add another picture).
Anyway it is listed in the manual as:
bpy.context.bone
Type:   bpy.types.Bone
bpy.context.edit_bone
Type:   bpy.types.EditBone
bpy.context.pose_bone
Type:   bpy.types.PoseBone
It comes out that I can't find C.bone or C.pose_bone in console.
Then why are they listed in this manual?

A:

Don't worry, learning to read an API is a skillset unto itself, and a non-trivial endeavor at that, so it's okay for it to feel daunting. Unfortunately, it's usually necessary.
To answer your first question, ArmatureBones is a member of armature. It is a container, but it's not a built in Python container like list or tuple. It's a Blender container of type bpy_prop_collection, and this instance of that type of container contains Bones.
This would be roughly equivalent to saying "Encyclopedia is list of Books."
To answer your second question, there are a number of different types of context. Without knowing which one you're referencing it's hard to guess. However, there is a screen context, and it makes sense that a screen doesn't have an armature. So if you're referencing one of those other contexts, it'd make sense for it to has no attribute 'armature'.
Furthermore, the context that does have an armature is the buttons context, which means it's probably not the armature you're looking for. I suspect that you're actually after bpy.data.objects["name_of_your_rig"].data as referenced in this answer over here.
I hope that helps!


Q:

How do you make money after paying trading fees on a small account?

I have been using the Robinhood platform for my trades since there is no fee for a trade. I'd like to switch to something a little more feature rich but I just can't figure out how you all pay the trading fees without always being in the red (aside from investing huge chunks of money at a time). Note. While I plain to have long term ETFs and MFs in my portfolio for diversification I also want to take an active role in my investments, do my research, find stocks that have a catalyst and make some swing trades. This seems like a more profitable approach (albeit more risky of course) and more interesting from my perspective of being involved in the process and constantly learning new things.
For example if I were to invest $100 and get a 10% return on that investment which would make be very happy as I could reinvest that and grow it. However if I'm not misunderstanding Ameritrade would have charged me $7 to buy and another $7 to sell so my net profits after fees would be $(4) leaving me in the red after making a 10% return on my investment.
Even if I were to save longer and start by investing $500 instead of $100 I'd be in the green but still losing a staggering 20% of my profits to fees and would have had to take 5 times the risk for that. I'd also lose any ability to have diversity in my portfolio because I'd always have to use my entire portfolio for a single trade to have enough money to stand to make a large enough profit to offset the fees.
How are you making large enough profits to negate the cost of fees? Are you all rich and only do trades in excess of like a thousand dollars or something?

A:

It's not feasible to day trade with an account worth $100 or $500.  Apart from that, in the U.S. you have to deal with the Pattern Day Trader rule.
A PDT-er is someone who makes 4 or more day trades (ETFs, options and equities) in 5 business days in a margin account, provided the number of day trades are more than six percent of the customer's total trading activity for that same five-day period.
A PDT-er must maintain a minimum equity of $25,000 on any day that trades are made. If the account falls below $25,000, you  will not be permitted to day trade until the account is restored to the $25,000 minimum equity level.
A benefit to a PDT is being able to trade four times the margin maintenance excess in the account as of the close of business of the previous day (2:1 allowed overnight).   So you can be 4 times as wrong or 4 times as right :->)
Once you are "rich" and have that much in your account, two of the lowest fee trading platforms are tastyworks ($5 to open, no fee to close) and Interactive Brokers (50 cents per 100 shares with a $1 minimum ticket).  If you trade larger blocks of shares, tastyworks makes more sense.  If 500 shares or less, IBKR is more cost effective.  If you're a scale in, scale out trader, IBKR is the better choice.


Q:

Cell with text, formula and conditional formatting.

I'm looking to see if you can add data to a cell, with a sum, and conditional formatting. An example.

A1
A2

100
120 (+20)

I want cell A2 to show a new value (120) with the difference (+20) but also to have conditional formatting as in if the 120 in A2 is greater than the 100 in A1 then turn the cell green.
One option is to do the difference in cell A3 then use the CONCATENATE formula but this adds in another column and I cannot establish how to run Conditional Formatting from that.

A:

Assuming A1 contains 100 (or any other number) and A2 120 (+20) (or anything of the style N (+/-N) where N is a string of numeric characters).
Please clear any existing conditional formatting, select A2 and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=--LEFT(A2,FIND(" ",A2))>A1

Format..., select your green format OK, OK.


Q:

Android: 'threadid=3: reacting to signal 3' when executing long task

I am executing a command with Runtime.getRuntime().exec(cmd) inside my app. As it takes long to finish execution(several minutes), I have put it inside a thread. but with thread approach also app is getting suspended halfway and I see this message:
threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'

following is the code that I am using:
Thread thread = new Thread() {
        public void run() {
            Process process = Runtime.getRuntime().exec(cmd);
            //cmd : command to be executed
            process.waitFor();

        }
    };
    thread.start();
    thread.join();

What am I missing here? How can I prevent my app from getting suspended due to long processing time?
Note: I know that there are other approaches such as AsyncTask etc. but I don't think it will make any different in this case. (or will it?)

A:

Your app is causing an ANR on this line: thread.join(). That call causes the current thread to wait for the other thread to die before it continues. If this is called on the main thread and the other thread takes longer than 5 seconds to continue, this will cause an ANR. Depending on what you are trying to do, it is best to not call join on the thread and call an observer once the thread is about to finish.
For an example of how to implement an observer, please see http://stackoverflow.com/questions/994840/how-to-create-our-own-listener-interface-in-android


Q:

comparing contents of a column to another data set

I am new to R and needed help to compare columns of content.
I ordered my first table in terms of a particular column. For this I used the following function:
 x = fread ("x.txt", sep = ";")
 x_order = x [order (x $ V3)]

I'm working with files that have some 5 million lines, only need to reduce this number.
One way would be to eliminate the data that is equal to a list of 10,450 items. That is, these 5 million lines I have a column with the same and different values to this list.
Any idea what I can do?
I tried to do this to my data but did not work!
##### Filter data: data that must remain
filter = read.csv ("filter.txt")
filter1 = data.frame (filter)

############# Dataset to be filtered
data = fread ("data.txt", sep = ";")
data1 = data.frame (date)

new_data = data1 [! data1 $ V5% in% filter] # allocate a variable in the amounts equal to the filter

write.table (new_data, "data_filter.txt", sep = ";")

If I want to see the data disponibilizei this link:
https://www.dropbox.com/sh/nau51en34xv394x/AAAWlkUwib0j0_xo47vYMh_Ja?dl=0

A:

You can use "negation of in-ness", if you will. By which I mean ! on %in%. Here's a simple demo:
set.seed(1);
x <- data.frame(letters=sample(letters[1:10]),numbers=sample(1:10));
x;
##    letters numbers
## 1        c       3
## 2        d       2
## 3        e       6
## 4        g      10
## 5        b       5
## 6        h       7
## 7        i       8
## 8        f       4
## 9        j       1
## 10       a       9
eliminate <- sample(letters[1:10],3);
eliminate;
## [1] "j" "b" "f"
x[!x$letters%in%eliminate,];
##    letters numbers
## 1        c       3
## 2        d       2
## 3        e       6
## 4        g      10
## 6        h       7
## 7        i       8
## 10       a       9

This will work regardless of the ordering of the data.frame x and vector eliminate.


Q:

Build Angular2 - Typescript in Visual Studio Code

I am trying to run an application on Visual Studio Code by using this command:
"npm start"
but I am receiving this error:
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v0.12.2
npm ERR! npm  v2.7.4
npm ERR! code ELIFECYCLE
npm ERR! angular-quickstart@1.0.0 start: `concurrently "npm run build:watch" "npm run serve"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the angular-quickstart@1.0.0 start script 'concurrently "npm run build:watch" "npm run serve"'.
npm ERR! This is most likely a problem with the angular-quickstart package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     concurrently "npm run build:watch" "npm run serve"
npm ERR! You can get their info via:
npm ERR!     npm owner ls angular-quickstart
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\user\Desktop\angular-tour-of-heroes\npm-debug.log

I did these steps:

git clone https://github.com/angular/quickstart.git quickstart
cd quickstart
npm install
npm start

and it fails on step 4.
how can I fix that?

A:

the problem was with the version of Node.
I install it from this link: https://nodejs.org/en/download/
and then I did:

npm install
npm start

and the server ran.


Q:

Go "unexpected end of JSON input" error

I know this has been asked a few times, but I don't see one that matches my need to support NULL values. I have fields that are optional in a DB. I need to output data in JSON format that includes these potentially NULL fields, which I would like to omit from the JSON if they are still NULL. I can change to some other default value other than NULL, but I haven't found one that works. I'm storing JSON arrays in JSON format (longtext) in MariaDB. Here's my code that fails (Playground link):
package main

import (
    "encoding/json"
    "fmt"
)

var respBytes = []byte("")
// Example data [12345, 23456, 34567]

func main() {
    var jsonData []interface{}
    err := json.Unmarshal(respBytes, &jsonData)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(jsonData)
}

Replace respBytes empty string with example data and it works. Example data is simple JSON number array such as: "[12345, 23456, 34567]". How can I get it to work with data and without?

A:

How can I get it to work with data and without?

Unfortunately, you can't, with the standard library json package. It validates the JSON input before (while) decoding it, and an empty string is not valid JSON, so it will err before you even have a chance to decode with a custom unmarshaler.
In this particular case, the only real option is to check for valid input first.  Of course, you can do this with a wrapping function if you want:
func myUnmarshal(input []byte, target interface{}) error {
    if len(input) == 0 {
        return nil
    }
    return json.Unmarshal(input, target)
}


Q:

How do I play rtmp streams with JW Player?

I want to know how to stream RTMP with JW Player I just begun this, the embed didnt help so if someone can share a code that works for him, would be helpful.

A:

We have a guide here for this - http://www.longtailvideo.com/support/jw-player/28854/using-rtmp-streaming
And an example - http://www.longtailvideo.com/support/jw-player/29395/rtmp-single-stream


Q:

Encoding problem while training my own Glove model

I am training a GloVe model with my own corpus and I have troubles to save it/load it in an utf-8 format.
Here what I tried:
from glove import Corpus, Glove

#data
lines = [['woman', 'umbrella', 'silhouetted'], ['person', 'black', 'umbrella']]

#GloVe training
corpus = Corpus()
corpus.fit(lines, window=4)
glove = Glove(no_components=4, learning_rate=0.1)
glove.fit(corpus.matrix, epochs=10, no_threads=8, verbose=True)
glove.add_dictionary(corpus.dictionary)
glove.save('glove.model.txt')

The saved file glove.model.txt is unreadable and I can't succeed to save it with a utf-8 encoding.
When I try to read it, for exemple by converting it in a Word2Vec format:
from gensim.models.keyedvectors import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_input_file="glove.model.txt",
word2vec_output_file="gensim_glove_vectors.txt")

model = KeyedVectors.load_word2vec_format("gensim_glove_vectors.txt", binary=False)

I have the following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

Any idea on how I could use my own GloVe model ?

A:

I just found myself a way to save the data with an utf-8 format, I'm sharing it here in case someone faces the same problem
Instead of using the glove saving method glove.save('glove.model.txt') try to simulate by yourself a glove record:
with open("results_glove.txt", "w") as f:
    for word in glove.dictionary:
        f.write(word)
        f.write(" ")
        for i in range(0, vector_size):
            f.write(str(glove.word_vectors[glove.dictionary[word]][i]))
            f.write(" ")
        f.write("\n")

Then you will be able to read it.


Q:

PyMySQL Select not working

I have a strange behaviour on a current project. I use python3 and pymysql to connect to my DB. In my database i'm storing time interval in the form of table planning :
------------------------------
| id |   start   |    end    |
------------------------------
| 1  | time1     |  time2    |
------------------------------

I have a thread loop which query every minute the database to select the interval with the next query :
SELECT * FROM `planning` WHERE `start` < 'current_timestamp' AND `end` > 'current_timestamp'

Ok here the problem :
If the interval exists before i start the thread, the thread will select the interval correctly
If the interval is created while the thread is already running, the thread will not select the interval, but if use the sql query in phpmyadmin for example i get the interval. Moreover if I stop the thread and restart it, the thread will select correctly the interval.
And I don't understand why the thread can't detect new interval in the db, if someone has any ideas ?

A:

Learn about transactions and isolation levels.


Q:

Variance of sum of two random variables

I am trying to show that:
$$\mathbb{V}[X+Y] = \mathbb{V}[X]+2\text{Cov}[XY]+\mathbb{V}[Y]$$
We have that:
$$\mathbb{V}[X+Y] = \mathbb{E}[(X+Y)^2]-\mathbb{E}[X+Y]^2$$
From the definition of covariance:
$$\text{Cov}[XY] = \mathbb{E}[X-\mathbb{E}[X]]\mathbb{E}[Y-\mathbb{E}[Y]]$$
First question: How come the above makes any sense at all? i.e. we know that expectation is idempotent, so: $\mathbb{E}[\mathbb{E}[X]]=\mathbb{E}[X]$, this mans that $\mathbb{E}[X-\mathbb{E}[X]] = \mathbb{E}[X]-\mathbb{E}[X]=0$...
I proceed to expand the second line of maths:
$$\mathbb{V}[X+Y] = \mathbb{E}[X^2] + 2\mathbb{E}[XY]+\mathbb{E}[Y^2] -(\mathbb{E}[X]^2 + 2\mathbb{E}[X]\mathbb{E}[Y]+\mathbb{E}[Y]^2)$$
Second question: How does $\mathbb{E}[X-\mathbb{E}[X]]\mathbb{E}[Y-\mathbb{E}[Y]] = \mathbb{E}[XY]-\mathbb{E}[X]\mathbb{E}[Y]$?

A:

From the definition of covariance:

$$\text{Cov}[XY] = \mathbb{E}[X-\mathbb{E}[X]]\mathbb{E}[Y-\mathbb{E}[Y]]$$

First question: How come the above makes any sense at all? i.e. we know that expectation is idempotent, so: $\mathbb{E}[\mathbb{E}[X]]=\mathbb{E}[X]$, this mans that $\mathbb{E}[X-\mathbb{E}[X]] = \mathbb{E}[X]-\mathbb{E}[X]=0$...
Second question: How does $\mathbb{E}[X-\mathbb{E}[X]]\mathbb{E}[Y-\mathbb{E}[Y]] = \mathbb{E}[XY]-\mathbb{E}[X]\mathbb{E}[Y]$?

It doesn't because you have the definition wrong.  It an expectation of a product not the product of expectations
$$\begin{align}\mathsf{Cov}[XY] = & ~ \mathsf{E}\big[(X-\mathsf{E}[X])(Y-\mathsf{E}[Y])\big]
\\ = & ~ \mathsf E\big(XY-X~\mathsf E(Y)-\mathsf E(X)~Y+\mathsf E(X)~\mathsf E(Y)\big)
\\ = & ~ \mathsf E(XY)-\mathsf E(X~\mathsf E(Y))-\mathsf E(\mathsf E(X)~Y)+\mathsf E(\mathsf E(X)~\mathsf E(Y))
\\ = & ~ \mathsf E(XY)-\mathsf E(X)~\mathsf E(Y)-\mathsf E(X)~\mathsf E(Y)+\mathsf E(X)~\mathsf E(Y)
\\ = & ~ \mathsf E(XY)-\mathsf E(X)~\mathsf E(Y)
\end{align}$$


Q:

How can I express this problem (a generalization of the three cups problem) in a group-theoretic way?

I don't know much about abstract algebra and would appreciate some help in framing a problem in a group-theoretic way (if it's possible).
The problem

There are $n$ cups in a row, some of them upside down.
  Is there a way to turn them all right-side up by turning
  three consecutive cups repeteadly?

I knew the solution to the problem in which the allowed operation is turning two consecutive cups. One can see that, assigning 0 to upside down cups and 1 to the rest, the parity of the configuration does not change.
So I was looking for an invariant for the three-consecutive-cups variation and found one.
The solution
We can assign the weights $w_1 = (1, 1)$, $w_2 = (0, 1)$ and $w_3=(1, 0)$ to the cups cyclically (so that we will always turn one cup with each weight) and add them modulo 2. This is an invariant, as one can see in a case-by-case check:
$$000 \Leftrightarrow 111 \equiv (0,0) = w_1+w_2+w_3$$
$$001 \Leftrightarrow 110 \equiv w_3 = w_1+w_2$$
$$010 \Leftrightarrow 101 \equiv w_2 = w_1+w_3$$
$$100 \Leftrightarrow 011 \equiv w_1 = w_2+w_3$$
Now, if we have $n$ cups, there are $n-2$ possible operations (turning cups $123$, or $234$, ... or $(n-2)(n-1)n$). We then have $2^{n-2}$ combinations of those operations. But there are $2^n$ different possible states for $n$ cups, which means there are $2^2$ families of states, which correspond to the 4 possible values for the invariant: $(0,0), (0,1), (1,0), (1,1)$. Since there are not different combinations of operations that yield the same result (because $(1,1,1,0,...,0)$, $(0,1,1,1,0,...,0)$, $\dots$, $(0,...,0,1,1,1)$ are all linearly independent) all states with a given invariant are reachable from any other state of that family.
A group-theory solution?
OK, now for my question. I've been studying a bit of abstract algebra and this looks like it could be expressed in that language, but I don't know how. The group would be $\Bbb Z2 \times...\times\Bbb Z2 $ and the operation addition modulo 2. The "families" of solutions look to me like cosets, somehow, but I don't that's think right because a coset is the subset obtained by applying a certain operation (let's say $(1,1,1,0,...,0)$) to all members of the group.
That's not what I do here. Instead, in this problem we are interested in finding what members are reachable by applying a combination of the allowed operations. Maybe it is more like a vector space and not a group?
I'd like some insight into this to better grasp the problem in a more formalized way. Thank you!

A:

Letting $\def\F{\mathbb F}\F_2$ be the finite field with two elements, the set of states in this problem is $\F_2^n$, as you mentioned. This is a group, but is also an $n$-dimension vector space over $\F_2$, and the latter interpretation is more fruitful.
There are $n-2$ different triplets of cups that can be turned over, so each possible method of turning over cups is represented by a vector in $\F_2^{n-2}$. To figure out how a strategy $x\in \F_2^{n-2}$ affects an arrangement $a\in \F_2^n$, you just have to multiply $x$ by this $n\times(n-2)$ matrix:
$$
A = \begin{bmatrix}
1 & 1 & 1 & 0 & 0 &0 &\dots&0&0&0\\
0 & 1 & 1 & 1 & 0 &0 &\dots&0&0&0\\
0 & 0 & 1 & 1 & 1 &0 &\dots&0&0&0\\
0 & 0 & 0 & 1 & 1 &1 &\dots&0&0&0\\
&\vdots\\
0& 0&0&0&0&0&\dots&1&1&1\end{bmatrix}
$$
The effect of the strategy is to change $a$ into $xA + a$. Therefore, to determine whether an arrangement $a$ can be transformed into $a'$, you need to solve the matrix equation
$$
xA=a'-a:=b
$$
Right off the bat, we know that the rank of $A$ is at most $n-2$, so that the set of vectors $b$ for which the above equation can be solved is a subspace with dimension at most $n-2$. Going even further, we can use standard linear algebra techniques to explicitly describe the subspace of $b$ for which this can be solved. After doing so, you will come up with the same clever invariant.
This cup puzzle has the same mathematics as the game lights out, where there is a grid of buttons which are all on or off, and touching a button toggles itself along with its neighbors. For more info, you might want to check out https://www.jaapsch.net/puzzles/lomath.htm.


Q:

Does importing actually include a module?

If I get a module called A which imports B and C :
module A exposing (..)

import B
import C

and B also imports C :
module B exposing (..)

import C

What will happen? Does import actually include B and C code, then C would appear twice inside A at compilation? Or does the compiler replace each occurrence of an imported module's member in A or B by its origin code?

A:

Regardless of how many modules another modules is referenced in, it only ever gets compiled once.
Here's an example that takes three files:
A.elm
module A exposing (..)

import B
import C

a : String
a =
    "Hi from A!\n" ++ B.b ++ "\n" ++ C.c

B.elm
module B exposing (..)

import C

b : String
b =
    "Hi from B!\n" ++ C.c

C.elm
module C exposing (..)

c : String
c =
    "Hi from C!"

The resulting transpiled javascript looks like this (your generated js may be different):
var _user$project$C$c = 'Hi from C!';

var _user$project$B$b = A2(_elm_lang$core$Basics_ops['++'], 'Hi from B!\n', _user$project$C$c);

var _user$project$A$a = A2(
    _elm_lang$core$Basics_ops['++'],
    'Hi from A!\n',
    A2(
        _elm_lang$core$Basics_ops['++'],
        _user$project$B$b,
        A2(_elm_lang$core$Basics_ops['++'], '\n', _user$project$C$c)));

As you can see, the C.elm code was only included once.


Q:

Javascript: ISO Conversion to Shortform of month

I have a date value that looks like this:
2015-07-12T22:00:00.000Z
I want to convert this into the short form string of the monthly value e.g. "Jan"
Can someone give me a hint at how I could go about this?

A:

The simplest way is to get the month number, use it to get the month name, then replace the number with the name in the string, e.g.:
function insertMonthAbbr(s) {
    var months = ['Jan','Feb','Mar','Apr','May','Jun',
                  'Jul','Aug','Sep','Oct','Nov','Dec'];
    var monthNumber = s.substring(5,7);
    return s.substring(0,5) + months[monthNumber-1] + s.substring(7);
}

console.log(insertMonthAbbr('2015-07-12T22:00:00.000Z')); // 2015-Jul-12T22:00:00.000Z

No need for Date methods.


Q:

Addition of different sized numbers in assembley

I'm asked to write a program to add a byte sized array elements. First 2 bytes are the number of elements in the array.
The array may contain thousands of numbers so I should put the sum in 32-bit register (e.g. ax:dx) but the problem is that I don't know how to take a byte from memory then add it to a 32-bit register (or a double variable in memory).
I have tried adding using a 16-bit register and a word variable in memory. Here is the code:
array db 07, 00, 30, 10, 77, 14, 9, 54, 100
sum dw ?

lea ax, data
mov ds, ax
mov es, ax

lea bx, array
mov cx, [bx]
mov bx, 0002h
mov dx, 0000h
Addition:
mov dl, [bx]
mov dh, 00h
add sum, dx
add bx, 1
loop Addition

mov ax, 4c00h
int 21h

It works correctly. But I want to know how to do that with a 32-bit register and a double variable.
I use emu8086

A:

To add an 8-bit value in BL to the 32-bit sum in DX:AX:
xor bh,bh  ; Clear BH (effectively zero-extends BL into BX)
add ax,bx  ; Add BX to the lower half of the sum
adc dx,0   ; If the lower half wrapped around (the above addition resulted
           ; in a carry), add 1 to the upper half, otherwise add 0.


Q:

two dimensional $_SESSION in php

I'm building a server side workers manager script which saves the "jobs to work on" data in the $_SESSION and each time calls itself with the next job to be done. This gives me control, because I can stop and re-continue whenever I need. This works great. The problem I'm having is to be able to run a couple of these Managers in the same browser because they share the $_SESSION. So I'm trying to create a two-dimensional $_SESSION array that keeps different data according to the sessionId I specify in the http request. I want to do this in order to run a number of crawlers from the same browser that do one task at a time and keep a list of remaining tasks in its' $_SESSION[$sessionId] variables. So I've added a sessionId to each request and then each script uses it. It works great without the sessionId and doesn't work as I expect with. I'm having a hard time understanding why. This is a sample code to demonstrate my problem:
session_start();
$sessionId = $_REQUEST['sessionId'];

if ($_REQUEST['currId'] == 0) {
    unset ($_SESSION[$sessionId]);
    $_SESSION[$sessionId]['log'] = "starting log for session " . $s;
}

if ($_REQUEST['currId'] < $_REQUEST['limit']) {
    $_SESSION[$sessionId]['log'] .= " adding ";

    // call with next currId
    echo '<META HTTP-EQUIV="Refresh" CONTENT="1;URL=' . "'test3.php?limit=" . $_REQUEST['limit'] . "&currId=" . ($_REQUEST['currId']+1) . "&sessionId=" . $sessionId . "'" . '">';
}

// reached limit
else {
    echo $_SESSION[$sessionId]['log'];
};

I'm invoking first a call to test3.php?limit=5&currId=0&sessionId=0 and than expect the code to re-call itself with currId=1,2,3,4,5. This is happening Ok. but the $_SESSION isn't kept as I
expect it to be. When I remove the sessionId usage, it does work.  But that way I can only invoke one crawler simultaneously unless I open a different browser...
Thanks

A:

You might have more luck with a sessionId that isn't a number. If you turn error reporting up with error_reporting(E_ALL); you'll see some notices, one of which is Notice: Unknown: Skipping numeric key 0 in Unknown on line 0.
According to one commenter on the php pages this is caused by using an integer as a key for the $_SESSION array - when I tried this without the error disappears.
You have also got a variable $s in there, which I assume should be $sessionId, that'd give a notice too.


Q:

Get full word containing a specific element

Having the reference to a specific DOM element (e.g. ), how can we get the full word containing that element?
For example :
Hello World, and Hello, Pluto!

I expect to get the following output :

First : Hello
Second: World
Third: Hello
Fourth: Pluto

var $marks = $("mark");

var tests = [
  "Hello",
  "World",
  "Hello",
  "Pluto",
];

function getFullWord($elm) {
  // TODO: How can I do this?
  //      This is obviously wrong.
  return $elm.html();
}

var $marks = $("mark");
tests.forEach(function(c, i) {
  var word = getFullWord($marks.eq(i));
  if (word !== c) {
    alert("Wrong result for index " + i + ". Expected: '" + c + "' but got '" + word + "'");
  }
});

Hello World, and Hello, Pluto!

A:

If you need fast and compact code (one-liner), try this:
var $marks = $('mark');

$marks.each(function() {
    var wholeWord = (this.previousSibling.nodeValue.split(' ').pop() +
                     this.textContent +
                     this.nextSibling.nodeValue.split(' ')[0]
                     ).replace(/[^\w\s]/gi, '');
});

JSFiddle (with logging into console and comments)


Q:

My program keeps waiting dont and does not even show the first printf

#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/shm.h>

typedef struct{long type;char resultado[10];} MsgAnswerLoginStruct;

typedef struct{long tipo;int meupid;char login[20];char password[20];}MsgReqLoginStruct;

main(){

printf("i am here");

int msg_id, status;
MsgReqLoginStruct msg;
MsgAnswerLoginStruct msg2;

msg_id = msgget(2000, 0600 | IPC_CREAT);
if(msg_id == -1){
    printf("erro\n");
    exit(1);
}

status = msgrcv(msg_id, &msg, sizeof(msg) - sizeof(long) , 1,  0);
if(status < 0){
    printf("erro2\n");
    exit(1);
}

printf("Tentativa de Autenticação de PID = %d\n", msg.meupid);

}

here is my problem, this is a program that receives messages from the IPC, but he keeps waiting even when I am trying to send from another process..
And I put that printf to debug.. It doesnt appear on my console?! why ?
when I run program it just keeps waiting..
Thanks in advance guys!!

A:

Because you are not flusing the buffer. It's likely stdout is line buffered in your implementation.
Try:
printf("i am here\n");
                  ^^

Or
printf("i am here");
fflush(stdout);


Q:

A Question about Functions

I know this may sound like a dumb question but I got to know since I have been trying to find an answer but can't find any. I noticed that in some functions, after the parentheses, the function is assigned a type? For example
Public Function getConn(ByVal AppId As String, ByVal TranId As String) As String
and it returns a value call sRet
After the parentheses, why is there an "As String"?

A:

It's defining the return type.
If you did something like
connection = getConn("1", "2")

then connection would be a string, that probably contains the connection string.
You can do other return types as well, such as Int, Float etc.


Q:

protractor - issues with scrolling into infinite scroller

I have a protractor test looking for a record in my infinite scroller component like this.
 searchPage.searchEntitlement('search criteria');
    var myHiddenElementInScroller = element(by.repeater('result in ctrl.results track by $index').row(12));
    browser.driver.executeScript(function () { arguments[0].scrollIntoView(); }, myHiddenElementInScroller .getWebElement());

myHiddenElementInScroller.click();

This is supposed to scroll to the element and click it. Instead its throwing me element not visible error.
Has anyone come across this situation? Any help greatly appreciated.

A:

Thanks for all the responses. I was able to resolve this issue by using element(by.CssContainingText(cssSelector, searchText)) locator.