text:
Q: Equicontinuity, compactness and uniform convergence. Let $X$ be a compact topological space and let $K\subset \mathbb{R}^n$ be compact. Let $F = \{f_n\}_{n \ge 1}$ be a sequence of continuous functions where $f_n : X \to K$ that converges pointwise to $f$.
Show that if $F$ is equicontinuous, then $f$ is continuous and $f_n$ converges uniformly to $f$.
Attempt
a) It is enough to show that the convergence is uniform, since the Uniform Limit Theorem then implies that $f$ is continuous, correct?
b) Since the convergence is pointwise, $F$ must be pointwise bounded, correct? (If it's not, then I have a big misunderstanding...)
c) By Arzela's theorem, since $X$ is compact,$F$ pointwise bounded and equicontinuous,  $F$ has a uniformly convergent subsequence, correct?
d) Since $F$ has a uniformly convergent subsequence, can I conclude that it converges uniformly to $f$? Why? Why not?
Any help is highly appreciated.

A: Hi you are right with point b) and c).
let's show that f is continuous
if $F$ is equicontinuous let $\epsilon >0$ let $x>0$
there exist $\delta >0$ such that  $\forall n \in N$ $|x-y|< \delta =>|f_n(x)-f_n(y)|< \frac{\epsilon}{3}$
So let $y$ such that $|x-y|< \delta$
by pointwise convergence let $n \in N $ such that $|f_n(y)-f(y)|<\frac{\epsilon}{3}$
and $|f_n(x)-f(x)|<\frac{\epsilon}{3}$
then $|f(x)-f(y)|< |f(x)-f_n(x)| + |f_n(x)-f_n(y)| + |f_n(y)-f(y)| < \frac{\epsilon}{3} + \frac{\epsilon}{3} + \frac{\epsilon}{3} = \epsilon$
then f is continuous.
As mentionned in the comment to conclude you can use this sub-subsequence argument :
let's show that $f_n$ uniformly converge to $f$
We assume that $f_n$ don't uniformly converge to $f$
So there exist $\epsilon$ and there exist $\phi$ such that
$\forall n \in N ~~ |f_{\phi(n)}-f|_{\infty}> \epsilon$
but you can apply arzela's theorem to the subsequence $(f_{\phi(n)})$ because the subsequence verify the theorem's conditions.
So there exist $\psi$ such that $(f_{\phi(\psi(n))})$ uniformly converge to $f$
but as a subsequence of $(f_{\phi(n)})$
$\forall n \in N$ $|f_{\phi(\psi(n))}-f|_{\infty }> \epsilon $
This is a contradiction hence $f_n$ uniformly converge to $f$


text:
Q: Total unicode characters in Ruby I have the following method that takes a string and converts the unicode character to an int.
def uni_total(string)
string.ord
end

This will total a character.  If I wanted to total all of the characters in a string I have tried the following method.
def uni_total(string)
string.ord each |item|
return item++
end
end

When I run it give me the following error message 'unexpected tIDENTIFIER, expecting keyword_end
   return item++
What is the best way to get around this? Any help would be appreciated.
Regards

A: Try this
def uni_total(string)
  acc = 0
  string.each_char do |item|
    acc += item.ord
  end
  acc
end

You'll need some accumulator to sum up each char of your string
Iterate on each char with each_char method ( string type does not have .each method anymore since Ruby 1.9 )
 and then return the accumulator

redpajama_set_name: RedPajamaStackExchange


text:
Q: dynamic content ellipsis based on predefined proportion I have the following template of a card: pen. It is comprised of two sections "one" and "two".

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's...

   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been...

Both of the sections have content that overflows their respective size. I would like to maximize #two div, so that it will take maximum (and ellipsis the rest) size and leave one line for the #three div.
If there is not enough content for #two then take its respective size and give all size left to #three.
Edit:
I would like to fix the width and allow the height to grow to a certain limit and then ellipsis


text:
Q: Dynamically disable a dropdown of reactive form I'm trying disable a dropdown built with ul and li i have to use ui and li instead of select for requirement inside a reactive form.
Html

Validation type

         {{input}}

ts
let fieldSetGroup = <FormArray>this.createTemplateForm.get("fieldSets");
        fieldSetGroup.push(this.fb.group({
            key: ["", Validators.required],
            "type": ["", Validators.required],
            mandatory : ["", Validators.required],
            validationType: [""]
}));
let fg  = <FormGroup> fieldSetGroup.controls[id];
if (fg.controls["key"] === "Apple") {
  fg.controls["validationType"].disable();
}

tried adding formControlName on both ul and li...didnt work...How to handle this case?

A: you have 2 options either use reactive form or use css class
for useing reactive form  add formControlname to your component

Validation type

         {{input}}

and add below code in your method (where you WANT TO disable it)
const ctrl = this.fg.get('validationType');
  ctrl.disable();

To achice this using css
  add this in your component css
.disabled{
    pointer-events:none;
    opacity:0.4;
  }

and in ur html add this calss to your element

Validation type

         {{input}}

Please replace fg.invalid with your validetion condition


text:
Q: Can MinGW Make be sped up without disabling implicit rules? GNU Make under MinGW is known to be very slow under certain conditions due to how it executes implicit rules and how Windows exposes file information (per "MinGW "make" starts very slowly").
That previous question and all other resources on the issue that I've found on the internet suggest working around the problem by disabling implicit rules entirely with the -r flag. But is there another way?
I have a "portable" Makefile that relies on them, and I'd like to make it so that it does not take around a minute to start it up each time, rather than having to get the Makefile owner to alter it just for me.

A: You should use make -d to see all the things make is doing and try to see where the time is going.  One common reason for lengthy make times are match-anything rules which are used to determine whether or not a makefile needs to be rebuilt.  Most of the match-anything rules CAN be removed; they're rarely needed anymore.
You can add this to your makefile and see if it helps:
%:: %,v
%:: RCS/%,v
%:: RCS/%
%:: s.%
%:: SCCS/s.%

And, if you don't need to auto-create your makefile you can add:
Makefile: ;

