text:
Q: How to make an object store itself in a hashmap So I have 4 classes, Testest which has a main method, Phone which extends Product, Product and ProductDB which has a hashmap. When I make a new phone I want the phone to be stored in the database automatically.
public class Product {

protected String productID;
protected String name;
private String description;
private double price;

public Product(){
    Product db = new ProductDB();
    productID = this.toString();
    db.add(productID, this);
}
(Getter and setter methods here...)
}

public class Phone extends Product {

private String make;
private String model;
private int storage;
public Phone(String make, String model, int storage){
    this.make = make;
    this.model = model;
    this.storage = storage;
}
(Getter and setter methods here...)
}

import java.util.HashMap;
public class ProductDB {
    private HashMap<String,Product> products = new HashMap<String, Product>();
    public void add(String productID, Product product){
        products.put(productID, product);
    }
    public void remove(String productID){
        products.remove(productID);
    }
    public Product find(String productID){
        return products.get(productID);
    }
    public Object showAll(){
        return products.values().toArray();
    }

}

public class Testest{
 public static void main(String[] args){
     ProductDB db = new ProductDB();
     Phone phone1 = new Phone("Huwawei P30", "HP30", 50000);
     Phone phone2 = new Phone("Huwawei P30 Pro", "HP30PRO", 70000);
     Phone phone3 = new Phone("Samsung Galaxy SX", "SGSX", 65000);
     System.out.println(db.find(phone1.productID));
     System.out.println(phone1.productID);
 }
}

I want this to return the object when I look for that specific id, but the problem is that the HashMap is empty for some reason
Edit I made productID private. Still nothing

A: It seems you want your database to include all created phones, in this case instead of creating a database each time which will be useless and also because your database is accessed from several places it will be more consistent to make your database fields and methods static and just access it from where you want:
public class ProductDB {
    final private static HashMap<String,Product> products = new HashMap<String, Product>();
    public static void add(String productID, Product product){
        products.put(productID, product);
    }
    public static void remove(String productID){
        products.remove(productID);
    }
    public static Product find(String productID){
        return products.get(productID);
    }
    public static Object showAll(){
        return products.values().toArray();
    }

}

And then in Product constructor just write:
    public Product{
        productID = this.toString();
        ProductDB.add(productID, this);
    }


text:
Q: How to write linq query (for different tables) that returns list What I need
The logged in user needs a list of all bugs that are linked to the projects the user is linked to/enrolled in.
What I try
I work in three layer (presentation - BLL - DALL) from the presentation layer I can send the pk_user_id. I try to write a Linq query that returns me a list of all the bugs. And I am lost on how to return that list.
I am quite new to Linq queries so I guess that's my problem. (I know I need to return my list at the end but I would be happy if I got to that point.
All information I have
I have a database with nine tables but only four that represent my problem
[Bugs], [Users], [UsersOnProjects], [Projects].
My relations
[Users].pk_users_id         ->  [UsersOnsProjects].fk_users
[Users].pk_users_id         ->  [Bugs].fk_creatorOfTheBug
[Users].pk_users_id         ->  [Bugs].fk_ResponsibleOfTheBug

[Projects].pk_projects_id   ->  [UsersOnProjects].fk_projects
[Projects].pk_projects_id   ->  [Bugs].fk_project

Additional information
I "think" I can't do anything with the relations of the table [Users] with [Bugs] because it is not the responsible or the creator that I need. It is the User that is logged in that needs to see every Bug that is linked to a project where he is enrolled in.
A user is linked to a project with the table [UsersOnPojects].
A bug is linked to a project.
**My code - 1 (her I get an error that I cannot convert the query to a list) **
  public List<Bug> getAllOnProject(int p_user)
        {

            var query4 = from t in dc.Bugs
                         join s in dc.Projects
                         on t.fk_project equals s.pk_project_id
                         join u in dc.Users
                         on s.pk_project_id equals u.fk_project
                         join v in dc.Users
                         on u.fk_user equals v.pk_User_id
                         where v.pk_User_id == p_user
                         select new
                         {
                             t.fk_bugstatus,
                             t.fk_creator,
                             t.pk_bug_id,
                             t.title,
                             t.description,
                             t.date,
                             t.fk_priority,
                             t.fk_project,
                             t.fk_responsible,
                             t.openclosed
                         };
    }

My code try nr 2 (Here I have a list with all "correct" rows from [UsersOnProjects] but I don't know what to do next)
 public List<Bug> getAllOnProject(int p_user)
        {
            var query1 = from t in dc.UsersOnProjects
                         where t.fk_user == p_user
                         select t;

            List<UsersOnProject> x = query1.ToList();

            foreach (var c in x)
            {

            }
      }

Thanks!

A: I think this might get your first attempt working - you just need to initialize your Bug entity so a List<Bug> can be created:
public static List<Bug> getAllOnProject(int p_user)
{
    var query4 = from t in dc.Bugs
                 join s in dc.Projects on t.fk_project equals s.pk_project_id
                 join u in dc.Users on s.pk_project_id equals u.fk_project
                 join v in dc.Users on u.fk_user equals v.pk_User_id
                 where v.pk_User_id == p_user
                 select new Bug
                 {
                     fk_bugstatus = t.fk_bugstatus,
                     fk_creator = t.fk_creator,
                     pk_bug_id = t.pk_bug_id,
                     title = t.title,
                     description = t.description,
                     date = t.date,
                     fk_priority = t.fk_priority,
                     fk_project = t.fk_project,
                     fk_responsible = t.fk_responsible,
                     openclosed = t.openclosed
                 };

    return query4.ToList();
}

A: I'm going to assume the existence of some navigation properties:
return (from p in dc.Projects
        where p.Users.Any(u => u.fk_users == pk_user_id)
        from b in p.Bugs
        select b).ToList();

General advice in composing LINQ queries is: use navigation properties in stead of these cluttered verbose joins. EF will generate all required SQL joins while you can use a much more succinct syntax.

redpajama_set_name: RedPajamaStackExchange


text:
Q: vertical multiline text and image lineup So I need to align a image and a text so that the text is right in the middle of the image, like this:

Here's my code, but the text stays on the top side:

 headline and text below it

.container {width: 600px; margin: 0 auto; clear: both;}
.container img {float: left;}
.container .text {float: right; vertical-align: middle;}

A: You need to change the CSS of .container .text float: left instead of float: right like that :
.container img {float: left; width: 300px; height: 300px}
.container .text {float: left; vertical-align: middle;margin-left:15px}

A: Try like below

    headline and text below it

.clear {clear: both}
.container {width: 600px; margin: 0 auto;}
.img {float: left;}
.container .text {float: left; vertical-align: middle;}

A: You can try with a table structure to get this. Check this
DEMO
HTML

Heading 1

     headline and text below it

CSS
.wrapper{
    width:600px;
    display:table;
}
.container {
    width: 600px;
    margin: 0 auto;
    clear: both;
    display:table-row;
}
.container img {
    display:table-cell;
    padding-right:10px;
}
.container .text {
    display:table-cell;
    vertical-align: middle;
    width:60%;
}

A: Here is the Demo of your requirement
you have to change image and content according to your requirements

HEADLINE

 Some content Some content Some content Some content Some content Some content Some content Some content Some content

CSS
    .myimg{
        width:200px;
        margin:10px
    }
.text{
    text-align:justify;
}
.cont{
    display:inline-block;
    width:300px
}

A: DEMO
Use the same old table technique.
HTML:

headline and text below it

CSS:
.container {
    display:table-row;
}
.img, .text {
    display:table-cell;
}
.text {
    vertical-align: middle;
}
.img {
    padding-right: 10px;
}

A: Demo
According to the HTML spec,  is an inline element and
 is a block element. Now that can be changed using the display CSS property but there is one issue: in terms of HTML validation, you can't put block elements inside inline elements so:
...
foo
...

is not strictly valid even if you change the
 to inline or inline-block.
So, if your element is inline or inline-block use a . If it's a block level element, use a
.
HTML

          Some text

          Some more text

          etc etc

CSS
.container {
    text-align: center;
    width: 600px;
    margin:auto;
    border: 1px solid black;
}
.container span {
    display: inline-block;
    vertical-align: middle;
}
.container #text {
    border: 1px solid red;
    /* to show the centering */
}
.cv {
    display: table;
    margin: 0 auto;
    text-align: left;
}
.photo {
    border: 1px solid green;
    /* to show the centering */
}


text:
Q: Product of a list in a list displayed as a list Input Parameter: takes a list of lists of numbers [[x1, x2, x3, ..., xn],[y1, y2, y3, ..., ym],...]
Returns: a single list of numbers where each element is product of the inner list at that position, [x1*x2*x3*...*xn, y1*y2*y3*...*ym, ...]
Cannot use append operator or other built in functions.
I don't know how to exactly approach this. This is what I have so far:
def listProducts(x):
    y = 1
    z = 0
    q = 0
    l = ""
    for i in x:
        for j in range(len(i)):
            z = int(i[j])
            y = z * y
            q = y
            l = str(q) + l
    l = list(l)
    return l

a = [[1],[2,3,4],[10,10,10,10]]
print(listProducts(a))

I haven't been able to find anything about it online. And I am not supposed to use any built in functions such as numpy or list operators. Just have loops and conversions like list() as shown above.

A: One approach could be to use a list comprehension, and functools.reduce to multiply all elements in the sublists, where you can multiply all elements in the sublist with operator.mul
a = [[1],[2,3,4],[10,10,10,10]]

from operator import mul
from functools import reduce

[reduce(mul,i) for i in a]
# [1, 24, 10000]

For a solution with no imports, you could do:
l = [1 for i in range(len(a))]
for ix, i in enumerate(a):
    for j in i:
        l[ix] *= j

print(l)
# [1, 24, 10000]

A: You can use the reduce method in order to get the result of a list multiplication. And use list comprehension to loop through the lists.
from functools import reduce
a = [[1],[2,3,4],[10,10,10,10]]
a = [reduce(lambda x, y: x*y, i) for i in a]
print(a)

A: Try this:
def listProducts(x):
y = 1
l = [0]*len(x)
for i in range(len(x)):
    for j in range(len(x[i])):
        z = int(x[i][j])
        y = z * y
    l[i] = y
return l

A: You could do simply:
inputlist=[[1,2,3],[4,5,6,7],[8,9,8,7,6]]
outputlist=[]
for each in inputlist:
    result=1
    for EACH in each:
        result=result*EACH
    outputlist.append(result)
print(outputlist)

Giving an output:
[6, 840, 24192]

A: simple solution , without use of external library and list operations
a = [[1],[2,3,4],[10,10,10,10]]

len_a= len(a)
new_list = [0]*len_a
product = 1
for i in range(len(a)):
    for j in range(len(a[i])):
        product *= a[i][j]
    new_list[i] = product
    product = 1

print(new_list)

# output [1, 24, 10000]


