text:
Q: Prevent form from submitting with jQuery So this is driving me nuts. This code,
$('#the_form').submit(function(e){
            alert("Submit!");

            return false;
            e.preventDefault();
        });

should prevent my HTML form,
<form id="the_form">
                <input type="text" name="q" />
                <input type="submit" />
            </form>

from refreshing the page, but it doesn't. Does anyone have insight on this?

A: $(function() {
    $('#the_form').on('submit', function(e){
        e.preventDefault();
        alert("Submit!");
    });
});

A: Try removing return false from your code, or putting it after e.preventDefault().

A: Just remove the return statement..
Also Make sure your code is encased in DOM ready Handler
$(document).ready( function() {
    $('#the_form').submit(function(e){
         alert("Submit!");
         e.preventDefault();
    });
});


text:
Q: Compose key not working on Ubuntu 16.04 I installed Ubuntu 16.04 AMD64 from the scratch recently, and I am facing a problem with the Compose key:

*

*I am using the Compose key as <Multi_key> for some characters in a
self-defined ~/.XCompose file.

*In the keyboard settings, I have activated the Compose key.

*In my profile, I use the following settings (as recommended in
other threads):

~/.profile :
export GTK_IM_MODULE="xim"
export QT_IM_MODULE="xim"
export XMODIFIERS="@im=none"

Result:

*

*The Compose key does work in the Terminal, in particular in vim, and also in the Dash search field for
applications.

*It does not work, unfortunately, in Firefox, Chrome, LibreOffice,
and Gedit.

So, the settings do have effect, but not for all applications.
Why? What am I missing?

A: I was having a very similar issue and for some reason what worked for me was putting all my custom compose key settings at the top of the original file all the way over in /usr/share/X11/locale/en_US.UTF-8/Compose and then making a hardlink to it called .XCompose in the home directory instead of writing my own .XCompose in the home directory from scratch.
It worked for me, maybe it'll work for you.

A: I had a similar problem with the Compose Key upgrading from 14.04.3 to 16.04 (US-keyboard used also for german, french and italian).
My choice for the compose key was the RightAlt key (al least for the last 10 years). After many unsuccessful trials and after searching everyhere for help I understood that I was fallen victim of the bug #1573755 and gave up, temporarily using an old 14.04.
But all my troubles under 16.04 disappeared abruptly last weekend after I configured the Compose Key as Shift-RightAlt. All my applications from vi to emacs to LibreOffice are now working perfectly. No other configuration gave me the same result. I do not know why, but hope that it can help.
Regards
Franco

A: I had the same problem and solved it with these steps:

*

*Remove (or comment) any lines that deal with XIM configurations from your ~/.profile:
# export GTK_IM_MODULE="xim"
# export QT_IM_MODULE="xim"
# export XMODIFIERS="@im=none"

*Set the input method "XIM" from the Language Support tool instead:

*Remove (or move) your ~/.config/dconf/user file (here's some info on what dconf is).

*Log out and log in again.

Thanks to Gunnar Hjalmarsson for pointing the bug #1573755 out. If this solutions doesn't work for you, you might find something useful in the thread.

A: Adding ibus-daemon --xim as a startup application fixes this for me. None of the other suggestions here worked.
Steps for doing this are:

*

*Search for 'startup' using the Ubuntu search button on the toolbar (also accessible via the windows key). Select Startup Applications

*Click the add button. In the dialogue that follows enter the following information:

*Name = Ibus Daemon (or whatever)

*Command = ibus-daemon --xim

*Comment = whatever you like

*Click Save

*Log out and then back in.

A: I had the same problem after upgrade from 20.10 to 21.04.
In my case the problem was with invalid LC_TIME environment variable setting, after I set LC_TIME to correct value my XCompose started to work again in firefox and geany.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop within a loop, Creating a top X list I have the function below to output top 5 restaurants results based on rating. How do I add a for loop in this loop so that the output includes the position in the top 5?
def print_top_5(restaurant_list):
    sorted_list = sorted(restaurant_list, key = itemgetter("rating"),reverse = True)
    for restaurant in sorted_list[:5]:
        print restaurant["name"]
        print restaurant["rating"]

Thanks!

A: Try Python's built-in enumerate function:
def print_top_5(restaurant_list):
    sorted_list = sorted(restaurant_list, key = itemgetter("rating"),reverse = True)
    for idx, restaurant in enumerate(sorted_list[:5]):
        print(idx, restaurant["name"], restaurant["rating"])

Note this counts up starting from 0, so your output will looking something like:
0 Restaurant 1 10
1 Restaurant 2 9
2 Restaurant 3 8.5

If you'd like the count to start at 1, just add 1 to idx:
print(idx+1, restaurant["name"], restaurant["rating"])


text:
Q: One of my Bollean field is displayed as select (Unknow/Yes/no) instead of checkbox I have a error I could not fix.
I have many boolean fields in a form and all arer displayed as checkbox except one that is displayed as select list
models.py
class Psychosocial2(Invalidite):
    """ A class to create a psychosocial 2 instance. """

    ide = models.AutoField(primary_key=True)
    ...
    ps2_res_pdr = models.BooleanField('Pas de réponse', null=True, blank=True) <- correctly displayed
    ps2_res_nap = models.BooleanField("NA", null=True, blank=True)             <- displayed as a select

forms.py
...
self.fields['ps2_res_nap'] = forms.BooleanField(label = 'NA',required=False)
...

template

{{ form.ps2_res|as_crispy_field }}
{{ form.ps2_res_pdr|as_crispy_field }}
{{ form.ps2_res_nap|as_crispy_field }} <--

A: Per the docs, the default form widget for a boolean field is CheckboxInput, or NullBooleanSelect if null=True.  So it seems the 'offending' one is acting correctly, and the real question is why the others which also have null = True are not.  Is it possible you're specifying widgets for the others so that the default is not used?


text:
Q: Split AMEX Transaction detail strings using regex I have an array of transaction description strings from an American Express Card that I will be using PHP's preg_split() to parse;
[
  "THE DISNEY STORE #90DANBURY             CT",
  "CHRISTMAS TREE SHOPSDANBURY             CT",
  "BATH & BODY WORKS 07DANBURY             CT",
  "CITGO DODGINGTOWN GANEWTOWN             CT",
  "DUNKIN #344944 Q35 3MONROE              CT",
  "DUNKIN #344944 Q35 3MONROE              CT",
  "DUNKIN #344944 Q35 3MONROE              CT",
  "DUNKIN #344944 Q35 3MONROE              CT",
  "AT&T RECURR BILL PAYDALLAS              TX",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "POSTAGE REFILL      STAMFORD            CT",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "ONLINE PAYMENT - THANK YOU",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "AOL SERVICE         800-827-6364        VA",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "EBAY INC. 0000      866-779-3229        CA",
  "WWW.ITUNES.COM/BILL CUPERTINO           CA",
  "THE HOME DEPOT      TRUMBULL            CT",
  "THE HOME DEPOT      TRUMBULL            CT",
  "AMEX GIFT CARDS     866-268-0582        NY",
  "APPLE ONLINE STORE  CUPERTINO           CA",
  "APPLE ONLINE STORE  CUPERTINO           CA",
  "AMAZON MKTPLACE PMTSAMZN.COM/BILL       WA",
  "THE HOME DEPOT      BRIDGEPORT          CT",
  "AT&T RECURR BILL PAYDALLAS              TX",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "AT&T RECURR BILL PAYDALLAS              TX",
  "SHELL OIL 5754389960NEWTOWN             CT",
  "WALGREENS           NEWTOWN             CT",
  "THE HOME DEPOT      TRUMBULL            CT",
  "ONLINE PAYMENT - THANK YOU",
  "AOL SERVICE         800-827-6364        VA"
]

What I am attempting to do is parse the vendor city and state from the description string. This data is in a CSV that gets uploaded to a PHP script. Using the online tool regexr.com I have been able to get close using this expression:
([A-Z&0-9 ./#\*\-]{0,19})\w

What I was able to infer is a 20 characters max for a description, except in the case of payments then the text runs on. The city starts right at the 20 character limit and is allowed to contain whitespace in some cases. The state is 2 characters with preceding white space.
Expected results:
CHRISTMAS TREE SHOPSDANBURY             CT

Would Parse to
Vendor: CHRISTMAS TREE SHOPS City: DANBURY State: CT
Payments;
ONLINE PAYMENT - THANK YOU

Would stay as is.
And edge cases;
AOL SERVICE         800-827-6364        VA

Would parse to
Vendor: AOL SERVICE Detail: 800-827-6364 State: VA
(Labels used for clarity)
Actual Results:
if you look at my saved results https://regexr.com/3j39m you can see that lines like ONLINE PAYMENT - THANK YOU and AOL SERVICE         800-827-6364        VA don't parse as expected.
How could I improve the expression to:

*

*Parse the first 20 or fewer characters in the vendor/description.

*Handle the payment description which lacks the 3 expected parts.

*Handle cases when the vendor has substituted other information into the expected city location that may exceed the 20 character limit.

A: You can use a regex to split a fixed-width string like this:
<?php

$re = '/(?<Store>.{20})(?<City>.{20})(?<State>.{2})/m';
$str = 'THE DISNEY STORE #90DANBURY             CT';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach( $matches as $match ){
    echo $match[1]."\t=>\t".$match[2]."\t=>\t".$match[3]."\n";
}

Demo.
You can achieve the same with substr().

A: It looks to me as if the list is tab delimited, so this should do the trick: /\t([A-Za-z ]+)\t+[A-Za-z]{2}$/
Explanation

*

*\t match a tab

*([A-Za-z ]+) match a string of characters and spaces, signifying a town name

*\t+ match one or more tabs (looks like it might be more than one in your data set)

*[A-Za-z]{2} match 2 characters, signifying a state abbreviation

*$ end of string


text:
Q: Xtext unordered list of optional items I'm trying to modify Xtext domain model example, so that entity properties can have two more attributes (in addition to the 'many' that is already included in the example). All attributes need to be optional and their order irrelevant. It seems that, no matter what I do, the first attribute must be the one that is listed first. So, for example, if I have this in xtext:
(many ?= 'many')? & (aBool ?= 'isBool')? & (anEnum = EnumType)?

If I use 'many', then it must be the first attribute, or I get an error. If I leave it out completely, I get no errors.
So, how do I tell xtext that I want three optional attributes, in an unordered group?

A: Apparently, all I had to do is enclose the group in parentheses :/
((many ?= 'many')? & (aBool ?= 'isBool')? & (anEnum = EnumType)?)

This helped.

A: The & operator is very problematic in Xtext! Because the parser has to implement all possible permutations. It would be better to implement an abstract Parser Rule 'OptionalElement' which can occure infinite often in a list. This parser rule then is specified as 'Many', 'Bool' or 'Enum'. The grammar then would look like this:
AnyRule: /* some stuff */ optElement+=OptionalElement*;
OptionalElement: Many | Bool | Enum;
Many: {Many} 'many';
Bool: {Bool} 'isBool';
Enum: anEnum=EnumType;

Then you only have to implement a check method in the validator class (...mydsl.validation.MyDslValidator) which checks whether Many, Bool or Enum occures max. one time in the 'optElement' list.
The class/method/field modifier are defined in the same way in the Java grammar.


text:
Q: Use StoreEntryId as unique id Is it a good idea to use StoreEntryId as a unique id of exchange items. I've got the problem, like a lot of other developers, that the ItemId changes when moving objects in the exchange server. So maybe using StoreEntryId is a good idea.
Has anyone any experience with it?


text:
Q: Parametrized pipeline in GoCD? I'm evaluating GoCD if we would be able to use it instead of Jenkins.
Is there any way how to create a parameterized pipeline like parametrized jobs in Jenkins?
In Jenkins, we're using these parameters in some jobs which are executed manually to configure "full-rebuild" of the project:

This bool value is passed as ENV variable to the job. I have found that GoCD has ENVs but I didn't find if there is a way how such ENV can be selected before manual executing.
Thanks

A: Yes. It is possible to parameterize pipelines in GoCD.
Go to pipeline settings -> parameters and add desired parameters. A parameter can be added with a default value, if required.
The next time a pipeline is triggered, one could override the default value with new value and trigger it.
The parameters can be accesses inside pipeline scripts using #{myParam}.
More detail here: https://docs.gocd.org/current/configuration/admin_use_parameters_in_configuration.html
Below is a snapshot to set Docker information as environment variables.
enter image description here


text:
Q: How to know which nodeport can be allocated from Kubernetes API Server? I want to figure out how does kubernetes knows which nodeport can be allocated when create a new service with nodeport type like this:
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
    - port: 80
      targetPort: 80

I had search google and find these kubernetes soure code, but I don't understand how does it works.
https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/allocator.go

A: The Nodeport is chosen randomly between 30000-32767. You can set it in the service definition.
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
      # By default and for convenience, the `targetPort` is set to the same value as the `port` field.
    - port: 80
      targetPort: 80
      # Optional field
      # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
      nodePort: 30007

From the documentation: https://kubernetes.io/docs/concepts/services-networking/service/#nodeport
Update
The classes placed in the package kubernetes/pkg/registry/core/service/portallocator are responsible for allocating a node port for a service.
This test documents the behavior: https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/operation_test.go
Kubernetes just takes a random port and if that one isn't free it takes the next one.
If you can read go the other classes in that package are a good starting point to understand the behavior.


text:
Q: How to add a block within twig template in Drupal 8 Does anybody know how to add a search block into main-menu block via twig template in Drupal8?
enter image description here
I need something like that in main-menu.html.twig:

 menu ....

 Search block should be added there

Thanks a lot!!!

A: I've found a solution!
We can add a new region in themename.info.yml, like that:
regions:
  navigation: 'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  blog_menu: 'Blog menu'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'
  sidebar_second: 'Secondary'
  footer: 'Footer'
  page_top: 'Page top'
  page_bottom: 'Page bottom'

And then call this wrapping this region in page.html.twig as needed.

    {{ page.blog_menu }}

So, both blocks (menu and search) will be added inside new region via admin and wrapped.


text:
Q: Maximum size of intersection of two families of sets Let $\mathcal A,\mathcal B\in \mathcal P([n])=2^{[n]}$ be two families of subsets of $[n]$. What is the maximal size of $\mathcal A\cap\mathcal B:=\{A\cap B:A\in\mathcal A,B\in \mathcal B\}$ ?
I believe the answer is $|\mathcal A|+|\mathcal B|$ but I don't know how to prove it. Could someone help me?

A: $\newcommand{\A}{\mathcal{A}} \newcommand{\B}{\mathcal{B}} \newcommand{\of}{\subseteq} \newcommand{\P}{\mathcal{P}}$
Consider $n=2m$ (with $m\ge 2$) and define $\A = \{A\of [n] \,:\, A\cap [m] = [m]\}$ and $\B=\{B\of [n]\,:\, B\cap [m+1,n]=[m+1,n]\}$. Then $\A \cap \B = \P([n])$ so $$ |\A \cap \B| = 2^n = |\A| \cdot |\B| \gg |\A| + |\B| = 2^{m+1} $$
The upper bound $|\A\cap \B| \le |\A|\cdot |\B|$ is trivial for all systems $\A$ and $\B$.


text:
Q: UIImage.pngData() - a struct or a closure? I am massively confused about what UIImage.pngData() returns. All along, i was under the impression that it's an instance of a Data struct, representing a buffer of bytes. However, it appears one can also append "()" to the returned value and it will compile, as if calling a closure with no arguments! Can't decipher what's happening.
Tried the following in XCode Playground. See output in comments:
let image = UIImage()
let png = UIImage.pngData(image)
print(type(of: png))   //prints --->   () -> Optional<Data>
print(type(of: png())) //prints --->   Optional<Data>

What is going on? Is png variable above an instance of a closure which takes no arguments and returns a Data optional?
FYI, Apple documentation's declaration of UIImage.pngData() is:
func pngData() -> Data?

How is it possible to use "()" on a structure instance?


text:
Q: How to find index before the max-value index, idxmax()? I have a dataframe with CountryName as the index and values for their GDP as a column. I'm trying to find the index (the country name) that comes before the country with the max GDP.
CountryName   GDP
US             350
UK             370
Australia      340
Germany        500
France         450

If i do, df['GDP'].idxmax() , it'll return Germany. But is there a simple way to return Australia? (the index before the max index).

A: The shift method of dataframes can help you out in this situation.
# Initialize dataframe
import pandas as pd
df = pd.DataFrame({
    'CountryName': ['US', 'UK', 'Australia', 'Germany', 'France'],
    'GDP': [350, 370, 340, 500, 450],
})
df = df.set_index('CountryName')

# Get the index value of the row directly before the row with max 'GDP' value
target = df['GDP'].shift(-1).idxmax()

gives as result:
In [1]: target
Out[1]: 'Australia'

A: You can use np.ndarray.argmax and index the index:
res = df.index[df['GDP'].values.argmax() - 1]  # Australia

A: Does this work?
df = pd.DataFrame({'CountryName': ['US', 'UK', 'Australia', 'Germany', 'France'], 'GDP': [350, 370, 340, 500, 450]})
print(df['CountryName'][df['GDP'].idxmax()-1])
# Australia

One thing I can see a problem in is if the highest GDP has index 0 which would return CountryName at position -1 or the last country in the dataframe.


text:
Q: Why is &> preferred over >&? The bash manpage says:

Redirecting Standard Output and Standard Error
  Bash allows both the standard output (file descriptor 1) and the
  standard error output (file descriptor 2) to be redirected to the
  file whose name is the expansion of word with this construct.
There are two formats for redirecting standard output and standard error:
&>word

and
>&word

Of the two forms, the first is preferred.  This is semantically equivalent to
>word 2>&1

Why is the first form preferred?

A: The author is saying that &>word and >&word are both the same, and both equivalent to >word 2>&1. In addition, the first form is preferred.
The immediately following text in the manual says why:

When using the second form, word may not expand to a number or '-'. If
  it does, other redirection operators apply (see Duplicating File
  Descriptors below) for compatibility reasons.


text:
Q: Object query language | execute both "order by" and "where" clauses How do I sort out some data according to an where clause and a order by clause using object query language this is the query that I'm using but i'm not sure if it is working or not.
SELECT user from user.User as user WHERE user.status=1 order by user.username

Thanks.

A: I think it should be written more like
SELECT `users`.* FROM `users` WHERE `users`.`status` = 1 ORDER BY `users`.`username`

This assumes you have a table called users and want to select all rows where status is 1, ordered by the username column.

A: Your query looks fine. From the reference documentation:

14.11. The order by clause
The list returned by a query can be
  ordered by any property of a returned
  class or components:
from DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate

The optional asc or desc indicate
  ascending or descending order
  respectively.


text:
Q: Need Help with Approval Process: When a user would like to mass/delete or transfer records they must be approved by the Office Manager I have never worked with approval processes so I would really appreciate your inputs.
An approval process needs to be be created based on ownership of accounts for mass record deletion and transfer. That is nobody shall be allowed to mass transfer or delete records without the approval of the Sales Coordinator or Office Manager.
Does anybody know the most efficient way of doing this?


text:
Q: Run-time error in .split("|") I'm using that method in that line:
f.getCmbAttori().getSelectedItem().toString().split("|")

with an input like "13|Il Signore degli Anelli" and insted of return:
f.getCmbAttori().getSelectedItem().toString().split("|")[0] = "13"
f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "Il Signore degli Anelli"

It returns an array where every character is alone, like this:
    f.getCmbAttori().getSelectedItem().toString().split("|")[0] = ""
    f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "1"
    f.getCmbAttori().getSelectedItem().toString().split("|")[2] = "3"
    f.getCmbAttori().getSelectedItem().toString().split("|")[3] = "|"
    f.getCmbAttori().getSelectedItem().toString().split("|")[4] = "I"
    f.getCmbAttori().getSelectedItem().toString().split("|")[5] = "l"
[...]

    f.getCmbAttori().getSelectedItem().toString().split("|")[25] = "l"
    f.getCmbAttori().getSelectedItem().toString().split("|")[26] = "i"

How can be possible that? I'm wrinting this method in a wrong way? Here a piece of code where I use that:
PreparedStatement stmSql = null;
                 int risultato = 0;
                 stmSql = f.conn.prepareStatement("insert into recita (CodAttore, CodFilm) values (?, ?)");
                 stmSql.setInt(1, Integer.parseInt(f.getCmbAttori().getSelectedItem().toString().split("|")[1]));
                 stmSql.setInt(2, Integer.parseInt(f.getCmbFilmRecita().getSelectedItem().toString().split("|")[1]));
                 risultato = stmSql.executeUpdate();

A: The String.split function takes a regex, try using this:
split("\\|")

this will make it split on a literal |

A: Generally if you want to split by fixed string (instead of a regex) use quote:
.split(Pattern.quote("|"))

A: Try split("\\|");
OR You can use
split(Pattern.quote("|"));

java.lang.String.split splits on regular expressions.
Twelve characters have special meanings in regular expressions: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), the opening square bracket [, and the opening curly brace {.
These special characters are often called "metacharacters".
For More


text:
Q: Comparar campo tipo SqlTimeStamp estou com uma dúvida aqui...
Tenho um campo no banco SQL Server do tipo DateTime que pode ser nulo.
No Delphi, dentro do MemTable (ou ClientDataSet... seria a mesma coisa nesse meu caso), o campo foi criado como SQLTimeStamp Field.
Eu quero ver se esse campo possui uma data ou está nulo, mas não cheguei a uma comparação correta sem dar erro de compilação dizendo que os tipos são diferentes.
Segue o código:
if fDm.fdmEmail.FieldByName('esr_ultimo').AsSQLTimeStamp > 0 then // Aqui dá erro na compilação
begin
  // Formatar o campo...
  edtUltimo.Text := SQLTimeStampToStr('dd/mm/yyyy', fDm.fdmEmail.FieldByName('esr_ultimo').AsSQLTimeStamp);
end;

Já tentei "<> NULL", "<> 'NULL'", e várias outras...
Desde já agradeço.

A: Tente usar o .AsDateTime ao inves de .AsSQLTimeStamp, e diga se o resultado foi positivo.

A: Você pode usar a propriedade IsNull, ficaria assim:
fDm.fdmEmail.FieldByName('esr_ultimo').IsNull;

Esta propriedade retorna true/false.


text:
Q: Is there any way I can integrate Minitube with a web browser like Chrome? I really enjoy using Minitube. It's a very comfortable and lightweight alternative to YouTube playback with flash. The only thing that bothers me is that I have to manually copy and paste interesting youtube links I found into the program to play them back.
Is there any way I can automate this and integrate Minitube into Google Chrome or another web browser?

A: Integrating Minitube with Chrome using a Chrome extension

Overview
Thanks to a Chrome extension by Nicu Farmache this is now possible. The extension source code may be checked out at the google code project page.
Installation
While trying to install the extension I found that the instructions provided by the author weren't working for me on Ubuntu 12.04.3 LTS. These are the steps I followed to get it to work anyway:

*

*Install the extension from the Chrome Webstore

*Create a script called minitubehandler.sh with the following content:
#!/bin/bash
# NAME:         minitubehandler.sh
# VERSION:
# AUTHOR:       (c) 2013 Glutanimate
# DESCRIPTION:  - parses youtube links coming from the Chrome minitube extension
# FEATURES:
# DEPENDENCIES: minitube-ubuntu
#
# LICENSE:      GNU GPL v3
#
# USAGE:        Please follow the instructions provided in [this Q&A](http://askubuntu.com/a/353176/81372)

MINITUBEURL="$1"
ACTUALURL="${MINITUBEURL#minitube}"
MINITUBE="/opt/minitube-ubuntu/minitube"

"$MINITUBE" "$ACTUALURL" > /dev/null 2>&1&

Please note that this will only work with the minitube-ubuntu package installed from the Ubuntu Software Center. In order to use the script with other version of minitube you will have to edit the path to the minitube executable.

*Either move the script to $PATH (e.g. ~/bin ) or move it to a folder of your choice and copy down the file path

*Create a new desktop file under ~/.local/share/applications called minitubehandler.desktop with the following contents:
[Desktop Entry]
Version=1.0
Type=Application
MimeType=x-scheme-handler/minitubehttp;x-scheme-handler/minitubehttps;
Terminal=false
Exec=minitubehandler.sh %u
Name=minitubehandler
Icon=minitube
NoDisplay=true

*Make sure to replace the Exec line with the path to your script if you decided against moving it to your $PATH

*Assign the desktop file to the extension's MIME type by executing the following lines in a terminal:
xdg-mime default minitubehandler.desktop x-scheme-handler/minitubehttp

xdg-mime default minitubehandler.desktop x-scheme-handler/minitubehttps

*Restart Chrome
From now on if you navigate to a YouTube video page you should see a small Minitube icon on the right side of your address bar:

Clicking it will launch Minitube and play back the video or - if Minitube is already running - switch playback to the video in question:


text:
Q: Laravel 5.6, How to Set option value on var.SetAttibute on dynamic form? Excuse me, I'm just learning web developing recently,
I have some trouble on dynamic form, here's the picture
I wanna make dynamic form with select type on it.
TAMBAH button = add more field
Simpan button = save,
The problem is, when I want to add more fields, select input did not show as the first one, it become normal input not select.
I know, maybe the problem is from javascript which I don't understand.
here is the code
On Form
{{ Form::text('jumlah[]', null, array('class'=>'form-control')) }}
{{ Form::text('satuan[]', null, array('class'=>'form-control')) }}
{{ Form::text('keterangan[]', null, array('class'=>'form-control')) }}
{{ Form::select('status_pi[]', ['Iya' => 'iya', 'Tidak' => 'Tidak'],
'Tidak',array('class'=>'form-control')) }}

On Javascript
var jumlah = document.createElement('input');
jumlah.setAttribute('name', 'jumlah[' + i + ']');
jumlah.setAttribute('class', 'form-control');

var satuan = document.createElement('input');
satuan.setAttribute('name', 'satuan[' + i + ']');
satuan.setAttribute('class', 'form-control');

var keterangan = document.createElement('input');
keterangan.setAttribute('name', 'keterangan[' + i + ']');
keterangan.setAttribute('class', 'form-control');

var status_pi = document.createElement('input');
status_pi.setAttribute('name', 'status_pi[' + i + ']');
status_pi.setAttribute('selected', 'selected');
status_pi.setAttribute('class', 'form-control');

I wanna make var status_pi field appear like on the first one below PI column,
Pls help sensei

A: var status_pi = document.createElement('input');

Should be:
var status_pi = document.createElement('select');

As you can see here the input field is for textfields, and a select field is for dropdown menus.
Keep in mind that you probably have to set your select's <option> values too in JavaScript.


text:
Q: Using themes in print layout in QGIS I can't work out how to create a print layout directly from a map theme - even though the QGIS 3.10 manual says "All configured themes are also accessible in the print layout, allowing you to create different map items based on specific themes."
Anyone know how?

A: You can see below GIF for an "How To" to get started.


text:
Q: Custom controller: Argument 1 must be instance of Context, instead Objectmanager is given Created a module which was working for a long time, however after some other edits to the site I got this error:

"Recoverable Error: Argument 1 passed to vendor\module\Controller\Cart\Index::__construct() must be an instance
  of Magento\Framework\App\Action\Context, instance of
  Magento\Framework\ObjectManager\ObjectManager given, called in
  /Applications/MAMP/htdocs/project/shop/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php
  on line 93 and defined in
  /Applications/MAMP/htdocs/project/shop/app/code/vendor/module/Controller/Cart/index.php
  on line 14"

Removing var/generation, var/di and var/cache folders solve the problem, however, it reappears after setup:di:compile
Any thoughts on possible fixes?
Here is the controller code:
<?php
namespace vendor\module\Controller\Cart;

class Index extends \Magento\Framework\App\Action\Action {

    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**      * @param \Magento\Framework\App\Action\Context $context      */
    public function __construct(\Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory)     {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Blog Index, shows a list of recent blog posts.
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
      header('Content-Type:text/plain');
      header("Access-Control-Allow-Origin: *");
      $resultPage = $this->resultPageFactory->create();
      return $resultPage;
    }

}

A: This error may occur due to use of case sensitive name in controller or module. Generally this error ignore without the code compilation. This type of error only generate after compilation. It seems that in your code:

shop/app/code/vendor/module/Controller/Cart/index.php

You used i instead of I.


text:
Q: Prevent opencsv from writing quotes to .csv file I'm populating a file from a resultSet like so :
      while(rs.next()){

          String[] entries = new String[3];
          entries[0] = rs.getString(1);
          entries[1] = ",";
          entries[2] = rs.getString(2);

          println("entries : "+entries);
          writer.writeNext(entries);

      }

When I open the excel file the values contain double quotes around them. So test1,test2,test3 when read from the database and written to a .csv file becomes "test1","test2","test3"
How can I write the text to file but not include the quotes ?
When I print the entries to the console the double quotes are not printed so I don't know where they are being added ?

A: Since this question pops up at the first place in google results when someone looks for OpenCSV and quotes issue, I'm going to add the newer solution here.
I'm using version 4.6 and it is indeed possible to skip the quotes, while keeping quotes in entires that contain separator char.
Sample code:
List<SomeCsvEntryTO> csvEntries = new ArrayList<>();
csvEntries.add(new SomeCsvEntryTO("sdf1", "sdf2"));
csvEntries.add(new SomeCsvEntryTO("hgh1", "hgh2;hghgh2"));

Writer writer = new FileWriter(filePath);
StatefulBeanToCsv<SomeCsvEntryTO> csvWriter = new StatefulBeanToCsvBuilder<SomeCsvEntryTO>(writer)
        .withSeparator(';')
        .withApplyQuotesToAll(false)
        .build();
csvWriter.write(csvEntries);
writer.close();

SomeCsvEntryTO:
public class SomeCsvEntryTO{

   @CsvBindByName(column = "sample1colname")
   private String sample1;

   @CsvBindByName(column = "sample2colname")
   private String sample2;
}

As you can see above, I am using semicolon as a separator and I do not change the quotechar. Just change the withApplyQuotesToAll to false.
This produces the following result:
SAMPLE1COLNAME;SAMPLE2COLNAME
sdf1;sdf2
hgh1;"hgh2;hghgh2"

A: Update (16-Oct-2019): This is now possible with later versions of OpenCSV. Please see Sikor's answer.

TL;DR You cannot do it with OpenCSV v2.3. But you can with Commons CSV.
OpenCSV (v2.3) does not seem to provide a safe way of turning off quotes when they are not required. Quotes usually are not required for values that do no have the separator character or line end character in them.
Using NO_QUOTE_CHARACTER as some have suggested:
CSVWriter writer = new CSVWriter(new FileWriter("data.csv"), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
String[] someData = new String[] {"Black and white", "Red, yellow and blue"};
writer.writeNext(someData);

produces the incorrect CSV representation as:
Black and white,Red, yellow and blue

A more valid representation of this data, which uses quotes only when required would be:

Black and white,"Red, yellow and blue"

I have not used Commons CSV, but it appears to provide this ability via QuoteMode.MINIMAL which does the following:

Quotes fields which contain special characters such as a delimiter, quote character or any of the characters in line separator.

A: Yes. There is a CSVWriter in the same package that follows the same semantics as the CSVReader. For example, to write a tab separated file:
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
// feed in your array (or convert your data to an array)
String[] entries = "first#second#third".split("#");
writer.writeNext(entries);
writer.close();

If you'd prefer to use your own quote characters, you may use the three arg version of the constructor, which takes a quote character (or feel free to pass in CSVWriter.NO_QUOTE_CHARACTER).
You can also customise the line terminators used in the generated file (which is handy when you're exporting from your Linux web application to Windows clients). There is a constructor argument for this purpose.

A: Just to extend on Matten's answer, use the built-in characters in the CSVWriter to specify the quotechar. So your writer would look like the following:
CSVWriter writer = new CSVWriter(new FileWriter(fileName), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

A: The constructor code of the writer allows you to give an escape character (quotechar):
CSVWriter(Writer writer, char separator, char quotechar)

If this is the wrong one, there is another constructor with escape character :-)
CSVWriter(Writer writer, char separator, char quotechar, char escapechar)

A: see this link on how to use NO_QUOTE_CHARACTER constructor and proper encoding when writing out to a file:
https://stackoverflow.com/a/29362439/1454926

A: Here is what works for me since version 5.x
import static com.opencsv.ICSVParser.*;

...
new CSVWriter(writer, DEFAULT_SEPARATOR, NO_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END)

A: Use this pattern to prevent from double quotes (checked on 5.3 version)
CSVWriter writer = new CSVWriter(new FileWriter(filename), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

A: A long time and many working answers, but as of 2021 and v5 the cleanest solution in my eyes is using the builder with defined constants. This allows you more control on the CsvWriter than with a fixed constructor.
import static com.opencsv.ICSVWriter.*;

CSVWriterBuilder builder = new CSVWriterBuilder(new FileWriter("yourfile.csv"));
ICSVWriter csvWriter = builder
      .withQuoteChar(NO_QUOTE_CHARACTER)
      .build();
csvWriter.writeAll(rs, true);

A: You can use the Constructor as mentioned by @Matten and along with that, use the other writeAll() of CSVWriter.
OpenCSV also provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following API can be used to write data to CSV from ResultSet.
java.sql.ResultSet myResultSet = getResultSetFromSomewhere();
writer.writeAll(myResultSet, includeHeaders);

The writeAll(ResultSet, boolean) method is utilized for this. The first argument is the ResultSet which you want to write to CSV file. And the second argument is boolean which represents whether you want to write header columns (table column names) to the file or not.


text:
Q: Facial Recognition in Java/Processing I am doing a project that requires some facial recognition. I am attempting to find a Java implementation of this. I am not looking for facial detection. We are trying to do facial recognition through a live camera feed.
Is there any way to implement this in Java or Processing?
At the moment the only ones I have been able to find are in some type of C, which is not going to work for me.

A: I am working on the Face Detection/ Face Recognition topic as well. I can recommend the following links for Face Recognition:
Direct Java Implementations:

*

*JavaFaces: A Java Implementation of Face Recognition with Eigenfaces

*Explanation and Refactoring of the above library

*Article Face Recognition using Eigenfaces
Implementation with OpenCV so you could use JavaCV to implement FR in Java:

*

*OpenCV implementation of Face Recognition
I used the first approach - using javafaces directly. If you accomplish using OpenCV/JavaCV to make FR work give me a hint please.
Cheers

A: For Processing, I recommend the OpenCV for Processing Library. Easy to use and with a lot of examples.

A: To complete the answer:
A repository of Processing examples for ITP fall workshop about face detection, recognition, and miscellaneous tracking methods.

*

*Face-It by Shiffman

A: Although quite old question but still relevant.
You can use opencv library. Although its written in C++. But it offers java bindings too. Only drawback is you will have to build java bindings yourself. Here is one article written by myself which explains the procedure to build the java bindings and sample programs for facial recognition.


text:
Q: Bag marbles with three colors and probability A bag contains one red, two blue, three green, and four yellow balls.  A sample of three balls is taken without replacement.  Let $Y$ be the number of yellow balls in the sample. Find the probability of $Y=0$, $Y=1$, $Y=2$ $Y=3$

Attempt 1
all three are yellow would be
$$ \frac{\binom{4}{3}}{\binom{10}{3}}=\frac{4}{120}=\frac{1}{30}  $$
two are yellow combinations would be
 yy red
$$ \binom{4}{2}\binom{1}{1} =6$$
yy green
$$ \binom{4}{2}\binom{3}{1}=18 $$
yy blue
$$ \binom{4}{2}\binom{2}{1} = 12$$
adding them together and dividing getting $P(Y=2)=.3$
for one yellow
it would be
combinations for Yellow red blue
combinations  for Yellow red green
combinations  for Yellow b   b
combinations  for Yellow b   g
combinations  for Yellow g   g
adding them all together and dividing by $120$
for no yellows
just keep going???Better algorithm?

A: I will first compute $Pr(Y=3)=\frac{(4)(3)(2)}{10(9)(8)}$ of which you have done so.
and then I will compute $Pr(Y=0)=\frac{6(5)(4)}{(10)(9)(8)}$
Then I will compute $Pr(Y=1)= 3 \times \frac{4(6)( 5)}{10(9)(8)}$
$Pr(Y=2)$ can be computed via sum of probability is equal to $1$.
Remark: The concern is yellow and non-yellow, we can group all the non-yellow together.

A: We have four yellow balls and $1 + 2 + 3 = 6$ balls that are not yellow.  The number of ways we can select exactly $k$ yellow balls and $3 - k$ balls that are not yellow is
$$\binom{4}{k}\binom{6}{3 - k}$$
Since there are $\binom{10}{3}$ possible selections of three of the ten balls, the desired probabilities are
\begin{align*}
P(Y = 0) & = \frac{\dbinom{4}{0}\dbinom{6}{3}}{\dbinom{10}{3}}\\
P(Y = 1) & = \frac{\dbinom{4}{1}\dbinom{6}{2}}{\dbinom{10}{3}}\\
P(Y = 2) & = \frac{\dbinom{4}{2}\dbinom{6}{1}}{\dbinom{10}{3}}\\
P(Y = 3) & = \frac{\dbinom{4}{3}\dbinom{6}{0}}{\dbinom{10}{3}}
\end{align*}


text:
Q: Take screenshot programmatically of the whole screen I'm taking screenshot as below:
 public static Bitmap takeScreenshot(Activity activity) {
      View view = activity.getWindow().getDecorView();
      view.setDrawingCacheEnabled(true);
      view.buildDrawingCache();
      Bitmap bitmap = view.getDrawingCache();
      Rect rect = new Rect();
      activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
      int statusBarHeight = rect.top;
      int width = activity.getWindowManager().getDefaultDisplay().getWidth();
      int height = activity.getWindowManager().getDefaultDisplay().getHeight();
      Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width,
          height - statusBarHeight);
      view.destroyDrawingCache();
      return bitmap2;
    }

But there is a Edittext in my layout. I click it and keyboard pop up, but screenshot doesn't contain keyboard using this way. How can I take screenshot programmatically also which can also capture the keyboard?

A: Read somewhere on the forums about another way: -
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream  os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();

You can try that out. Don't know if it works or not, just saved it for a rainy day :P.
EDIT:
Found the link to the post - How to take a screenshots?
User says, screenshots work for him. I think this should suit your requirement.

A: It seems there is no way to get screenshot from screen of a device that is not rooted.Here,CommonsWare says:

If you mean "screenshot of somebody else's activity", that is not
  supported, for obvious privacy and security reasons.

Although you can get screenshot of emulator when your App is running!
Edit:
But there exists a library that is called ASL(Android Screenshot Library):

Android Screenshot Library (ASL) enables to programmatically capture
  screenshots from Android devices without requirement of having root
  access privileges. Instead, ASL utilizes a native service running in
  the background, started via the Android Debug Bridge (ADB) once per
  device boot.

I did not try it,but you can see more details in about it here.


text:
Q: Comportamiento inesperado en mi checkbox quería saber si me podían ayudar con este tema que, para mi, es 100% visual.
Lo que tengo es un checkbox que selecciona Todos los demás inputs, que hasta ahi funciona bien, el tema es cuando yo cambio de vista, y vuelvo a la del checkbox, éste aunque tenga valor true o false, siempre se va a poner como si estuviese en true.
Adjunto imágenes (final de todo):
IMAGEN 1: CHECKBOX ON, ESTADO: TRUE
IMAGEN 2: CHECKBOX ON, ESTADO: FALSE
Códigos:
CHECKBOX:

            <input name="SeleccionarTodos" type="checkbox" id="SeleccionarTodos" onclick="checkAll()" />

Como lo estoy guardando:
var checkStatus = $('#SeleccionarTodos').prop('checked');
sessionStorage.setItem("SeleccionarTodos", checkStatus);

Como lo estaroy recuperando:
 $(document).ready(function () {
        var sessionStatus = sessionStorage.getItem("SeleccionarTodos");
        console.log(sessionStatus);

        $('#SeleccionarTodos').prop('checked', sessionStatus);
}

Como ven en la imagen, este console.log() me dice el valor de la propiedad 'checked'
console.log(sessionStatus);

A: Parece ser que el problema es porque sessionStorage guarda toda la información como cadena y, aunque en la consola veas false, no se trata de un valor booleano, sino de un texto.
Entre las curiosidades de Javascript, cuando compara valores no booleanos como booleano, se hace una conversión y solo resulta falso con:

*

*null o falso

*Cadena vacía

*Arreglo vacío

*Cero

*(Probablemente algún otro que se me escapa)

Entonces, la cadena 'false', al no estar vacía, se convierte a verdadero, por lo que solo debes comparar y asignar un valor booleano:
$(document).ready(function () {
    // Si no se puede leer, asignar valor por defecto
    let sessionStatus = sessionStorage.getItem("SeleccionarTodos") || false;
    // Asegurar que es un valor booleano
    if(sessionStatus === 'true') {
        sessionStatus = true;
    } else {
        sessionStatus = false;
    }
    console.log(sessionStatus);
    $('#SeleccionarTodos').prop('checked', sessionStatus);
}


text:
Q: System Preferences constantly jumps to Keyboard screen Whenever I open System Preferences directly to one of the subscreens (e.g. Network or Bluetooth), that screen appears for a split second, then Sys Prefs immediately jumps to the Keyboard screen.  I have to Search and select the screen I want again before it will "stick."
Also, if go to another prefs screen, then click away from it to another app, Sys Prefs again consistently jumps to the keyboard screen.
Even after switching to another tab under Keyboard (Text, Shortcuts, etc.), clicking away will again jump back to the first tab (Keyboard -> Keyboard).
Happens in Sierra but also happened in El Capitan.
This makes it pretty hard to do some tasks and is extremely annoying.  Haven't found any solutions online - ideas?

A: Since this issue isn't present when you create a new user account, I suggest you also test whether this behaviour is replicated in Safe Mode.
Boot into Safe Mode
Follow these steps to boot your MacBook Pro into Safe Mode:

*

*Fully shut down your Mac

*Restart your Mac

*Immediately press the Shift key and keep it down

*Let go of the Shift key when you see the login window (NOTE: If you have FileVault enabled you may need to log in twice).

*Take a note of what happens (i.e. is the issue still present when accessing System Preferences)

*Now exit Safe Mode by restarting your Mac as normal

*Once logged in again, test to see whether the behaviour continues

If the problem is not present during Safe Mode and still remains when you log back in normally, it's time to investigate login items, fonts, and kernel extensions.
Investigating login items, fonts, and kernel extensions
Let's start with Login Items:

*

*Startup normally

*Go to System Preferences > Users & Groups

*Select the Login Items tab

*Take a note of your Login Items

*Now remove all of them by highlighting them and clicking on the - button below

*Restart your computer

Now your Mac will boot up without those login items loading. Test this and see if the problem persists:

*

*If the problem goes away you know one (or more) of the Login items were causing the problem. You can then add them back in one by one until you've identified the culprit. Problem solved.

*If the problem does persist, it's either a problem with fonts you've installed yourself or with a 3rd party kernel extension. A little more info below:

Fonts:- You can remove any of the fonts you've installed yourself to see if this makes a difference.
Kernel Extensions:- You can open Terminal (found within your Utilites folder) and enter the following command:
kextstat | grep -v com.apple
The above command will list 3rd party kernel extensions (you may need to stretch the Terminal window so it's easier to read). Look for anything you don't remember installing, or something that belongs to software you've removed, or just anything that looks out of place. Remember though, this is a list of 3rd party kernel extensions and therefore any of them could be causing the problem.
After making these changes, use your Mac long enough to see what difference, if any, they make. This is basically a troubleshooting step to help narrow down the possible cause of your problem, so let me know how you go.

A: There will be some debugging involved here.
The following 2 facts give the suggestion that the problem is located in your ~/Library/Preferences folder, and is likely a .plist file.

*

*The problem migrated from El Capitan to Sierra

*The problem is connected to your user profile

You might try to move the ~/Library/Preferences elsewhere. It is likely this will solve your problem, but this will give lots of new annoyance as well (preferences from any app will be gone). You want to search for the culprit .plist file.
I would start doing the following:

*

*Open ~/Library/Preferences, press cmd2 (list view) and order by date modified.

*Then I would change some keyboard settings and simultaneously look at the recently modified plist files

*You will notice that ~/Library/Preferences/com.apple.systempreferences.plist changes, among some other files.

I would then move these .plist files to the desktop, log out and log back in.


text:
Q: Error when installing "Maven Integration for Eclipse (Juno and newer)" in Eclipse Kepler I just downloaded and installed Eclipse Kepler (Java EE version). Then I was hoping to install Maven Integration for Eclipse (Juno and newer) from Eclipse Marketplace.
I kept getting the error message "There is nothing to update".
Anyone knows what went wrong and fix?
I am not sure this question is allowed in SO. If not, let me know. I will delete it.

A: If you downloaded the EE version, then the m2e is already installed along with the IDE.
On another note, with concise question content and proper formatting, your question is allowed.


text:
Q: Removing dynamically created child nodes from a form with js / jQuery? The below post was hugely helpful for what I'm trying to do:
Builing a cart with multiple items and the PayPal button in PHP
This part works beautifully:
    var inp1 = document.createElement("input");
    inp1.setAttribute("type", "hidden");
    inp1.setAttribute("id", "item_number_" + current_item);
    inp1.setAttribute("name", "item_number_" + current_item);
    inp1.setAttribute("value", current_item);

    document.getElementById("paypal-form").appendChild(inp1);

but I'm getting a bit stuck on how to remove an item when needed... I am looking for something like:
    document.getElementById('payPalForm').removeChild(inp1);

But obviously I need a way to specify/track those dynamically created id's... or is there an easier way I'm missing?
Any help would be appreciated.

A: use the parentNode property to retrieve the parent element of an element, and use the removeChild method of the parent:
inp1.parentNode.removeChild (inp1);

Reference:
parentNode property

A: I'm not sure where this code belongs, but it would be helpful to encapsulate this within a class.
function NewClass() {
    var formPP = document.getElementById('payPalForm');
    var lInputs = [];
    this.addItem = function(val) {
        var inp1 = document.createElement("input");
        inp1.setAttribute("type", "hidden");
        inp1.setAttribute("id", "item_number_" + val);
        inp1.setAttribute("name", "item_number_" + val);
        inp1.setAttribute("value", val);
        formPP.appendChild(inp1);
        lInputs.push(inp1);
    }
    this.removeItem = function(val) {
        var e = formPP.firstChild;
        while( e ) {
            var eNext = e.nextSibling;
            if( e.value == val )
                formPP.removeChild(e);
            e = eNext;
        }
    }
}

You'll have to tailor this to meet your needs, but hopefully this gives you a start.


text:
Q: AngularJS doesn't work Visual Studio? I have just started with learning AngularJS and everthing works great before I started to write some easy controller method and method doesn't work even i include ng-contoller I tried to include it as separated js file but that also doens't work I am new to angularJS so I would appreciate any help I also tried with notped++ to do the same but doesn't work this is my code;
  <!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

               <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-toggle">

               </button>
               Contact Manager

Browse

Add contacts

               <form class="navbar-form navbar-right" role="search">
                   <input type="text" class="form-control" placeholder="Search"/>
               </form>

Prvo poglavlje Hello world

Hello, {{name||"World"}}

               <input type="text" class="form-control input-lg" data-ng-model="name" />

Prvi

Drugi

                   This is our sidebar

                   <button ng-click="clickHandler()">Click me</button>

A: You have not defined the module anywhere in the code,
In View:

In JS:
var app = angular.module("myApp", []);

Working Sample

A: You have to define a module before instantiate your controller:

angular
  .module('app', [])
  .controller('AppController', AppController);

AppController.$inject = ['$scope'];

function AppController($scope) {
  $scope.clickHandler = function () {
    window.alert("Clicked");
  };
}
<!DOCTYPE html>

  <title></title>
  <meta charset="utf-8" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-toggle">

        </button>
        Contact Manager

Browse

Add contacts

        <form class="navbar-form navbar-right" role="search">
          <input type="text" class="form-control" placeholder="Search" />
        </form>

Prvo poglavlje Hello world

Hello, {{name||"World"}}

        <input type="text" class="form-control input-lg" data-ng-model="name" />

Prvi

Drugi

          This is our sidebar

          <button ng-click="clickHandler()">Click me</button>

A: You need to include the angular module. Angular works with modules.
Controllers are part of module.
Try something like this:
app = angular.module("myApp", []);
app. Controller(...);

And use this module in your html like

Also,
    The controller declaration you are using is old.
Try this:
app.controller('controllerName', ['$scope', function($scope){...}]);


text:
Q: asp.net mvc uploaded image size How can I check the size of an image a user is uploading?  Client side first with server side double check would be the best solution.

A: What you describe is the ultimate battle to get more information of the HttpFileUpload in HTML 2.0 specs, as that the is HTML spec you are referencing for a Form POST.  Unfortunately, HttpFileUpload does not allow you to get this - not even in Javascript.  It's a very common problem.
Two solutions:

*

*The normal solution is to change your web.config and modify the http runtime (how long to allow an upload, like 30 minutes for a big file) and the http filesize to increase the limit (default is 4 MB).  This applies to Ruby/php, ASP.NET, and ASP.NET MVC - it applies to all languages as it is the HTML 2.0 spec that limits the HttpFileUpload data you can obtain on a form POST.  This will allow the user to upload the entire file; and then, you would process the restrictions on your side in server code.  Not the best solution; but, it is the only solution unless you use a 3rd part.

*Use a 3rd party "file monitor" plugin.
One of the easiest I've seen is RadControls by Telerik.  What these controls do us they install an HttpModule, HttpHandler, and special javascript.  There are several 3rd parties out there that does does, but basically this is how it works:

*

*Javascript captures the HttpFileUpload submission, and re-routes the form POST to a special handler (/RadControlsUploadHandler.asmx for example).

*The RadControlsUploadHandler updates a static variable of the actual bytes uploaded in realtime.

*Then the Javascript loads a "Progress Bar" popup that constant hits the RadControlsUploadHandler.asmx for a "Status" update.  This status update executes the HttpModule that reads the static variable data that is in process of the original Form post to the same handler.

*Then, the module returns JSON data back through the "Progress Bar" ajax call, giving the status of the amount of bytes upload, the bandwidth estimated etc.

Here's a demo of Telerik's Progress Bar upload:
http://demos.telerik.com/aspnet-ajax/upload/examples/customprogress/defaultcs.aspx
Personally, I don't like not knowing how they are locking the thread for these uploads - as I have scalability concerns when using these 3rd party tools under high use.  But, for Joe Bloe's blog, they are great tools for.
Problem w/ASP.NET MVC
The problem with these 3rd party tools is that they only work under ASP.NET WebForms - the standard ASP.NET.  ASP.NET MVC removes the entire ASP.NET WebForms concept - therefore, rendering these controls useless.
Humm, perhaps there's a new project for someone to write.  :)

A: Finding the size on the client without an applet or ActiveX control that allows the user to access the file system won't be possible.  For security reasons, the browser restricts access to the file system.  On the server side, the uploaded file should have a content length associated with it that you can check.


text:
Q: Running docker command in azure docker VM I'm a trying to setup a docker enabled linux VM on azure. I have a VM created with the docker extension by using azure cross platform command line tool. however i have 2 issues right now

*

*When I ssh into the VM and try to run the docker command (ex docker images), it returns the following error.

FATA[0000] Get http:///var/run/docker.sock/v1.18/images/json: dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?

*I am only able to run the docker command against the vm remotely (docker --tls images ...something like this). According to their documentation the "azure create docker vm" command will create the certificate for the server to use. How do I connect from a remote on a different machine? where can I find the generated certificate and how to use it for remote access?

A: Once the software is installed, you can start using it. However, you may encounter the following two issues the first time you attempt to run docker commands:

docker
  FATA[0000] Get http: ///var/run/docker.sock/v1.18/images/json: dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?

And the other error is:

docker
  FATA[0000] Get http: ///var/run/docker.sock/v1.18/containers/json: dial unix /var/run/docker.sock: permission denied. Are you trying to connect to a TLS-enabled daemon without TLS?

The reason is, you need to start the Docker service first. Moreover, you must run the technology as root, because Docker needs access to some rather sensitive pieces of the system, and interact with the kernel. That's how it works.

systemctl start docker

Now we can go crazy and begin using Docker.
This is the original


text:
Q: Why won't padding-bottom work to move an element up? I'm trying to move the orange plus sign (lower right of screen) up so that it's closer to the other icons, directly below them.  Padding-bottom does not work, but padding-top does.  I figured the element above it must have a lot of padding that kept it from being able to move up more, but the inspector tool shows there's space between them.

It's hard for me to know what's going on here, as my instructors wrote this code and I don't therefore understand exactly how it's constructed. I'm also quite new to Html/Css, though padding-bottom hasn't failed me thus far.
Here is the partial view code that makes up the second table. The orange plus icon is at the very bottom, underneath the table end tag:
@model IEnumerable<JobPlacementDashboard.Models.JPOutsideNetworking>

}

            Name

            Position

            Company

            LinkedIn

            Location

            Email

            Stack

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.Position)

                @Html.DisplayFor(modelItem => item.Company)

                LinkedIn

                @Html.DisplayFor(modelItem => item.Location)

                @Html.DisplayFor(modelItem => item.Contact)

                @Html.DisplayFor(modelItem => item.Stack)

                @if (User.IsInRole("Admin"))
                {
                    @Html.ActionLink(HttpUtility.HtmlDecode("✎"), "Edit", new { id = item.OutsideNetworkingID })
                    |
                    @Html.ActionLink(HttpUtility.HtmlDecode("🗑"), "Delete", new { id = item.OutsideNetworkingID })
                }

    }

@if (User.IsInRole("Admin"))
{

        @Html.ActionLink(HttpUtility.HtmlDecode("+"), "Create")

}

Here is the part of the Css that targets the plus:
.createnewplus  {
font-size:30px;
font-weight:800;
margin-left:1075px;

}

The margin-left is because it automatically displays on the far left, under student name, when it needs to be under the other icons.
If anyone has an idea as to why padding-bottom doesn't work in this case, I'd be very appreciative.  I apologize if this is a painfully dumb question; and if you would need more details to be able to tell what's going on, please let me know!
Edit: padding-bottom is not in the css currently because I took it out, as it was doing nothing.

A: Padding-bottom will create space (padding) below the createnewplus div, therefore moving any content that comes after it farther down the page. It appears that the createnewplus div is the last element on the page, so that is why nothing is changing when you add padding-bottom.
You need to find the css that is responsible for the padding/margin following each table. Lowering it will move your icon up.


text:
Q: Why const char pointer assigned to another in C? In compute_scrabble_value function const char word[] is assigned to const char *p.
#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 30

int compute_scrabble_value(const char *word);

const int scrabble_values[26] = {1, 3, 3, 2,  1, 4, 2, 4, 1, 8, 5, 1, 3,
                                 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void)
{
    const char word[MAX_LEN + 1];
    printf("Enter a word: ");
    scanf("%s", word);
    printf("Scrabble value: %d", compute_scrabble_value(word));

    return 0;
}

int compute_scrabble_value(const char *word)
{
   const char *p = word;
   int total = 0;

   while (*p) {
       total += scrabble_values[toupper(*p++) - 'A'];
   }

   return total;
}

But even if you don't assign like below, the output seems same.
int compute_scrabble_value(const char *word)
{
   int total = 0;

   while (*word) {
       total += scrabble_values[toupper(*word++) - 'A'];
   }

   return total;
}

Why is const char word[] assigned to another pointer variable?

A: There's no programmatic reason to do so; your code using word directly is equivalent.
But using word directly is mildly confusing to people reading the code; after the first pointer increment, word no longer points to the actual word, so if you later needed to refer to the word as a whole, you can't, but a maintainer might think you could because you still have word available. Making the copy into p avoids that semantic disagreement between the variable name and what it represents. An optimizing compiler would likely produce the same machine code anyway (word is never used again, so word and p could be implemented as the same variable), and even if it didn't, as long as you're not running out of registers it hardly matters if it actually uses two different pointers.


text:
Q: Error when creating a static variable: 'expected identifier, found `(` ' I am trying to create global variables but I got multiple compilation errors in the process.
First I tried this:
static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel();

error: expected identifier, found `(`

|
109 | static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel();
                 ^
|

Then I have tried some other forms but it seems that they always give me a similar error:
thread_local!(static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel());

error: no rules expected the token `(`

|
109 | thread_local!(static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel());
                               ^
|

Finally, and in case this helps others to respond, it also happens with this:
static (x, y, z) = (1, 2, 3);

error: expected identifier, found `(`

    |
109 | static (x, y, z) = (1, 2, 3);
    |        ^

Maybe it is some error when creating the tuples from a static declaration, but I'm new to Rust, so I do not know if this is true.

A: As you well found out in your last attempt, the same issue can be reproduced more easily:
static (A, B): (i32, i32) = (1, 2);

According to the Rust reference, the grammar for a static binding is defined as thus:
static_item : "static" ident ':' type '=' expr ';' ;

Mutable statics, although not included, is most likely defined to include
mut after static:
mut_static_item : "static" "mut" ident ':' type '=' expr ';' ;

The compiler fails to parse your statement because it expects an identifier, not a pattern. This contrasts with let binding declarations, which accept a pattern after the keyword let:
let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;

On this end, you have no choice but not to use patterns to declare static or const variables.
In your former case of mpsc channels, even this limitation would not solve your problem, since static bindings contain many other restrictions: consider for instance the declaration of a static Vec:
static moo: Vec<i32> = Vec::with_capacity(10);

This would yield the following error:
error[E0015]: calls in statics are limited to struct and enum constructors
 --> src/main.rs:1:24
  |
1 | static moo: Vec<i32> = Vec::with_capacity(10);
  |                        ^^^^^^^^^^^^^^^^^^^^^^

Channels are meant to be created locally and their endpoints sent to other threads from there. The documentation on the mpsc module provides some examples.


text:
Q: Not all Spark Workers are starting: SPARK_WORKER_INSTANCES I have my spark-defaults.conf configuration like this.
my node has 32Gb RAM. 8 cores.
I am planning to use 16gb and 4 workers with each using 1 core.
SPARK_WORKER_MEMORY=16g
SPARK_PUBLIC_DNS=vodip-dt-a4d.ula.comcast.net
SPARK_WORKER_CORES=4
SPARK_WORKER_INSTANCES=4
SPARK_DAEMON_MEMORY=1g

When i try to start the master and workes like this, only 1 worker is being started where an i am expecting 4 workers.
start-master.sh --properties-file /app/spark/spark-1.6.1-bin-hadoop2.6/conf/ha.conf
start-slaves.sh

these commands started the master and showed that they were starting 4 workes where as only 1 worker was started.
The one worker that started using all 4 cores.
Please let me know why my other 3 worked are not starting.

A: Memory and core properties are for every executor. So when you say SPARK_WORKER_CORES=4 this is every executor with 4 cores.
Also you cant use all memory in your server for executors. If you want 4 executors with total 16gb memory, your properties should be like this
SPARK_WORKER_MEMORY=4g
SPARK_PUBLIC_DNS=vodip-dt-a4d.ula.comcast.net
SPARK_WORKER_CORES=1
SPARK_WORKER_INSTANCES=4


text:
Q: How can I convert a hierarchical table to xml in SQL I have a requirement to transform the result of a query into an xml fragment using t-SQL.
My table/query looks like this:
[Col1]  [Col2]      [Col3]      qty
A       group1      mod1        5
A       group1      mod2        7
A       group1      NULL        12
A       group2      mod3        8
A       group2      mod4        5
A       group2      NULL        13
A       NULL        NULL        25

and the desired XML output should look like this
<A qty="25">
    <group1 qty="12">
        <mod1 qty="5"/>
        <mod2 qty="7"/>
    </group1>
    <group2 qty="13">
        <mod3 qty="8"/>
        <mod4 qty="5"/>
    </group2>
</A>

Is there a way to achieve this without pivoting the table and using dynamic sql which would be very messy

A: Good day, Please confirm that this solve your need. We can next work on improving performance. It is important to have the right indexes
DDL+DML
DROP TABLE IF EXISTS T
GO

CREATE TABLE T(
    [Col1] VARCHAR(10),
    [Col2] VARCHAR(10),
    [Col3] VARCHAR(10),
    qty VARCHAR(10)
)
GO

INSERT T([Col1],[Col2],[Col3],qty) VALUES
('A', 'group1', 'mod1', 5 ),
('A', 'group1', 'mod2', 7 ),
('A', 'group1',  NULL , 12),
('A', 'group2', 'mod3', 8 ),
('A', 'group2', 'mod4', 5 ),
('A', 'group2', NULL  , 13),
('A',  NULL   , NULL  , 25)
GO

SELECT [Col1],[Col2],[Col3],qty
FROM T
GO

Solution
;with l1 as (
    SELECT COL1, qty
    FROM T
    where col2 is null and col3 is null
)
, l2 as (
    SELECT Col1, COL2, qty
    FROM T
    where col2 is not null and col3 is null
)
, l3 as (
    SELECT Col1, COL2, COL3, qty
    FROM T
    where col2 is not null and col3 is not null
)
, a1 as (
    SELECT COL2, X = STRING_AGG('<' + COL3 + ' qty="' + qty + '"/>' ,'')
    FROM l3
    GROUP BY Col2
)
, a2 as (
    select X = '<' + a1.Col2 + ' qty="' + l2.qty + '">' + a1.X + '</' + a1.Col2 + '>', l2.Col1
    from a1
    LEFT JOIN l2 on a1.Col2 = l2.Col2
)
select CONVERT(XML,
    '<' + l1.Col1 + ' qty="' + l1.qty + '">' + STRING_AGG(a2.X,'') + '</' + l1.Col1 + '>'
)
from a2
left join l1 on l1.Col1 = a2.Col1
group by l1.Col1, l1.qty
GO

Note! at the end I convert the value to XML in order to check that the result fit. In production there is no reason for this step, which cost resources.

A: @RonenAriely your solution inspired me. I've modified it a little. Because I could not run it.
My solution looks a little dirty and complicated and not elegant but the result is correct.
DECLARE @Tbl TABLE (Col1 CHAR(1), Col2 CHAR(6), Col3 CHAR(4), qty INT);
INSERT INTO @Tbl
VALUES ('A', 'group1', 'mod1', 5),
       ('A', 'group1', 'mod2', 7),
       ('A', 'group1', '', 12),
       ('A', 'group2', 'mod3', 8),
       ('A', 'group2', 'mod4', 5),
       ('A', 'group2', '', 13),
       ('A', '', '', 25);

WITH l1
  AS (SELECT Col1,
             Col2,
             SUM(qty) AS qty FROM @Tbl WHERE Col2 <> ''
         AND Col3 <> ''
         AND Col2 <> ''
       GROUP BY Col1,
                Col2),
  l2
  AS (SELECT Col2,
             SUM(qty) AS qty FROM @Tbl WHERE Col3 <> ''
       GROUP BY Col2),
  l3
  AS (SELECT Col2,
             Col3,
             SUM(qty) AS qty FROM @Tbl
       GROUP BY Col2,
                Col3),
  a1
  AS (SELECT Col2,
             '<' + Col3 + ' qty="' + CAST(qty AS VARCHAR(10)) + '"/>' AS c FROM l3 WHERE Col3 <> ''),

  a2
  AS (SELECT l1.Col1,
             '<' + aa.Col2 + ' qty="' + CAST(l2.qty AS VARCHAR(10)) + '">' +

             STUFF((SELECT DISTINCT '' + c FROM a1 WHERE Col2 = aa.Col2
                 FOR XML PATH ('')), 1, 0, '')
             + '</' + aa.Col2 + '>' AS c FROM a1 aa
        LEFT JOIN l1
          ON l1.Col2 = aa.Col2
        LEFT JOIN l2
          ON aa.Col2 = l2.Col2
       GROUP BY l1.Col1,
                aa.Col2,
                l2.qty)

SELECT REPLACE(REPLACE(REPLACE('<' + aa.Col1 + ' qty="' + CAST(l1.qty AS VARCHAR(10)) + '">'

    + STUFF((SELECT DISTINCT '' + c FROM a2 WHERE Col1 = aa.Col1
        FOR XML PATH ('')), 1, 0, '')
    + '</' + aa.Col1 + '>', '&', '&'), '<', '<'), '>', '>') AS c

  FROM a2 aa
  LEFT OUTER JOIN (SELECT Col1, SUM(qty) AS qty FROM l1 GROUP BY Col1) l1
    ON l1.Col1 = aa.Col1
GROUP BY aa.Col1,
         l1.qty;

A: Replying to my own post.
Thank you all for your help. In the end, I have implemented a solution using dynamic SQL as I have many blocks to process and I need a generic solution. My final code looks like this:
DECLARE @SQL nvarchar(4000)
SELECT @SQL = 'SELECT ' +
  STUFF((SELECT ',' + qty + ' as '''
         + Col1
         + ISNULL('/'+ Col2,'')
         + ISNULL('/'+ Col3,'')
         + '/@qty''' FROM T ORDER BY Col1, Col2, Col3 FOR XML PATH(''))
      ,1,1,'') + ' FOR XML PATH('''')'
EXEC(@SQL)

Unfortunately, it cannot be implemented as a function (which was my initial goal) because it requires a physical table and because of the string size limitation. This would also not work for a large dataset with many sublevels. I will have to live with it!


text:
Q: Function with LOOP in postgres I'm at a loss I'm having an error occur when i try to create a function with some LOOPS in it. Any idea whats the problem with it?
  create or replace function prueba()
RETURNS varchar as $$
    declare
        hores varchar[] :=ARRAY['0:00-1:00',
                         '1:00-2:00',
                         '2:00-3:00',
                         '3:00-4:00',
                         '4:00-5:00',
                         '5:00-6:00',
                         '6:00-7:00',
                         '7:00-8:00',
                         '8:00-9:00',
                         '9:00-10:00',
                         '10:00-11:00',
                         '11:00-12:00',
                         '12:00-13:00',
                         '13:00-14:00',
                         '14:00-15:00',
                         '15:00-16:00',
                         '16:00-17:00',
                         '17:00-18:00',
                         '18:00-19:00',
                         '19:00-20:00',
                         '20:00-21:00',
                         '21:00-22:00',
                         '22:00-23:00',
                         '23:00-24:00'];
        dies date;
        cur_acd CURSOR FOR SELECT * FROM acd;
        row_acd acd%ROWTYPE;
        ateses int:=0;
        ateses_10 int :=0;
        ateses_30 int:=0;
        ateses_60 int:=0;
        ateses_more int:=0;
    begin

        for dies in select distinct acd.dia::date from acd order by 1 LOOP
            FOR i in 0..23 LOOP

                OPEN cur_acd;
                FETCH cur_acd INTO row_acd;
                EXIT WHEN NOT FOUND;

                if row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada < 10 then
                    ateses_10=ateses_10+1;
                else if row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada < 30 and durada >= 10 then
                    ateses_30=ateses_30+1;
                else if row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada < 60 and durada >= 30 then
                    ateses_60=ateses_60+1;
                else if row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada > 60  then
                    ateses_more=ateses_more+1;
                else
                    ateses=0;
                end if;
                INSERT INTO acd_detall values (dies,hores[i+1],ateses_10,ateses_30,ateses_60,ateses_more,ateses);
            END LOOP;
        END LOOP;
        close cur_acd;
        return 'Todo ha ido bien';
    end;
$$ LANGUAGE plpgsql;

The error that i get is this one:
ERROR:  syntax error at or near "LOOP"
LINE 60: END LOOP;
Any idea why? I think i left something without closing but i can't see it.

A: Correct your else if to elsif or ELSEIF. this should work.
Details are hier

The key word ELSIF can also be spelled ELSEIF.

.......
elsif row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada < 30 and durada >= 10 then
                ateses_30=ateses_30+1;
elsif row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada < 60 and durada >= 30 then
                ateses_60=ateses_60+1;
elsif row_acd.dia::date = dies and to_char(row_acd.dia,'HH24')=i and durada > 60  then
 ateses_more=ateses_more+1;
........


text:
Q: uint8 little endian array to uint16 big endian In Python2.7, from an USB bulk transfer I get an image frame from a camera:
frame = dev.read(0x81, 0x2B6B0, 1000)

I know that one frame is 342x260 = 88920 pixels little endian, because that I read 2x88920 = 177840 (0x2B6B0) from the bulk transfer.
How can I convert the content of the frame array that is typecode=B into an uint16 big endian array?

A: Something like this should do the trick:
frame_short_swapped = array.array('H', ((j << 8) | i
                                        for (i,j)
                                        in zip(frame[::2], frame[1::2])))

It pairs two consecutive bytes from frame and unpacks that pair into i and j. Shift j one byte left and or it with i, effectively swap bytes (aka endianness conversion for 2 byte type) and feed that into an H type array. I am a bit uneasy about that bit, since it should correspond to C short type (according to docs), but type sizes really only guarantee minimal length. I guess you would need to introduce ctypes.c_uint16 if strict about that?


text:
Q: How to convert a BigInteger to Objectid with spring data I working with java 8 and the following spring specification:
<spring.version>4.2.3.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
<spring.data.version>1.8.1.RELEASE</spring.data.version>

I have a document that obviously has an _id, which is working perfectly, but I have another field that stores a reference that is another _id, this is my expected JSON
{
    "_id" : ObjectId("56c8f330d4c65e543ceac8de"),
    "companyId" : ObjectId("56c8f330d4c65e543ce8c8de"),
    "name" : "COMPANY S.R.L",
    more fields......
}

I have created the following converter:
 @Component
   public class PurchaseWriterConverter implements Converter<Purchase, DBObject>
   {
       @Override public DBObject convert(Purchase source)
        {
        DBObject dbo = new BasicDBObject();
        dbo.put("_id", source.getId());
        **ObjectId objCompany = new ObjectId(source.getCompany().toString(16));
        dbo.put("company", objCompany);**
        dbo.put("supplier", source.getSupplier());
        dbo.put("status", source.getStatus().toString());
        dbo.put("attendant", source.getAttendant());
        dbo.put("cashier", source.getCashier());

        List<Object> orders = new BasicDBList();

        for (OrderWrapper order : source.getOrders())
        {
            DBObject orderDBObject = new BasicDBObject();
            orderDBObject.put("description", order.getDescription());
            orderDBObject.put("basePrice", order.getBasePrice());
            orderDBObject.put("grossWeight", order.getGrossWeight());
            orderDBObject.put("netWeight", order.getNetWeight());
            orderDBObject.put("subtotal", order.getSubtotal());
            orderDBObject.put("totalWeight", order.getTotalWeight());
            orders.add(orderDBObject);
        }
        dbo.put("orders", orders);
        dbo.put("createDate", source.getCreateDate());
        dbo.put("updateDate", source.getUpdateDate());
        dbo.put("approvedBy", source.getApprovedBy());
        dbo.put("createDate", source.getCreateDate());
        dbo.put("updateDate", source.getUpdateDate());
        dbo.removeField("_class");

        return dbo;
    }
}

The following lines are not working
dbo.put("_id", source.getId());
            **ObjectId objCompany = new ObjectId(source.getCompany().toString(16));
So, I tried to create another converter in order to convert BigInteger to ObjectId, something like this
public class BigIntegerToObjectIdConverter implements Converter {
@Override
public ObjectId convert(BigInteger source) {
    return source == null ? null : new ObjectId(source.toString());
}

}
But I getting the same error:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type com.xxxxxxxxxxx.entity.Purchase to type com.mongodb.DBObject for value 'Purchase{company=1, orders=[com.xxxxxxx.equilibrium.wrapper.OrderWrapper@9cd3f65], supplier=26857458392532697059830357595, approvedBy='', status=TO_BE_APPROVED, attendant='User Admin', cashier=''}'; nested exception is java.lang.IllegalArgumentException: invalid ObjectId [1]

the value that I sending as a biginteger is "1".
Can anybody gives me some directions about how to convert a BigInteger to ObjectId or suggest something different.

A: I just answered to a similar question here https://stackoverflow.com/a/46508892/4660481
A valid ObjectId can be constructed from exactly 24 hexadecimal characters. In this case, your .toString(16) will return "1" which does not have a length of 24. What you would want in this case is "000000000000000000000001". You can resolve this issue by padding with 0s:
String hexString24 = StringUtils.leftPad(source.getCompany().toString(16), 24, "0");
ObjectId objCompany = new ObjectId(hexString24);


text:
Q: how to write a procedure to multiply two matrices using maple Visit http://www.mapleprimes.com/questions/35644-Multiply-2-Matrices-In-Maple-Using-A-Procedure

A: restart:

mmm:=proc(a::Matrix,b::Matrix)
local c, i, j, k, m, n, p;
(m,n,p):=op([1,1],a), op([1,2],b), op([1,2],a);
if op([1,1],b) <> p then error "incompatible dimensions"; end if;
c:=Matrix(m,n);
for i from 1 to m do
   for j from 1 to n do
      c[i,j] := add(a[i,k]*b[k,j],k=1..p);
   end do;
end do:
c;
end proc:

a:=LinearAlgebra:-RandomMatrix(2,3):
b:=LinearAlgebra:-RandomMatrix(3,5):

mmm(a,b);
a.b; # check

mmm(a,a^%T);
a.a^%T; # check

mmm(b,a); # test for dimension mismatch
b.a; # test for dimension mismatch

a:=LinearAlgebra:-RandomMatrix(33,33):
b:=LinearAlgebra:-RandomMatrix(33,33):
LinearAlgebra:-Norm(a.b - mmm(a,b));


text:
Q: Using R, how to reference variable variables (or variables variable) a la PHP Using R stats, I want to access a variable variable scenario similar to PHP double-dollar-sign technique:  http://php.net/manual/en/language.variables.variable.php
Specifically, I am looking for a function in R that is equivalent to $$ in PHP.

UPDATE:  The approved answer contains the basic function needed
##################################
    hello="hello world";
    a="hello";
    result=get(a);
    print(result);
##################################

In PHP, I can assign $a="hello"; and $hello="hello world";. I can then use an eval to dynamic change variables; this is called a variables variable in php, using two dollar signs ($$): echo($$a); will print "hello world". It evaluate $a which is hello, then evaluates $hello.
So, I have a regression setup using R, with 4 data options and 3 model options.  I perform about 60 lines of stats using R and mainly the library plm, but also tseries, lmtest (a bunch of diagnostic tests, a pooled OLS, fixed effects (FE), and random effects (RE) with tests for heteroskedasticity, serial autocorrelation, cross-dependence autocorrelation, and so on.  If these elements exist, I smartly update the standard errors depending on what is present:  only hetero [vcovHC white], hetero-serial or hetero-cross [vcovHC arellano], all [vcovSCC Driscoll-Kraay].
In the end, I want to display the adjusted regression models FE/RE for 3 model options on a page.  Each page will have one of the four data options.  I want to output this in Latex.  So in this scenario, I need a variables variable approach.  I am trying eval(, parse(, substitute(, assign(.
so consider I have a variable in R mDat.total that contains the data I need for a regression.  I also have mDat.hi, mDat.mid, mDat.low.  These 4 elements, I can represent as a list of strings pointing to the variable:
d = c("mDat.total","mDat.low","mDat.mid","mDat.hi");  # data loop
Similarly, for the models, I have formula datatypes (using formula,Formula,pForumla such as model.main = emp~wage+capital|lag(wage,1)+capital:
m = c("model.main","model.lone","model.interaction"); # model loop
I want to loop over i in d, j in m, and perform a bunch of regressions.
for(i in 1:length(d))
    {
    myData = $$d[i];
    for j in 1:length(m))
        {
        myModel = $$m[j];
        ... ### do stuff with myData, myModel
            that has been assigned the values of myData (a data frame)
            and myModel (a model specification)

For i=1;j=1, myData evaluates to be the mDat.total dataframe, and myModel evaluates to be the model.main
Ideally, I want a standalone function using R that behaves like $$ (e.g., in above pseudo code, replace $$ with a function doubleEvaluate(x) or VariableVariable(x).
Thanks in advance.
monte
{x:

A: Consider using get() to obtain environment variables from string values. Additionally, consider the nested lapply() between dataframe and model lists for more organized returned object. Nested for loops would require appending each iteration into growing list unless you just need to output. Below examples use linear models, lm():
model1 <- y ~ x1
model2 <- y ~ x2
model3 <- y ~ x3

dflist <- c("df1","df2","df3")
modelist <- c("model1", "model2", "model3")

# MODEL DATA RETURNS NESTED LIST OF 3 ELEMENTS
# EACH WITH CORRESPONDING DATA METRICS (COEFF, RESIDUALS, ETC.)
modeldata <- lapply(dflist,
                    function(x) {
                    df<-get(x)
                    lapply(modelist,
                           function(y) {
                           model <- get(y)
                           ols <- lm(model, df)
                    })
               })

# BELOW CREATES MODEL SUMMARY LIST OF 3 ELEMENTS
# FOR FIRST THREE MODELS USING FIRST DATASET
modelsummary <- lapply(modeldata[[1]], summary)

Example with nested for loop:
# INITIALIZE A LIST TO CONTAIN DATA
modeldata <- list()

for (i in dflist){
  df<-get(i)
  for (j in modelist){
    model <- get(j)

    # APPEND TO MODELDATA LIST
    # FINAL RETURN IS LARGE LIST OF ALL DATA MODELS
    modeldata <- c(modeldata, lm(model, df))
  }
}


text:
Q: Trouble understanding Charlieplexing problem I am trying to make a circuit that uses 3 pins to drive 6 LEDs using charlieplexing. The cicuit im using is this:

What I don't understand though, is that when I want to turn D1 on, PB0=1, PB1=0, and PB4=high impedance. That turns D1 on, but also D5 and D4, as shown in the other image. I don't understand how to avoid that. Could it be because im using different color LEDs with different forward voltages?

Thanks in advance

A: The section on Forward Voltage in Wikipedia's Charlieplexing article explains it like this:

[Unwanted LEDs lighting] is also a problem where the LEDs are using individual resistors instead of shared resistors, if there is a path through two LEDs that has less LED drop than the supply voltage these LEDs may also illuminate at unintended times.

A: With Charliplexing, you have to have an array of pure LEDs, with the current limiting resistors in series with the driving pins. This allows the 'on' LEDs to pull the voltage down to a point where two series 'off' LEDs cannot light. If there are resistors within the matrix, then enough voltage can still be developed to leave the off LEDs on. It uses fewer resistors this way as well.


text:
Q: Scala specs2 matchers with "aka" I would like to check if a string contains another while providing a label using "aka". For instance:
"31 west 23rd street, NY" aka "address"  must contain("11065")

This fails with
address '31 west 23rd street, NY' doesn't contain '11065'.

However, I would like to specify that 11066 is a zip code. I.e.:
"31 west 23rd street, NY" aka "address"  must contain("11065") aka "zip code"

Which doesn't work.
Any idea how to achieve that?
The required result I expect is:
address '31 west 23rd street, NY' doesn't contain zip code '11065'.

Below is a possible solution, but I dislike it since it's not spec2 native and only supports strings:
def contain(needle: String, aka: String) = new Matcher[String] {
  def apply[S <: String](b: Expectable[S]) = {
    result(needle != null && b.value != null && b.value.contains(needle),
      s"${b.description} contains $aka '$needle'",
      s"${b.description} doesn't contain $aka '$needle'", b)
  }
}

A: I don't think there is a solution applicable to all matchers. In this case you can reuse the aka machinery
def contain(expected: Expectable[String]): Matcher[String] = new Matcher[String] {
  def apply[S <: String](e: Expectable[S]): MatchResult[S] =
    result(e.value.contains(expected.value),
      s" ${e.value} contains ${expected.description} ${expected.value}",
      s" ${e.value} does not contain ${expected.description}",
      e)
}

"31 west 23rd street, NY" aka "address"  must contain("11065" aka "the zip code")

This displays
 31 west 23rd street, NY does not contain the zip code '11065'


text:
Q: I can't see usb at boot options, how can I fix that? I installed Ubuntu 16.04 by formating all hdd. Everything is perfect, but for work reasons I have to install Windows. I downloaded company image (as I know untouched image) of Windows and wrote to USB with Rufus.
Now problem starts with the booting options, when I click to F12 for BIOS Booting Options (the white menu on blue background that listes HDD, CD-ROM etc.) there was only one option that says "ubuntu" and when I click that it directs me to Ubuntu. When I click to F2 for BIOS menu it redirects me to GRUB (only OS so again to Ubuntu). So I find something call rEFInd so maybe it can find my USB (it worked on my another laptop before), and no luck still I can't see my USB and all I could find is Ubuntu. (EFI i guess)
I am not expert at EFI or UEFI or other protocols, so if you can explain how can I get out of this cycle and reach to my bootable usb for someone new to this?


text:
Q: Call Stored Procedure Repeatedly for version comparison SSMS: 2008 R2
We are having our software system updated, which may contain an unknown number of undocumented changes to the way data is entered and stored in our database. We have asked for documentation, but only have schema compares for "physical" changes to the database, not the way the data is treated. They may change in the future, but for now we have to assume not.
In order to check that our stored procedures work as expected after the update, we would like to run a sample of procedures using a sample of parameters before and after the update to compare the actual data results. The stored procedures here all take a single Id as the parameter (they are used to make SSRS reports within the software system)
I have set some things up, but I am having problems with my approach and would welcome any suggestions about either a better way to do things, or how to fix my approach. The problem is that an error is returned whenever a called stored procedure uses a temporary table. Here is what I have done:
Made a script to get a random sample of Ids for paramaters (only one table used at the moment - that's fine).
ALTER PROC [dbo].[UpdateValidation_GET_RandomIdSample](@TestSizePercent DECIMAL(6,3))
AS
-- This table is already created and will persist both sides of the update
--CREATE TABLE Live_Companion.dbo.UpdateValidationIds
--( Id          INT IDENTITY(1,1)NOT NULL PRIMARY KEY CLUSTERED
-- ,MyTableId   NT               NULL)

IF @TestSizePercent > 100 RAISERROR('Do you even percent, bro?',16,1)
DECLARE @SQL VARCHAR(255)
TRUNCATE TABLE UpdateValidationIds

SET @SQL =
'INSERT dbo.UpdateValidationIds(Id)
SELECT TOP ' + CONVERT(VARCHAR(10),@TestSizePercent) + ' PERCENT ID FROM Live.dbo.MyTable ORDER BY NEWID()'
EXEC (@SQL)

Made a second script to run a stored procedure for each Id in the table:
ALTER PROC [dbo].[UpdateValidation_GET_ProcedureResultsManyTimes](@Procedure_Name VARCHAR(255))
AS

--DECLARE @Procedure_Name VARCHAR(255) = 'Live_Companion.dbo.MyProc'

DECLARE @ID INT
DECLARE @GET_ID CURSOR
DECLARE @SQL VARCHAR(MAX) = ''
DECLARE @MyTableId INT
DECLARE @FirstRun BIT = 1
SET @GET_ID = CURSOR FOR
    SELECT Id FROM Live_Companion.dbo.UpdateValidationIds
    WHERE MyTableId IS NOT NULL
OPEN @GET_ID
FETCH NEXT FROM @GET_ID INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @MyTableId = MyTableId FROM Live_Companion.dbo.UpdateValidationIds
    WHERE Id = @ID

    IF @FirstRun = 1
    BEGIN
        SET @SQL = 'SELECT * INTO #ProcedureOutput FROM OPENROWSET(''SQLNCLI'',''Server=SQL1;Trusted_Connection=yes;'',''EXEC ' + @Procedure_Name + ' ' + CONVERT(VARCHAR(50),@MyTableId) + ''');'
        SET @FirstRun = 0
    END
    ELSE
    BEGIN
        SET @SQL = @SQL + '
        INSERT #ProcedureOutput SELECT * FROM OPENROWSET(''SQLNCLI'',''Server=SQL1;Trusted_Connection=yes;'',''EXEC ' + @Procedure_Name + ' ' + CONVERT(VARCHAR(50),@MyTableId) + ''');'
    END
    FETCH NEXT FROM @GET_ID INTO @ID
END

SET @SQL = @SQL + '
SELECT * FROM #ProcedureOutput
DROP TABLE #ProcedureOutput'
EXEC (@SQL)

CLOSE @GET_ID
DEALLOCATE @GET_ID

So now I should be able to execute the second procedure for various stored procedures and output the results to file over a range of Ids, then repeat using the saved (initially random) Ids again after the update and compare the results.
The trouble is, it fails when any of the called procedures use a temporary table:
EDIT:
Error Message returned:

Cannot process the object "EXEC Live_Companion.dbo.MyProc 12345". The
  OLE DB provider "SQLNCLI10" for linked server "(null)" indicates that
  either the object has no columns or the current user does not have
  permissions on that object.

Any suggestions or ideas for how to proceed?


text:
Q: Why this Firebase database trigger not working I'm planning to write a Firebase database trigger. My use case is very simple. Whenever Facebook messenger webhook called database gets updated with user text message and using the Firebase database trigger to get the message from AI and return back to messenger.
Right now my Firebase database trigger is not working. Even though my test cases are all passed.
myapp
|_ messages
   |__ 432423423423
     |__ 32432432432423
        |__ owrijrw8hy2487hf34
          |_ recipient: "45354353"
          |_ sender: "422342342"
          |_ text: "this is text"

Now I want to perform sending message back to user using firebase database trigger.
// Realtime Database triggers
exports.facebookMessage = functions.database.ref('/messages/{pageID}/{userID}')
  .onCreate(event => {
    console.log(event)
    return;
  })

/test.js
describe('Database /messages/{pageID}/{userID}', () => {
    it('Should trigger when the message write it t', () => {

      pushParam = {
        text:  'Hello',
        sender: 'USER_ID',
        recipient: 'PAGE_ID',
        timestamp: 1458692752478
      }

      // Firebase database fake event
      const fakeEvent = {
        // DeltaSnapshot(app: firebase.app.App, adminApp: firebase.app.App, data: any, delta: any, path?: string);
        data: new functions.database.DeltaSnapshot(null, null, null, pushParam),
        params: {
          pageID: 'PAGE_ID',
          userID: 'USER_ID'
        }
      }

      // Stub data reference
      refParam = '/messages/'
      childPageParam = 'PAGE_ID'
      childUserParam = 'USER_ID'

      // Stubs are objects that fake and/or record function calls.
      // These are excellent for verifying that functions have been called and to validate the
      // parameters passed to those functions.
      const refStub = sinon.stub()
      const childPageStub = sinon.stub()
      const childUserStub = sinon.stub()
      const pushStub = sinon.stub()

      Object.defineProperty(fakeEvent.data, 'ref', {get: refStub})
      refStub.returns({parent: {child: childPageStub}})
      childPageStub.returns({parent: {child: childUserStub}})
      childUserStub.returns({push: pushStub})
      pushStub.withArgs(pushParam).returns(true)

      return assert.eventually.equal(fiobotFunctions.facebookMessage(fakeEvent), undefined);

In console I don't see any logs from facebookMessage what should I do now?

A: This code looks correct to me except for the missing ';' after the console.log()
// Realtime Database triggers
exports.facebookMessage = functions.database.ref('/messages/{pageID}/{userID}')
  .onCreate(event => {
    console.log(event)
    return;
  })

However, you state

In console I don't see any logs from facebookMessage what should I do
  now?

Something is wrong with your function. You should have something in the log. I'd also add a console.log("Test"); to your facebookMessage function just to be sure. If you don't see anything in the logs then your functions is not uploaded correctly or you're not listening at the correct location.
You can test the function without all that Javascript. Just manually write something to the database under /messages/{pageID}/{userID} if the log of test doesn't appear I'd check to make sure everything is uploaded correctly.

A: It seems that there is missing key in your reference ..
myapp
|_ messages // /messages
   |__ 432423423423 // {pageID}
     |__ 32432432432423 // ??
        |__ owrijrw8hy2487hf34 // {userID}
          |_ recipient: "45354353"
          |_ sender: "422342342"
          |_ text: "this is text"

A: Turns out I need to add another params to get the correct value.
exports.facebookMessage = functions.database
  .ref('/messages/{pageID}/{userID}/{messageKey}')