(also put any included makefiles there that you don't need to auto-create).
ETA
It seems your real question can be summed up as, "why does make take so much longer to start on Windows than on Linux, and what can I do to fix that without changing makefiles?"
The answer is, nothing.  Make does exactly the same amount of work on both Windows and Linux: there are no extra rules or procedures happening on Windows that could be removed.  The problem is that Windows NTFS is slower than typical Linux filesystems for these lookups.  I know of no system setting, etc. that will fix this problem.  Your only choice is to get make to do less work so that it's faster, and the only way to do that is by removing built-in rules you don't need.
If the problem is you really don't want to edit the actual makefiles, that's simple enough to solve: just write the rules above into a small separate makefile, maybe something like speedup.mk, then set the environment variable MAKEFILES=speedup.mk before invoking make.  Make will parse that makefile as well without you having to change any makefiles.


text:
Q: Pandas: replace values in dataframe with another dataframes values based on condition I have the following dataframes:
df1:
+-----+------+------+------+------+------+
| No. | col1 | col2 | col3 | Type | ...  |
+-----+------+------+------+------+------+
| 123 |    2 |    5 |    2 | MN   | ...  |
| 453 |    4 |    3 |    1 | MN   | ...  |
| 146 |    7 |    9 |    4 | AA   | ...  |
| 175 |    2 |    4 |    3 | MN   | ...  |
| 643 |    0 |    0 |    0 | NAN  | ...  |
+-----+------+------+------+------+------+

df2:
+-----+------+------+------+------+
| No. | col1 | col2 | col3 | Type |
+-----+------+------+------+------+
| 123 |   24 |   57 |   22 | MN   |
| 453 |   41 |   39 |   15 | MN   |
| 175 |   21 |   43 |   37 | MN   |
+-----+------+------+------+------+

I want to replace col1, col2 and col3 in df1 with corresponding values in df2 if Type equals MN
Desired output:
df1:
+-----+------+------+------+------+-----+
| No. | col1 | col2 | col3 | Type | ... |
+-----+------+------+------+------+-----+
| 123 |   24 |   57 |   22 | MN   | ... |
| 453 |   41 |   39 |   15 | MN   | ... |
| 146 |    7 |    9 |    4 | AA   | ... |
| 175 |   21 |   43 |   37 | MN   | ... |
| 643 |    0 |    0 |    0 | NAN  | ... |
+-----+------+------+------+------+-----+

EDIT
I tried:
df1[df1.Type == 'MN'] = df2.values

but I get this error:
ValueError: Must have equal len keys and value when setting with an ndarray

Guess the reason is, that df2 does not have equal number of columns. So how do I make sure, that only the specific columns (col1 - col3) are replaced in df1?

A: I think need combine_first for match by No. column:
#filter only `MN` rows if necessary
df22 = df2[df2['Type'] == 'MN'].set_index('No.')
df1 = df22.combine_first(df1.set_index('No.')).reset_index().reindex(columns=df1.columns)
print (df1)

   No.  col1  col2  col3 Type  col
0  123  24.0  57.0  22.0   MN  ...
1  146   7.0   9.0   4.0   AA  ...
2  175  21.0  43.0  37.0   MN  ...
3  453  41.0  39.0  15.0   MN  ...
4  643   0.0   0.0   0.0  NAN  ...

A: Your code doesn't work because the number of columns of df1 and df2 are different.
from io import StringIO
import pandas as pd

x1 = """No.,col1,col2,col3,Type,Oth
123,2,5,2,MN,...
453,4,3,1,MN,...
146,7,9,4,AA,...
175,2,4,3,MN,...
643,0,0,0,NAN,...
"""
x2 = """No.,col1,col2,col3,Type
123,24,57,22,MN
453,41,39,15,MN
175,21,43,37,MN
"""

df1 = pd.read_csv(StringIO(x1), sep=",")
df2 = pd.read_csv(StringIO(x2), sep=",")

df1.loc[df1.Type == 'MN', ["No.","col1","col2","col3","Type"]] = df2.values
# Output:
# >>> print(df1)
#    No.  col1  col2  col3 Type  Oth
# 0  123    24    57    22   MN  ...
# 1  453    41    39    15   MN  ...
# 2  146     7     9     4   AA  ...
# 3  175    21    43    37   MN  ...
# 4  643     0     0     0  NAN  ...

But there is a problem if the column order of df1 and df2 are different.
df1 = pd.read_csv(StringIO(x1), sep=",")
df3 = df2.copy()[["No.","Type","col1","col2","col3"]]
df1.loc[df1.Type == 'MN', ["No.","col1","col2","col3","Type"]] = df3.values
# Output:
# >>> print(df1)
#    No. col1  col2  col3 Type  Oth
# 0  123   MN    24    57   22  ...
# 1  453   MN    41    39   15  ...
# 2  146    7     9     4   AA  ...
# 3  175   MN    21    43   37  ...
# 4  643    0     0     0  NAN  ...

To avoid this, you can try
df1.loc[df1.Type == 'MN', ["No.","col1","col2","col3","Type"]] = (
    df3[["No.","col1","col2","col3","Type"]].values)
# Output:
# >>> print(df1)
#    No.  col1  col2  col3 Type  Oth
# 0  123    24    57    22   MN  ...
# 1  453    41    39    15   MN  ...
# 2  146     7     9     4   AA  ...
# 3  175    21    43    37   MN  ...
# 4  643     0     0     0  NAN  ...

However, there is still a problem if the number of 'MN' records are different in df1 and df2
df1 = pd.read_csv(StringIO(x1), sep=",")
df4 = df2.copy().iloc[:2]
df1.loc[df1.Type == 'MN', ["No.","col1","col2","col3","Type"]] = (
    df4[["No.","col1","col2","col3","Type"]].values)
# Error:
# ValueError: shape mismatch: value array of shape (2,) could not be broadcast to
# indexing result of shape (3,)

So what you need may be like this
df = pd.merge(df1, df2, how='left', on=['No.', 'Type'])
df['col1'] = df.apply(lambda x: x.col1_y if x.Type == 'MN' else x.col1_x, axis=1)
df['col2'] = df.apply(lambda x: x.col2_y if x.Type == 'MN' else x.col2_x, axis=1)
df['col3'] = df.apply(lambda x: x.col3_y if x.Type == 'MN' else x.col3_x, axis=1)
df = df[["No.","col1","col2","col3","Type"]]
# Output:
#>>> print(df)
#   No.  col1  col2  col3 Type
#0  123  24.0  57.0  22.0   MN
#1  453  41.0  39.0  15.0   MN
#2  146   7.0   9.0   4.0   AA
#3  175  21.0  43.0  37.0   MN
#4  643   0.0   0.0   0.0  NAN


text:
Q: Cucumber tests fails to start with error "Display socket is taken but lock file is missing.." After running cucumber

bundle exec cucumber features/emails.feature:20

I am getting error

Display socket is taken but lock file is missing - check the Headless
  troubleshooting guide (Headless::Exception)
  /Users/me/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/headless-2.2.0/lib/headless.rb:195:in
  ensure_xvfb_is_running'
  /Users/me/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/headless-2.2.0/lib/headless.rb:184:in
  launch_xvfb'
  /Users/me/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/headless-2.2.0/lib/headless.rb:172:in
  `block in pick_available_display'

I am running MacOS 10.11.5, xquartz installed, test started first time and I cant make it to start again. Any suggestions?

A: Full disclosure: I have no idea what is happening here, and would love for someone to explain it to me, but running the following commands gets Xvfb and my test suite working correctly:
mkdir /tmp/.X11-unix
sudo chmod 1777 /tmp/.X11-unix
sudo chown root /tmp/.X11-unix/

I found this answer here:
https://github.com/leonid-shevtsov/headless/issues/47 (first comment)


text:
Q: Trigger on Lead - Variable does not exist: isConverted Trying to write a trigger that runs on lead conversion after update, I get the error above on trigger.oldMap.
What am I missing?
public with sharing class LeadTriggerHandler extends TriggerHandler{

    Boolean isLeadConversionMethod = false;

    public override void afterUpdate() {
        if (!isLeadConversionMethod) {
            LeadConversionMethod();
            isLeadConversionMethod = true;
        }
    }

    public void LeadConversionMethod(){
        Map<Id,Id> leadIdswithOppIds = new Map<Id,Id>();
        for (Lead l : (List<Lead>)Trigger.New) {
            If (trigger.isUpdate && l.IsConverted && trigger.oldMap.get(l.Id).isConverted == false){
                leadIdswithOppIds.put(l.Id,l.convertedopportunityid);
            }
        }
    }

}

A: The compiler gets confused here as you are not writing this in the trigger itself. So pass through the old map from a trigger in your function.
Or maybe you can create a class member for it.
rewrite your code as below
public with sharing class LeadTriggerHandler extends TriggerHandler{

    Boolean isLeadConversionMethod = false;
    Map<Id, Lead> oldMap = new Map<Id, Lead>();

    public LeadTriggerHandler(Map<Id, Lead> oldMap){
        this.oldMap = oldMap;
    }
    public override void afterUpdate() {
        if (!isLeadConversionMethod) {
            LeadConversionMethod();
            isLeadConversionMethod = true;
        }
    }

    public void LeadConversionMethod(){
        Map<Id,Id> leadIdswithOppIds = new Map<Id,Id>();
        for (Lead l : (List<Lead>)Trigger.New) {
            If (trigger.isUpdate && l.IsConverted && oldMap.get(l.Id).isConverted == false){
                leadIdswithOppIds.put(l.Id,l.convertedopportunityid);
            }
        }
    }
}

A: You are getting this issue because the compiler does not know the context where it will be used and what it will contain i.e. it does not know the concrete class that will be used. In that case, it will consider Trigger.oldMap as Map<Id,sObject> (Same is the case with other data context variables i.e. it will consider everything as sObject, you did this typecasting in the for loop, similarly you need to do it for other data context variables as well wherever it is used).
As it considers it as sObject, you won't be able to use the dot notation. In such cases, you can use following approaches

*

*Pass the context variables in constructor either via your handler class or via methods i.e. you will have to change your signature of interface to have parameterized methods and assign it to a concrete variable.

*Assign the context variables to a local concrete copy or typecast it to a concrete class in method i.e. Assign Trigger.oldMap to Map<Id, Lead> and use this variable for your logic.

*Instead of using dot notation, get the field value dynamically using get method of sObject i.e. instead of using oldMap.get(l.Id).isConverted, you can use oldMap.get(l.Id).get('isConverted')
Assigning to a concrete local copy or by typecasting
public void LeadConversionMethod(){
    Map<Id,Id> leadIdswithOppIds = new Map<Id,Id>();
    Map<Id,Lead> leadIdswithLeads = new Map<Id,Lead>();
    leadIdswithLeads = Trigger.OldMap;
    for (Lead l : (List<Lead>)Trigger.New) {
        If (trigger.isUpdate && l.IsConverted && leadIdswithLeads.get(l.Id).isConverted == false){
            leadIdswithOppIds.put(l.Id,l.convertedopportunityid);
        }
    }
}

Using the get method of the sObject class
public void LeadConversionMethod(){
    Map<Id,Id> leadIdswithOppIds = new Map<Id,Id>();
    for (Lead l : (List<Lead>)Trigger.New) {
        If (trigger.isUpdate && l.IsConverted && Boolean.valueOf(Trigger.OldMap.get(l.Id).get('isConverted')) == false){
            leadIdswithOppIds.put(l.Id,l.convertedopportunityid);
        }
    }
}


text:
Q: Getting the last active window's title of a process running under system account in services We need to get the  last active window's title of a process.
Currently We are using the command tasklist /v and parsing it to get the window title.
Problem:
We are not able to get the last active window's title if we run the command under system account in services.
Output If we run under windows account/system account (not from services):
Image Name
PID
Session Name
Session#
Mem Usage
Status
User Name
CPU Time
Window Title

firefox.exe
4476
Console
1
509,224 K
Running
Ramesh
0:01:47
Getting the window title of a process

Output If we run under windows account/system account (from services):
Image Name
PID
Session Name
Session#
Mem Usage
Status
User Name
CPU Time
Window Title

firefox.exe
4476
Console
1
509,224 K
Running
Ramesh
0:01:47
N/A

Our application is running under system account from services. Is there a way to get the windows title from a program running under system account from services?

A: In Windows Vista and later Windows service run in a separate session. When a user logs in a Terminal Services enabled computer a new session is created with each logon. That's the reason we are not able to access the window title of a process since it is running under different session.
However, an interactive service can display a user interface and receive user input. To access the window title of the process in another user's session, I need to create an interactive services.
MSDN article: Interactive services.


text:
Q: Duplicate results from function applied to DataFrame using groupby I am trying to calculate the percentage of income groups that are in debt compared to the total of individuals in those income groups (in debt = 1, no debt = 0)
I've also tried the groupby() method but did not manage to make it work.
This is what I've typed:
import pandas as pd
import numpy as np
credit_scoring = pd.read_csv('/datasets/credit_scoring_eng.csv')

in_debt = credit_scoring[credit_scoring['debt'] == 1]['income_group'].value_counts()
total = credit_scoring['income_group'].value_counts()
print(in_debt)
print(total)

def percentage_of_debt(incomegroup):
    calc = in_debt / total * 100
    return calc

credit_scoring.groupby('income_group')['debt'].apply(percentage_of_debt)

The result shows the correct percentages but it also groups the result into the income groups again as so:
< 20000          608
25000 - 29999    409
>= 35000         290
20000 - 24999    288
30000 - 34999    146
Name: income_group, dtype: int64
< 20000          7369
25000 - 29999    4856
>= 35000         4071
20000 - 24999    3378
30000 - 34999    1851
Name: income_group, dtype: int64
income_group
20000 - 24999  < 20000          8.250780
               25000 - 29999    8.422570
               >= 35000         7.123557
               20000 - 24999    8.525755
               30000 - 34999    7.887628
                                  ...
>= 35000       < 20000          8.250780
               25000 - 29999    8.422570
               >= 35000         7.123557
               20000 - 24999    8.525755
               30000 - 34999    7.887628
Name: debt, Length: 25, dtype: float64

I would like the output to show:
< 20000          8.250780
25000 - 29999    8.422570
20000 - 24999    8.525755
30000 - 34999    7.887628
>= 35000         7.123557

Appreciate all of the suggestions and guidance!

A: without the underlying table is a bit tricky, but I think what you want is
credit_scoring.groupby("income_group").agg(lambda df: 100 * df['debt'].sum() / df['debt'].count()).sort_index()

Is that what you are after?


text:
Q: Web Socket handshake error in Docker I use Python 3.5, Flask and Meinheld web socket middleware to serve sockets. Here is server side code sample:
@app.route('/chat')
def chat():
    ws = request.environ.get('wsgi.websocket')
    while True:
        m = ws.wait()
        if m is None:
            break
        ws.send(m)

    return ""

Client side code sample:
var s = new WebSocket("ws://localhost:4567/chat");

However, everything works properly while I run it in local mode, but when i add this into docker container i always get error like this:
WebSocket connection to 'ws://localhost:4567/chat' failed: Error during WebSocket handshake: Unexpected response code: 500
It does not matter where docker container is run, on remote server or local environment, the error is always the same. All necessary ports are exposed.


text:
Q: TFS Manual Mstest Publish Results? Following a MSDN web page, I am trying to manually run mstest within my tfsbuild.proj and put the results into the pass/fail logic so the build will fail if this particular test fails. It's kind of like running a FxCop or something else from CMD and capturing a "0" or "1" and force-fail the build.
MSTest /testcontainer:test.dll /publish:http://ourtfsmachine:8080 /teamproject:ProjectName /publishbuild:BuildNumber01 /platform:AnyCpu /flavor:Release
I could understand running this inside an Exec task, butI don't know what the BuildNumber is, for example.
Help?

A: Instructions for getting the Build Number from http://msdn.microsoft.com/en-us/library/ms243151%28VS.100%29.aspx:

*

*Open Visual Studio and connect to a Team Foundation Server.

*Open Team Explorer.

*Open your team project and expand the team project node.

*Under the build, double-click All Build Types or a specific build type to see its builds. Build names that you can use are in the Name column.


text:
Q: Не равны prefab объекта и объект Есть prefab (являющийся trigger'ом), передающийся в скрипт через public переменную:
public GameObject RedSphere;

В скрипте создается объект с его помощью:
Instantiate(RedSphere);

Объект spawn'ится, но при сравнении (в функции OnTriggerEnter, когда тело с прикрепленным скриптом касается объекта) условие не выполняется:
other.gameObject == RedSphere

Почему так происходит и как это исправить?

A: Вы можете сравнивать так базовые типы:
int A = 3;
int B = 3;
bool AB = A == B; // true

Тоже самое с структурами(struct):
Vector2 A = new Vector2(1, 2);
Vector2 B = new Vector2(1, 2);
bool AB = A == B; // true

С объектами это не так:
int[] A = { 1, 2, 3 }; // массив это объект
int[] B = { 1, 2, 3 };
bool AB = A == B; // false

При передачи объектов в значение полей/переменных или как аргументы, передаётся только ссылка на объект, а не значения как с базовыми типами и структурами. При сравнении объектов сравниваются именно их ссылки и это является проверкой, является ли объект тем самым.
Вы можете присвоить префабу уникальный Tag или Layer и сравнивать по ним:
other.gameObject.tag == RedSphere.tag;
other.gameObject.layer == RedSphere.layer;

Либо повесить на них какой нибудь скрипт для сравнения объектов по нему:
public enum ObjectColor { Red, Green, Blue }
public enum ObjectShape { Sphere, Cube }

public class ColorShape : MonoBehaviour
{
    public ObjectColor Color;
    public ObjectShape Shape;
}

public class Foo : MonoBehaviour
{
    [SerializeField] private ColorShape _redSphereTemplate;

    public void SpawnRedSphere ()
    {
        Instantiate(_redSphereTemplate.gameObject);
    }

    private void OnCollisionEnter (Collision collision)
    {
        if (collision.TryGetComponent(out ColorShape colorShape))
        {
            bool Same = SameColorShape(colorShape, _redSphereTemplate);
        }
    }

    private bool SameColorShape (ColorShape csA, ColorShape csB)
    {
        return csA.Color == csB.Color && csA.Shape == csB.Shape;
    }
}


text:
Q: How to sort column fields in Django model.object.values() I am using this
objects = Model.objects.values('var1', 'var2', 'var4')

IN template i use
{% for fieldname in object.keys %}<th>{{ fieldname }}</th>{% endfor %}
But the field names appear in arbitrary order like
var4---var1----var2

I want them to appear like i provided in function
var1---var2----var4

is this possible

A: The easiest solution is to just use values_list, which returns tuples and change your template accordingly.
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.values_list
If for whatever reason, you want to keep using dict-s, and want an "automagical" solution, you'd have to do quite a bit of work:

*

*Subclass Django's ValuesQuerySet, name it for ex. OrderedValuesQueryset and change it's iterator method to use OrderedDict http://docs.python.org/dev/library/collections.html#collections.OrderedDict

*Create a Queryset subclass which
in it's .values method returns an instance of
your OrderedValuesQuerySet

*Create a custom models.Manager
class which in it's get_query_set
method uses your custom QuerySet
from 2.

*Set the custom Manager to be used in your model. See https://docs.djangoproject.com/en/1.3/topics/db/managers/#custom-managers
Now what you are trying to do will work automatically on that model. You can also set the custom manager to a different attribute than objects, to also keep the default manager available.

A: The question is rather how to sort a Python dictionary, because this is what values() returns. Python dictionaries by definition do not have an ordering.
See this blog post


text:
Q: Loading data from generator using tf.data.Dataset.from_generator() I want to load data for my metric learning model, and the data generating function is the get_data()  function
def get_data():
    def my_generator():
        for i in range(10):
            anchor = list(np.expand_dims(cv2.imread('img1'), axis=0))
            positive = list(np.expand_dims(cv2.imread('img2'), axis=0)
            true = 0
            a = (true, anchor, positive)
            yield a

    return tf.data.Dataset.from_generator(
        my_generator,
        output_types=(tf.int64, tf.Tensor, tf.Tensor),
        output_shapes=(1, (1, 256, 256, 3), (1, 256, 256, 3))
    )

dataset = get_data()

when I run this code, I get the following error. I've tried to pass some other arguments to output_types, tf.float64 for example, but it doesn't work either. I think I do something wrong with the shapes, but I can't figure what.

TypeError: Cannot convert value <class 'tensorflow.python.framework.ops.Tensor'> to a TensorFlow DType.

Any help is appreciated :)

A: As I thought, the problem was in shapes, this worked for me
    return tf.data.Dataset.from_generator(
        my_generator,
        output_types=(tf.float64, tf.float64, tf.float64),
        output_shapes=(tf.TensorShape(None), tf.TensorShape((1, 256, 256, 3)),
            tf.TensorShape((1, 256, 256, 3))))


text:
Q: Phonegap.js on second html page I basically have two pages in my phonegap application that I am building with PGB (index.html and main.html), that both use angular.js. Index.html is a login for the app, which redirects to main.html afterwards. All my plugins and phonegap.js are being injected fine into main, but none of the inline JS (alerts on doc ready, device ready, window load) are firing, let alone phonegap.js being loaded as well.
Any advice would be appreciated.
Script Includes:

Scripts:
 alert("p2 adding")
 document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
    alert("main.html: device is ready");
}

$(window).load(function(){
  alert("window.load happening");
})
</script>


text:
Q: How to sort an integer array in-place in Python? how can one sort an integer array (not a list) in-place in Python 2.6?  Is there a suitable function in one of the standard libraries?
In other words, I'm looking for a function that would do something like this:
>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])

Thanks in advance!

A: @steven mentioned numpy.
Copies vs. in-place operation
-----------------------------
Most of the functions in `numpy` return a copy of the array argument
(e.g., `sort`).  In-place versions of these functions are often
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
Exceptions to this rule are documented.

A: Well, you can't do it with array.array, but you can with numpy.array:
In [3]: a = numpy.array([0,1,3,2], dtype=numpy.int)

In [4]: a.sort()

In [5]: a
Out[5]: array([0, 1, 2, 3])

Or you can convert directly from an array.array if you have that already:
a = array.array('i', [1, 3, 2])
a = numpy.array(a)

A: Looking at the array docs, I don't see a method for sorting.  I think the following is about as close as you can get using standard functions, although it is really clobbering the old object with a new one with the same name:
import array
a = array.array('i', [1,3,2])
a = array.array('i', sorted(a))

Or, you could write your own.
With the extra information from the comments that you're maxing out memory, this seems inapplicable for your situation; the numpy solution is the way to go.  However, I'll leave this up for reference.


text:
Q: ion-checkbox:checked not working angular 2 ionic 2 I want to execute css when ion-checkbox is checked. But ion-checkbox:checked doesnt execute.
I want to highlight all column below it.
Here's what I've done.
**Html file
<ion-row class = "DefaultBundle">
    <ion-col col-4>Description of Services</ion-col>
    <ion-item col-4 style = "background-color: #84AEF9 !important;">
        <ion-label class = "Services">Full Service Agency</ion-label>
        <ion-checkbox class = "Bundle1"></ion-checkbox> // <-- Here's the check box
    </ion-item>
    <ion-item col-4 [hidden] = "!DefaultBundle.checked" style = "background-color: #84AEF9 !important;">
        <ion-label class = "Services">Frost & Co Lite</ion-label>
        <ion-checkbox class = "Bundle2"></ion-checkbox>
    </ion-item>
</ion-row>

Here are some of the fields that I want to highlight.
<ion-row>
    <ion-col>Market Appraisal</ion-col>
    <ion-col><ion-checkbox disabled checked></ion-checkbox></ion-col>
    <ion-col [hidden] = "!DefaultBundle.checked"><ion-checkbox disabled checked></ion-checkbox></ion-col>
</ion-row>
<ion-row>
    <ion-col>For Sale Board</ion-col>
    <ion-col><ion-checkbox disabled checked></ion-checkbox></ion-col>
    <ion-col [hidden] = "!DefaultBundle.checked"><ion-checkbox disabled checked></ion-checkbox></ion-col>
</ion-row>
<ion-row>
    <ion-col>Rightmove Portal Listing</ion-col>
    <ion-col><ion-checkbox disabled checked></ion-checkbox></ion-col>
    <ion-col [hidden] = "!DefaultBundle.checked"><ion-checkbox disabled checked></ion-checkbox></ion-col>
</ion-row>

Here's my CSS.
.Bundle1:checked
{
    background-color: red; // <-- this is just for testing. And it never executes.
}

Question: What am I missing here?

A: You are assuming ion-checkbox to be like a simple input of type checkbox/radio or option.
:checked docs

The :checked CSS pseudo-class selector represents any radio (), checkbox (), or option ( in a ) element that is checked or toggled to an on state.

If you glance at the ion-checkbox component code,

'
' +
      '

' +
    '
' +
    '<button role="checkbox" ' +
            'type="button" ' +
            'ion-button="item-cover" ' +
            '[id]="id" ' +
            '[attr.aria-checked]="_value" ' +
            '[attr.aria-labelledby]="_labelId" ' +
            '[attr.aria-disabled]="_disabled" ' +
            'class="item-cover"> ' +
    '</button>',

It is a button when it is shown.
You will need to create a custom class
  .isChecked{
     background-color: red;
  }

And set it using [class] dynamically based on a boolean value.
 <ion-checkbox [class.isChecked] = "isCurrentCheckboxChecked"></ion-checkbox>


text:
Q: Java Manual Implementation of Doubly Link List I need help writing this addAfterCurrent method for my PerformanceList Which is a doublely linked list with a standerd head , tail and cursor(current) nodes declared. The node class uses
PerformanceNode next;
PerformanceNode previous;
as pointers they also have set and get methods
public void addAfterCurrent(PerformanceNode newPerformance)
Method Definiton
Inserts the new data into the PerformanceList such that the new node directly follows the current node, if it exists. If there is no current node (i.e., the current node is null), simply insert the node at the end of the list. The current node should now be the newly created node
My current method does not insert a node after the current node .This is the problem i need help with I cant get it to set a newPerformance after the current node
public void addAfterCurrent(PerformanceNode element)
    {
        PerformanceNode temp = element;
        if (cursor == null)
        {
        head = temp;
        tail = temp;
        cursor = temp;
        }
        else
        {
            temp.setNext(cursor);
            cursor.setPrev(temp);

            cursor = temp;

            if(cursor == null)
            {
                tail = cursor;
            }
        }

    }

A: I implemented with some comments according to the definition:
public void addAfterCurrent(PerformanceNode node) {
    if (node == null)  {
        throw new IllegalArgumentException("Node to be added cannot be null!");
    }

    if (cursor == null && tail == null) {
        throw new IllegalStateException("There is neither current nor tail node!");
    }

    if (cursor == null) { // there is no current node
        // insert the node at the end of the list
        tail.setNext(node);
        node.setPrev(tail);

        // mode end cursor
        tail = node;

        // current node should now be the newly created node
        cursor = node;
    } else { // there is current node
        PerformanceNode temp = cursor.getNext();

        // new node directly follows the current node
        cursor.setNext(node);
        node.setPrev(cursor);

        if (temp != null) {
            node.setNext(temp);
            temp.setPrev(node);
        } else { // current node was the last node
            tail = node; // mode end cursor
        }
    }
}


text:
Q: Using async-await with node-fetch does not return the response to the calling method I have a function defined in a module that is supposed to do a fetch and return the response. I am having trouble returning the response from the fetch. The calling function gets the return value as "undefined".
I am new to JavaScript and Node so might need a little bit of hand-holding if you don't mind.
Calling function
async function executeTest() {
    try {
        const response = await bpc.postLendingApplication(
            blendConnection,
            loanData
        );
        console.log("Response from POST Loan: ", response);
    } catch (error) {
        console.log(error);
    }
}

Module function doing the fetch request
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
    console.log("Processing POST Loan.");
    await fetch(connection.url, {
        method: "POST",
        headers: connection.headers,
        body: data,
    }).then(async res => {
        console.log("Status: ", res.status);
        console.log("StatusText: ", res.statusText);
        console.log("OK: ", res.ok);
        return await res;
    });
}

The console output is:
Processing POST Loan.
Status:  200
StatusText:  OK
OK:  true
Response from POST Loan:  undefined

As you can see, the fetch did what it was supposed to do and if I log the res.json() within the module method, it prints the payload. But I would like to return the error and response from the fetch so the module behaves as a generic method and the processing and error handling is done in the calling method.

A: When you mark a function as async, JavaScript will always return a Promise, thus making it asynchronous. When you return a value, it is resolving the Promise. Using await inside of these functions "pauses"  execution (it is technically creating a new function for code that occurs after the await) until the awaited Promise is resolved, standing in place of the usage of then(callback). As such, you don't need then inside of any async function.
You do, however, need to treat your own async function as a Promise.
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
    try {
      console.log("Processing POST Loan.");

      // the await eliminates the need for .then
      const res = await fetch(connection.url, {
          method: "POST",
          headers: connection.headers,
          body: data,
      })
      // this code is resumed once the fetch Promise is resolved.
      // res now has a value.
      console.log("Status: ", res.status);
      console.log("StatusText: ", res.statusText);
      return res;
   }
   catch(err) {
     // because the promise could error, it is advised to use
     // try/catch. With a Promise, you would .then(cb).catch(errHandler)
     // but async/await doesn't utilize callbacks.

     // perform error handling or you can bubble it up.
    throw err
}

When calling postLendingApplication(connection, data) make sure that you are either using await, if inside an async function or postLendingApplication(connection, data).then(callback) as the return value will be a Promise.
postLendingApplication(connection, data).then(callback).catch(errHandler)

A: You forget to return form function. return await fetch(connection.url, {
You dont need async-await in then function. You can return res.json()
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
    console.log("Processing POST Loan.");
    return await fetch(connection.url, {
        method: "POST",
        headers: connection.headers,
        body: data,
    }).then(res => {
        console.log("Status: ", res.status);
        console.log("StatusText: ", res.statusText);
        console.log("OK: ", res.ok);
        return res.json();
    });
}


text:
Q: Writing performance critical C# code in C++ I'm currently working on some performance critical code, and I have a particular situation where I'd love to write the whole application in C#, but performance reasons mean C++ ends up being FAR faster.
I did some benchmarking on two different implementations of some code (One in C#, another in C++) and the timings showed that the C++ version was 8 times faster, both versions in release mode and with all optimizations enabled. (Actually, the C# had the advantage of being compiled as 64-bit. I forgot to enable this in the C++ timing)
So I figure, I can write the majority of the code base in C# (Which C# makes very easy to write), and then write native versions of things where the performance is critical. The particular code piece I tested in C# and C++ was one of the critical areas where > 95% of processing time was spent.
What's the recommended wisdom on writing native code here though? I've never written a C# application that calls native C++, so I have no idea what to do. I want to do this in a way that minimizes the cost of having to do the native calls as much as possible.
Thanks!
Edit: Below is most of the code that I'm actually trying to work on. It's for a n-body simulation. 95-99% of the CPU time will be spent in Body.Pairwise().
class Body
{
    public double Mass;
    public Vector Position;
    public Vector Velocity;
    public Vector Acceleration;

    // snip

    public void Pairwise(Body b)
    {
        Vector dr = b.Position - this.Position;
        double r2 = dr.LengthSq();
        double r3i = 1 / (r2 * Math.Sqrt(r2));

        Vector da = r3i * dr;
        this.Acceleration += (b.Mass * da);
        b.Acceleration -= (this.Mass * da);
    }

    public void Predict(double dt)
    {
        Velocity += (0.5 * dt) * Acceleration;
        Position += dt * Velocity;
    }

    public void Correct(double dt)
    {
        Velocity += (0.5 * dt) * Acceleration;
        Acceleration.Clear();
    }
}

I also have a class that just drives the simulation with the following methods:
    public static void Pairwise(Body[] b, int n)
    {
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                b[i].Pairwise(b[j]);
    }

    public static void Predict(Body[] b, int n, double dt)
    {
        for (int i = 0; i < n; i++)
            b[i].Predict(dt);
    }

    public static void Correct(Body[] b, int n, double dt)
    {
        for (int i = 0; i < n; i++)
            b[i].Correct(dt);
    }

The main loop looks just like:
for (int s = 0; s < steps; s++)
{
    Predict(bodies, n, dt);
    Pairwise(bodies, n);
    Correct(bodies, n, dt);
}

The above is just the bare minimum of a larger application I'm actually working on. There's some more things going on, but the most performance critical things occur in these three functions. I know the pairwise function is slow (It's n^2), and I do have other methods that are faster (Barnes-hutt for one, which is n log n) but that's beyond the scope of what I'm asking for in this question.
The C++ code is nearly identical:
struct Body
{
public:
    double Mass;
    Vector Position;
    Vector Velocity;
    Vector Acceleration;

    void Pairwise(Body &b)
    {
        Vector dr = b.Position - this->Position;
        double r2 = dr.LengthSq();
        double r3i = 1 / (r2 * sqrt(r2));

        Vector da = r3i * dr;
        this->Acceleration += (b.Mass * da);
        b.Acceleration -= (this->Mass * da);
    }

    void Predict(double dt)
    {
        Velocity += (0.5 * dt) * Acceleration;
        Position += dt * Velocity;
    }

    void Correct(double dt)
    {
        Velocity += (0.5 * dt) * Acceleration;
        Acceleration.Clear();
    }
};

void Pairwise(Body *b, int n)
{
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            b[i].Pairwise(b[j]);
}

void Predict(Body *b, int n, double dt)
{
    for (int i = 0; i < n; i++)
        b[i].Predict(dt);
}

void Correct(Body *b, int n, double dt)
{
    for (int i = 0; i < n; i++)
        b[i].Correct(dt);
}

Main loop:
for (int s = 0; s < steps; s++)
{
    Predict(bodies, n, dt);
    Pairwise(bodies, n);
    Correct(bodies, n, dt);
}

There also exists a Vector class, that works just like a regular mathematical vector, which I'm not including for brevity.

A: You'll need to interface to the native code.  You could put it in a DLL and pinvoke.  Okay when you don't transition very often and the interface is thin.  The most flexible and speediest solution is to write a ref class wrapper in the C++/CLI language.  Have a look at this magazine article for an introduction.
Last but not least, you really ought to profile the C# code.  A factor of 8 is quite excessive.  Don't get started on this until you at least have half an idea why it is that slow.  You don't want to repro the cause in the C++ code, that would ruin a week of work.
And beware of the wrong instincts.  64-bit code is not actually faster, it is usually a bit slower than x86 code.  It's got a bunch of extra registers which is very nice.  But all the pointers are double the size and you don't get double the cpu cache.
.

A: You have two choices:  P/Invoking and C++/CLI.
P/Invoking
By using P/Invoke, or Platform Invoke, it is possible for .NET (and therefore C#) to call into unmanaged code (your C++ code).  It can be a bit overwhelming, but it is definitely possible to have your C# code call into performance critical C++ code.
Some MSDN links to get you started:

*

*Consuming Unmanaged DLL Functions

*Interop Marshaling

*DllImportAttribute
Basically, you will create a C++ DLL that has defined all the unmanaged functions you want to call from C#.  Then, in C# you will use the DllImportAttribute to import that function into C#.
For instance, you have a C++ project that creates a Monkey.dll with the following function:
extern "C" __declspec(dllexport) void FastMonkey();

You will then have a definition in C# as follows:
class NativeMethods
{
    [DllImport("Monkey.dll", CallingConvention=CallingConvention.CDecl)]
    public static extern void FastMonkey();
}

You can then call the C++ function in C# by calling NativeMethods.FastMonkey.
Few common gotchas and notes:

*

*Spend time learning Interop Marshaling.  Understanding this will greatly help creating proper P/Invoking definitions.

*The default calling convention is StdCall, but C++ will default to CDecl.

*The default character set is ANSI, so if you want to marshal Unicode strings, you will have to update your DllImport definition (see MSDN - DllImport.CharSet documentation).

*http://www.pinvoke.net/ is a useful resource for knowing how to P/Invoke standard Windows functions call.  You can also use that for a clue how to marshal something if you know of a Windows function call that is similar.

C++/CLI
C++/CLI is a series of extensions to C++ created by Microsoft to create .NET assemblies with C++.  C++/CLI also allows you to mix unmanaged and managed code together into a "mixed" assembly.  You can create a C++/CLI assembly that contains both your performance critical code and any .NET class wrapper around it you want.
For more information with C++/CLI, I recommended starting with MSDN - Language Features for Targeting the CLR and MSDN - Native and .NET Interoperability.
I recommend you start with the P/Invoking route.  I have found having a clear separation between unmanaged and managed code helps to simplify things.

A: In C#, is Vector a class or struct?  I suspect it's a class, and Arthur Stankevich hit the nail on the head with his observation that you may be allocating many of these. Try making Vector a struct, or reusing the same Vector objects.

A: Easiest way to do it is create C++ ActiveX dlls.
Then you can reference them in the C# project, Visual Studio will create interops that will wrap the ActiveX COM Object.
You can use the interop Code like C# code, no additional wrapping code.
More about AciveX/ C#:
Create and Use a C++ ActiveX component within a .NET environment

A:
"I did some benchmarking on two
  different implementations of some code
  (One in C#, another in C++) and the
  timings showed that the C++ version
  was 8 times faster"

I did some numerical calculation in C#, C++, Java and a bit of F# and the biggest diffrence between C# and C++ was 3.5.
Profile your C# version and find the bottleneck (maybe there are some IO - related problems, unnecessary allocation)

A: P/Invoke is definitely easier than COM Interop for the simple case. However, if you do bigger chunks of a class model in C++, you might really want to consider C++/CLI or COM Interop.
ATL makes you whip up a class in no time, and once the object is instantiated, the invocation overhead is basically as small as with P/Invoke (unless you use dynamic dispatch, IDispatch, but that should be obvious).
Of course, C++/CLI is the very best option there, but that's not going to work everywhere. P/Invoke can be made to work everywhere. COM interop is supported on Mono up to degree

A: Looks like you are doing a lot of implicit Vector class allocations in your code:
Vector dr = b.Position - this.Position;
...
Vector da = r3i * dr;
this.Acceleration += (b.Mass * da);
b.Acceleration -= (this.Mass * da);

Try reusing already allocated memory.


text:
Q: In Node.js and Mongoose, how can I use a variable in place of a model name? I have a couple of collections with tons of documents, like "all books in the world" and "all movies in the world." To reduce the size of my collections and because there are so many unique properties between the two, I have them as separate collections.
But I have a lot of Node.js functions where the only difference between two functions is the model I am querying on. I would like to make more generic functions to reduce the amount of code.
To greatly simplify the example, I currently have this:
import { Book, Movie } from '../models'

const getBooks = (bookId) => Book.findById(bookId)
const getMovies = (movieId) => Movie.findById(movieId)

And I would like to be able to do something like this, where type would be either 'Book' or 'Movie':
import { Book, Movie } from '../models'
const getItems = (type, itemId) => type.findById(itemId)

I have tried all kinds of things, but the only thing I can get to work is having ternary operators all over the place (which will probably become switch statements when I add additional collections).
Is there a more elegant way of doing this? And if so, recommended? Or does this just point to schema design issues?
This would kind of be like using computed properties, but not for the name of a property, but for the name of the object itself. This does not seem to work"
import { Book, Movie } from '../models'
const getItems = (type, itemId) => [type].findById(itemId)

A: If you could pass the type as the string name of your collection and the number of models doesn't grow every day (if that is not the case you should be always updating the myModels object) the following solution should do the job
import { Book, Movie } from '../models'

const myModels = {
    book: Book,
    movie: Movie,
};

const getItems = (type, itemId) => myModels[type].findById(itemId)

I would suggest doing something if there's a chance that the type passed as a parameter cannot exist.

EDIT
As mentioned via comments by @Meiogordo mapping the Models against the strings would be pointless if you are not going to use the functions outside the data access layer.
import { Book, Movie } from '../models';

const getItems = (model, itemId) => model.findById(itemId);

const book = getItems(Book, 1);
const movie = getItems(Movie, 3);

With this solution, you lose some encapsulation due to the need for requiring the models outside the data access layer, but you are not mapping the models on a separated structure.

A: As discussed via comments, this should work for your use-case:
// Defining the function
const getItems = (model, itemId) => model.findById(itemId)

// And assuming this import
imports { Book, Movie } from '../models';

// You can just call it like so
const book_one = getItems(Book, 1);
const movie_three = getItems(Movie, 3);

The first argument to getItems can just be the Model class itself.


text:
Q: Capitalization in military writing The editor for a book I'm writing tells me that Delta Company should be written Delta company within the text of the story. Examples: (1) "The only thing the old man told me was get on that helicopter and take command of Delta company." (2) "The other flight of choppers will pick up the rest of Delta company."
The limited info that I can find explains that Delta Company may also be written Company D, but not interchangeably in the work. A Marine Corps style guide refers to Company D or Delta Company as proper nouns and that the word company should be capitalized.
Your ideas are appreciated!
Thanks

A: This is a style question, so there is no right answer unless it be that whatever style preference a publishing house insists on is the right answer. Still, there does seem to be a tendency in mainstream U.S. style guides to treat military units (companies, battalions, etc.) as part of a proper name when it appears with a particular identifying word, letter, or number designation.
For example, although Words into Type, third edition (1974), doesn't show any awareness of the Alpha, Bravo, Charlie, Delta alternative designations for companies, it has this general style advice for dealing with military units:

Organizations. Cap the names of organizations of the military. Army, navy, and air force, used as noun and adjective, are not usually capped (army post, navy patrol, air force blue), unless they refer to the official organization of a country (Army policy, Navy officer) or if the name of the country precedes (United States Army, British Navy).
[Relevant examples of unit names:] B Company, Company B

The Associated Press Stylebook (2002) doesn't address the OP's specific question, but it strongly suggests that it, like Word into Type, would favor capitalizing company in the phrase "Delta Company" but lowercasing it when cited generically as "the company":

military units Use Arabic figures and capitalize the key words when linked with the figures: 1st Infantry Division (or the 1st Division), 5th Battalion, 395th Field Artillery, 7th Fleet.
But: the division, the battalion, the artillery, the fleet.

The Chicago Manual of Style, fifteenth edition (2003) takes the same general approach as AP:

8.120 Armies, battalions, and such. Titles of armies, navies, air forces, fleets, regiments, battalions, companies, corps, and so forth are capitalized. Unofficial but well-known names, such as Green Berets, are also capitalized. Words such as army and navy are are lowercased when standing alone, when used collectively, or when not part of an official title.

So the consensus does not favor your editor's view that "Delta company" is preferable to "Delta Company"—but as choster observes in a comment above, that fact won't help you if the editor is enforcing a house style decision that is graven in stone.

A: One would normally consider a Marine Corps style guide as authoritative for a military word or phrase over an editor.  That said, is it really worth a fight with an editor even if they are wrong?


text:
Q: (AMDGPU-PRO) Secondary Screens VGA W/DVI doesn't work but HDMI does So I have R9 380 fresh install of Ubuntu Mate.
Install the AMDGPU Pro drivers.  Op success
Issue:
Secondary Monitor with VGA w/DVI adaptor is detected but gets no signal.
Trouble Shoot: Swapped it out w/32in HDTV and the TV worked with HDMI
Hypnosis:
Some kind of analog issue with AMD.  The secondary monitor with vga w/dvi adaptor works fine on Windows and default amdgpu drivers.
Aspirations:
Someone awesome provides a software solution so I do not have to buy a new secondary non-vga 19" monitor.

A: On my Dell M6700 laptop containing Heathrow XT Radeon HD 7870M with amdgpu-pro 17.10-446706 installed (on kde neon), the external display wasn't being recognised either.
Swapped the VGA cable for a DisplayPort one, problem solved.

A: Since I'm not allowed to comment, I'm having the same issue. Got a  new (to me) tv as a secondary monitor to replace my ancient 4:3 lcd, plugged it in via vga and it won't let me set a 16:9 resolution. Installed the AMDGPU PRO drivers, rebooted and now it doesn't even see the secondary screen as connected. Will uninstall AMDGPU Pro drivers for the time being.


text:
Q: Undefined method with link to next comment Using this post as guidance I am trying to create a link to the next comment on my comments show page. I am getting this error however:
undefined method `next' for #<Comment:0x00000103d59db0>

In my routes comments belong to posts:
resources :posts do
  resources :comments
end

In my posts model I have this:
 def next
   post.comments.where("id > ?", id).order("id ASC").first
end

My comments controller:
@post = Post.find(params[:post_id])
@comment = Comment.find params[:id]
@commentnext = @post.comments.find(params[:id])

and then in my comments show view I have the link:
<%= link_to "Next Comment", post_comment_path(@post, @commentnext.next) %>

A: From the Source you attached,I guess you put the method in wrong model.It should be in Comment model
Try putting this in the Comment model instead of Post model
#comment.rb
def next
   post.comments.where("id > ?", id).order("id ASC").first
end


text:
Q: Swift UI @FocusState triggering NavigationLink Twice What am I doing wrong here? Tapping on the navigation link triggers the navigation, then the focusState value updates, causing body to run and trigger the navigation link again.
How do I prevent the link from being triggered twice causing my destination views init to fire twice?

import SwiftUI

struct ContentView: View {
    @State var text: String = "text"

    @FocusState var focussed: Bool

    @State var isActive: Bool = false

    var body: some View {
        NavigationView {
            List {
                TextField("", text: $text)
                    .focused($focussed)
                    .onChange(of: focussed) { _ in }

                let _ = Self._printChanges()
                NavigationLink("Tap Me", destination: MyViewTwo(), isActive: $isActive)
            }
        }
    }
}

struct MyViewTwo: View {
    init() {
        print("Init Called")
    }

    var body: some View {
        Text("Hello View 2")
    }
}


text:
Q: Using numericUpDown to display panels on certain values I have several panels on a form that I want to appear corresponding to a numericUpDown value.
(ie- panel 1 is visible when the value is 1, panels 1 and 2 are visible when the number is 2, panels 1 2 and 3 are visible when the value is 3, ect)
I am able to get the initial panel to function as expected with my existing code, but the subsequent ones are not appearing or disappearing as I intended. I'm not quite sure why. Is it because the value of the NUP is not updating when it is changed?
Code:

private void petNumNumericUpDown_ValueChanged(object sender, EventArgs e)

    {
        if ((petNumNumericUpDown.Value == 1) || (petNumNumericUpDown.Value == 2) ||(petNumNumericUpDown.Value == 3) || (petNumNumericUpDown.Value == 4) || (petNumNumericUpDown.Value == 5))
        {
            pet1Panel.Visible = true;
        }

        else
        {
            pet1Panel.Visible = false;
        }

        if((petNumNumericUpDown.Value == 2) || (petNumNumericUpDown.Value == 3) || (petNumNumericUpDown.Value == 4) || (petNumNumericUpDown.Value == 5))
        {
            pet2Panel.Visible = true;
        }

        else
        {
            pet2Panel.Visible = false;
        }
    }

I'm looking to have this continue up until 5. Any insight on what I'm doing wrong would be appreciated.

A: You can write simpler code to achieve your goal:
pet1Panel.Visible = (petNumNumericUpDown.Value >= 1);
pet2Panel.Visible = (petNumNumericUpDown.Value >= 2);
...


text:
Q: I want image path through XML in HTML page Can anybody help me, i have 4-5 images in my HTML page but I want to load it through XML. I want code for the same using Javascript or Jquery

A: Could you formulate your question more precisely?
You can do an AJAX call to get your XML via jQuery.get(...), then do something like
 $(xml).find('image').each( function() {
        $(document).append($('<img src="' + $(this).attr('source') + '">;')
  });
in success of your get().
The code above assumes you have <image source="myimage.png"/> kind of tags in your xml... change it accordingly.


text:
Q: Measure of $\lbrace (x_1,...,x_n) \in \mathbb{R}^n : \sum_{k=1}^{n} x_k \leq 1 \rbrace$ I have to determine the measue of $$\Delta_n=\lbrace (x_1,...,x_n) \in \mathbb{R}^n : \sum_{k=1}^{n} x_k \leq 1, x_k \geq 0, k=1,...,n \rbrace$$
The hint that I have is express $\Delta_n$ in terms of $\Delta_{n-1}$.
My attempt was to calculate the case $n = 2$ and $n = 3$, where I got $\frac{1}{2}$ and $\frac{1}{6}$ respectively. From there I could write the measure of $\Delta_n$ as
$$\int_{\Delta_{n-1}}dx_{n-1} \cdots dx_1 \int_{x_n=0}^{1- \sum_{k=1}^{n-1}}dx_n$$
and from there integrate step by step. The problem is that I think it is too long a process and I would like to know if there is a faster way to find the measure of $\Delta_n$.
Note: I was able to write the previous expression since in the cases $n = 2$ I wrote:
$$\int_{x=0}^{1}\int_{y=0}^{1-x}dydx$$
and for the case $n=3$ :
$$\int_{x=0}^{1}\int_{y=0}^{1-x}\int_{z=0}^{1-x-y}dzdydx$$

A: This way, let $f_n(x)$ be (for $x\geqslant 0$ and $n>0$) the measure of $$\left\{(x_1,\ldots,x_n)\in\mathbb{R}_+^n : \sum_{k=1}^n x_k\leqslant x\right\}.$$ Then $f_1(x)=x$ and $f_n(x)=\int_0^x f_{n-1}(x-x_n)\,dx_n$ for $n>1$.
By induction, $f_n(x)=x^n/n!$, and the answer is $f_n(1)=1/n!$.


text:
Q: How to Redirect a Child Popup Window to a Different URL as soon as its loaded? I am using javascript/jQuery to redirecting a child popup window. I am using the following code to redirect it, but it is not working.
 $('#opennewwin').click(function(){
    var strURL =dynurlpath+"start.swe?SWECmd=ExecuteLogin&SWEAC=SWECmd=GotoView&SWEView=Home+Page+View+(WCC)&SWERF=1&SWEBU=1";
    var w = window.open(strURL, 'childwin', 'height=' + screen.height + ',width=' + screen.width + '');

    window.w.location.replace(dynurlpath+"start.swe?SWECmd=GotoView&SWEView=Home+Page+View+(WCC)&SWERF=1&SWEHo="+SWEHo+"&SWEBU=1&SRN="+MySRN1);
}

Here as soon as I enter credentials for login it takes me to a view which is set up as the startup view in the application, though I gave the url of Home Page. I can't change the start up view yet I need to go to the Home Page of the application. So, I thought of achieving the same after loading of the startup view and then redirecting the page to the Home Page.I tried it with this code but it is not working.
I think I am missing how to capture the location of child Popup and redirect it. Any help will be appreciated.
Thanks!!!

A: not much code but i have used javascript, hope it's what you're looking for
function openWin(win)
{
    var win = window.open(win);
    win.location.assign('http://google.co.uk');
}

openWin('url.php');

use window.location.assign and not window.replace


text:
Q: Error Message "Use The New Keyword To Create An Object Instance" I keep having error message at ArrayGroup(count).dateDate = valueListString(0), have no idea what's wrong with the code below, please help.
Structure dataAttribute
    Dim dateDate As Date
    Dim timeString As String
    Dim volString As String
    Dim openString As String
    Dim closeString As String
    Dim minString As String
    Dim maxString As String
End Structure

Private ArrayGroup() As dataAttribute

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)     Handles Button1.Click
    Dim currencyString As String
    Dim valueListString() As String

    currencyString = dataTextFieldParser.ReadToEnd
    RichTextBox1.Text = currencyString

    strArr = currencyString.Split(Environment.NewLine)

    For count = 1 To strArr.Length - 1
        valueListString = strArr(count).Split(";")

        ArrayGroup(count).dateDate = valueListString(0)
        ArrayGroup(count).timeString = valueListString(1)
    Next

End Sub

A: the ArrayGroup probably does actually have items in it.
so before the line ArrayGroup(count).dateDate = valueListString(0) try adding to the array
ArrayGroup(count) = New ... what ever type should be in the array...

A: It does not appear that you have dimensioned you array:
Try

ReDim ArrayGroup(0)

Have a look at ReDim and ReDim Preserve
Private ArrayGroup() As dataAttribute

Just declares that ArrayGroup is an array of type dataAttribute but does not specify how many members are in it.

A: ArrayGroup is Nothing.
the line
Private ArrayGroup() As dataAttribute

does not assign a value to ArrayGroup so it is not instantiated and you'll get the normal with block error when you try to use it.
you probably want to change the end of your function to something like.
    Redim ArrayGroup(strArr.Length - 1) As dataAttribute

    For count = 1 To strArr.Length - 1
         valueListString = strArr(count).Split(";")

          ArrayGroup(count).dateDate = valueListString(0)
          ArrayGroup(count).timeString = valueListString(1)
    Next
End Sub

Note the ReDim. I'm not sure if you need the As.


text:
Q: SSH keys in environment variables So I'm setting up a really awesome hubot setup which will automatically deploy code from github to heroku, via a free heroku nodejs app. I'm having trouble checking out the repo properly on AWS. I created SSH keys on the remote box, had them working and verified it. Then, I added them as Heroku environment variables like this:
~$ heroku config:add PRIVATE_KEY="...
aoijsdfasoidjfasodijfasodifjaodsifjasdofija"

I then try to echo both the public and private keys back to their normal location in .ssh/id_rsa, but they ask me for a passphrase, which I didn't set, and always fail.
Any idea how to successfully write a key to an environment variable? I think it's something to do with the linebreaks not showing up correctly.

A: If you would like to read from the key file, this works:
heroku config:set PRIVATE_KEY="$(cat id_rsa)"

A: AH! Of course.
If you do echo "$VAR" it retains its formatting. Updating my scripts now.
(i had been working on this all day. Thank you rubber duck.)


text:
Q: Is there any kind of annotations like the ones in Java for swift? I was looking for some dependency injection framework for swift(found some: Cleanse, Dip, Swinject, Typhoon) but they don't have what I'm looking for(they only work like: container.getInstance(Class)).
I was looking for something to use DI in constructors, like in java:
property1;
contructor(property1){
 this.property1 = property1;
}

Is there any way to do this in swift?
Is very useful for testing and decoupling
thanks

A: I recently pre-released Weaver, a dependency injection framework which allows you to inject dependencies by annotating your code (https://github.com/scribd/Weaver)
For example, you can do things like this:
final class MoviesViewController: UIViewController {

    private let dependencies: MoviesViewControllerDependencyResolver

    private var movies = [Movie]()

    // weaver: movieManager <- MovieManaging
    // ^ this is how you inject movieManager

    required init(injecting dependencies: MoviesViewControllerDependencyResolver) {
        self.dependencies = dependencies
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // This is how you access to movieManager.
        dependencies.movieManager.getMovies { result in
            switch result {
            case .success(let page):
                self.movies = page.results
                self.tableView.reloadData()

            case .failure(let error):
                self.showError(error)
            }
        }
    }

    // ...
}


text:
Q: Evaluation of this statement I am reading a C book and don't understand this statement it is asking me to evaluate:
!(1 && !(0 || 1))
I can understand some things here... This is what I have so far, not(1 and not(0 or 1))
So is it not 1 and not 0 or 1? Or is it not 1 and 0 or 1? Do those two ! cancel each other out like a double negative? The answer is true but I expected false.
What is the explanation?

A: Use De Morgan's laws to simplify the original expression: !(1 && !(0 || 1)). When you negate a parenthetical logical expression, the negation is applied to each operand and the operator is changed.
!(1 && !(0 || 1))   // original expression
!1 || !!(O || 1)    // by De Morgan's law
!1 || (0 || 1)      // the two !!'s in front of the second operand cancel each other
0 || (0 || 1)       // !1 is zero
0 || 1              // the second operand, 0 || 1, evaluates to true because 1 is true
1                   // the entire expression is now 0 || 1, which is true

The answer is true.
A couple of other answers have said that the parentheses determine order of evaluation. That is wrong. In C, precedence is not the same as order of evaluation. Precedence determines which operands are grouped by which operators. The exact order of evaluation is unspecified. The logical operators are an exception: they are evaluated in strictly left-to-right order in order to enable short-circuit behavior.

A: *

*(0 || 1) == 1

*!1 == 0

*1 && 0 ==  0

*!0 == 1 also known as true :)

Keep in mind that || and && are short circuit operators, but in this case you still have to evaluate the right side because the operators do not short circuit

A: !(1 && !(0 || 1))           =>     not(1 and not(0 or 1))
not(1 and not(0 or 1))      =>     not(1 and (0 and 1))      // !(a or b) = a and b
not(1 and (0 and 1))        =>     not(0)    =>  1  =>  true

A:    !(1 && !(0 || 1))
=> ! (1 && !(1))     //0 || 1 is 1
=> ! (1 && 0)        // !1 is 0
=> !0                // 1 && 0 is 0
=> 1                 // !0 is 1
=>true

A: If A =1 A && B = B. So the final expression inside !(....) is !(!(0 || 1)) which is 0 || 1 and 0 + 1 =1, hence the answer is true.

A: !(1 && !(0 || 1))  =>  !(1 && !(1)) =>  !(1 && !1)  => !(1 && 0) => !(0) => !0 => 1(true)

A: Starting from the deepest nesting and working outwards adding piece by piece;
(0 || 1) = (0 OR 1) = 1

!(0 || 1) = !1 = NOT 1 = 0

1 && !(0 || 1) = 1 && 0 = 1 AND 0 = 0

!(1 && !(0 || 1)) = !0 = NOT 0 = 1

A: To evaluate this, start with the innermost parentheses and work your way out like so:
not(1 and not(0 or 1)) -> not(1 and not(1)) -> not(1 and 0) -> not(0) -> 1 -> true.

A: !(1 && !(0 || 1))

since 0 || 1 evaluates as 1, is the same as
!(1 && !1)

continue
!(1 && 0)

continue
!0

so it's 1, true.

A: (0 || 1) --> 1

! 1      --> 0

1 && 0   --> 0

! 0     -- > 1

Answer true

A: It easy if you remember about which operation order
 !(1 && !(0 || 1)) = !(1 && !(1)) = !(1 && 0) = !(0) = 1


text:
Q: Issue with retrieving some values out of my Database <?php
include 'session.php';
?>

<link href="css/adminOpmaak.css" rel="stylesheet" type="text/css"/>
<?php
        mysql_connect("localhost", "admin", "") or die(mysql_error());
        mysql_select_db("test") or die(mysql_error());
?>

<form action="Login.php" method="POST">

<input type="text" align="center" name="Account"  value="<?php echo isset     ($_POST['Account'])?$_POST['Account']:"";?>"/>

<input type="text" align="center" name="Password" value="<?php echo isset    ($_POST['Password'])?$_POST['Password']:"";?>" />

<input type="submit" name="Login" value="Login"/>

<?php
if(isset ($_POST ['Login']))
{
    $querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';";
    $result = mysql_query($querystring);

    mysql_query($querystring)or die (mysql_error());

    if (empty($_POST['Account']) || empty($_POST['Password']))
    {
        echo "niet alles is ingevoerd";

    }
    elseif (mysql_num_rows($result) == 1)
    {
        $user = mysql_fetch_assoc($result);
    }
    else
    {
        echo "dit account bestaat niet";
    }

    if(md5($_POST['Password']) != $user['Password'])
    {
        echo "wachtwoord is niet correct";?>
 <?php
        echo "Het account is:".$user['Account'];?>
 <?php
        echo "het wachtwoord is: ".$user['Password'];?>
 <?php
        echo mysql_fetch_assoc($result);
    }
}
?>
</form>

It's kinda strange since he does recognize the $user['Account'];
and he doesnt recognize the password version.
My database has the right values. This is what he echo's:
wachtwoord is niet correct
Het account is:Probeersel
het wachtwoord is:

So I dont know why he DOES recognize the account but he doesn't recognize wachtwoord. Why is that?

A: There are a few problems.
First, your mysql statement is wrong.
Change this:
$querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';";

To this:
$querystring ="SELECT * FROM Admins WHERE Account ='" .$_POST['Account']. "'";

Next, for one test, echo out the account name and password that you get from the db query, just so you can make sure you are getting what you expect (perhaps the capitalization is wrong for the field name or something like that).
$user = mysql_fetch_assoc($result);
echo 'Got this username: ' .$user['Account']. '
';
echo 'Got this password: ' .$user['Password']. '
';

Once you have confidence that you are getting the correct data, then you can finish your script.

This:
if(md5($_POST['Password']) != $user['Password'])
{
    echo "wachtwoord is niet correct";?>
 <?php
    echo "Het account is:".$user['Account'];?>
 <?php
    echo "het wachtwoord is: ".$user['Password'];?>
 <?php
    echo mysql_fetch_assoc($result);
}

Can be re-written as:
if(md5($_POST['Password']) != $user['Password'])
{
    echo "wachtwoord is niet correct
";
    echo "Het account is: " .$user['Account']. "
";
    echo "het wachtwoord is: " .$user['Password']. "
";
}


text:
Q: Adding  to my code breaks the stickyness of my footer Adding <!DOCTYPE html> is breaking my CSS only sticky footer meaning that as soon as I add it, the footer does not stick to the bottom of a web page anymore.
Following is a working example without the <!DOCTYPE html>.
Doing further tests I've noticed that when not declaring the page as HTML5 by adding the DOCTYPE statement, the div with CSS class wrapper is able to be stretched to take the full document height thus pushing the footer to the bottom. This is not happening when declaring the document as HTML5.
https://jsfiddle.net/muvwh4zn/

        body {
            background-color: #f0f0f0;
        }

        .navbar {
            background-color: #444;
            width: 100%;
        }

        .footer {
            background-color: #444;
            width: 100%;
            height: 50px;
        }

        html,
        body {
            height: 100%;
            margin: 0;
        }

        .wrapper {
            min-height: 100%;
            margin-bottom: -50px;
            padding: 0px 0px 80px 0px;
        }
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

                        HEADER

                    BODY

                    FOOTER

Please also see my own comment just below for a possible solution to this issue.

A: Add flexibility to the container class. Your footer will always be pinned to the bottom.
https://www.w3.org/QA/2002/04/valid-dtd-list.html
.container {
   display: flex;
   flex-direction: column;
   justify-content: space-between;
   height: 100%;
}

        body {
            background-color: #f0f0f0;
        }

        .container {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
        }

        .navbar {
            background-color: #444;
            width: 100%;
        }

        .footer {
            background-color: #444;
            width: 100%;
            height: 50px;
        }

        html,
        body {
            height: 100%;
            margin: 0;
        }

        .wrapper {
            min-height: 100%;
            margin-bottom: -50px;
            padding: 0px 0px 80px 0px;
        }

        .push {
            height: 50px;
            z-index: -1;
        }
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

                        header

                    BODY

                    FOOTER


text:
Q: how to diagonally reduce box size when scroll down $(function(){
var navIsBig = true;
var $nav = $('#header_nav');

$(document).scroll( function() {
    var value = $(this).scrollTop();

    if ( value > 50 && navIsBig ){
        $nav.animate({height:45},"medium");
        $('.box').animate({height:36},"medium");
        $('.box').animate({width:78},"medium");
        navIsBig = false;

    }
    else if (value <= 50 && !navIsBig ) {
       $nav.animate({height:80},"medium");
         $('.box').animate({height:53},"medium");
        $('.box').animate({width:104},"medium");
        navIsBig = true;
    }
});
});

Here box reduce its size, first it height and then its width. But i want to reduce its size diagonally...
http://jsfiddle.net/9fact/466/

A: You can animate both properties:
DEMO jsFiddle
$('.box').animate({height:36, width:78});


text:
Q: Multiple autocomplete in same page with different source in angular 4 with angular material Multiple autocomplete in same page with different source in angular 4 with angular material:
source :https://material.angular.io/components/autocomplete/examples
I have followed the material autocomplete example and trying to add one more autocomplete in the same page but the source is different but not working.
Is formcontrol is creating problem ??

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
  selector: 'autocomplete-overview-example',
  templateUrl: 'autocomplete-overview-example.html',
})
export class AutocompleteOverviewExample {
  stateCtrl: FormControl;
  testCtrl: FormControl;
  filteredStates: any;
  filterTests:any;
tests = [
    'Nawab',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California'];
  states = [
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California',
    'Colorado',
    'Connecticut',
    'Delaware',
    'Florida',
    'Georgia',
    'Hawaii',
    'Idaho',
    'Illinois',
    'Indiana',
    'Iowa',
    'Kansas',
    'Kentucky',
    'Louisiana',
    'Maine',
    'Maryland',
    'Massachusetts',
    'Michigan',
    'Minnesota',
    'Mississippi',
    'Missouri',
    'Montana',
    'Nebraska',
    'Nevada',
    'New Hampshire',
    'New Jersey',
    'New Mexico',
    'New York',
    'North Carolina',
    'North Dakota',
    'Ohio',
    'Oklahoma',
    'Oregon',
    'Pennsylvania',
    'Rhode Island',
    'South Carolina',
    'South Dakota',
    'Tennessee',
    'Texas',
    'Utah',
    'Vermont',
    'Virginia',
    'Washington',
    'West Virginia',
    'Wisconsin',
    'Wyoming',
  ];

  constructor() {
    this.stateCtrl = new FormControl();
    this.filteredStates = this.stateCtrl.valueChanges
        .startWith(null)
        .map(name => this.filterStates(name));
        this.testCtrl = new FormControl();
    this.filteredTests = this.testCtrl.valueChanges
        .startWith(null)
        .map(name => this.filterTests(name));
  }

  filterStates(val: string) {
    return val ? this.states.filter(s => s.toLowerCase().indexOf(val.toLowerCase()) === 0)
               : this.states;
  }
  filterTests(val: string) {
    return val ? this.tests.filter(s => s.toLowerCase().indexOf(val.toLowerCase()) === 0)
               : this.tests;
  }

}

/**  Copyright 2017 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */
<md-input-container>
  <input mdInput placeholder="State" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>

<md-autocomplete #auto="mdAutocomplete">
  <md-option *ngFor="let state of filteredStates | async" [value]="state">
    {{ state }}
  </md-option>
</md-autocomplete>
<md-input-container>
  <input mdInput placeholder="Test" [mdAutocomplete]="auto" [formControl]="testCtrl">
</md-input-container>

<md-autocomplete #auto="mdAutocomplete">
  <md-option *ngFor="let test of filteredTests | async" [value]="test">
    {{ test }}
  </md-option>
</md-autocomplete>

A: You have the same reference variable (#auto) assigned to both inputs. The id needs to be unique for each input. Change your second input and md-autocomplete to following:
<md-input-container>
  <input mdInput placeholder="Test" [mdAutocomplete]="autoTest" [formControl]="testCtrl">
</md-input-container>
<md-autocomplete #autoTest="mdAutocomplete">
  <md-option *ngFor="let test of filteredTests | async" [value]="test">
    {{ test }}
  </md-option>
</md-autocomplete>

Link to Plunker Demo

For cycles like *ngFor there is no need to create dynamically named template variable, since

Template reference variables are scoped to the template they are
  defined in. A structural directive creates a nested template and,
  therefore, introduces a separate scope. (This question)


text:
Q: Undefined is not a function with a combobox I have got the Uncaught TypeError: undefined is not a function in this line
$('.for_checkbox select').combobox();

What does it mean? The combobox is filled correctly. What is wrong?

A: Please make sure all of those lines i provide appear in your html file
<link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
<script type="text/javascript" src="easyui/jquery.min.js"></script>
<script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>

That must be the only reason it fails, except for 1 other.
Please be sure that $('.for_checkbox select') returns an element and not an empty array.
You can do it by opening your web application in Chrome/Firefox, Hit F12 and go to Console.
Inside the console, paste $('.for_checkbox select') and hit enter.
If the result is [], that means that the element could not be found and that is the issue, otherwise, the import line codes are missing.
Links for import + documentation can be found HERE

A: I'm not actually sure if jQuery UI's autocomplete set includes combobox(). Maybe that is just a custom demo they had on their site. I had to copy their source code into mine (combobox.js for the jQuery extension, and their CSS for it into my CSS file), and that is the only way I could get it to work.


text:
Q: How to replace href url without having all & replaced by a & I'm trying to replace a few empty href="" statements with computed URL's on pageload.
The replacement string, however, contains several &amp's, which need to be in the href.
What ever I try, as soon as setAttribute("href", url); or $(id).attr('href', url) is used, all &amp's are replaced by a & and the links fail.
How can I prevent this from happening? I'm pretty sure any code that ends in .href or contains href is going through a translation stage and will all fail.
You might have noticed that I've edited this message a lot of times because you simply cannot type a full '& a m p ;' in this box without it being translated to a '&' here too.

A: Let's step back a bit, and think about this from the ground up. The escape sequence &xxx; is the way to embed "special characters" into an HTML document. To be clear, it is an HTML escape sequence.
This way of escaping characters is useful because it means characters can be placed into an ASCII file that would otherwise be impossible to embed.
For example, the Euro sign (€) can be embedded using a numeric code representing its Unicode codepoint €. Or, a non-breaking space can be embedded using its character entity name,  . (Aside: these characters would be easier to embed in a UTF-8 file, with no escaping needed, but that's beside the point here)
Now, because this escape sequence always begins with an ampersand, it means that a bare ampersand in an HTML document is ambiguous - as the browser reads through the document it doesn't know if you want an actual ampersand or whether there's an HTML entity escape sequence coming up. To remove this ambiguity, if you want to embed an ampersand in an HTML document then you need to escape it.
Let me highlight that sentence: To remove this ambiguity, if you want to embed an ampersand in an HTML document then you need to escape it.
Because this escaping only applies to HTML documents, if you are writing Javascript in a .js file then this escape sequence is irrelevant to you. You can just drop your ampersands in unescaped and there's no problem. What it means is, your Javascript files can replace the URLs with bare ampersands, no & needed.
As far as the browser is concerned, all of those URLs you write only contain bare ampersands. The escape sequence & is only needed to express those in HTML form, as soon as the browser has read the HTML then that escape sequence is forgotten about.
I've repeated myself a few times here but that's because I've tried to make it as clear as possible.

A: You have to replace & with & in the url, prior to setting href property of an a tag.
var url = 'www.example.com?a=1&b=2'
url = url.replace(/\&/g, '&')
$('a').attr('href', url)


text:
Q: Xcode 4.3 Passing Variables between Views Xcode 4.3 Storyboard query
Hi, I'm relatively new to Xcode and am completely confused by the variety of solutions to this innocuous question, none of which are working for me in a Storyboard setup. In most non Obj C languages this is a three line solution.
If I have variable X in view A how do I pass X to view B intact?
Could someone point me to robust solution for a limited number of variables in Xcode 4.3 using Storyboards.
I have another similar query at the other end of the spectrum where I need to pass several hundreds of pieces of data to other views. Do I write then to a temp file...
TIA

A: HY, You need implement in the sender view controller the:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
 //...//
}

function, and you can pass the data in the function body like:
(ImageController *)( segue.destinationViewController).property=passed_data;


text:
Q: How to use resource file for displaying column name in JQ grid As by default the "colNames" property of the JQgrid displays the names that we harcode there like:
colNames: ['ProductID'],
                //columns model
                colModel: [
                            { name: 'ProductID', index: 'ProductID', align: 'left', search: true, stype: 'text', searchoptions: { sopt: ['eq', 'ne'] } },
                           ],
As here the "ProductID" in colnames property is harcoded here. Now my requirement is that this value should not be hard coded instead it should get the value from .resx file where we are maintaning the Translations.
Can we acheive this in jqgrid??

A: After reading of your question and thinking about all problems I made some minor changes in the localization files, made this and this demos and posted the feature request in the trirand forum. In the second demo I use less known column templates which was implemented in jqGrid based on one from my previous feature requests. The usage of templates can reduce and the length of JavaScript code used jqGrid and simplify it.
In your case you can probably simplify my demos and load all column headers (or lables of colModel) and the grid title (the caption) from the resource file. You can choose the language based on headers of the HTTP requests (Accept-Language) received from the client.
The exact implementation on the server side will be very depend on the technology which you use on the server.


text:
Q: IMNSHO the inmates are running the asylum == an appeal process is required Call me biased:
https://stackoverflow.com/questions/2590604/are-there-code-signing-certificates-cheaper-than-us-99-per-year-closed
The comment (reason for closing):
Questions on Stack Overflow are expected to generally relate to programming or software development in some way, within the scope defined in the faq.
IMNSHO, this reason is silliness. As a programmer security and money are both important to me. On the one hand, I want to secure freeware that I intend to distribute;
OTOH, it's been a very tough economy and I wish to get the lowest price that I can.
So,
(a) how does one reopen a closed question?
(b) why is this closing process so much like
 ~~ convicting the accused without her/his right to a fair trial?
(c) WHY does this closing mechanism even exist?
If the question is spam, then moderators can delete it;
OTOH, it is just is a question that few are interested in,
THEN simply ignore it.
This allowing the inmates to run the Stack Overflow asylum simply creates such an unfriendly environment than community members with skin less thick than mine will likely go away and never return!
[2010 May 5] Here is just one more reason why I still strongly believe that the inmates are still running the asylum:
https://stackoverflow.com/questions/2772864/how-do-i-contact-microsofts-legal-department-by-e-mail-and-or-phone-regarding-t
-- there is such negativity here at Stack Overflow
~~ In case you're wondering why I do not sulk off into the woods and die, it's because I'm fool enough to believe that if Jeff Atwood steps forward and sets a more positive tone, that such a tone will become contagious.  That said, I must credit Jeff Atwood with setting the reputation floor at +1 ~~ otherwise I'd likely be in the hole, as would so many others.  I wish I knew how many develpers from novice to very senior have be driven away from Stack Overflow by all of this negativity.  IMO, the negativity at Stack Overflow can be toxic.  Fortunately, it's not infected everyone.  There are Stack Overflow members who actually do their best to be helpful; to those members, I offer a very sincere "Thank you".

A: A couple of points before I answer your points:

*

*Just because something is interesting to a programmer does not mean it is relevant to the site. One could make the same argument about the question "What is the best place to get my morning coffee?".

*Starting a question critizing most of the high-rep users with "imnsho" is not, perhaps, the most tactful method I could think of.

Now:

*

*"How does one reopen a closed question?"
By getting five people to reopen it. It's the same as closing, but in reverse.

*"Why is this closing process so much like convicting the accused without her/his right to a fair trial?"
Well, for one thing, the appeals process starts as soon as the question is closed, and often without further intervention from the original poster.

*"WHY does this closing mechanism even exist?"
Two words: Yahoo! Answers.
"If the question is spam, then moderators can delete it; otoh, it is just is a question that few are interested in, THEN simply ignore it."
Yes, and most of the moderation is delegated to high-rep users (and who said moderators are infallible, anyway?). The process has already started for your question. I do not recall seeing questions closed simply because of lack of interest. If anything, such a question would survive longer, because fewer potential closers would see it.
I was going to address your question in particular next, but I see that Bill the Lizard has covered that aspect already. I was just going to say that it's a borderline case.

A:
why is this closing process so much
  like ~~ convicting the accused without
  her/his right to a fair trial?

You had a fair trial.  When you posted your question, it included a implied assertion from you that you believed your question was on-topic, well written, objective, not offensive, and not a duplicate of existing questions.
A jury of five of your peers read your question and decided that they disagreed with your implied assertion and voted to close.

A: Having read the question, it really doesn't pass the "peanut butter sandwich" test.

The little quip I have for this situation is, "Yes what you are saying is true of [programming] but it's also true of peanut butter sandwiches."

Stated another way, "where do I get the cheapest X" is awfully generic. I can think of a few ways this question could perhaps be restated that would (perhaps) be more palatable to the community, such as

Is it really worth $99 to get my code signed? Does signing the code I have written confer any benefits to my users?

Of course such questions have been asked in various forms as well...
https://stackoverflow.com/search?q=%22code+signing%22

A: I'd call that a righteous close.  You're asking about the price of the certificate, not its utility to a programmer.  As a rule of thumb, if your question doesn't involve the act of writing code, it's subject to closing.  A lot of borderline questions get through, but not all of them make it.
I will try to address your points though:

how does one reopen a closed case?

The same way it was closed in the first place, the community votes on it.

why is this closing process so much like
  ~~ convicting the accused without her/his right to a fair trial?

Well, this is the Internet, not a U.S. court of law, so I'm not sure where you got the idea that have a right to a fair trial.  You do have the right to edit your question to make it more on-topic though, and you can leave comments telling why you think it already is.  So I guess in a way you can argue your case.  (Or, as already pointed out, you can discuss it here on meta.)

WHY does this closing mechanism even exist?
  if the question is spam, then moderators can delete it;
  otoh, it is just is a question that few are interested in,
  THEN simply ignore it.

Moderators tend to stay out of borderline cases, preferring instead to let the community decide what it wants to allow.  If it were spam, we would delete it.  This question is only closed, which means it has a chance of being reopened by the community.  If it's just a question that few are interested in, then it eventually will be deleted.  Ignoring questions that are off-topic isn't how we handle things here.  That's why Stack Overflow hasn't turned in to Yahoo! Answers.  By keeping it on topic, we keep the site useful to the core audience.

A: Keep in mind that the "inmates" you refer to have spent at least 30 hours over at least 15 days to vote on closing questions, and that it requires at least 5 of them to do so (assuming it takes about an hour to get 100 rep, which is faster than typical).  So for any given question to be closed, you have to have people that together have accrued 150 hours of actively answering questions on Stackoverflow, and 75 days of usage on the site.  That's a total of 15,000 reputation that is needed to close a question, spread out among 5 people.
The people who closed your question, however, have together accrued over 40,000 reputation, which together likely required over 500 man-hours of actively answering questions - the equivalent of 12 weeks of full time work.  Together they have been active users of stackoverflow for nearly 4 years.
These "inmates" are exactly who we want closing questions.


text:
Q: character encoding problem - cross-domain scripting I have an Asp.Net web app which users include a script tag in their web page, and
get data from my server (using JsonP & a Generic handler (ashx))
The data is in hebrew, and I set the charset to utf-8 in the response.
When the client web site (which displays the data) uses "windows-1255"
I don't see the text properly.
The script can be included in any web page with any character set.
Do I need to convert my data or set the response charset property differently?
Thanks
Yaron

A:
When the client web site (which displays the data) uses "windows-1255" I don't see the text properly.

Yeah. Here's the thing: when you are serving <script>, you can set the 'charset' parameter in the response's Content-Type to anything you like, but IE will ignore you and use the encoding of the origin page instead. (Maybe some other browsers too.)
So if you're doing JSONP or another script-tag-based means of pulling in data, that data must be either in the same encoding as the origin page, or plain ASCII. If you are providing an external service for many web pages in potentially different encodings, you must stick to ASCII.
That means your JSON encoder must convert all non-ASCII characters in string literals to their JS-escaped form, for example \u20AC instead of a raw €.

A: Its probably better that you specify clearly to your clients that your interface uses UTF-8 encoding.  When they forward your data down to their clients they should set the Response.CharSet to UTF-8.  Of course you are alreadying doing that on your end right?