text:
Q: AutoHotkey: swapping modifier keys when a specific ahk_exe/process is active, regardless of ahk_class or window title I am trying to make the windows and alt keys swap when I am using REAPER so that my shortcuts on the PC are typed the same (as in the same keyboard locations by muscle memory) as when I am using it on the Mac.
In other words, on a Windows/PC keyboard, the alt key is in the location where the command key is on the Mac keyboard, and the windows key is in the location of the option key. Since the corresponding/cross-platform mapping for these keys is actually alt=option and command=windows, I just need to remap each of these modifier keys to the other so that, when used alone or in combination with any other keys or modifiers, and only when I'm using REAPER, pressing the alt key will always send a windows keypress, and pressing the windows key will always send alt.
I have tried the following, but it doesn't seem to work:
#IfWinActive ahk_class reaper
!::#
#::!

I've also tried this:
#IfWinActive ahk_exe reaper.exe
!::#
#::!

But that doesn't work either.
The main problem is that there can be any number of different windows open/active in REAPER, and most of them have a different title and class. So I really need this modifier keyswap to be dependent on the active process and not the active window. The ahk_exe that is shown in Window Spy when REAPER is the active process is reaper.exe.
Someone PLEASE help me out here. I'm losing my mind from going between work and home and constantly forgetting shortcuts, or hitting the wrong ones and doing things I don't want to be doing.
Thanks!

A: *

*"!" and "#" are the modifier symbols for the Alt- and the windows-key.

*Modifier symbols are used only in key-combinations in order to modify
other keys.

*Unlike Control/Alt/Shift, there is no generic/neutral "Win" key because the OS does not support it. (See Modifier_keys)
In this case you have to use the full name of those keys, otherwise AHK remaps the literal keys/characters ! to # and # to !:
#IfWinActive ahk_exe reaper.exe

    Alt::LWin
    LWin::Alt
    RWin::Alt

#IfWinActive


text:
Q: Is there is a way to construct a covering space of a wedge of two circles for a given normal subgroup I would like to construct a covering space of a wedge of two circles with a given normal subgroup $H \subset \pi_{1}(S^{1} \vee S^{1})=F_{a,b}$. The goal is to find a covering space $\tilde{X}$ so that $p_{*}(\pi_{1}{(\tilde{X}}))=H$, where $p: \tilde{X} \rightarrow X$.
First, for more or less non-sophisticated cases it's not very diffucult to  notice, how does the covering space should look like: for example, let $H= <a^{2}, b^{2}, (ab)^{5}>$ - a free subgroup of a $F_{a,b}$ (the covering space will look as a 5 pairwise conserning circles, with 'a' put on the one half of the circle, and 'b' on the another).
The trouble is that it becomes more difficult to draw a covering space in more complicated case, for instance, where $H= <a^{3}, ab^{3}>$ (it should be a 9-sheeted covering, since the $[G:H]=9$). Is there more or less general way in how to proceed it? Moreover, it would be great to know, whether there is a general aproach to solve, since we can classify subgroups of free groups just by drawing various covering spaces a wedge of two circles, the inverse problem seems to be challenging enough -- can we draw a covering according to a given subgroup?
Any sort of help would be much appreciated.

A: Let me describe, in words, the method of folds due to Stallings. Pictures would be better, but perhaps you can figure out the pictures from my words.
I'll carry out the construction using your example $H = \langle a^3,ab^3\rangle$, which as it turns out has infinite index, not index 9. (You may have been deceived by the fact that the abelianization of $H$ has index $9$ in the abelianization of $F_{a,b}$)
Let $R$ be a graph with one vertex and two oriented edges labelled $a,b$, representing the free group $F_{a,b}$.
To represent $H = \langle a^3, ab^3 \rangle$, draw a graph $G$ with one vertex and two oriented edges $A,B$. Subdivide $A$ into three oriented edgelets labelled $a,a,a$. Subdivide $B$ into four oriented edgelets labelled $a,b,b,b$. These labellings define a simplicial map $f : G \to R$ taking each $a$ edgelet of $G$ to the $a$-edge of $R$, and similarly for $b$. Notice that $H$ equals the image of the induced map of $f$:
$$H = \text{Image}\bigl(\pi_1(G) \xrightarrow{f_*} \pi_1(R) = F_{a,b}\bigr)
$$
You might notice: $f : G \to R$ is not locally injective (details below).
The strategy is: simply $G$ and the map $G \xrightarrow{f} R$ until one has a locally injective map.
The simplification step is: "Stallings folds".
In order to explain the first Stallings fold, I'll first explain the non-local-injectivity of $f:G \to R$. At the valence 4 vertex $v \in G$ there are four directions with initial vertex $v$: the initial ends of two $a$-edgelets which I will call "$a$-directions"; the terminal end of one $a$-edgelet which I will call a "$\bar a$-direction"; and the terminal end of one $b$-edgelet which I will call a "$\bar b$-direction". The reason that $f:G \to R$ is not locally injective is because of the two $a$-directions at $v$.
Now we're ready to do the first Stallings fold. Define a quotient map $f_1 : G \to G_1$ by folding: take the two $a$-edgelets of $H_0$ whose initial $a$-directions are located at $v$, and identify those two $a$-edgelets to a single $a$-edgelet of $G_1$. The graph $G_1$ inherits a subdivision into oriented and labelled edgelets from the graph $G$.
By the way that $G_1$ and $f_1$ were constructed, it follows that the map $G \xrightarrow{f} R$ factors as
$$G \xrightarrow{f_1} G_1 \xrightarrow{g} R
$$
Notice three things:

*

*$G_1$ is homeomorphic to a $\theta$ graph, with two vertices of valence 3.

*The map $g : G_1 \to R$ is locally injective. From this, it follows pretty easily that the induced $\pi_1$ map $g_* : \pi_1(G_1) \to \pi_1(R) = F_{a,b}$ is injective.

*The maps $f$ and $g$ have the same $\pi_1$-induced image, which equals $H$.

The map $g : G_1 \to R$ is locally injective and so it shares an important property with covering maps, but it is not a covering map. To correct this, examine each vertex of $G_1$, examine the directions at that vertex, and attach a tree of $a,b$-edges to recover the covering map property.
For instance, $G_1$ has a valence $3$ vertex $w$ with an $a$-direction, a $\bar a$-direction, and a $\bar b$-direction, but it is missing a $b$-direction which accounts for why the covering map property fails at $w$. To correct for this, attach to $w$ a copy of a subtree of the Cayley graph of $F_{a,b}$, namely the subtree which contains the identity vertex of the Cayley graph, and the $b$-direction at the identity vertex, and every embedded path in the Cayley graph that starts with that $b$-direction.
After you have done similar appropriate tree attachements to each vertex of $G_1$, you obtain a covering map to $R$ which represents the subgroup $H$. This covering map has infinite degree, hence $H$ has infinite index.
The general method will usually require more than just one fold, but if you understand this one example you'll probably understand the method in general.


text:
Q: How to get 'last Monday' on BigQuery? With BigQuery, I need to find out when was "last Monday". How can I calculate this date?
For example, today is Monday, so the formula should return today's date if called. Yesterday it should have returned the 27th of last month.
Based on https://blog.svpino.com/2015/08/03/how-to-determine-last-mondays-date-in-bigquery

A: As Santiago Pino published on his blog:
select
    date(date_add(current_date(),
    if(dayofweek(current_date()) = 1,
        -6,
        -(dayofweek(current_date()) - 2)),
    "DAY"))

(copied with permission)

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT DATE_TRUNC(CURRENT_DATE(), WEEK(MONDAY))

A: You can use the UTC_USEC_TO_WEEK function:
Select
  STRFTIME_UTC_USEC( UTC_USEC_TO_WEEK(NOW(), 1), "%Y-%m-%d" )

A: The answers by @Felipe Hoffa and @YABADABADOU are in the old legacy SQL. Here's an answer in the standard SQL (which is very similar to Felipe Hoffa's answer):
#standardSQL
SELECT
    DATE_SUB(CURRENT_DATE(),
             INTERVAL
             IF( EXTRACT(DAYOFWEEK FROM CURRENT_DATE()) = 1,
                 6,
                 EXTRACT(DAYOFWEEK FROM CURRENT_DATE()) - 2)
             DAY);


text:
Q: Question about Shell method
I drew the graph and its 3 dimensional shape. I'm confused on what the Radius would be in this problem. What should I look for when finding this shape's radius?

A: You have drawn the shape, and the line $x=4$. That gets us close to the end. Take a point $x$ between $-2$ and $-1$. Draw the vertical line at $x$, up to the curve $y=x^{-4}$. Now take a tiny positive "number" $dx$, and draw a vertical line at $x+dx$, up to the curve.
The thin strip between these vertical lines is rotated about the line $x=4$. About how far is the strip from $x=4$? That's your radius.
The distance is $4$ plus the distance from $x$ to $0$. Since $x$ is negative, this distance is $|x|$, or, better, $-x$.
Thus the radius is $4-x$. The height of the cylindrical shell is $x^{-4}$. This makes the volume of the shell roughly $2\pi (4-x)(x^{-4})\,dx$. It follows that our volume is
$$\int_{-2}^{-1}2\pi(4-x)(x^{-4})\,dx.$$
For the integration, note that $(4-x)(x^{-4})=4x^{-4}-x^{-3}$.
Remark: Because of a medical condition (allergy to negative numbers) I would almost automatically reflect across the $y$-axis, and rotate the region from $x=1$ to $x=2$ about the line $x=-4$. The integral is then
$$\int_1^2 2\pi(x+4)x^{-4}\,dx.$$
This is quite a bit more pleasant.


text:
Q: Calling the constructor and initializing What is the main different of these 2 and why doesn't the second one work when like this?
template <class T> MyStack<T>::Node::Node(T& input, Node* head):next(head),value(input) {}

template <class T> MyStack<T>::Node::Node(T& input, Node* head) {next = head; value = input;}

My guess on why the second one doesn't work, is because it has nothing to assign variable when initializing.

A: MyStack<T>::value looks like it is of type T&.  If that's the case, then remember that references must be initialized, and they cannot be rebound to a different object.  Using the initializer list is the only way to correctly initialize references that are object data members; you cannot initialize them with assignment in the constructor.  (In fact, if you omit the initializer list entry you should get some error similar to "uninitialized reference member.")

A: next and value might not have empty default constructors.
Besides that, const and reference members must be initialized in the initialization list, you can't assign to them.


text:
Q: How to read value from proj.params in the Biml file I'm developing a SSIS project, where I use global project params. Recently I linked values for these params with VS configurations:

Now, I would like to assign values of these params to variables in my Biml code, depending on the which configuration is active at the moment in VS. However, I do not know how to access these parameters using Biml class hierarchy:
<Biml xmlns="http://schemas.varigence.com/biml.xsd">

<#
var s = Dts.Variables[$Project::strFolderPath];
#>

The above expression I tried is unfortunately not valid.
Any idea which expression should I use to access a value of parameter that is active at the moment?

A: When calling the Dts.Variables, you need to treat the parameter reference like a string:
var s = Dts.Variables["$Project::strFolderPath"];
                      ^                       ^


text:
Q: Image placement I've spent couple hours trying to make this work, but it didn't pay off.
I want to make little shop for my Minecraft server.
Big images: image of that buyer is going to buy.
Small images: hyperlinked images that redirect to PayPal paying thing.
I want it to look like this:

I don't want whole code, just small part or explanation. I'm not HTML/CSS expert.
Thanks.

A: You can start with something like this:
div { /* <- use a class here! */
  float: left;
  padding: 10px;
}

But you'll need a lot more...
(First of all: Instead of just "div" you'll need to use a class, which you also apply to the DIVs in your HTML code)
see a simple example here: http://codepen.io/anon/pen/zBRraB


text:
Q: PostGIS - Get a point inside a line or polygon I need to get the center point of a line or polygon to make marker for my app. So that when you click a marker the geometry appears (line or polygon). I used ST_Centroid to make it work.
The result is what I expected unnest some polygons or lines whichs centroids are out of the geometry. What i would like for those lines or polygons is to get the "most center point" but inside the geometry.
How can I do this? Is there a solution?

A: In my case I have each geometry in disctint tables. What I did was :

*

*For lines -> ST_LineInterpolatePoint() with 0.5 factor.

*For polygons -> Test if ST_Centroid() is inside its geometry. If so, ST_Centroid() is the best choice, if not I choose PointOnSurface().

Here's the query :
SELECT
    CASE WHEN (SELECT the_geom FROM points WHERE gid = d.gid) IS NOT NULL
    THEN (SELECT the_geom FROM points WHERE gid = d.gid)
    WHEN (SELECT the_geom FROM lines WHERE gid = d.gid) IS NOT NULL
    THEN ST_LineInterpolatePoint((SELECT the_geom FROM lines WHERE gid = d.gid), 0.5)
    WHEN (SELECT the_geom FROM polygons WHERE gid = d.gid AND ST_Intersects(ST_Centroid(the_geom),the_geom)) IS NOT NULL
    THEN ST_Centroid((SELECT the_geom FROM polygons WHERE gid = d.gid))
    ELSE ST_PointOnSurface((SELECT the_geom FROM polygons WHERE gid = d.gid))
    END AS center
FROM someTable d

A: In the @Jose 's answer, instead of intersect we should use contains and in when condition we should use Boolean validation
SELECT
    CASE
       WHEN (ST_Contains(the_geom, ST_Centroid(the_geom))) IS TRUE
       THEN ST_Centroid(the_geom)
       ELSE ST_PointOnSurface(the_geom)
    END AS center
FROM someTable

A: From the doc: ST_PointOnSurface — Returns a POINT guaranteed to lie on the surface.


text:
Q: How to keep the grid with 3 columns per row in mobile - Bootstrap 4 I want to break row in 3 columns in mobile, desktop, etc.
but currently, in mobile, it only shows 1 column per row.

                            demotext1

                            demotext1

                            demotext1

A:

             demotext1

             demotext1

             demotext1

In bootstraph 4 col-xs-4 is replaced with col-4


text:
Q: Transparent wxPanel member in wxFrame I have a MainFrame which is derived from wxFrame. The frame has a panel member m_panel of a custom class, derived from wxPanel.
I overloaded the OnPaint() function of the MainFrame to set a background image.
From the background image I only see a 5 pixel boarder. The rest is blocked by the wxPanel. And for some reason I cannot make the panel transparent. I tried m_panel->Hide() which had no effect at all and m_panel->SetBackgroundStyle(wxBG_STYLE_CUSTOM). The latter had the weird effect that I could see the desktop (however the background image was still visible in the 5px border).
I did add the wxTRANSPARENT_WINDOW style in the constructor of the wxPanel.
How can I have this panel and make it transparent?

A: Have a custom wxPanel where you override OnPaint to have your drawings. Then use this as the main panel of your wxFrame. Example shown below:
class BackgroundPanel: public wxPanel
{
public:
    BackgroundPanel(wxFrame* parent);
    void OnPaint(wxPaintEvent & evt);

private:
    wxBitmap    backgroundBitmap;

    DECLARE_EVENT_TABLE()
};

BackgroundPanel::BackgroundPanel(wxFrame* parent)
:wxPanel(parent)
{
    //Set backgroundBitmap
}

void BackgroundPanel::OnPaint(wxPaintEvent& evt)
{
    wxPaintDC dc(this);
    int height = GetClientRect().GetHeight() - backgroundBitmap.GetHeight();
    dc.DrawBitmap(backgroundBitmap,0,height,false);
}


text:
Q: golang timezone daylight savings time doesn't work I know that on 26 Oct, 2014 02:00am the clock should go backwards 1 hour, but I can't reproduce this using a simple golang program
const timeFormat = "2 Jan, 2006 3:04pm"

loc, err := time.LoadLocation("Europe/Moscow")
log.Print(loc, err)

testz , _ := time.ParseInLocation( timeFormat, "26 Oct, 2014 01:59am",  loc)
fmt.Println( testz , testz.UTC())
testz = testz.Add( time.Minute )
fmt.Println( testz , testz.UTC())
testz = testz.Add( time.Minute )
fmt.Println( testz , testz.UTC())

outputs
2014-10-26 01:59:00 +0300 MSK 2014-10-25 22:59:00 +0000 UTC
2014-10-26 02:00:00 +0300 MSK 2014-10-25 23:00:00 +0000 UTC
2014-10-26 02:01:00 +0300 MSK 2014-10-25 23:01:00 +0000 UTC

go 1.6, linux

A: Given your output, it looks like this line:
testz , _ := time.ParseInLocation(timeFormat, "26 Oct, 2014 01:59am", loc)

... is actually giving you the later of the two occurrences of 1:59am, given that it's showing an offset of +3. In other words, you're looking at three minutes of time an hour later than you want to be - starting nearly an hour after the daylight saving transition.
You can change your code to start with an unambiguous value like this:
testz, _ := time.ParseInLocation(timeFormat, "26 Oct, 2014 00:59am", loc)
testz = testz.Add(time.Hour)

I'd expect that to then show
2014-10-26 01:59:00 +0400 MSK 2014-10-25 21:59:00 +0000 UTC
2014-10-26 01:00:00 +0300 MSK 2014-10-25 22:00:00 +0000 UTC
2014-10-26 01:01:00 +0300 MSK 2014-10-25 22:01:00 +0000 UTC

(I haven't tried this, as I don't have Go installed - but I'd expect it to work.)

A: It's not because your code has error,just for time.UTC() will print UTC time,that is timezone 0 time,and from your code time.LoadLocation("Europe/Moscow") we can know maybe you are in Moscow,which belongs to east timezone 3,so the time will be earlier than utc time by three hours,meaning that <your time>=<utc time>+3.


text:
Q: Phoenix assets taking incredibly long time to compile when using Elm My asset compilation in Phoenix is taking around 20 to 60 seconds each time, and it seems to be related to adding Elm to the project. What would cause this to happen?

A: I figured out this was happening because I wasn't telling brunch not to use the ES6 compiler on Elm code. It was compiling Elm code to a 10,000+ line javascript file and then trying to compile that through Babel. This is fixable by either putting the Elm code in the vendor folder (which is ignored by Babel by the default Brunch settings) or telling Babel specifically to ignore the (in my case) main.js file that is the output of the Elm code compilation.


text:
Q: Retornar form com dados após falha no validator Tenho um form de cadastro de usuário no Laravel
<form class="form-horizontal" method="post" action="{{url('/usuarios')}}">
    @csrf

    @if(session()->has('message'))

            {{ session()->get('message') }}

    @endif

has('tipo') ? 'has-error' : '' }}">
            Tipo

                <select id="tipo" class="form-control" name="tipo" required>
                    <option value="" selected>--- Escolha um tipo ---</option>
                    @foreach($tipos as $tipo)
                        <option value="{{ $tipo->id }}">{{$tipo->nome}}</option>
                    @endforeach
                </select>
                @if ($errors->has('tipo'))

                        {{ $errors->get('tipo')[0] }}

                @endif

has('name') ? 'has-error' : '' }}">
            Usuário

                <input type="text" class="form-control" name="name" placeholder="" minlength="4" maxlength="50" required>
                @if ($errors->has('name'))

                        {{ $errors->get('name')[0] }}

                @endif

has('email') ? 'has-error' : '' }}">
            Email

                <input type="emais" class="form-control" name="email" id="email" placeholder="" minlength="7" maxlength="50" required>
                @if ($errors->has('email'))

                        {{ $errors->get('email')[0] }}

                @endif

has('password') ? 'has-error' : '' }}">
            Senha

                <input type="text" class="form-control" name="password" id="password" placeholder="" minlength="6" maxlength="50" required>
                @if ($errors->has('password'))

                        {{ $errors->get('password')[0] }}

                @endif

has('cidadao') ? 'has-error' : '' }}">
            Cidadão

                <select id="cidadao" class="form-control" name="cidadao" required>
                    <option value="" selected>--- Escolha um cidadão ---</option>
                    @foreach($cidadaos as $cidadao)
                        <option value="{{ $cidadao->id }}">{{$cidadao->nome}}</option>
                    @endforeach
                </select>
                @if ($errors->has('cidadao'))

                        {{ $errors->get('cidadao')[0] }}

                @endif

        <button type="submit" class="btn btn-primary pull-right">Salvar</button>

</form>

Com este tudo certo, no meu controller também, cadastra e o validator funciona bem
public function store(Request $request)
{
    $v = Validator::make($request->all(), [
        // user
        'tipo' => 'required|integer|not_in:--- Escolha um tipo ---',
        'name' => 'required|string|min:4|max:50|unique:users',
        'email' => 'required|string|email|min:7|max:50|unique:users',
        'password' => 'required|string|min:4|max:50',
        'cidadao' => 'required|integer|not_in:--- Escolha um cidadão ---',
    ]);

    if($v->fails()) {
        return back()->with('message', 'Confira os dados informados!')->withErrors($v)->withInput();
    }

    $user = new user;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = Hash::make($request->password);
    $user->tipo_id = $request->tipo;
    $user->cidadao_id = $request->cidadao;
    $user->save();
    return redirect('/usuarios')->with('message', 'Cadastro realizado com sucesso!');
}

Porém gostaria que quando caísse no back() o form retornasse com os dados anteriormente preenchidos
Tentei algumas maneiras que pensei, a unica que funcionou foi colocar um form no @if(session()->has('message')) e retorno do $request preenchendo os campos, e outro form no @else dai normal
Porém acredito que deva ter alguma maneira mais pratica

A: Aparentemente está tudo bem, à excepção de uma coisa que falta, old():
Nos values do form deves colocar, ex:
<input type="emais" class="form-control" value="{{old('email')}}" name="email" id="email" placeholder="" minlength="7" maxlength="50" required>

Para os selects:
<select id="tipo" class="form-control" name="tipo" required>
    <option value="" selected>--- Escolha um tipo ---</option>
    @foreach($tipos as $tipo)
        <option @if(old('tipo') == $tipo->id) selected @endif value="{{ $tipo->id }}">{{$tipo->nome}}</option>
    @endforeach
</select>

old() retorna null caso não haja withInput() na resposta, ou não haja input submitido com o name que entra como argumento em old().
DOCS


text:
Q: Cookie not set after adding www to cookie domain I can't get the cookie set in the browser. This happens when I add www to the cookie domain, but can't figure out why.
Problem description
We have a domain mycompany.com, an application running under mycompany.com and another application under subdomain.mycompany.com. Each of them has their own cookie, secure and httpOnly. We don't want this cookies to be shared between domains. We had the domain for the cookie of mycompany.com set as .mycompany.com. The problem with this is that it leaks to subdomain.mycompany.com, so to avoid it I've changed the domain to www.mycompany.com. In our apache config, we redirect all requests for mycompany.com to www.mycompany.com and all traffic is redirected to https.
So when I go to mycompany.com or www.mycompany.com I end up in www.mycompany.com, the domain and the cookie domain match, this should work, but it doesn't. The cookie for mycompany.com is not in the local storage (Chrome and Firefox). (I've also tried using just mycompany.com as the cookie domain, but as expected the cookie leaks to subdomain.mycompany.com as when I used .mycompany.com)
Here is the cookie as sent back by the server:
my_cookie=xxxxxxxxxxxxxx;Version=1;Comment=;Domain=www.mycompany.com;Path=/;Max-Age=604800000;Secure;HttpOnly;Expires=Fri, 26 Aug 2016 09:32:40 GMT

Reading about this, I thought the problem could be the redirection, but this happens regardless of whether I go to mycompamy.com or www.mycompany.com.
What am I doing wrong?
PS: The cookie is not being generated by the application running under mycompany.com, but by another process running under services.mycompany.com, which the client sends the requests to in order to get the cookie. Maybe this could be the problem.

A:
PS: The cookie is not being generated by the application running under
  mycompany.com, but by another process running under
  services.mycompany.com, which the client sends the requests to in
  order to get the cookie. Maybe this could be the problem.

Yes as a security measure, services.mycompany.com would only be able to set cookies for services.mycompany.com or .mycompany.com.
If browsers could set cookies for other domains then this would lead to cookie poisoning attacks (e.g. compromising the Double Submit Cookie CSRF control, allowing Session Fixation or introducing XSS where raw cookie values are reflected in a response).
Even if you do change it so that www.mycompany.com sets a www.mycompany.com cookie, be aware that something-outside-your-control.mycompany.com can set a cookie at .mycompany.com level  which your www.mycompany.com domain wouldn't know where it had been set from. This is because in the HTTP request only the name and value is sent for the cookie, not the domain from where it was set.


text:
Q: What change of variables is used in this integral? I was following a lecture yesterday and we were computing the product of two independent identically distributed Gamma random variables, in the calculations we stumbled upon this integral:
$$\int_0^{+\infty} \frac{1}{x} e^{\frac{-z-x^2}{bx}} \,dx$$
and we said that with a change of variables this becomes a Bessel modified function of the second kind:
$$\int_1^{+ \infty} \frac{e^{-2 (t\sqrt{z})/b}}{\sqrt{t^2-1}} \, dt$$
I can't find this change of variables, what is it?

A: It seems to be:
$$\frac{z+x^2}{x}=2t\sqrt{z}$$
that is:
$$x^2-2 xt\sqrt{z}+z=0$$
$$x=\frac{2t\sqrt{z}\pm \sqrt{4t^2z-4z}}{2}=t\sqrt{z}\pm \sqrt{t^2z-z}$$
$$x=t\sqrt{z}+ \sqrt{t^2z-z}=\sqrt{z}(t+ \sqrt{t^2-1})$$
$$dx=\left(\sqrt{z}+ \frac{tz}{\sqrt{t^2z-z}}\right)dt=\left(\frac{z\sqrt{t^2-1}+zt}{\sqrt{t^2z-z}}\right)dt=\sqrt{z}\left(\frac{\sqrt{t^2-1}+t}{\sqrt{t^2-1}}\right)dt$$
$$\frac{dx}{x}=\left(\frac{1}{\sqrt{t^2-1}}\right)dt \quad \square$$


text:
Q: Morphia: Search for null values in a list of embedded objects I have a list of embedded entities:
@Embedded
private List<EmbeddedEntity> embedded = new ArrayList<EmbeddedEntity>();

In this list, I want to search for any embedded entity which has a specific attribute (let's call it foo), but not another one (bar). So foo should be non-null and bar null in Java / inexistant in MongoDB.
I tried the following code (I do have the UUID of the Entity containing the list):
Query<Entity> query = mongoDataStore.find(Entity.class).field("uuid").equal(uuid)
    .field("embedded.foo").exists()
    .field("embedded.bar").doesNotExist();

This works correctly if the list is empty or has a single entry (where foo has a value and bar does not yet exist). But as soon as any bar attribute has a value, the query returns the wrong result. So I'm looking for a query, which iterates through all the embedded entities and fires on any missing bar. Is that possible?
Example data:
// the query does not pick up the entity as it doesn't have a foo -
// that's what I want
{ uuid: "...", [ { embedded: } ] }

// the query picks up the entity as there is a foo but no bar -
// that's what I want
{ uuid: "...", [ { embedded: { foo: date } } ] }

// the query does not pick up the entity - that's not what I want
// as one foo has a value and its bar doesn't
{ uuid: "...", [ { embedded: { foo: date, bar: date } },
                 { embedded: { foo: date } }
               ] }

PS: I get the same result with .field("embedded.bar").hasThisOne(null).
PPS: Manually iterating through the list elements is not really an option, as I want to use the query for an update operation.
PPS: I think this is a bug in Morphia - see my answer below (https://stackoverflow.com/a/9705175/573153) for a workaround

A: I've found a workaround. While I don't seem to be able to query on null, I can query for a specific value.
In my case, the bar field is a Date. So I can initialize the entity with private Date bar = new Date(0) - this is clearly an invalid date in my case, which is never used. So the query then looks like this:
Query<Entity> query = mongoDataStore
    .find(Entity.class)
    .field("uuid").equal(uuid)
    .field("embedded.foo").exists()
    .field("embedded.bar").hasThisOne(new Date(0));

And in case anyone needs it, here is the update operation (you need to disable the validation as .$. will otherwise raise an error):
UpdateOperations<Entity> update = mongoDataStore
    .createUpdateOperations(Entity.class)
    .disableValidation()
    .set("embedded.$.bar", new Date());

mongoDataStore.update(query, update);

A: I think you have a conceptual problem with your schema. Remember that you always query for top level documents. The reason your query isn't working is because you're asking it to return top level documents where at least one of the elements has foo and at least one of the elements does not have a bar value. Note that both conditions need not apply on the same array element.
You can do what you want in MongoDB using a $elemMatch :
find({embedded:{$elemMatch:{foo:{$exists:true}, bar:{$exists:false}}}}) as demonstrated here :
> db.test.save({embedded:[]})
> db.test.save({embedded:[{foo:1}]})
> db.test.save({embedded:[{bar:1}]})
> db.test.save({embedded:[{foo:1, bar:1}]})
> db.test.find({embedded:{$elemMatch:{foo:{$exists:true}, bar:{$exists:false}}}})
{ "_id" : ObjectId("4f60c4d56fa40267a11d2f2c"), "embedded" : [ { "foo" : 1 } ] }

If "null" is a valid value for bar you can simply change it to :
> db.test.save({embedded:[{foo:1, bar:null}]})
> db.test.find({embedded:{$elemMatch:{foo:{$exists:true}, $or:[{bar:{$exists:false}}, {bar:null}]}}})
{ "_id" : ObjectId("4f60c4d56fa40267a11d2f2c"), "embedded" : [ { "foo" : 1 } ] }
{ "_id" : ObjectId("4f60c52a6fa40267a11d2f30"), "embedded" : [ { "foo" : 1, "bar" : null } ] }

Now, in Morphia the $elemMatch is wrapped by the FieldEnd method "hasThisElement". I'm not that familiar with Morphia (I wrote and use my own mapper) but this should take a DBObject with the above clause as it's value and that should result in what you need to do.
But again, this will return the top level documents that have elements in their embedded array that match these criteria. If you only want to return the matching elements you may have to turn your embedded structure in a top-level collection. It will be sufficient if your update only involves modifying the matching element(s) through the $ positional operator though :
db.test.update(
    {embedded:{$elemMatch:{foo:{$exists:true}, $or:[{bar:{$exists:false}}, {bar:null}]}}},
    {$set:{'embedded.$.bar':"yay!"}}
)


text:
Q: How do tech support scams work in windows? Is it malware, phishing, or how else would threats gain access to computers? I'm currently working for Geek Squad at Best Buy in the front of the operation checking in client computers and I am frequently encountering bogus tech support scams which involves copious amounts of remote access software and who knows what else to gain complete access to the devices.  In some instances the attackers cause data loss or disable the computers when the users don't pay for their "services".
My question is about how this happens because it's often very similar and it makes me wonder if these are connected organizations or there is some sort of script they go by when breaching someone's system.  Often, there is text written in the Windows taskbar with something like "Tech Support 24/7: 1-800-555-5555" and even including the name of their "technician".
I've seen everything from VPNs installed, to VLC, and other software that somehow gets installed but doesn't appear to be malware and instead is legitimate business or enterprise software.  How do they do this?  Is there an initial infection with malware that they then use to install remote software, or is it that they somehow dupe these people to install these programs themselves thus not setting off any alarms with an antivirus?
From what I can tell, we will usually "clean" and remove the software, but to me, that seems like something I wouldn't be comfortable or satisfied with, and if it were my device, I would definitely opt for a complete wipe of the OS.  Am I overreacting here about going nuclear with the response?
Oh, I would like to know how they make the label in the taskbar if anyone could explain that.

A: As Drink Some Pimp Juice IT said in a comment, it's mostly social engineering.
You can get popups that warn about issues with your computer in a wide variety of ways. It can come from downloading shady programs, unsafe free software on the Internet, clicking bad ads, phishing emails, and more.
The way they tend to go about this is just to blast their ads to as many people as possible. They hope for someone with no technical knowledge to call their number, which is really just directs to a scam center somewhere.
The user will hop on a call with a "technician" who asks them to follow some steps to install remote access software.
What they do from there is up in the air. They could just provide bogus service and charge a fee for actually doing nothing at all, just to obtain debit/credit card details. Others may install keyloggers in hopes of getting other information like banking login. Their goal is to steal peoples money.
The best thing you can tell your customers is to never call a number that shows up on a popup, attempt to log into anything an ad may direct them to, give up any personal info, etc. No tech company like Amazon, Microsoft, Apple, etc is going to reach out to users through calls or emails to notify them that their computer has an "issue." Even if your bank calls you about an issue, just hang up and call them back with the number found on their website.
Generally removing the software and bogus crap should be enough, but you could consult with your managers about asking customers if they wish to reinstall the OS. I would imagine that option is probably more expensive and I assume you would also charge for data backup/restoration. As long as the options and pricing differences are explained to the customer, I would say it's worth asking so they can decide what they want to do.
If you want to see more in-depth about some of this Jim Browning on YouTube has fantastic videos about scam centers. I'm not sure if his exact job title, but he is involved in actually gathering evidence and trying to close these call centers.


text:
Q: Why can i run grubinst.exe in 64 bit ubuntu grubinst.exe is a console mode program to install GRUB4DOS boot code to the MBR or partition
boot sector.
I downloaded it from GRUB4DOS project page grubinst_1.0.1_bin_win.zip, and I think its for 32 bit windows.
But I can run it in 64 bit ubuntu
$ ./grubinst.exe --version
grubinst version : 1.0.1

A: There is so-called binfmt support on Linux that allows passing of arbitrary binary file (e.g. Windows executables) executions to some Linux application that knows how to handle it (e.g. wine).
Also bootlace.com is a specially formatted binary that has ELF header and both Linux and DOS code: ELF (linux executable) header must be placed at start of file and DOS code must be started at position 0x100 (remember, COM is not PE, NE or MZ executable, it is just a piece of code), so there it is and ELF header redirects Linux file loader to Linux code that is placed after DOS'.

A: Do you have wine (or something similar) installed?  Then that can be expected to work.  Try
sudo update-binfmts --display

A: Perhaps because you have wine installed.
Wine runs a background daemon to allow windows .exe files to be run the same way that normal linux programs are run.
However, you would likely find that the program would still not be able to write to the MBR, simply because wine doesn't implement that sort of thing.


text:
Q: android tablet app compatibility What,s the reason that my Android app when installed on a tablet occupies the same space that it does on a phone. What do I have to do to hav it stretched out to occupy the full area of the tablet screen?

A: This problem is well understood and easy to fix - it only occurs in applications set for compatibility to API level 3 or below. So the easiest solution is to go into the manifest and change the minimum API (unless this is an issue to you)
Android documents your problem as 'basically, the system displays the application in a small window that is roughly the size of the normal screen size'
The android docs suggest some other solutions

A: There are couple of things you need to consider to make your app work across different size of screens (For example using dp for size etc.,). Here is android supporting multiple screens tutorial.

A: This is a problem I have been having too. It really kinda irks me, but it's to be expected. Refer here: Android Docs: Supporting multiple screen sizes.
What's going on, is as hardware gets better, the screen sizes (and effective dpi) increases. This makes the screen of the new hardware be able to support more content on the screen, thus making everything you place on it appear smaller.
To get around this, you will need to provide larger images to stretch out the content. This is where nine patch comes in. It is extremely useful for making hugely different sizes of stuff for one simple (and small) base image. Android has a fantastic tutorial on nine patch here.
In addition to the normal nine patch, I recommend different layouts for different screen sizes. This is what eats me, but it really is a necessity. Look here for some help on that.

A: This might appear unrelated at first but I recently had an awful time getting my android app appearing in the Google Play store for a Hudl 2 tablet.
It turned out I needed to add a couple of lines in my manifest in order to increase my apps compatibility with more devices.
More about "uses-feature"
<!--  Features are required by default so set as false if you want them to be optional -->
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.telephony" android:required="false" />


text:
Q: chi squared selectKbest bad input shape error I'm a little new to scikit and ML. I'm trying to train an Adaboost classifier for one vs Rest classification. I'm using the following code
# To Read Training data set
test = pd.read_csv("train.csv", header=0, delimiter=",", \
                   quoting=1, error_bad_lines=False)
num_reviews = len(test["text"])
clean_train_reviews = []
catlist=[]
for i in xrange(0,num_reviews):
    data=processText(test["text"][i])
    data1=test["category"][i]
    clean_train_reviews.append(data)
    catlist.append(data1.split('.'))

# To read test dataset
test = pd.read_csv("test.csv", header=0, delimiter=",", \
                   quoting=1, error_bad_lines=False)
num_reviews = len(test["text"])
clean_test_reviews = []
for i in xrange(0,num_reviews):
    data=processText(test["text"][i])
    clean_test_reviews.append(data)
X_test=np.array(clean_test_reviews)

lb = preprocessing.MultiLabelBinarizer()
Y = lb.fit_transform(catlist)

classifier = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range=(1,2), max_features=1500,min_df=4)),
    ('tfidf', TfidfTransformer()),
    ('chi2', SelectKBest(chi2, k=200)),
    ('clf', OneVsRestClassifier(AdaBoostClassifier()))])
classifier.fit(clean_train_reviews, Y)
predicted = classifier.predict(X_test)

I use a pipeline, where text is inserted as clean_train_reviews and Y is the class (multi-Label, N = 10). Textual features are extracted in the pipeline using TfidfVectorizer() and selected using Chi squared feature selection method. Adaboost classifiers give: ValueError: bad input shape (1000, 10)
 File "<ipython-input-10-9dbc8b18e6b8>", line 1, in <module>
    runfile('C:/Users/Administrator/Desktop/nincymiss/adaboost.py', wdir='C:/Users/Administrator/Desktop/nincymiss')

  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
    execfile(filename, namespace)

  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 66, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/Administrator/Desktop/nincymiss/adaboost.py", line 179, in <module>
    classifier.fit(clean_train_reviews, Y)

  File "C:\Python27\lib\site-packages\sklearn\pipeline.py", line 164, in fit
    Xt, fit_params = self._pre_transform(X, y, **fit_params)

  File "C:\Python27\lib\site-packages\sklearn\pipeline.py", line 145, in _pre_transform
    Xt = transform.fit_transform(Xt, y, **fit_params_steps[name])

  File "C:\Python27\lib\site-packages\sklearn\base.py", line 458, in fit_transform
    return self.fit(X, y, **fit_params).transform(X)

  File "C:\Python27\lib\site-packages\sklearn\feature_selection\univariate_selection.py", line 322, in fit
    X, y = check_X_y(X, y, ['csr', 'csc'])

  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 515, in check_X_y
    y = column_or_1d(y, warn=True)

  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 551, in column_or_1d
    raise ValueError("bad input shape {0}".format(shape))

ValueError: bad input shape (1000, 10)

A: This is because feature selection does not work as you'd expect for multilabel problems. You can try the following which will select the 'best' features for each label separately.
classifier = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range=(1,2), max_features=1500, min_df=4)),
    ('tfidf', TfidfTransformer()),
    ('chi2', SelectKBest(chi2, k=200)),
    ('clf', AdaBoostClassifier())])

clf = OneVsRestClassifier(classifier)


text:
Q: How to "get" from NodeJS with AngularJS I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work

Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
    $http.get("localhost:8080/product")
         .success(function (response) {
             $scope.keys = response;
             console.log(response)
         })
};
$scope.keyLoad();

A:
I get 404 not found. I figured it would be a cors problem

If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:

$http.get("localhost:8080/product")

That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.

A: You should use $http service.
For example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

Or
$http.get('/someUrl', config).then(successCallback, errorCallback);


text:
Q: How would one see if an array has consecutive numbers in C++? This is basically the 8 Queens problem, but solving it with brute force in a 1D array. Say I have an array (named b) of size 8, with elements ranging from 0 to 7.
I initialize each index in the array with 8 for-loops, like this:
int b[8]={0};

int count = 0;

for(b[0] = 0; b[0]<8; b[0]++){
for(b[1] = 0; b[1]<8; b[1]++){
for(b[2] = 0; b[2]<8; b[2]++){
for(b[3] = 0; b[3]<8; b[3]++){
for(b[4] = 0; b[4]<8; b[4]++){
for(b[5] = 0; b[5]<8; b[5]++){
for(b[6] = 0; b[6]<8; b[6]++){
for(b[7] = 0; b[7]<8; b[7]++){
                if(check(b))
                {
                count++;
                print(b, count);
                }
            }}
        }}
    }}
}}

What this program is supposed to do is check every combination of numbers 0 to 7 and returning true for only certain conditions. There are supposed to be 92 solutions, if this sounds familiar, it should be - it is the 8 Queens problem using brute force. From here, this is what I understand are the conditions:
I want to be able to check if an array has a consecutive string of numbers; such as:
[0|5|7|1|2|3|6|4]
Here, the elements b[3], b[4] and b[5] are consecutive. I don't want that, I want to return false, since there is a consecutive string of numbers (basically queens are attacking)
I also do not want an array that has a string of backwards consecutive numbers like this:
[0|5|7|3|2|1|6|4]
And lastly, I do not want two or more numbers in indexes where it would make them look consecutive if we had simply changed then numbers between them:
[0|2|4|6|1|3|5|7]
Above is not acceptable because b[0] and b[7] are numbers in their "consecutive index" (because at least 2 queens are attacking each other).
[6|1|3|0|4|7|5|2]
Above is also not acceptable because b[1] and b[4] are also in consecutive indexes.
Similarly, when the values are swapped, the arrays
[7|2|4|6|1|3|5|0]
[6|4|3|0|1|7|5|2]
are also not acceptable. I also cannot have 2 or more of the same number.
The problem I am having is in creating the check function. I am told I need to use 1 for loop and 1 if-then statement. Can the check function just take the whole array as is? And if it does, how do look at the right-most element in the array, and check to see if it has consecutive indexes (queens are attacking it)? I've tried this:
bool ok(int board[8]){

    for(int c = 7; c >= 0; c--){ //row check
        for (int j=0; j<c; j++){
            if (board[c]==board[j]){
                return false;
            }
        }

        for(int i = 1; i <= c; i++){
            // diagonal check from top left to bottom right
            if  ((board[c]-i >= 0) && (board[c-i] == board[c]-i))
                {return false;}
            if ((board[c]+i <= 7) && (board[c+i] == board[c]+i))
                {return false;}
            // diagonal check from bottom left to top right
            if ((board[c]-i >= 0) && (board[c-i] == board[c]+i))
                {return false;}
            if ((board[c]+i <= 7) && (board[c+i] == board[c]-i))
                {return false;}

        }

    }

    return true;
}

But not only does this not work (I get 300+ solutions), it is not as small as I am told it should be.

A: I think there is a little problem with your check of collisions in the diagonals: you've got 15 diagonals going each way (including the very short one-square diagonals in the corners), while your code checks only seven of each due to the board[c]+i <= 7 and board[c]-i >= 0 conditions.
Here is how you can simplify the checks and make them faster with the use of three boolean arrays: you've got 8 rows, 15 ascending diagonals, and 15 descending diagonals:
bool row[8];
bool ascending[15];
bool descending[15];

Initially, there are no queens in any of these rows/diagonals. As you go through the elements of board, do this:
for (int i = 0 ; i != 8 ; i++) {
    // Check and mark the row
    if (row[board[i]]) return false;
    row[board[i]] = true;
    // Check and mark the ascending diagonal
    int ascIdx = board[i]+i;
    if (ascending[ascIdx]) return false;
    ascending[ascIdx] = true;
    int descIdx = 7+board[i]-i;
    if (descending[descIdx]) return false;
    descending[descIdx] = true;
}
return true;


text:
Q: How to get the inner element of a dome detached element I am trying to do as following:

var bbb = $('#bbb').detach();
var ccc = $('#ccc :' + bbb);

but I cant seem to get it right, any ideas?
Thanks

A: You can use .find()
var bbb = $('#bbb').detach();
var ccc = bbb.find('#ccc');


text:
Q: Delayed off circuit with SPDT circuit I'm having trouble with a circuit I'm putting together. I think this is how to represent it (may be wrong about that).
I'm using a SPDT switch to turn off a circuit, but I want it to turn off after a delay. I have a 12v Delay Switch Ne555 Module that I switch on when MAG is in an NC state. This works.
The issue is the circuit is permanently on and never switches off. It seems like the timer fires immediately but never switches. The module makes a buzzing noise.
If I move the timer switch to the opposite leg the timer works - it turns off immediately and then turns on after a delay - the opposite of what I want. No noise is made.

simulate this circuit – Schematic created using CircuitLab
I think the diagram is slightly wrong - there isn't two switches inside the module. I just wasn't sure how to represent a timer switch that needed voltage.
What am I doing wrong?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Using a delay-on timer to switch off a load after a delay.
How it works:

*

*Initial conditions: SW1 is open. The time delay module NC (normally closed contact) is closed and the load is powered.

*SW1 (an SPST will do) is closed.

*The timer module starts timing.

*At the end of the preset time the relay energises and disconnects the load.

*When SW1 is opened the relay immediately resets and the load is energised again.

This circuit will do what you require if you can tolerate the switch being left in the "on" position to switch the circuit off! (It's just a matter of labeling it backwards.)


text:
Q: Do I need to setup my ZFS (using FreeBSD 10) for foreign-language files (e.g. filenames in Japanese/Thai/etc language)? I am in the process of setting up a ZFS file server. I am planning to store all sorts of files in it. I have several hundred music tracks that are in Japanese/Korean native character.
I want the file server to retain this native character naming. Do I need to setup my ZFS pool with utf8only and/or normalization options?
e.g.
copy japanese songs into file server (via mounted shared folder in Windows). If I view the files on my file server in Windows Explorer, they must be displayed in their native characters.
Thanks a lot.

A: ZFS currently has a 255 bytes limit on names. If you decide to use UTF-16 names, you will get a limit of 127 characters. UTF-8, OTOH might encode japanese/korean in 3-byte character, limiting you even further (255/3 = 85).
I'm not aware of other concerns, aside from slower indexing of UTF-8 3-byte char strings compared to UTF-16 2-byte char strings.
So - if all names are in UTF8 - go ahead and set the 2 properties. If you use UTF16, don't.
Notice that UTF8 has specialized handling in code (zol,not *bsd, but codebase is the same). I would probably set utf8only to force conversions to utf8, and normalization to allow proper comparison of file names.


text:
Q: python requests post request request payload:
(The spaces are suppose to be there)
{input01: {Input: "adress", adress: "g", FirstName: "", LastName: ""}, Locale: "en"}
     Locale:"en"
input01:{Input: "adress", adress: "g", FirstName: "", LastName: ""}
  FirstName:""
  adress:"g"
  Input:"adress"
  LastName:"

This is my attempt (Which returns a 400).
data = {
      "input01": {
        "Input": "adress",
        "adress": "test",
        "FirstName": "",
        "LastName": ""
      },
      "Locale": "en"
    }

r = requests.post(url, data=data)
print(str(r.text))

A: You are not posting JSON. When you pass a dictionary to the data argument, it will be encoded to a application/x-www-form-urlencoded request instead, the default encoding for HTML forms.
To post JSON, use the json parameter:
r = requests.post(url, json=data)


text:
Q: Number(id) or +id result in different values depending on the input value id: number;

this.id = +id;

When local id is null then +id results in 0
When local id is undfined then +id results in NaN

The same results I get with Number(id) instead of the +id
How can I get consistent/same return value for the not successful conversion into a number?

A: As both 0, null, NaN and undefined are falsy, you could just set the value to something if it's falsy
this.id = (+id) || 0;

console.log( (+0) || 0 )           // 0
console.log( (+null) || 0 )        // 0
console.log( (+undefined) || 0 )   // 0


text:
Q: Are any ships in Star Wars capable of intergalactic travel? It always made me curious to hear:

A long time ago, in a galaxy far, far away ...

Which implies that the Star Wars universe is in a separate galaxy to our own.  Then I was reading Are there Star Wars medical doctors and can/do they scan for midichlorians? which included this image in one of the answers:

R2-D2 and C-3PO are gazing out at what appears to be a galaxy that the ship (I presumed) was approaching.  That seemed to suggest that 'galaxy hopping' was as practical as 'star hopping'.  But if you view the image at full size (or have good eyes) it becomes clear that there are stars between the observer and the galaxy in the background, so the droids are simply viewing a (very close) galaxy from the outskirts of the current galaxy, and it is not evidence of intergalactic travel.
This leads me back to the question:
Are any ships in Star Wars capable of intergalactic travel (in the age depicted in the movies)?

A: Are any ships in Star Wars capable of intergalactic travel (in the age depicted in the movies)?
To answer your question directly, yes, but it depends on what you mean by intergalactic, and any answer is constrained by my second and third points below.
Part A
Within the overall Galaxy there were seven satellites galaxies as part of the main galactic disk (the hyperspace disturbance mentioned below was outside of this whole construct) and there was travel to and from these satellite galaxies:

*

*The Nagai accomplished it, coming from the Firefist galaxy.

*In the era of the movies, the Rebel Alliance had a base in the Rishi Maze.
Part B
As a supplement to Petersaber's answer, there is also something of a constraint on travelling outside of the SW galaxy, and it is called the Hyperspace disturbance beyond the edge of the galaxy. This is an energy barrier that apparently makes travelling outside the galaxy impossible. The Outbound Flight Project, which did not succeed (thanks to Darth Sidious/the Chiss as described here), was an attempt by the Jedi to penetrate this barrier (using the Force).
The Yuuzhan Vong, however, succeeded in finding a way around this barrier at Vector Prime and apparently the Silentium and Abominor, two extra-galactic droid races, must have as well since they came from the same galaxy as the Yuuzhan Vong and settled in the Unknown Regions of the SWG.
Part C
To expand on Petersaber's point about running out of fuel; unlike Yuuzhan Vong ships that used gravity for propulsion (gravity doesn't run out, though it is never explicitly stated how the dovin basals use gravity other than the mention of micro black holes, so we don't know the exact physics of it), ships in the SWG depended on hyperdrives (a technology they had reverse-engineered from the Rakata and which they did not fully understand) which employed hypermatter and some form of reactant fuel, usually antimatter, for propulsion.
I can't find any evidence of how they actually mined hypermatter (which is only found in hyperspace) or that they had some sort of antimatter scoop technology, both of which would presumably be required for them to refuel their ships along the way. When you consider this, alongside the vast amounts of fuel used (the Venator-class Star Destroyer's main reactor annihilated the equivalent of 40,000 tons of matter each second as quoted here), there were most likely real constraints within the SWG of effectively accomplishing true intergalactic travel.
N.B.1. Although it apparently had FTL capability and consumables for 10 years, I have no idea how Outbound Flight was supposed to accomplish its second mission - to seek out extragalactic life - unless they had a more conservative idea of what that meant, for instance finding Ship in the intergalactic void, or they just didn't know what they would find.
N.B.2. It isn't entirely clear how far away the Yuuzhan Vong galaxy is, for instance, only that it took the Vong millenia to travel the intergalactic void at sublight speeds, and that the living planet Zonama Sekot apparently arrived before they did, though whether it arrived as a seed or a whole planet I do not know, nor what propulsion system it used. The Langhesi shaped Sekot to possess a hyperdrive but it is unclear what propulsion system it may have used before that.
N.B.3. With reference to the picture that you quote, the galaxy that they are looking at could be the Rishi Maze, or it could be the SWG itself seen from the Rishi Maze. I don't think the issue is entirely settled, and an interesting discussion on it can be found here and here. In any event, as travelling to and from satellite galaxies was possible/accomplished, it does not impact the substance of the question.

A: Kind of... In theory, all ships are intergalactic*, but all of them would run out of resources before they got anywhere worthwhile.
In the Expanded Universe, there was one attempt at intergalactic travel, The Outbound Flight Project; however, it was stopped before they could leave the galaxy.
*There is no mention of the Outbound Flight having any kind of special hyperdrive or other kind of special engine. It was just 6 Dreadnaughts and a space station.
There is one race of aliens from the EU capable of travelling between galaxies, the Yuuzhan Vong. However, their journey took them entire millennia, because their "engines" couldn't get a good lock-on on another galaxy's gravity well. The Yuuzhan Vong have been infiltrating the Star Wars Galaxy for decades before the invasion, even before Order 66.
There is an energy barrier surrounding the galaxy and preventing safe hyperspace travel, but it can be penetrated. After that, you should be golden (see Phyneas' answer, part about YV, Silentium and Abominors).
That image from the movie is most likely just a not-well-thought-out backdrop. "Rule of cool" and such. You would have to get really god-damn far away (5 or 7 times the diameter of it) from a galaxy to have such a clear and nice view, and yet there were stars around them.
However, Leland Chee (SW "canon master") said that the Rebels had to flee the galaxy to find safe haven (Star Wars message boards, 2003), which is an inconsistency. In other sources, this object is identified as a cluster called the Rishi Maze (2002, Episode II DVD Exclusive Content). In the The Complete Star Wars Trilogy Scrapbook (1997), it's simply identified as a spinning star cluster. Wookieepedia even has exact coordinates.
So yeah. According to EU and Leland Chee, SW-universe ships are capable of intergalactic travel. The reasons why it's not usually done are related to resources and environmental dangers, rather than the lack of technology.

A: There is another answer which doesn't rely on the Extended Universe.
As you can see from this highly upvoted (+155) answer to this question

Are E.T. and Star Wars in the same universe?

there is ample evidence that these aliens in the Galactic Senate

are the same race as E.T. (Honestly, just read the linked answer.)
Therefore the species officially called The Children of the Green Planet from the planet called Brodo Asogi travelled intergalactically to Earth since we know the Galactic Senate of the Republic on Coruscant is in a galaxy far, far away.

A: Disney Canon:
Possibly, but it isn't relevant, because intergalactic travel is seen as a death sentence.
Even some areas within the galaxy are avoided by sane people:

It lies at the margins of the Western Reaches, flung so far into the galaxy she's not really sure if they're even in the galaxy anymore. The system is close to Unknown Space—the uncharted end of the galaxy, beyond which lurk terrible nebula storms and gravity wells. Those who have tried to traverse the space outside the galaxy have never returned, though distorted, half-missing communications have come back—messages warning of geomagnetic anomalies and slashing plasma winds.
  -  Star Wars: Aftermath: Life Debt

In another canon novel, Star Wars:  Bloodline, a pilot reacts to a story about ancient warriors leaving the galaxy as follows:

"Which means they spent eternity wandering around in the void of space... Who names themselves after those guys?"
  -  Star Wars: Bloodline

Building an intergalactic ship would be like installing a diving board over the Sarlacc Pit:  sure, you could do it, but you'd die if you tried to use it.

A: The hyperspace disturbance beyond the edge of the galaxy was at the very edge of the galaxy, which did not include the galactic halo and the seven satellite galaxies. But this disturbance did not hamper all travel, because there was the yuzon vong entry point, and the hyperlane that leads to the Rishi Maze dwarf galaxy from the planet Rishi in the main galaxy.


text:
Q: Adding objects in ArrayList in iteration Ok, I don't know why but I am thinking I am missing something very basic to solve this.
Here is my problem:
I have a method createPublisherRequestObject(String str) which takes string argument and returns a List of ReportRequest Object. Normally for a given String 65 objects will be created. I have another method getTimeFrameValues() which returns arraylist of string. Normally this method would return around 15 strings in arraylist.
So basically I would be iterating in loop for 15 times (Num of String) and then for each iteration, I will be calling method createPublisherRequestObject to create 65 objects.
At the end of this I wanted to have a list of 65*15 objects. Here is my code -
ArrayList<String> timeList = er.getTimeFrameValues();
List<ReportRequest> reqList = new ArrayList<>();
for (Iterator iterator = timeList.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    reqList = rj.createPublisherRequestObject(string);
}
log.info("Final List Size "+reqList.size());

But this returns 65
Please help!!!
Thanks,
pratik

A: Every time you go through the list, you're replacing reqList. It seems that what you're wanting to do is either reqList.add or reqList.addAll.
Additionally, if you already know how many objects you're creating per string, you'll get a lot better performance by creating an ArrayList of the appropriate size:
new ArrayList<>(65 * timeList.size())

Finally, since you're using Java 7, go ahead and use the enhanced for loop; it's much more readable:
for(String string: timeList)
    reqList.addAll(rj.createPublisherRequestObject(string));

A: You're reassigning to reqList on every iteration. You need to append.
reqList.addAll(rj.createPublisherRequestObject(string));

Should work.

A: You have 65 because you replace your reqlist with the result of the call to rj.createPublisherRequestObject(string) instead of using the addAll() method. So you don't add the elements but overwrite the content of reqlist. Therefore at the end the list have been overwritten 15 times and only contains 65 elements...

A: String string = (String) iterator.next();
reqList = rj.createPublisherRequestObject(string);

here you are assigning the result got from rj.createPublisherRequestObject(String) to reqList, so at end of itteration you have the last reurned value.
Instead use reqList.addAll(rj.createPublisherRequestObject(string)); which will keep on adding the reult list to the reqList, at end you have all the value.

A: You need to do
reqList.add(rj.createPublisherRequestObject(string));
You were not adding that's why it's returning last iteration value.


text:
Q: What is the difference between Java vararg with direct type vs wildcard generic via extends? How do following 2 Java method declarations differ:
public <S extends Item> void withExtra1(S... extra) {
    Collections.addAll(pool, extra);
}

and:
public void withExtra2(Item... extra) {
    Collections.addAll(pool, extra);
}

A: They don't, since S will be erased to Item, both signatures end up as Item....

A: The Java spec says

A Java compiler must output generic signature information for any class, interface, constructor or member whose generic signature in the Java programming language would include references to type variables or parameterized types.

If you check the bytecode you can see the method with generics has a different signature:
  public <S extends Item> void withExtra1(S...);
    descriptor: ([LItem;)V
    flags: (0x0081) ACC_PUBLIC, ACC_VARARGS
    Code:
      stack=2, locals=2, args_size=2
         0: aload_0
         1: getfield      #2                  // Field pool:Ljava/util/List;
         4: aload_1
         5: invokestatic  #3                  // Method java/util/Collections.addAll:(Ljava/util/Collection;[Ljava/lang/Object;)Z
         8: pop
         9: return
      LineNumberTable:
        line 9: 0
        line 10: 9
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      10     0  this   LItem;
            0      10     1 extra   [LItem;
      LocalVariableTypeTable:
        Start  Length  Slot  Name   Signature
            0      10     1 extra   [TS;
    Signature: #23                          // <S:LItem;>([TS;)V

  public void withExtra2(Item...);
    descriptor: ([LItem;)V
    flags: (0x0081) ACC_PUBLIC, ACC_VARARGS
    Code:
      stack=2, locals=2, args_size=2
         0: aload_0
         1: getfield      #2                  // Field pool:Ljava/util/List;
         4: aload_1
         5: invokestatic  #3                  // Method java/util/Collections.addAll:(Ljava/util/Collection;[Ljava/lang/Object;)Z
         8: pop
         9: return
      LineNumberTable:
        line 13: 0
        line 14: 9
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      10     0  this   LItem;
            0      10     1 extra   [LItem;

#23 in the constant pool is #23 = Utf8               <S:LItem;>([TS;)V

You can access this information at runtime using reflection:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Item {

    List<Item> pool;

    public static void main(String[] args) {
        for (var m : Item.class.getMethods())
            System.out.println(m.getName() + " " +
                    Arrays.toString(m.getGenericParameterTypes()));
    }

    public <S extends Item> void withExtra1(S... extra) {
        Collections.addAll(pool, extra);
    }

    public void withExtra2(Item... extra) {
        Collections.addAll(pool, extra);
    }

}

stdout:
main [class [Ljava.lang.String;]
withExtra1 [S[]]
withExtra2 [class [LItem;]
wait [long]
wait [long, int]
wait []
equals [class java.lang.Object]
toString []
hashCode []
getClass []
notify []
notifyAll []

A: The two signatures are equivalent, assuming the caller does not provide an explicit type witness. Any set of arguments that can be accepted by one signature is accepted by the other:

*

*Any set of arguments that is accepted by the first signature, must consist of expressions that have type equal to or a subtype of S, and since S is equal to or a subtype of Item, all the expressions have type equal to or a subtype of Item, and is accepted by the second signature.

*Any set of arguments that is accepted by the second signature, must consist of expressions that have type equal to or a subtype of Item, and can be passed to the first signature if S is inferred to be Item (which it can, since Item is within S's bound of extends Item)


text:
Q: Recursively finding all combinations 'n' of set stored in a map. How do I "choose"? I understand the overarching idea of what I want to do, but I'm not sure how to begin with implementation. I have a map of named int sets. Meaning the keys are strings and the values are set.
map<string, set<int> > data;

I want to find the max # of unique ints shared between 'n' sets. So I need to check all possible combinations and update some max variable every time I come across a better combination.
From what I gather I need to use Iterators to traverse through the map values. So am I carrying around 'n' Iterators in my recursive function? What would my base case even look like? Would it be it.end() of the first value being chosen? I'm a bit lost as you can imagine.
I am willing to abandon the map (tho I'd prefer to stick with it so that I can keep a name) and use something simpler like a vector for the sets if that simplifies things (which it seems like it might). Hmm...


text:
Q: How to retrieve and update data from visualforce to apex controller I don't have problem on retrieving data. But on updating the fields. I'm curios on how to do it.I tried something but seems not working.
This is my apex Code:
public class ProntoEventSettingsController {

    List<ProntoEVents_Setting__c> settings;
    public String X2 { get; set; }

    public ProntoEventSettingsController (){
    }

    public List<ProntoEVents_Setting__c> getSettings() {
        if(settings == null) {

           settings = [SELECT Id, Name, Available_Credits__c, Digital_Key__c, Gateway__c, Record_Events_to_Opportunities__c,Stages_for_Failed_Process__c,Stages_for_In_Progress__c,Stages_for_Successful_Process__c  FROM ProntoEVents_Setting__c Limit 1];
        }

        return settings;
    }

    public List<SelectOption> getopenPresentationOptions(){

        List<SelectOption> optns = new List<Selectoption>();

       optns.add(new SelectOption('','--None--'));
       optns.add(new SelectOption('Prospecting','Prospecting'));
       optns.add(new SelectOption('Qualification','Qualification'));
       optns.add(new SelectOption('Needs Analysis','Needs Analysis'));
       optns.add(new SelectOption('Value Proposition','Value Proposition'));
       optns.add(new SelectOption('Id. Decision Makers','Id. Decision Makers'));
       optns.add(new SelectOption('Perception Analysis','Perception Analysis'));
       optns.add(new SelectOption('Proposal/Price Qoute','Proposal/Price Qoute'));
       optns.add(new SelectOption('Negotiation/Review','Negotiation/Review'));
       optns.add(new SelectOption('Closed Won','Closed Won'));
       optns.add(new SelectOption('Closed Lost','Closed Lost'));

       return optns;
    }

    public PageReference save() {
      return null;
    }

}

and this is my VF code.
Just want to try to update the checkbox and the SelectOption.
<apex:form>

                            <apex:repeat var="setting" value="{!settings}">
                             <apex:inputCheckbox styleClass="opp-checkbox" value="{!setting.Record_Events_to_Opportunities__c}" />  Record Events to Opportunities

                                    Stage for In-Progress:

                                        <apex:selectList value="{!setting.Stages_for_In_Progress__c}" size="1" styleClass="form-control">
                                            <apex:selectOptions value="{!openPresentationOptions}" />
                                        </apex:selectList>

                                    Stage for Successful Process:

                                        <apex:selectList value="{!setting.Stages_for_Successful_Process__c}" size="1" styleClass="form-control">
                                            <apex:selectOptions value="{!openPresentationOptions}" />
                                        </apex:selectList>

                                    Stage for Failed Process:

                                        <apex:selectList value="{!setting.Stages_for_Failed_Process__c}" size="1" styleClass="form-control">
                                            <apex:selectOptions value="{!openPresentationOptions}" />
                                        </apex:selectList>

                                    <apex:commandButton action="{!save}" value="Save" id="theButton"/>

                            </apex:repeat>

                        </apex:form>

A: You have to update your object in your save method...
public PageReference save() {
     update settings;
     return null;
}

And check one more thing you should use
List<ProntoEVents_Setting__c> settings{set;}


text:
Q: Flash Organisation Chart I've been searching for a library that can render organisation charts in either flash and/or javascript(preferably jQuery). I know of several javascript and/or flash chart libraries but none of them seem to be able to render an organisation chart such as this: http://www.fsai.ie/images/org_chart.gif

A: iLog Elixir seems to have what you're looking for, in Flash/Flex. It's a commercial product and quite expensive, though. I Also found these blog posts (apparently by people from their dev team) where you can see a bit of how org charts are implemented in their product.

A: I have tried Google Org Chart. It is free and pretty simple to use. I have used it to create a dynamic org chart in SharePoint. There are a few issues with it. But overall I was satisfied with it.

A: have you considered just embedding something like gliffy?  it has it's own versioning and editing.  Do you need to just render something already created or enable visio creation?


text:
Q: Python: get name of file piped to stdin I have a python program that reads input from stdin (required), and processes lines from stdin:
for lines in stdin:
     #do stuff to lines
     filename = #need file name
     #example print
     print(filename)

However, in this for loop, I also need to get the name of the file that has been piped in to this python program like this:
cat document.txt | pythonFile.py #should print document.txt with the example print

Is there a way to do this?

A: No, this is not possible. As the receiving end of a pipe you have no knowledge where your data stream is coming from. The use of cat further obfuscates it, but even if you would write ./pythonFile.py < document.txt you would have no clue.
Many unix tools accept filenames as argument and - as a special code for 'stdin'. You could design your script the same way, so it can be called like

*

*cat document.txt | pythonFile.py -  (your script doesn't know the input origin)

*./pythonFile.py document.txt (your script does know the file)


text:
Q: Assigning array variable in smarty I'm quite new to smarty template in php. I want to assign a value to a variable inside the smarty template:
{assign var=all_person_exams value={$gdao->getGrade({$val->getTotal()},{$smarty.session.schoolsection})}

The value returned by the method $gdao->getGrade(...) is an array. This method has been thoroughly tested without smarty. But, it's not working here. How do i go about it?
Note: it should have returned a value when i do something like: {$all_person_exams.grade}

A: Try
{assign var=all_person_exams value=$gdao->getGrade($smarty.session.schoolsection)}

Smarty assign
or even
{$all_person_exams=$gdao->getGrade($smarty.session.schoolsection)}

Smarty short form assign


text:
Q: move some data from excel to sql I want to move some data from an Excelfile to my database. I use c#
this is my code:
        //conecting to DB
        SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=ghalamchi;Integrated Security=True");
        SqlCommand SqlCmd = new SqlCommand();
        SqlCmd.Connection = sqlcon;
        SqlCmd.CommandType = CommandType.StoredProcedure;
        SqlCmd.CommandText = "SP_AddStudent";

        int counter = 0;

         int i = 21;
        {
            SqlCmd.Parameters.Add("@id", SqlDbType.Char, 20).Value = Ds.Tables[0].Rows[i][0].ToString();
            SqlCmd.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = Ds.Tables[0].Rows[i][1].ToString();
            SqlCmd.Parameters.Add("@family", SqlDbType.NVarChar, 80).Value = Ds.Tables[0].Rows[i][2].ToString();
            SqlCmd.Parameters.Add("@codeM", SqlDbType.Char, 15).Value = Ds.Tables[0].Rows[i][3].ToString();
            //SqlCmd.Parameters.Add("@city", SqlDbType.NVarChar, 30).Value = txb_city.Text;
            //SqlCmd.Parameters.Add("@street", SqlDbType.NVarChar, 40).Value = txb_street.Text;
            SqlCmd.Parameters.Add("@Addres", SqlDbType.NVarChar, 150).Value = Ds.Tables[0].Rows[i][4].ToString();
            SqlCmd.Parameters.Add("@telephon", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][5].ToString();
            SqlCmd.Parameters.Add("@mobile", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][6].ToString();
            SqlCmd.Parameters.Add("@rabet1", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][7].ToString();
            SqlCmd.Parameters.Add("@rabet2", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][8].ToString();
            SqlCmd.Parameters.Add("@SchoolName", SqlDbType.NVarChar, 50).Value = Ds.Tables[0].Rows[i][9].ToString();
            SqlCmd.Parameters.Add("@avg", SqlDbType.Char, 6).Value = Ds.Tables[0].Rows[i][10].ToString();
             SqlCmd.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
            sqlcon.Open();

            SqlCmd.ExecuteNonQuery();

            if (SqlCmd.Parameters["@returnValue"].Value.ToString() == "1")
                counter++;

            sqlcon.Close();
        }

in this code , read a specefice row that declare with variable "i". it work correctly .but when i use a for() , for reading all of the rows of an excell file, this code have an error
this is the error :

Procedure or function SP_AddStudent has too many arguments specified.

i think this error occured ,because speed of db is low and it can't read an write all of the rows quickly
for (int i = 0; i < Ds.Tables[0].Rows.Count; i++)
        {
            SqlCmd.Parameters.Add("@id", SqlDbType.Char, 20).Value = Ds.Tables[0].Rows[i][0].ToString();
            SqlCmd.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = Ds.Tables[0].Rows[i][1].ToString();
            SqlCmd.Parameters.Add("@family", SqlDbType.NVarChar, 80).Value = Ds.Tables[0].Rows[i][2].ToString();
            SqlCmd.Parameters.Add("@codeM", SqlDbType.Char, 15).Value = Ds.Tables[0].Rows[i][3].ToString();
            //SqlCmd.Parameters.Add("@city", SqlDbType.NVarChar, 30).Value = txb_city.Text;
            //SqlCmd.Parameters.Add("@street", SqlDbType.NVarChar, 40).Value = txb_street.Text;
            SqlCmd.Parameters.Add("@Addres", SqlDbType.NVarChar, 150).Value = Ds.Tables[0].Rows[i][4].ToString();
            SqlCmd.Parameters.Add("@telephon", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][5].ToString();
            SqlCmd.Parameters.Add("@mobile", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][6].ToString();
            SqlCmd.Parameters.Add("@rabet1", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][7].ToString();
            SqlCmd.Parameters.Add("@rabet2", SqlDbType.NChar, 15).Value = Ds.Tables[0].Rows[i][8].ToString();
            SqlCmd.Parameters.Add("@SchoolName", SqlDbType.NVarChar, 50).Value = Ds.Tables[0].Rows[i][9].ToString();
            SqlCmd.Parameters.Add("@avg", SqlDbType.Char, 6).Value = Ds.Tables[0].Rows[i][10].ToString();
             SqlCmd.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
            sqlcon.Open();

            SqlCmd.ExecuteNonQuery();

            if (SqlCmd.Parameters["@returnValue"].Value.ToString() == "1")
                counter++;

            sqlcon.Close();

        }

what should i do?
 at the end
i cant speak englishe very well, sorry...

A: --Here is the code for bulk Insert .write a function to write data in database without Parameter .In procedure you use same temp table to insert data in your actual table
public void WriteData()
        {
            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
            {
                //System.Data.SqlClient.SqlBulkCopyOptions st = new System.Data.SqlClient.SqlBulkCopyOptions();

                //GetBulkCopy(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString, SqlBulkCopyOptions.KeepIdentity)
                using (System.Data.SqlClient.SqlBulkCopy bulk = new SqlBulkCopy(conn))
                {
                    conn.Open();
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(TempTable, conn);
                    cmd.ExecuteNonQuery();

                    bulk.DestinationTableName = "#ImportData";
                    for (Int32 I = 0; I < DTFinal.Columns.Count; I++)
                    {
                        bulk.ColumnMappings.Add(DTFinal.Columns[I].ToString(), DTFinal.Columns[I].ToString());
                    }
                    bulk.WriteToServer(DTFinal);
                    cmd = new System.Data.SqlClient.SqlCommand("dbo.SP_AddStudent", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();

                }
                //conn.Open();
                //System.Data.SqlClient.SqlCommand

                conn.Close();

            }
        }

A: my Guess was correct
speed of input data was more than the database control, so it cant handel it.
so i put all of the above code in a method(Add_SQL(int row)) an call it with a for loop :
for (int i = 0; i < Ds.Tables[0].Rows.Count;i++ )
                Add_SQL(i);
by this way , calling method and doing the code and calling the next method make a delay an data base can manage the data


text:
Q: TypeError: Argument 1 of Window.getDefaultComputedStyle does not implement interface Element I have the following code outside my polymer element (in another polymer):
        $(mainThis.shadowRoot.querySelector('#test1')).click(function(e){
            mainThis.$.testelement.openPopup();
        });

The line:
mainThis.$.testelement.openPopup();

Is causing error:
TypeError: Argument 1 of Window.getDefaultComputedStyle does not implement interface Element.

openPopup - is my custom function in polymer "testelement".
The error appears only in FireFox (version 31) on other browsers (Chrome, Safari, Opera) works perfect. How to fix it ?
Edit (openPopup function):
<script type="text/javascript">
    Polymer('popup-element', {

        domReady : function() {
            var mainThis = this;
            $(this.$.popup).on('click','.closebutton', function(e){
                mainThis.closePopup();
            });
        },
        openPopup : function (){
            $(this.$.popup).show();
            return this;
        },
        closePopup : function (){
            $(this.$.popup).hide();
            return this;
        }
    });

</script>

A: Ok, now I can see. I had the same problem. I have solved it like this:
Instead of:
$(this.$.popup).show();

Try this:
this.$.popup.style.display = "block";

It seems, it is impossible to use jQuery in polymer element javascript function when you execute it from another polymer element (in firefox only!). Please somebody smarter than me to improve this answer :)


text:
Q: SlideDown Effect on div with text  jsFiddle
I am trying to slideDown a  which is inside a div element

    <form id='fform'>
        Enter your name

        <input type='text' id='tf' placeholder='name' />
        <input type='submit' id='get_button' value='Get' text='Get'>
    </form>

Js:
 $('body').on('submit', '#fform', function () {
     $('#delete').html("Processing...").slideDown('slow');
     // ajax call
     return false;
 });

The new span doesn't seem to slideDown, it just show's up straight with no effect
What's the problem ?
Edit:
  As the Title of the question says : '..with text'  none of the answers address to that point. Can you please make the text to slide with div(something like what we see in vertical marquee)
This is what i wanted: thanks to  adeneo Fiddle

A: Add the element as hidden, then slide it down :
$('body').on('submit','#fform',function(){
     var div = $('
', {'class': 'front',
                                text  :'Processing...',
                                style :'display:none;'
                              }
                );
     $('#delete').html( div );
     div.slideDown('slow');
     return false;
 });

FIDDLE
And slideDown() sometimes has issues with inline elements that are not placed properly, so use a block element.

A: The new div is created in the shown state, so is immediately visible on the page.
If you create it hidden, you can then slide it down:
$('#delete').html("Processing...").hide().slideDown('slow');

http://jsfiddle.net/ua2GM/

A: The reason it wasn't sliding down because it was already visible. Try to hide it first then slide down:
$('#delete').html("Processing...").hide().slideDown('slow');

Demo: http://jsfiddle.net/9SsUN/2/

A: Just replacing the contents of #delete with the element as you're doing shows the element immediately. Also, you may want to access the form later, so it's probably best to just hide it.
Here's a slight restructure that achieves the slideDown you want, and only hides the form so you can show it again later on.
See this jsfiddle: http://jsfiddle.net/z2gYZ/