text:
Q: If $|x| := \sqrt{|x|_1^2 + |x|_2^2}$ on $E$, then $\|f\|^2 = \min_{g\in E'} \left [ \|f - g \|_1^2 + \|g\|_2^2 \right ]$ on its dual $E'$ In solving this exercise, I come across below question.

Let $(E, |\cdot|_1)$ be a n.v.s and $(E', \| \cdot \|_1)$ its dual. Let $|\cdot|_2$ be an equivalent norm of $|\cdot|_1$ on $E$ and $\| \cdot \|_2$ its dual norm on $E'$. We define a new norm $|x| := \sqrt{|x|_1^2 + |x|_2^2}$ on $E$ and let $\| \cdot \|$ be its dual norm on $E'$. Then
$$
\|f\|^2 = \min_{g\in E'} \left [ \|f - g \|_1^2 + \|g\|_2^2 \right ].
$$
If ether $\| \cdot \|_1$ or $\| \cdot \|_2$ is strictly convex, then so is $\| \cdot \|$.

Could you have a check on my attempt?
I post my proof separately as an answer below. This allows me to subsequently remove this question from unanswered list.

A: First, we need some auxiliary results.

Let $(E, |\cdot|)$ be a normed linear space and $(E', \| \cdot \|)$ its dual. Let $\varphi, \psi:E \to (-\infty, +\infty]$ such that $\varphi, \psi \not\equiv +\infty$. The conjugate $\varphi':E' \to (-\infty, +\infty]$ of $\varphi$ is defined as
$$
\varphi'(f) := \sup_{x\in E} [ \langle f, x \rangle - \varphi(x)], \quad \forall f \in E'.
$$
The conjugate $\psi'$ of $\psi$ is defined similarly. The inf-convolution of $\varphi$ and $\psi$ is defined by
$$
(\varphi \nabla \psi)(x) := \inf_{y\in E} [\varphi(x-y) + \psi(y)], \quad \forall x\in E.
$$
Lemma 1: $\|f\|^2 = \sup_{x\in E} \left [ 2 \langle f, x \rangle - |x|^2 \right ]$ for all $f\in E'$. A proof can be found here.
Lemma 2: Assume $\varphi, \psi$ are convex, and there exists $x_0 \in E$ such that $\varphi(x_0), \psi(x_0) \neq +\infty$ and that $\varphi$ is continuous at $x_0$. Then
$$
(\varphi+\psi)' = ( \varphi' \nabla \psi') \quad \text{on} \,\, E'.
$$
This is Ex 1.23.3 in Brezis's book of Functional Analysis.
Lemma 3: The space $E$ is strictly convex if and only if the map $x \mapsto |x|^2$ is strictly convex. A proof is given here.

We have $|\cdot|_1$ is equivalent to $|\cdot|_2$ if and only if $\|\cdot \|_1$ is equivalent to $\|\cdot\|_2$. There exist $\alpha, \beta >0$ such that $\alpha \|f\|_2 \le \|f\|_1 \le \beta \|f\|_2$. Let $\varphi(x) := |x|_1^2$ and $\psi(x) := |x|_2^2$. By Lemma 1,
$$
\|f/2\|^2 = \sup_{x\in E} \left [ \langle f, x \rangle - |x|^2 \right ] = \sup_{x\in E} \left [ \langle f, x \rangle - \varphi(x) - \psi(x) \right ] = (\varphi + \psi)'(f).
$$
Also by Lemma 1, $\varphi'(f) = \sup_{x\in E} \left [ \langle f, x \rangle - |x|_1^2 \right ] = \|f/2\|_1^2$. Similarly, $\psi'(f) = \|f/2\|_2^2$. By Lemma 2:
$$
(\varphi + \psi)'(f) = ( \varphi' \nabla \psi')(f) = \inf_{g\in E'} \left [ \|f/2 - g/2 \|_1^2 + \|g/2\|_2^2 \right ].
$$
It follows that
$$
\|f\|^2 = \inf_{g\in E'} \left [ \|f - g \|_1^2 + \|g\|_2^2 \right ].
$$
Consider $\Psi_f: g \mapsto  \|f - g \|_1^2 + \|g\|_2^2$. If $\|g\|_2 \ge \|f\|_2$, then
$$
\Psi_f(g) \ge \alpha^2 \|f - g \|_2^2 + \|g\|_2^2 \ge (\alpha^2+1) \|g\|_2^2 - \alpha^2 \|f\|_2^2 \ge \|f\|_2^2 = \Psi_f(f).
$$
Let $G_f:=\{g\in E' ; \|g\|_2 \le \|f\|_2\}$. Then
$$
\|f\|^2 = \inf_{g\in G_f} \Psi_f(g).
$$
Because the norm of dual space is l.s.c. in weak$^\star$ topology, so is $\Psi_f$. By Banach-Alaoglu theorem, the set $G_f$ is compact in weak$^\star$ topology, so
$$
\|f\|^2 = \min_{g\in G_f} \Psi_f(g) = \min_{g\in E'} \left [ \|f - g \|_1^2 + \|g\|_2^2 \right ].
$$
Now we assume that $\| \cdot\|_1$ is strictly convex. By Lemma 3, we need to prove that the map $f \mapsto \|f\|^2$ is strictly convex. Let $t \in (0, 1)$ and $f,h\in E'$ such that $f \neq h$. Let $g,g'$ be the minimizers of $\Psi_f$ and $\Psi_h$ respectively. Then
\begin{aligned}
  & \|tf+(1-t)h\|^2 \\
\le & \left \|[tf+(1-t)h] - [tg+(1-t)g'] \right\|_1^2 + \|tg+(1-t)g'\|_2^2 \\
= & \left \| t(f-g)+(1-t)(h-g') \right\|_1^2 + \|tg+(1-t)g'\|_2^2 \\
< & t \| f-g\|_1^2 + (1-t) \| h-g' \|_1^2 + t\|g\|_2^2 + (1-t)\|g'\|_2^2  \text{ because } \| \cdot\|_1 \text{ is strictly convex}\\
= & t\|f\|^2 + (1-t) \|h\|^2.
\end{aligned}
This completes the proof.


text:
Q: Playing MP3 files with Python I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it has too much in the way of documentation. Are there any other alternatives?

A: There is http://pyglet.org/ and also have you tried http://code.google.com/p/mp3play/? It's also available from PyPi (http://pypi.python.org/pypi/mp3play/) However, I think mp3play is Win32 only for now.
Looking at the updates, there were commits within last couple of months.

A: I've been using PyMedia in Python 2.6.5 on Windows successfully. Caveats: the documentation is bad and wrong -- many of the tutorials have glaring errors or otherwise don't work -- so I had to do some experimentation and Googling to get my code to work right. Also for whatever reason the maintainers seem to have stopped updating the project site 4 years ago, though they seem to be actively doing something.
I found installers here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
The semi-active forum linked from their website includes some code maintainers who are semi-helpful. I'm jboyd99 if anyone is looking for tips.
For reasons that are beyond me the focus is on car audio systems, despite the fact that it is a fairly fully featured library that does some things no other free Python library does, like read MP3s into raw PCM data. The library has some flaws -- I'll probably use PyAudio or PyAudiere for actual playback for better control of synchrony issues.

A: Maybe it'd be simpler to write that part of your application in Python 2.4 as a separate "backend". This way you could use PyMedia (http://pymedia.org/) (as you mentioned) for the actual playback. It'd allow you to write your GUI in another Python version (like 2.6), which would also mean more decoupling of program components and parallelism (smoother GUI).
If you target only the Windows platform, then using Media Player via COM might help:
http://www.daniweb.com/code/snippet216465.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Most idiomatic way to group structs? I'm trying to group together a set of structs by multiple keys. In the example below, cats are grouped together with their age and name used as the key. Is there a more idiomatic, generic or just a better way to do this in Go?
I need to apply "group by" for multiple types of different structs, so this could get very verbose.
http://play.golang.org/p/-CHDQ5iPTR
package main

import (
    "errors"
    "fmt"
    "math/rand"
)

type Cat struct {
    CatKey
    Kittens int
}

type CatKey struct {
    Name string
    Age  int
}

func NewCat(name string, age int) *Cat {
    return &Cat{CatKey: CatKey{Name: name, Age: age}, Kittens: rand.Intn(10)}
}

func GroupCatsByNameAndAge(cats []*Cat) map[CatKey][]*Cat {
    groupedCats := make(map[CatKey][]*Cat)
    for _, cat := range cats {
        if _, ok := groupedCats[cat.CatKey]; ok {
            groupedCats[cat.CatKey] = append(groupedCats[cat.CatKey], cat)
        } else {
            groupedCats[cat.CatKey] = []*Cat{cat}
        }
    }

    return groupedCats
}

func main() {
    cats := []*Cat{
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
        NewCat("Leeroy", 12),
        NewCat("Doofus", 14),
    }

    groupedCats := GroupCatsByNameAndAge(cats)

    Assert(len(groupedCats) == 2, "Expected 2 groups")
    for _, value := range groupedCats {
        Assert(len(value) == 5, "Expected 5 cats in 1 group")
    }

    fmt.Println("Success")
}

func Assert(b bool, msg string) {
    if !b {
        panic(errors.New(msg))
    }
}

A: Here is a more idiomatic version of the GroupCatsByNameAndAge function.  Note that a if groupedCats doesn't have a cat.CatKey then groupedCats[cat.CatKey] will be nil, however nil is a perfectly acceptable value for append. Playground
func GroupCatsByNameAndAge(cats []*Cat) map[CatKey][]*Cat {
    groupedCats := make(map[CatKey][]*Cat)
    for _, cat := range cats {
        groupedCats[cat.CatKey] = append(groupedCats[cat.CatKey], cat)
    }
    return groupedCats
}


text:
Q: NSolve Evaluated Too Early Inside NExpectation Motivation / Context
I'm working on an economic model which, for present purposes, we can think of as a mapping from parameters to results. Some of the parameters are fixed and given, while others are assumed to be random variables with a known distribution. I would like to calculate the expected value of the results of the model.
Structure of Problem
I've written a simpler outline of my project, which preserves the structure of my approach. var1 is constant that I choose, while var2 has a Log Normal distribution. Given var1 and var2, I have an equation in one variable that I solve using NSolve. I want to calculate the expectation of soln (the solution to the equation) over the distribution of var2 using NExpectation. I can get this to work when the equation solved by NSolve can be solved symbolically, but not when it cannot. I think this happens because NSolve is evaluated before being mapped over whatever table of values is used for numerical integration.
Working Example of Problem
(*Example of the problem*)
Clear[dBeta, solnEquation, solnFun, modelMoment];

dBeta[k_Integer, x_, var1_] =
  Derivative[k, 0][Beta[#1, #2, 2] &][x, var1];
solnEquation[var1_, var2_, x_] :=
  Sum[Binomial[5, k]*dBeta[k, x, var1]*var2^k, {k, 0, 5}];

solnFun[var1_, var2_] :=
  x /. NSolve[
      solnEquation[var1, var2, x] == Beta[var1, 2] && 0 < x < 1, x,
      Reals][[1]][[1]];

modelMoment[var1_, mu_, sigma_] :=
  NExpectation[solnFun[var1, var2],
   Distributed[var2, LogNormalDistribution[mu, sigma]]];

solnFun[2, 1/10]
testMoment[2, 1/10, 1/20]

(*Variation with no problem *)
Clear[solnEquation, solnFun]
solnEquation[var1_, var2_, x_] := var1 - var2 + x;

solnFun[var1_, var2_] :=
  x /. NSolve[solnEquation[var1, var2, x] == 0, x, Reals][[1]][[1]];

solnFun[2, 1/10]
testMoment[2, 1/10, 1/20]

output below
0.328152
This system cannot be solved with the methods available to NSolve.
{-20 var2^3+10 var2^2 (1-2 x)+5 var2 (1-x) x+Beta[x,2,2]==1/6} is
neither a list of replacement rules nor a valid dispatch table, and
so cannot be used for replacing.
...
"Further output of \!\(\* StyleBox[RowBox[{\"ReplaceAll\", \"::\", \"reps\"}], \"MessageName\"]\) will
be suppressed during this calculation."
NExpectation[  x /. -20 var2^3 + 10 var2^2 (1 - 2 x) + 5 var2 (1 - x) x +
    Beta[x, 2, 2] == 1/6,   var2 \[Distributed] LogNormalDistribution[1/10, 1/20]]

-1.9
-0.893447

In both cases, solnFun can be evaluated successfully. In the first case, the NExpectation attempt fails, in the second case, it works. I think the difference between the two examples is that the NSolve inside of SolnFun is evaluated before any specific values for var2 are given to it by NExpectation. If a closed form solution exists for symbolic equation, then no error messages appear. But in my project NSolve cannot provide a solution until after it has a specific value for var2.
Question
Is there some way I can get NSolve to be evaluated after the equation has been mapped over whatever table of values NExpectation uses to perform the numeric integration?
I'm new to MMA, so in addition to help with this main problem, I would appreciate any other tips or references on better programming style or approaches.

A: Pragabhava's guess is correct: it is indeed the well-known _?NumericQ issue.
Basically you need to define solnFun as solnFun[var1_?NumberQ, var2_?NumberQ] := .... Incorporating also a workaround for NSolve bug, your code can be rewritten as follows:
Clear[dBeta, solnEquation, solnFun];

dBeta[k_Integer, x_, var1_] = Derivative[k, 0][Beta[#1, #2, 2] &][x, var1];
solnEquation[var1_, var2_, x_] = Sum[Binomial[5, k]*dBeta[k, x, var1]*var2^k, {k, 0, 5}];
equation[var1_, var2_, x_] := solnEquation[var1, var2, x] == Beta[2, 2];

solnFun[var1_?NumberQ, var2_?NumberQ] :=
 x /. NSolve[FunctionExpand[equation[2, 1/10, x]] && 0 < x < 1, x, Reals][[1]][[1]];

modelMoment[var1_, mu_, sigma_] :=
  NExpectation[solnFun[var1, var2], Distributed[var2, LogNormalDistribution[mu, sigma]]];

Now
modelMoment[2, 1/10, 1/20]

0.328152


text:
Q: Select data Only if it doesnt have a certain value inside it we have a legacy case management that runs via sql thru ms access.
our table example shows like this

is there a way to pull or select show a certain data only if it doesnt have a certain SNUM.
like we have casenum with multiple snum entry. but we only want to select casenum that never had an entry from a certain snum
so if for example there is a casenum with an entry only from 151 and 152 but no entry from 153 and 154 then it will show.
but if a casenum has an entry from snum 153 or 154 then it will not show it

A: select casenum
from your_table
group by casenum
having sum(case when snum in (153, 154) then 1 else 0 end) = 0
   and sum(case when snum = 151 then 1 else 0 end) >= 1
   and sum(case when snum = 152 then 1 else 0 end) >= 1


text:
Q: How can we retrieve variable from invocation.module_args when we register some data? When I do this:
- name: get snapshot

  vmware_guest_snapshot_facts:

     hostname: "{{ fe_rhel_maj_template_vw__vc_drv }}"

     username: "{{ vcenter_ad_rw.username }}"

     password: "{{ vcenter_ad_rw.password }}"

     datacenter: "{{ fe_rhel_maj_template_vw__cluster_drv }}"

     folder: "{{ fe_rhel_maj_template_vw__cluster_drv }}"

     name: lphost

  register: snapshot_facts_lin_win

I retrieve this:
{

    "_ansible_parsed": true,

    "invocation": {

        "module_args": {

            "username": "xxx@xxx.xxx",

            "datacenter": "xxx",

            "name": "lphost",

            "hostname": "xxxfff@xxx.xxx",

            "folder": "yyyyyy",

            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",

            "validate_certs": true,

            "port": 443,

            "uuid": null

        }

    },

    "changed": false,

    "_ansible_no_log": false,

    "guest_snapshots": {

        "current_snapshot": {

            "id": 1,

            "state": "poweredOff",

            "creation_time": "2018-11-06T14:39:40.431223+00:00",

            "description": "",

            "name": "Pré-CIS"

        },

        "snapshots": [

            {

                "id": 1,

                "state": "poweredOff",

                "creation_time": "2018-11-06T14:39:40.431223+00:00",

                "description": "",

                "name": "Pré-CIS"

            }

        ]

    }

}

I am able to retrieve data from guest_snapshots structure but not from invocation structure...
Is there any way to retrieve and match guest_snapshots and invocation, especially the invocation.module_args.name?

A: No. invocation is an internal field and it is stripped out of registered result by Ansible.
Otherwise it can be used to steal sensitive data like passwords.


text:
Q: Has anyone experience migrating Spring JSP + JS based application toward react? The frameworks we use in the application are Spring+JSP on backend, and custom-made JS page based scripts with home-standardized displaying components on front end. This works good for the moment but we need faster development time and better handling of customizing user UX. We are fully separated betwen both worlds using only an API.
I'm looking at react as a better way to handle customer requirements but I don't know how/where to start. Does anyone has experience/pointers towards a successfull experience in such matters?

A: I am rebuilding a Spring JSP application in React in a modular fashion.  Replacing JSP pages with React components . Loading them in the DOM by injecting them in the footer or header JSP page for now.


text:
Q: Evaluating functions within arithmetic grammar of a DSL I am working on a simple DSL to transform data extracted from MongoDB. I am using python and pyparsing and have gotten reasonably far in creating a grammar that works for basic operators like +/-*, starting from the examples provided. I am currently stuck on how to get my program to evaluate functions of the form Rank[dbRef]. I can evaluate and do arithmetic on dbRefs through the simple operators, but something is not working with my recursion in evaluating functions. I cannot figure out how to access the dbRef argument that was passed in the function call.
Here is the grammar and associated setParseActions:
# Define parser, accounting for the fact that some fields contain whitespace
chars = Word(alphanums + "_-/")
expr = Forward()
integer = Word(nums).setParseAction(EvalConstant)
real = Combine(Word(nums) + "." + Word(nums)).setParseAction(EvalConstant)

# Handle database field references that are coming out of Mongo
dbRef = Combine(chars + OneOrMore(":") + chars)

dbRef.setParseAction(EvalDBref)

# Handle function calls
functionCall = (Keyword("Rank") | Keyword("ZS") | Keyword("Ntile")) + "[" + dbRef + "]"
functionCall.setParseAction(EvalFunction)
operand = (real | integer) | functionCall | dbRef

signop = oneOf('+ -')
multop = oneOf('* /')
plusop = oneOf('+ -')

# Use parse actions to attach Eval constructors to sub-expressions

expr << operatorPrecedence(operand,
    [
     (signop, 1, opAssoc.RIGHT, EvalSignOp),
     (multop, 2, opAssoc.LEFT, EvalMultOp),
     (plusop, 2, opAssoc.LEFT, EvalAddOp),
    ])

formulas = ['Rank[Person:Height]']

for f in formulas:
    ret = expr.parseString(f)[0]
    print p + ": " + line + " --> " + str(ret.eval())

Here is the relevant code for my evaluation class. The class DOES get called by the parser, but how do I access the argument that is passed to the function?
# Executes functions contained in expressions
class EvalFunction(object):
    def __init__(self, tokens):
        self.value = tokens[0]
    def eval(self):
        func = self.value
        if func == 'Rank':
            # How to evaluate the token that is arg of Function?
            return 'Rank Found';

I think I just need a nudge in the right direction to get to the next stage ..

A: I sorted this out and wanted to provide an answer. My function evaluation class looks like this:
# Executes functions contained in expressions
class EvalFunction(object):
  pop_ = {}
  def __init__(self, tokens):
    self.func_ = tokens.funcname
    self.field_ = tokens.arg
  def eval(self):
      # Get the name of the requested field and source db
      # Functions can only be called on dbRef so this always done
      v = self.field_.value
      fieldRef = v.split(':')
      source = fieldRef[0]
      field = fieldRef[1]

      # Evaluate the dbRef (get the value from the db)
      val = self.field_.eval()

      if self.func_ == 'Avg':
        rec = db['Stats'].find_one({'_id' : field})
        return rec['value']['avg']
      elif self.func_ == 'Root':
          return math.sqrt(val)

my function grammar is:
functionCall = funcNames("funcname") + "[" + dbRef("arg") + "]"
functionCall.setParseAction(EvalFunction)


text:
Q: Multiple state objects to Socket.Begin* I have this class:
class NetworkManager {
    public void Connect(IPAddress address, int port, Action callback) {
        Socket socket = new Socket(...);
        socket.BeginConnect(address, port, r => EndConnect(r, socket, callback), null);
    }

    private void EndConnect(IAsyncResult r, Socket socket, Action callback) {
        //End the connection and call the callback method
    }
}

Is this method of sending multiple state objects good?
If I put the begin in a loop, would I still pass by the correct socket?
Socket socket;
for(...){
    socket = new Socket(...);
    socket.BeginConnect(address, port, r => EndConnect(r, socket, callback), null);
}

I feel like there should be a more correct way of doing it, any suggestions?

A: That will work, by way of creating a capture-context that snags socket and callback. It'll get the job done, usually. However, you MUST MUST understand the scoping rules of capture-contexts, and know whether socket refers to a per-iteration variable vs a variable shared between iterations. For my money, for that reason it isn't worth risking here.
But other mechanisms exist:

*

*you can pass an explicit state object in as the last parameter to BeginConnect, and access as r.AsyncState; this allows you to do things like repeatedly using a single delegate instance to avoid allocations, but you would still need some kind of tuple to contain the socket and callback

*you can use ConnectAsync; this has the same advantages in terms of re-using the delegate and having a state object (this time known as UserToken), but you don't need to package the socket, because that is exposed as the ConnectSocket in the event-handler - but it needs a SocketAsyncEventArgs instance, so it doesn't gain you much over BeginConnect in terms of allocations, but it does mean you are using the most recent (and most efficient) API
Whether it is worth changing depends on how high-volume this is.


text:
Q: What's wrong with the scala code in Play Framework with Morphia? I wrote the following code in Play Framework 2.2 with Scala.
def findContainerByUID(uid: String): UserToolbar = {
    var userToolbar = MorphiaHelper
       .getDataStore().find(UserToolbar.getClass(), "uid", uid).get()

    userToolbar.asInstanceOf[UserToolbar]
}

However, when i try to compile, i got the following error.
ow can getCommonSuperclass() do its job if different class symbols get the same bytecode-level internal name:xxxxxx
What is the problem?

A: Replace UserToolbar.getClass() with classOf[UserToolbar]. UserToolbar.getClass() returns the class of the UserToolbar companion object, not the class UserToolbar itself.


text:
Q: Awesome Bootstrap Checkboxes for Bootstrap Multiselect I'm using http://davidstutz.github.io/bootstrap-multiselect/ and I wanted to style my checkboxes (http://flatlogic.github.io/awesome-bootstrap-checkbox/demo/) ... BUT for some reason I can't change it to the required html structure.
The default Bootstrap Multiselect HTML:

                <input value="AD" type="checkbox"> Andorra (AD)

    ...

That's how it should be e.g.

            <input id="multiselect-0" value="vikings" type="checkbox">
             Minnesota Vikings

That's how I initialize it:
$('.test-select').multiselect({
    templates: { // Use the Awesome Bootstrap Checkbox structure
        li: '

'
    }
});

That's how I wanted to change the structure:
$('.multiselect-container div.checkbox').each(function (index) {

    var id = 'multiselect-' + index,
        $input = $(this).find('input');

    $(this).find('label').attr('for', id);
    $input.attr('id', id);

    $input.detach();

    $input.prependTo($(this));

    $(this).click(function (e) {
        e.stopPropagation();
    });

});

I got this from here: http://jsfiddle.net/natearmagost/aznvcLps/ Anyone an idea why it might not be working on my side or an alternative how to do so?
The below solution works, but unfortunately not yet if I load the options via $.ajax get and rebuild the multiselect. Anybody an idea why?
$.ajax({
type: 'GET',
url: '/country.php',
dataType: 'json',
success: function(data) {
     $.each(data.data, function (i, item) {
         display = item.display;
         $('.select-country').append('<option value="' + display + '">(' + display + ')</option>');
         //console.log(item)
    });
    $('.select-country').multiselect('rebuild');
}
});

A: Seems like you have conflicts between the Bootstrap-Multiselect CSS and the Awesome Checkbox CSS since they box use the class .checkbox. Try changing the Awesome Checkbox class to something else.
Working Template Structure:

Based on the default Bootstrap-Multiselect markup, the above template works. Basically just adding the a tag to it.
I also had to modify the .checkbox label rule to accommodate Bootstrap-Multiselect with the following:
padding: 0 20px 0 10px; cursor: pointer;
Working Example:

$(document).ready(function() {
  $('select').multiselect({
    templates: { // Use the Awesome Bootstrap Checkbox structure
      li: '

'
    }
  });
  $('.multiselect-container div.aweCheckbox').each(function(index) {

    var id = 'multiselect-' + index,
      $input = $(this).find('input');

    // Associate the label and the input
    $(this).find('label').attr('for', id);
    $input.attr('id', id);

    // Remove the input from the label wrapper
    $input.detach();

    // Place the input back in before the label
    $input.prependTo($(this));

    $(this).click(function(e) {
      // Prevents the click from bubbling up and hiding the dropdown
      e.stopPropagation();
    });

  });
});
body {
  padding: 20px;
}
form {
  max-width: 500px;
  margin: auto;
}
.aweCheckbox {
  padding-left: 20px;
}
.aweCheckbox label {
  display: inline-block;
  vertical-align: middle;
  position: relative;
  padding: 0 20px 0 10px;
  cursor: pointer;
}
.aweCheckbox label::before {
  content: "";
  display: inline-block;
  position: absolute;
  width: 17px;
  height: 17px;
  left: 0;
  margin-left: -20px;
  border: 1px solid #cccccc;
  border-radius: 3px;
  background-color: #fff;
  -webkit-transition: border 0.15s ease-in-out, color 0.15s ease-in-out;
  -o-transition: border 0.15s ease-in-out, color 0.15s ease-in-out;
  transition: border 0.15s ease-in-out, color 0.15s ease-in-out;
}
.aweCheckbox label::after {
  display: inline-block;
  position: absolute;
  width: 16px;
  height: 16px;
  left: 0;
  top: 0;
  margin-left: -20px;
  padding-left: 3px;
  padding-top: 1px;
  font-size: 11px;
  color: #555555;
}
.aweCheckbox input[type="checkbox"] {
  opacity: 0;
  z-index: 1;
}
.aweCheckbox input[type="checkbox"]:focus + label::before {
  outline: thin dotted;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}
.aweCheckbox input[type="checkbox"]:checked + label::after {
  font-family: "FontAwesome";
  content: "\f00c";
}
.aweCheckbox input[type="checkbox"]:indeterminate + label::after {
  display: block;
  content: "";
  width: 10px;
  height: 3px;
  background-color: #555555;
  border-radius: 2px;
  margin-left: -16.5px;
  margin-top: 7px;
}
.aweCheckbox input[type="checkbox"]:disabled + label {
  opacity: 0.65;
}
.aweCheckbox input[type="checkbox"]:disabled + label::before {
  background-color: #eeeeee;
  cursor: not-allowed;
}
.aweCheckbox.aweCheckbox-circle label::before {
  border-radius: 50%;
}
.aweCheckbox.aweCheckbox-inline {
  margin-top: 0;
}
.aweCheckbox-danger input[type="checkbox"]:checked + label::before {
  background-color: #d9534f;
  border-color: #d9534f;
}
.aweCheckbox-danger input[type="checkbox"]:checked + label::after {
  color: #fff;
}
.aweCheckbox-danger input[type="checkbox"]:indeterminate + label::before {
  background-color: #d9534f;
  border-color: #d9534f;
}
.aweCheckbox-danger input[type="checkbox"]:indeterminate + label::after {
  background-color: #fff;
}
input[type="checkbox"].styled:checked + label:after {
  font-family: 'FontAwesome';
  content: "\f00c";
}
input[type="checkbox"] .styled:checked + label::before {
  color: #fff;
}
input[type="checkbox"] .styled:checked + label::after {
  color: #fff;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet" />

<form>

    <select name="teams" id="teams" multiple="multiple" class="form-control">
      <option value="vikings">Minnesota Vikings</option>
      <option value="packers">Green Bay Packers</option>
      <option value="lions">Detroit Lions</option>
      <option value="bears">Chicago Bears</option>
      <option value="patriots">New England Patriots</option>
      <option value="jets">New York Jets</option>
      <option value="bills">Buffalo Bills</option>
      <option value="dolphins">Miami Dolphins</option>
    </select>

</form>


text:
Q: phpmailer SMTP with STARTTLS encryption would anyone know if it is possible to run phpmailer with STARTTLS encryption?
The story: an online order form that sends the output to both the site visitor and site owner. The goal is that the visitor receives an email from orders@ownerdomain.com, while the site owner receives an email from visitor@somedomain.com (the address that the visitor has filled i the online form).
I have the phpmailer running fine with my Gmail account, using TLS on port 587. I would, however, like to use mailbox provided along with the hosting (so that the from/replyTo looks professional, no freemail). Unfortunately, the hosting provider does not provide TLS - in their knowledgebase they only mention STARTTLS. I tried all combinations of SSL, TLS and STARTTLS for encryption and 465 and 587 for ports with no success.
Would anyone know if STARTTLS is somehow achievable, please?

My plan B would was to use the Gmail SMTP credentials and then tinker with addReplyTo, setFrom and addAddress in the phpmailer SMTP settings. I tried but if I use...
$mail->addReplyTo($_POST['customeremail'], $_POST['customername']);

...the from email address the site owner receives is that of my Google email - I understand this may be some Google email spoofing protection, which just doesn`t allow the SMTP to send an email with the From address taken from the form. - please see the attached ![Thunderbird screen( image: imgur.com/a/1f6vY).
Can this be possibly overridden?
I mean, with that plan B solution, I can grant Google access to send emails on behalf of orders@ownerdomain.com, that`s all fine, it will then mimick the professional domain address. But I cannot do the same for the visitor address (taken from the form), that makes sense, right?
Thanks a bunch in advance...

A: Yes, PHPMailer does TLS encryption by default. Look at the SMTPSecure property for more details.
Gmail does indeed prevent you from setting arbitrary from addresses, though you can pre-set aliases in your account. This is mentioned in the PHPMailer docs and has been covered many times on here.


text:
Q: Strictly decreasing sequence Let $$a_n=\sum_{k=1}^n\sqrt{k^2+1}$$
Define the sequence $b_n=\dfrac{2a_n}{n} - n$.
I need to show that the sequence $\langle b_n\rangle_{n=1}^\infty$ is strictly decreasing.

A: Note:
$\sum_{k=1}^n\sqrt{k^2+1}$ > $a_k=\sum_{k=1}^n\sqrt{k^2}$
for any positive n
As the definition of the RHS series (lets call it $c_n$) suggests, it is equal to the sum of the positive integers up to n.
This sum is given by the formula:
$$c_n=(n/2)(n+1)$$
Plugging this into your original definition for $b_n$ yields: $n + 1 - n$ or simply $1$.
Also note that the sum for $a_n$ approaches $c_n$ as $n$ approaches infinity. Now, with each increase in n, the difference between the 2 series steadily decreases.
Proving that the difference steadily decreases (from one term to the next) proves that $b_n$ steadily decreases (and as it seems, approaches 1). It's up to you to prove this critical bit.
Good day! :)

A: Try to show $b_{n+1} - b_n < 0$:
$b_{n+1} - b_n = \left[\dfrac{2a_{n+1}}{n+1} - (n+1)\right] -  \left[\dfrac{2a_n}n - n\right]$
$ = \dfrac1{n(n+1)}\left[2n \sum_{k=1}^{n+1}\sqrt{k^2+1} - 2(n+1) \sum_{k=1}^n\sqrt{k^2+1} - n(n+1)\right]$
$ = \dfrac1{n(n+1)} \left[2n \sqrt{(n+1)^2 + 1} - 2 \sum_{k=1}^n\sqrt{k^2+1} - n(n+1)\right]\qquad\qquad\mbox{(1)}$
$ < \dfrac1{n(n+1)} \left[2n \sqrt{\left(n + 1 + \dfrac1{2n}\right)^2} - 2 \sum_{k=1}^n \left(k + \dfrac1{2k}\right) - n(n+1)\right]$
$ < \dfrac1{n(n+1)} \left[2n \left(n + 1 + \dfrac1{2n}\right) - n(n+1) - \ln(n+1) - n(n+1)\right]$ ... [Ref: http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Integral_test to show $\sum_{k=1}^n\dfrac1k > \ln(n+1)$]
$ = \dfrac1{n(n+1)} \left[1 - \ln(n+1)\right]$
$ < 0$ for all $n \geq 2$.
For $n = 1$ case: calculate: $b_2 - b_1 = \sqrt5 - \sqrt2 - 1 < 0$.
Revised part to fix mistake GL5 found, following from (1):
$ < \dfrac1{n(n+1)} \left[2n \sqrt{\left(n + 1 + \dfrac1{2(n+1)}\right)^2} - 2 \sum_{k=1}^n \left(k + \dfrac1{2(k+1)}\right) - n(n+1)\right]$
$ < \dfrac1{n(n+1)} \left[2n \sqrt{\left(n + 1 + \dfrac1{2(n+1)}\right)^2} - n(n+1) -  \sum_{k=2}^{n+1} \dfrac1{k} - n(n+1)\right]$
$ < \dfrac1{n(n+1)} \left[2n \left(n + 1 + \dfrac1{2(n+1)}\right) - n(n+1) - \ln(n+1) + 1 - \dfrac1{n+1} - n(n+1)\right]$
$ = \dfrac1{n(n+1)} \left[2 - \dfrac2{n+1} - \ln(n+1)\right]$
$ < 0$ for all $n \geq 4$.
Initial cases for $1 \leq n \leq 3$ to be done by individual calculation. Having 3 initial cases is inelegant. There might be a way to tighten up the inequalities to reduce it.
Mick


text:
Q: i cannot understand what does theese error mean     #include <iostream>
    #include <sstream>
    #include <cstring>
    using namespace std;

    class Student {
        int age;
        char first_name[30];
        char second_name[30];
        int standard;
        public:
        void set_age(int a) {
            age=a;
        }
        void set_standard(int b){
            standard=b;
        }
        void set_last_name(char temp[]) {
            strcpy(second_name,temp);
        }
        void get_age() {
            cout<<age;
        }
        void get_last_name(){
            cout<<second_name;
        }
        void get_first_name() {
            cout<<first_name;
        }
        void get_standard(){
            cout<<standard;
        }
    };

    void Student::set_first_name(char temp[]){
        strcpy(first_name,temp);
    }

    int main() {
        int age, standard;
        string first_name, last_name;

        cin >> age >> first_name >> last_name >> standard;

        Student st;
        st.set_age(age);
        st.set_standard(standard);
        st.set_first_name(first_name);
        st.set_last_name(last_name);

        cout << st.get_age() << "\n";
        cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
        cout << st.get_standard() << "\n";
        cout << "\n";
        cout << st.to_string();

        return 0;
    }

errors
Solution.cpp:35:6: error: no declaration matches 'void Student::set_first_name(char*)'
 void Student::set_first_name(char temp[]){
      ^~~~~~~
Solution.cpp:35:6: note: no functions named 'void Student::set_first_name(char*)'
Solution.cpp:6:7: note: 'class Student' defined here
 class Student {
       ^~~~~~~
Solution.cpp: In function 'int main()':
Solution.cpp:48:8: error: 'class Student' has no member named 'set_first_name'; did you mean 'get_first_name'?
     st.set_first_name(first_name);
        ^~~~~~~~~~~~~~
        get_first_name
Solution.cpp:49:31: error: no matching function for call to 'Student::set_last_name(std::__cxx11::string&)'
     st.set_last_name(last_name);
                               ^
Solution.cpp:18:10: note: candidate: 'void Student::set_last_name(char*)'
     void set_last_name(char temp[]) {

A: You have provided a definition of the method, but the method is not declared in the class.
Add this line inside the Student class to provide a declaration:
void set_first_name(char temp[]);

A: you don't declare your function in your class
add this line to class body and the error will disappear
void set_first_name(char temp[]);

A: You have several issues:
cout cannot print void.
you haven't declared a function but you try to define it.
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;

class Student {
    int age;
    char first_name[30];
    char second_name[30];
    int standard;
    public:
    void set_age(int a) {
        age=a;
    }
    void set_standard(int b){
        standard=b;
    }
    void set_last_name(const char* temp) {
        strcpy(second_name,temp);
    }
    void get_age() {
        cout<<age;
    }
    void get_last_name(){
        cout<<second_name;
    }
    void get_first_name() {
        cout<<first_name;
    }
    void get_standard(){
        cout<<standard;
    }
    void set_first_name(const char* temp){
    strcpy(first_name,temp);
}
};

int main() {
    int age, standard;
    string first_name, last_name;

    cin >> age >> first_name >> last_name >> standard;

    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name.c_str());
    st.set_last_name(last_name.c_str());

    st.get_age();
    st.get_last_name();
    st.get_first_name();
    st.get_standard();
    cout << "\n";
    //cout << st.to_string();

    return 0;
}

A: You need to have something like void set_first_name(char temp[]) in the deceleration of your student class. Also, strings are not the same as char arrays and must be casted to that type. I recommend using strings in your class and not char arrays. This would be causing your last few errors.

A: I want to add to Oblivion's answer that you cannot cout first_name, second_name as well. First_name and second_name are pointers to the first element of the character array. Printing them would lead to just printing their addresses in the console.
You have to change these function declarations:
void get_last_name(){
    cout<<second_name;
}
void get_first_name(){
    cout<<first_name;
}

You need to add '\0' (end of string character) to the character arrays and then print it as a string. Check out how to do it by searching. You will learn a lot about working of character arrays and string.


text:
Q: convert dot graph to networkx graph with same layout and attributes I am looking for other alternatives to render grpah and save as image from dot file. I can't use Graphviz tool in my work machine as I have restriction.
In my search I found networkx python which has pydot/pygraphviz support through which
i) I can import dot files and convert to networkx graph
ii) I can create pydot/grphviz graph using those packages API and convert to networkx graph.
I have bleow dot code which I want to convert to networkx graph using python and later plot using matplotlib for rendering and saving graph as image.
digraph aud {
    graph [fontname=sans fontsize=10 label="Graph" labelloc=t nodesep=.1 rankdir=LR ranksep=.2]
    node [fontname=sans fontsize=9 margin="0.0,0.0" shape=box style="filled,rounded"]
    edge [fontname=monospace fontsize=9 labelfontsize=6]
    subgraph cluster_0_filesrc {
        graph [color=black fillcolor="#ffaaaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label="filesrc
location=song.ogg"
        subgraph cluster_0_filesrc_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_0_filesrc_src0 [label=src]
        }
    }
    subgraph cluster_1_decodebin {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=decodebin
        subgraph cluster_1_decodebin_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_1_decodebin_sink0 [label=sink]
        }
        subgraph cluster_1_decodebin_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_1_decodebin_src0 [label=src]
        }
    }
    subgraph cluster_2_tee {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label="tee
t"
        subgraph cluster_2_tee_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_2_tee_sink0 [label=sink]
        }
        subgraph cluster_2_tee_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_2_tee_src0 [label=src_0]
            cluster_2_tee_src1 [label=src_1]
        }
    }
    subgraph cluster_3_queue {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=queue
        subgraph cluster_3_queue_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_3_queue_sink0 [label=sink]
        }
        subgraph cluster_3_queue_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_3_queue_src0 [label=src]
        }
    }
    subgraph cluster_4_audioconvert {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=audioconvert
        subgraph cluster_4_audioconvert_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_4_audioconvert_sink0 [label=sink]
        }
        subgraph cluster_4_audioconvert_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_4_audioconvert_src0 [label=src]
        }
    }
    subgraph cluster_5_audioresample {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=audioresample
        subgraph cluster_5_audioresample_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_5_audioresample_sink0 [label=sink]
        }
        subgraph cluster_5_audioresample_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_5_audioresample_src0 [label=src]
        }
    }
    subgraph cluster_6_autoaudiosink {
        graph [color=black fillcolor="#aaaaff" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=autoaudiosink
        subgraph cluster_6_autoaudiosink_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_6_autoaudiosink_sink0 [label=sink]
        }
    }
    subgraph cluster_7_queue {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=queue
        subgraph cluster_7_queue_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_7_queue_sink0 [label=sink]
        }
        subgraph cluster_7_queue_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_7_queue_src0 [label=src]
        }
    }
    subgraph cluster_8_audioconvert {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=audioconvert
        subgraph cluster_8_audioconvert_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_8_audioconvert_sink0 [label=sink]
        }
        subgraph cluster_8_audioconvert_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_8_audioconvert_src0 [label=src]
        }
    }
    subgraph cluster_9_goom {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=goom
        subgraph cluster_9_goom_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_9_goom_sink0 [label=sink]
        }
        subgraph cluster_9_goom_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_9_goom_src0 [label=src]
        }
    }
    subgraph cluster_10_videoconvert {
        graph [color=black fillcolor="#aaffaa" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=videoconvert
        subgraph cluster_10_videoconvert_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_10_videoconvert_sink0 [label=sink]
        }
        subgraph cluster_10_videoconvert_src {
            graph [label="" style=invis]
            node [color=black fillcolor="#ffaaaa" height=0.2 style="filled,solid"]
            cluster_10_videoconvert_src0 [label=src]
        }
    }
    subgraph cluster_11_autovideosink {
        graph [color=black fillcolor="#aaaaff" fontname="Bitstream Vera Sans" fontsize=8 style="filled,rounded"]
        label=autovideosink
        subgraph cluster_11_autovideosink_sink {
            graph [label="" style=invis]
            node [color=black fillcolor="#aaaaff" height=0.2 style="filled,solid"]
            cluster_11_autovideosink_sink0 [label=sink]
        }
    }
    cluster_1_decodebin_sink0 -> cluster_1_decodebin_src0 [style=invis]
    cluster_2_tee_sink0 -> cluster_2_tee_src0 [style=invis]
    cluster_3_queue_sink0 -> cluster_3_queue_src0 [style=invis]
    cluster_4_audioconvert_sink0 -> cluster_4_audioconvert_src0 [style=invis]
    cluster_5_audioresample_sink0 -> cluster_5_audioresample_src0 [style=invis]
    cluster_7_queue_sink0 -> cluster_7_queue_src0 [style=invis]
    cluster_8_audioconvert_sink0 -> cluster_8_audioconvert_src0 [style=invis]
    cluster_9_goom_sink0 -> cluster_9_goom_src0 [style=invis]
    cluster_10_videoconvert_sink0 -> cluster_10_videoconvert_src0 [style=invis]
    cluster_0_filesrc_src0 -> cluster_1_decodebin_sink0
    cluster_1_decodebin_src0 -> cluster_2_tee_sink0
    cluster_2_tee_src0 -> cluster_3_queue_sink0
    cluster_3_queue_src0 -> cluster_4_audioconvert_sink0
    cluster_4_audioconvert_src0 -> cluster_5_audioresample_sink0
    cluster_5_audioresample_src0 -> cluster_6_autoaudiosink_sink0
    cluster_2_tee_src1 -> cluster_7_queue_sink0
    cluster_7_queue_src0 -> cluster_8_audioconvert_sink0
    cluster_8_audioconvert_src0 -> cluster_9_goom_sink0
    cluster_9_goom_src0 -> cluster_10_videoconvert_sink0
    cluster_10_videoconvert_src0 -> cluster_11_autovideosink_sink0
}

For creating graph using graphviz tool I am using below command:
dot -Tpng Graph.dot -o Graph_dot.png
graph rendered using Graphviz tool
I am using below python code,
import pydot
import networkx as nx
import matplotlib.pyplot as plt

graphs = pydot.graph_from_dot_file('Gstreamer_Pipeline.gv')
graph = graphs[0]
gst_nx = nx.drawing.nx_pydot.from_pydot(graph)
position = nx.nx_pydot.pydot_layout(gst_nx)
plt.figure()
nx.draw_networkx(gst_nx, position)
plt.axis('on')
plt.show()

I am not getting same graph as like grpahviz tool output. attached the graphviz tool output graph file. could someone help how to plot the networkx graph with same node/edge attributes like graphviz tool output


text:
Q: Duvida na integração de aplicação web com mobile Olá, estou com uma dúvida sobre como fazer a integração do meu sistema web já existente com uma aplicação mobile.
Já desenvolvemos uma aplicação web cuja arquitetura é basicamente a seguinte: REST (através da API do Jersey) como web service, Maven como gerenciador de dependências, hibernate e jetty como servidor de aplicação. Para autenticação utilizamos o Spring Security.
Agora, precisamos criar um app mobile utilizando Phonegap que possua forma de login no próprio app e também através do Facebook, porém pretendemos utilizar os mesmos serviços do portal web para acessar e gravar as informações. Isso é possível? Qual a melhor forma de integração? E sobre o login com o Facebook, qual o melhor framework utilizar?
Obrigada! Aguardo.

A: Particularmente eu gosto e utilizo Ionic, AngularJs e ngCordova, juntos permitem fazer o que vc está precisando.
Como vc pode ver neste link o ngCordova tem plugin para login através de redes sociais, e com AngularJs pode fazer a comunicação com a API.
Além de permitir desenvolver para multi plataformas.


text:
Q: Remoting in .net I am doing applications on .net remoting ,i write the code for
       Client -----------> server

but
       client <------------ server

i don't know how to do it(just like a chat),Please give suggestions and some samples to look up.
   without any request from server i send messages from my client application

A: Try using MarshalByRefObject and events.  This would allow the Server to respond back to the client.
Here is a sample on code project
Another Sample with Event CallBack


text:
Q: How to approach Flyway migration when using Envers? I need to add some data to my DB. Simple INSERT statement. I would do it in Flyway migration SQL script. But how to approach this task when Hibernate Envers is also in place? Do I need to manually alter audit tables and revision table? Or is there any better approach?
I was thinking about java-based migration using hibernate (it would automatically update also audit tables), but I'm afraid that's not the way. I don't know, how could I do it. Any suggestions?

A: I am afraid that you do not have other choices than do it manually.
Envers detects Hibernate's Session operations, so if your migrations are outside the Session you have to alter audit tables yourself.


text:
Q: JBPM - How to use CMT Command within a process I am trying to create a merge tool to merge multiple different branches together through SVN.
I am wanting to use JBPM running through AS7.
I am using JBPM 5.4 as it is the highest version that is compatible with my enviroment.
If it is run once, it works fine. However, when it is run more than once. If it gets to a human task, it will pause and wait for that human task to be complete. When the task is resolved it appears to look for a Ksession but it finds the first run throughs session and carries on from there using the first runs session.
It seems as if it isn't disposing of the ksessions.
I have come across CMTDispose. However I am not sure how to make it run in the AS7 as I need to call
ksession.execute(new CMTDisposeCommand());

Although I am not sure where I can call ksession within the process?
Any help would be good, thanks.

A: Container-managed transactions work by simply making sure a transaction is already active when invoking the jBPM engine, in which case the engine will join the existing transaction.
At the end of the transaction, the state of all process instances is stored in the database.  If they are needed later, the state will be restored from the database again to continue where they left off.
It's unclear what's going wrong to give more concrete advice.


text:
Q: Is my hard drive starting to fail? My MacBook Pro (mid-2012, 16GB, i7 2.3) has started to misbehave:

*

*very slow to start up and shut down

*application launches are slow

*system becomes nearly unusable when "free" memory approaches zero.

Disk Utility is showing SMART status of the drive as "verified". However, Blackmagic Disk Speed Test is showing a read speed of 27 MB/s and a write speed of 25.7 MB/s. This seems slow to me, though I'm have trouble finding any benchmark values to compare against.
I've run "verify disk" in the Disk Utility app twice. The first time it completed with no errors. The second time the computer froze before the procedure finished.
Here is the system profiler information for the drive.
Capacity:   500.11 GB (500,107,862,016 bytes)
  Model:    APPLE HDD HTS547550A9E384
  Revision: JE3AD70F
  Serial Number:          J226008BJ65LKC
  Native Command Queuing:   Yes
  Queue Depth:  32
  Removable Media:  No
  Detachable Drive: No
  BSD Name: disk0
  Rotational Rate:  5400
  Medium Type:  Rotational
  Partition Map Type:   GPT (GUID Partition Table)
  S.M.A.R.T. status:    Verified
  Volumes:
disk0s1:
  Capacity: 209.7 MB (209,715,200 bytes)
  BSD Name: disk0s1
  Content:  EFI
Macintosh HD:
  Capacity: 499.25 GB (499,248,103,424 bytes)
  Available:    101.87 GB (101,868,064,768 bytes)
  Writable: Yes
  File System:  Journaled HFS+
  BSD Name: disk0s2
  Mount Point:  /
  Content:  Apple_HFS
  Volume UUID:  BBF6F6B8-26B8-39B4-A206-81471EA7F2B2
Recovery HD:
  Capacity: 650 MB (650,002,432 bytes)
  BSD Name: disk0s3
  Content:  Apple_Boot
  Volume UUID:  DB9ED89F-80DF-3A80-BCC4-58DF1F234256

Does any of this indicate an imminent drive failure? The AppleCare plan for this computer expires in 6 days.

A: There is no harm in getting a call logged before your apple care expires, although from your description nothing you say would suggest to me that the hard drive is at fault.  It sounds more like the slow build up of unwanted startup items, and inevitable disk fragmentation is just slowing things down, or you could plain be out of memory more often than before.  If you have a secure backup, I might consider a couple of things to test:
1) Create a new user, and see if it is as slow as your usual user account
2) From a complete backup, format your drive and restore to defrag the drive, and again see if the same happens.
HD problems would usually manifest themselves in unusual noises, clicks and whirs, repeated attempts to load a file, genuine errors in log files where you could use the Console app to search for things like "disk0s" "error" and "I/O error" - especially if they correlate in time to the slowness or freezing you are seeing.

A: From the information provided it does not look like hard drive problem.
To verify what is going on use the:
Activity monitor to see who is hugging the CPU
and use the Console to see who is doing what
those 2 will tell you more about why is your computer slow.
Meanwhile since you running out of warranty time, call the support anyway.

A: You say:

system becomes nearly unusable when "free" memory approaches zero.

That is absolutely normal. Without memory nothing moves. The problem is why you get short of memory? Look inside the Preferences>>user>>login elements and get rid of all background program you do not need. Makes sure you never run too low on memory closing apps that you do not use and check if this makes your mac happy again.


text:
Q: How to reset EditForm after its been submitted? I have an EditForm that I would like to reset after the save button is clicked. I input data into the textboxes (InputText) on the EditForm. Each textboxes is binded to an object field so that a new object can be saved to my SQL Database.
<EditForm Model=@newSystem OnValidSubmit="HandleSubmit" >
    <DataAnnotationsValidator/>

    System Name:
    <InputText id="systemName"  @bind-Value="@newSystem.SystemName" ></InputText>
    <ValidationMessage For="@(() => newSystem.SystemName)" />

    System Description:
    <InputText id="systemDescription"  @bind-Value="@newSystem.SystemDescription"></InputText>
    <ValidationMessage For="@(() => newSystem.SystemDescription)" />

    System Access Details:
    <InputText id="systemAccessDetails"  @bind-Value="@newSystem.SystemAccessDetails"></InputText>
    <ValidationMessage For="@(() => newSystem.SystemAccessDetails)" />

    Additional Information:
    <InputText id="additionalInformation" @bind-Value="@newSystem.AdditionalInformation"></InputText>
    <ValidationMessage For="@(() => newSystem.AdditionalInformation)" />

    System Manager Name:
    <InputText id="systemManagerName"  @bind-Value="@newSystem.SystemManagerName"></InputText>
    <ValidationMessage For="@(() => newSystem.SystemManagerName)" />

    System Manager Email Address:
    <InputText id="systemManagerEmailAddress"  @bind-Value="@newSystem.SystemManagerEmailAddress"></InputText>
    <ValidationMessage For="@(() => newSystem.SystemManagerEmailAddress)" />

    System Manager Contact Number:
    <InputText id="systemManagerContactNumber"  @bind-Value="@newSystem.SystemManagerContactNumber"></InputText>
    <ValidationMessage For="@(() => newSystem.SystemManagerContactNumber)" />

    <input type="checkbox" @bind="checkboxValue" /> Is this system retired?

        When did this system retire?
        <input type="date" @bind="retiredDate"  />

    <button type="submit" class="btn-primary">Add</button>

</EditForm>

@code {

    private bool checkboxValue;
    private DateTime retiredDate = DateTime.Now;

    SystemDatum newSystem = new SystemDatum();

    public void HandleSubmit(EditContext editContext)
    {

        var newSystem = (SystemDatum)editContext.Model;

        newSystem.DateAdded = DateTime.Now;

        if (checkboxValue == true)
        {
            newSystem.DateRetired = retiredDate;
        }
        else
        {
            newSystem.DateRetired = null;
        }

        systemService.AddSystem(newSystem);

    }

}

How can I reset each textbox back to null? I'm using blazor-server-side c# and EF.


text:
Q: Okteto doesn't sync file changes even though syncthing reports changes I'm using Okteto CLI version 2.2.1, MacOS Monterey (Macbook 2015). I've cloned and deployed their playground app and created the following Okteto configuration:
name: movies-with-compose

# The build section defines how to build the images of your development environment
# More info: https://www.okteto.com/docs/reference/manifest/#build
build:

  # You can use the following env vars to refer to this image in your deploy commands:
  #  - OKTETO_BUILD_API_REGISTRY: image registry
  #  - OKTETO_BUILD_API_REPOSITORY: image repo
  #  - OKTETO_BUILD_API_IMAGE: image name
  #  - OKTETO_BUILD_API_TAG: image tag
  api:
    context: api
    dockerfile: api/Dockerfile

  # You can use the following env vars to refer to this image in your deploy commands:
  #  - OKTETO_BUILD_FRONTEND_REGISTRY: image registry
  #  - OKTETO_BUILD_FRONTEND_REPOSITORY: image repo
  #  - OKTETO_BUILD_FRONTEND_IMAGE: image name
  #  - OKTETO_BUILD_FRONTEND_TAG: image tag
  frontend:
    context: frontend
    dockerfile: frontend/Dockerfile

  # You can use the following env vars to refer to this image in your deploy commands:
  #  - OKTETO_BUILD_INIT_REGISTRY: image registry
  #  - OKTETO_BUILD_INIT_REPOSITORY: image repo
  #  - OKTETO_BUILD_INIT_IMAGE: image name
  #  - OKTETO_BUILD_INIT_TAG: image tag
  init:
    context: api
    dockerfile: api/Dockerfile

  # You can use the following env vars to refer to this image in your deploy commands:
  #  - OKTETO_BUILD_MOVIES_REGISTRY: image registry
  #  - OKTETO_BUILD_MOVIES_REPOSITORY: image repo
  #  - OKTETO_BUILD_MOVIES_IMAGE: image name
  #  - OKTETO_BUILD_MOVIES_TAG: image tag
  movies:
    context: reverse-proxy
    dockerfile: reverse-proxy/Dockerfile

# The deploy section defines how to deploy your development environment
# More info: https://www.okteto.com/docs/reference/manifest/#deploy
deploy:
  compose:
    file: docker-compose.yml

# The dependencies section defines other git repositories to be deployed as part of your development environment
# More info: https://www.okteto.com/docs/reference/manifest/#dependencies
# dependencies:
#   - https://github.com/okteto/sample

# The dev section defines how to activate a development container
# More info: https://www.okteto.com/docs/reference/manifest/#dev
dev:
  api:
    command:
      - yarn
      - start
    sync:
      - api:/usr/src/app
    environment:
      - MONGODB_DATABASE=okteto
      - MONGODB_HOST=mongodb
      - MONGODB_PASSWORD=mongodb123
      - MONGODB_USERNAME=okteto
    forward:
      - 8081:8080
  frontend:
    image: okteto/node:14
    command: bash
    workdir: /src
    sync:
      - frontend:/src
    forward:
      - 9229:9229
      - 8080:80
  movies:
    command: bash
    workdir: /usr/src/app
    sync:
      - .:/usr/src/app
    forward:
      - 9229:9229
      - 8080:80

I'm deploying the api container and no matter what file changes I perform to server.js they're not reflected in the deployment. I ran okteto status --info to get the remote Syncthing URL and it does display that server.js was changed when I click Recent Changes:

I started okteto by running okteto up and this is the output I get:

I can't figure out why changes to files which I make on my local machine are not reflected in okteto deployment (they're only reflected if I run okteto build and then re-deploy). Perhaps I misunderstood Okteto docs but I expected for file changes to be reflected instantly in okteto deployment.
The dockerfile for the service I'm starting in Okteto is:
FROM node:14

WORKDIR /src

COPY package.json yarn.lock ./
RUN yarn install

COPY . .

EXPOSE 8080

CMD ["yarn", "start"]

EDIT: the issue shouldn't occur anymore as a pull request fixing the issue was merged

A: The issue was that the volume in docker-compose.yml for the api service is:
    volumes:
      - api:/usr/src/app

which is incorrect because the nodejs app is located in /src folder. Then when running okteto init the okteto manifest will automatically set the sync folder to api:/usr/src/app so any file changes locally will not result in updates in okteto cluster. Setting the volume in docker-compose.yml to be:
volumes:
      - api:/src

will solve the issue. In general I'm not sure volume should be defined at all in docker-compose.yml, I think it's enough to just define sync folder in okteto.yml (at least it worked for me because I guess Syncthing syncs files regardless of docker volume).


text:
Q: C# how i can know if a UDP packet sent or not? i'm using this code
      bool NotSent = true;
        while (NotSent)
        {
            try
            {
                UdpClient udpServer = new UdpClient(port);
                udpServer.Connect(IPAddress.Parse("192.168.1.66"), port);
                Byte[] sendBytes = Encoding.ASCII.GetBytes("Hello");
                int res = udpServer.Send(sendBytes, sendBytes.Length);
                MessageBox.Show("Sent : " + res);
                udpServer.Close();
                NotSent = false;
            }
            catch (Exception ex) { MessageBox.Show("Error : " + ex.ToString()); continue; }
        }

so how i can know if "Hello" sent and received or not because all results always return 17

A: UDP does not implement an acknowledgement segment like TCP or other protocols.

UdpClient.Send() sends datagrams to the specified endpoint and
  returns the number of bytes successfully sent.

Thus, the 17 that you are seeing in res is telling you that 17 bytes have successfully been sent.
Source: https://msdn.microsoft.com/en-us/library/82dxxas0(v=vs.110).aspx

A: UDP is a connectionless protocol so there is no gurantee that the data was sent to its receipient.
One simple way to confirm that the data was indeed sent is to have the remote host send back an ack (acknowledgement) to the server.
Here is a simple implementation you can find from MSDN
// Sends a message to a different host using optional hostname and port parameters.
     UdpClient udpClientB = new UdpClient();
     udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

     //IPEndPoint object will allow us to read datagrams sent from any source.
     IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

     // Blocks until a message returns on this socket from a remote host.
     Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
     string returnData = Encoding.ASCII.GetString(receiveBytes);


text:
Q: How to set up settings.py on Google app engine I changed from GAE/Py2.5 to 2.7 and from Django0.9 to Django1.2.
I am useing relative paths extends tag to Template Engine When caused TemplateDoesNotExist error and disable.
It's use Template "google.appengine.ext.webapp.template".
I think , how do I set up your own loader to TEMPLATE_LOADERS or setting the template path TEMPLATE_DIRS.
However, I don't know how to set.
Please tell me how to set up.

A: Can you use just a regular requesthandler? What happens if you test:
class Home(RequestHandler):
  def get(self):
    data = {}
    path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
    self.response.out.write(template.render(path, data))


text:
Q: Test Runner class is not running but able to execute the feature file I have given correct step definition class, but when I tried to execute the Test Runner class , it not executing. But when I run the feature file, the test is getting executed.
Also my code was working before with my existing code and all on a sudden it is not getting executed when I try to run the Test Runner class as Junit test.
Test Runner Class
Project structure
package org.Cucumber.TestExecution;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"Feature"}
        ,glue={"src.org.Cucumber.StepDefinition"}
        )

public class TestRunner {

}


text:
Q: How to query from two database servers There are two identical Databases present on two different servers. Each of the two Databases have similar information, but from different companies. I am trying to get the information from both the Databases, somthing similar to this. I dont have permission to create a linked server.
Any suggestions? ( I am using T-SQL)
select A,B,C
from server1.Database1.dbo.table1

UNION ALL

select A,B,C
from server2.Database2.dbo.table1

A: Linked Server is best, IMO, if you can manage it.
In cases where our DBA won't allow that, I'll often use a client-installed database (like MS Access), and link to the tables in both servers, and then write my query there.


text:
Q: ord(os.urandom(x)) clarification - string, character The following is a function that my professor made, and we are to use this function in our code:
    import os
    def rando_num(num_bytes):
        return ord(os.urandom(num_bytes))

Instructions say to make a create_list function, call rando_num within create_list, and to do some checks on the return. I keep getting errors, and out of curiosity I tested rando_num by itself and got the same errors.
If I call
    rando_num('5')
I get "'str' object cannot be interpreted as an integer"
If I call
    rando_num(5)
I get "ord() expected a character, but string of length 5 found"
If I try
    rando_num('a') I get "'str' object cannot be interpreted as an integer"
I read up on os.urandom and ord, so I'm confused about what I need to put in the function. I thought urandom returns a string, but then the error says ord expects a character. I can't alter the professor's code, so how in the world do I use it?

A: As Python's documentation for os.urandom says, urandom returns "a string of n random bytes." And as Python's documentation for ord says, ord must be "given a string representing one Unicode character."
The only way I can see to reconcile those two without modifying your professor's code is to have urandom return only one byte which Python interprets as a string with one Unicode character. That character will be limited to have the ord result of 0 through 255, but it will work.
So set up your code to always call rando_num with an argument of 1. Calling that repeatedly in effect gives a sequence of random numbers between 0 and 255, but done by the operating system rather than by the programming language (which is want random does). This does work in my Python 3.7.


text:
Q: Issues with writing a new flowfile in ExecuteScript NiFi I am trying to use ExecuteScript processor to execute a piece of java code to filter the csv file and output a new csv file.
It will occur an error: transfer relationship not specified. How can I fix that?
My code:
FlowFile flowFile = session.get();
    if (flowFile == null) {
      return;
    }
FlowFile newflowFile = session.create();

try {
Reader reader = Files.newBufferedReader(Paths.get(flowFile), StandardCharsets.UTF-8);
Writer writer = Files.newBufferedWriter(Paths.get(newflowFile), StandardCharsets.UTF-8, StandardOpenOption.CREATE);
CSVPrinter printer = CSVFormat.DEFAULT.print(writer);

...
//using printer write a new content

session.transfer(newflowFile, REL_SUCCESS);

} catch (Exception e) {

session.transfer(flowFile, REL_FAILURE);
}

A: i suggest you to use ExecuteGroovyScript instead of ExecuteScript - it has more features and it does compilation on processor init once. so, it's a bit faster.
here is a base for the script if you plan to read and write data from/to the same flow file.
def ff=session.get()
if(!ff)return

ff.write{InputStream rawIn, OutputStream rawOut->
    //rawIn - current flowfile content
    //rawOut - stream for a new flowfile content
    rawIn.withReader("UTF-8"){reader->
        rawOut.withWriter("UTF-8"){writer->
            CSVPrinter printer = CSVFormat.DEFAULT.print(writer)
            ...
        }
    }
}

REL_SUCCESS << ff  //the same as session.transfer


text:
Q: MobaXterm gets stuck on "Please wait while opening file..." dialog I am using MobaXterm v20.6 build 4532 to connect to a Linux machine over SSH. I am trying to open a file in the Scp panel on the left by double-clicking on it, and this brings up a dialog box saying "Please wait while opening file...", and it gets stuck here forever.
Interestingly enough, this works on some servers but not others. Is there some way to debug this? Is there a log file which shows the scp command that MobaXterm is trying to run?

A: I figured out the problem. I was able to enable logging by running "MobaXterm.exe -log". This left a log in C:\Users\jdoe\Documents\MobaXterm\MobaXterm.log. This was printed when I tried to open a file:
[11:31.39.305]  (SSH-Browser)    Starting MobaSCP(2, OpenFile, /local/jdoe/.bashrc, C:\Users\JDOE\DOCUME~1\MobaXterm\slash\RemoteFiles\526608_2_0\.bashrc)
[11:31.39.307]  BEGIN ShellExecuteA(C:\Users\JDOE\DOCUME~1\MobaXterm\slash\bin\MobaSCPOpenFile.exe, -v -batch -scp -load "TERM5266082" mobauser@mobaserver:"/local/jdoe/.bashrc" "C:\Users\JDOE\DOCUME~1\MobaXterm\slash\RemoteFiles\526608_2_0\.bashrc")
[11:31.39.308]      ShellExecuteA: ShellExecuteEx succeeded.
[11:31.39.308]  END ShellExecuteA(C:\Users\JDOE\DOCUME~1\MobaXterm\slash\bin\MobaSCPOpenFile.exe, -v -batch -scp -load "TERM5266082" mobauser@mobaserver:"/local/jdoe/.bashrc" "C:\Users\JDOE\DOCUME~1\MobaXterm\slash\RemoteFiles\526608_2_0\.bashrc")
[11:31.39.405]  [MobaSCP2]  Multiplex=0
[11:31.39.406]  [MobaSCP2]  HOSTNAME: 192.168.1.104
[11:31.39.406]  [MobaSCP2]  USERNAME: jdoe
[11:31.39.724]  Received verification request for hostkey: ssh-ed25519@22:192.168.1.104
[11:31.39.724]  Hostkey corresponds to the cached one
[11:31.39.748]  WMNewTab2: Saving sshkey and NOT CONNECTING SSH-Browser...
[11:31.39.748]  BEGIN SavePassword
[11:31.39.749]  END SavePassword
[11:31.39.845]  [MobaSCP2]  Using SCP1
[11:31.39.845]  [MobaSCP2]  Connected to 192.168.1.104
[11:31.39.845]  [MobaSCP2]  Protocol error: Expected control record

Looks like the "Expected control record" error was being caused by my .bashrc printing output. Apparently this confuses SCP: https://documentation.help/PuTTY/faq-pscp-protocol.html
I was able to fix this by changing my .bashrc to not print anything.


text:
Q: How to prepend headers to a NetBuffer in NDIS 6? We are upgrading our NDIS 5.1 Intermediate Miniport driver to NDIS 6.
We need to prepend some header information to a packet that is goind to be sent. In 5.1 we used NdisChainBufferAtFront().
We already did the entire kitchen to traverse and clone the entire NetBufferLists structure, we are down to preparing each cloned NetBuffer.
What is the correct way to prepend (means, at front!) a 22-byte header to a packet (NetBuffer) that is going to be sent? (We would prefer a method that avoids copying original MDL data)

A: You can use NdisRetreatNetBufferDataStart to add bytes for header information.
read this link till remarks to know how its done. It will surely help:
http://msdn.microsoft.com/en-in/library/windows/hardware/ff564527%28v=vs.85%29.aspx
ps: you  dont at all need to copy mdl


text:
Q: Load Flash object in Java Web Browser I was wondering if there was some way to be able to load Flash objects from a custom Java web-browser. I want to be able to view YouTube videos for example.
I have read this: Embedding Flash Component into Java App, but I am not sure how I would use this seeing as I do not have the Flash locally as a .swf. I do not know where it loads the Flash file from. Also, I would prefer the solution to not require buying a product.
I know for sure that this is do-able using C# and the WebBrowser class because that uses the Flash plugin for IE, I was just wondering if there was a way to do this with Java.


text:
Q: Windows Mobile: using phone's camera with C# I want to show the image that mobile phone's camera its taking on a control in a WinForm. The idea is that my application works like camera's program. I want to show the image like if the user is going to take a photo.
How can I do that? Can I do that?
If you need more details ask me.
Thank you!

A: Not very sure what you need, but you may try using Microsoft.WindowsMobile.Forms.CameraCaptureDialog:
    string originalFileName;
    using (CameraCaptureDialog dlg = new CameraCaptureDialog()) {
        dlg.Mode = CameraCaptureMode.Still;
        dlg.StillQuality = CameraCaptureStillQuality.Low;
        //dlg.Resolution = new Size(800, 600);
        dlg.Title = "Take the picture";
        DialogResult res;
        try {
            res = dlg.ShowDialog();
        }
        catch (Exception ex) {
            Trace.WriteLine(ex);
            return null;
        }

        if (res != DialogResult.OK)
            return null;
        this.Refresh();
        originalFileName = pictureFileName = dlg.FileName;
    }

Later Edit:
Some of you might find useful this link, too:
http://community.intermec.com/t5/General-Development-Developer/CN50-MS-Camera-Capture-Dialog-generates-error/m-p/12881#M4083

A: What you want is a preview, not the capture, which is far more difficult.  The best (and maybe only) solution is to insert a DShow Filter into the filtergraph to pipe the preview window to where you want.
COM is a bear in the Compact Framework, and DShow is tough no matter what platform you're on. There are some resources online, like the DShow.NET library at sourceforge, and Alex Mogurenko's blog, but nothing specific to creating a capture.
There is a native capture sample in the WinMo SDK that would be a useful guide to getting you there.

A: I think you should program against the hardware directly using a sdk or something similar.
Since programming against hardware directly is usually in c/c++ the sdk will probably be native. So either you probably have to use pinvoke and the unsafe keyword.
But first you should find the way to access the camera, and since this is hardware dependant you can start on the website of the phone's manufacturere.

A: Check SmartDeviceFramework from OpenNetCF.org have some tools for PocketPC including capturing frames from Camera.


text:
Q: Create file usb storage android? Unable to create a folder or file in USB storage android version above 5.0+ non-root device using this method.
 File root = new File("/mnt/media_rw/usbotg-sda1", "Notes");
File gpxfile = new File(root, "Sample.txt");   FileWriter writer = new FileWriter(gpxfile); writer.append("ANDROID");  writer.flush();  writer.close();
Exception : /mnt/media_rw/usbotg-sda1/Notes/Sample.txt: open failed: EACCES (Permission denied)


text:
Q: There is no Xamarin debug.keystore I am trying to find  SHA-1 of a Xamarin.android app to develop an app with visual studio and firebase on windows 7, I followed Microsoft documentations https://learn.microsoft.com/en-us/xamarin/android/deploy-test/signing/keystore-signature?tabs=windows
but it gives me an error :
"keystore file does not exist"
Please how can i fix this.

A: Have just encountered this problem.  In my case it was with an existing Xamarin Android project on a new machine, new VS2019 install.
The solution:
Create a new Android project, and deploy it to the emulator.
This process seemingly creates the keystore.
I just used the template Single View App. Create the new project, select emulator, deploy.  It fires up and ... does nothing.
I was then able to return to my real app, and deploy as required.

A: maybe you/it changed during install so the path is diffrent?
try browsing your appdata/local folder and see if you can find the xamarin mono map, and then use the whole path directly instead of %LocalAppData%
if you cant find it, or it still doesnt work, try checking the build log when you build in debug, the path for the keystore will be logged in the console during the build process.
This is what it loooks like when i build an example project, in the "deploy to device console"
Target _Sign:
/Users/theusername/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_8.0.25/bin/keytool -list -alias androiddebugkey -storepass android -keypass android -keystore "/Users/theusername/.local/share/Xamarin/Mono for Android/debug.keystore"
/Users/theusername/Desktop/AndroidSdk/build-tools/27.0.3/zipalign -p 4 "/Users/theusername/theProjectName/theProjectName/Droid/obj/Debug/android/bin/com.project.theProjectName.apk" "bin/Debug//com.project.theProjectName-Signed.apk"
/Users/theusername/Desktop/AndroidSdk/build-tools/27.0.3/zipalign -p 4 "/Users/theusername/theProjectName/theProjectName/Droid/obj/Debug/android/bin/com.project.theProjectName.apk" "bin/Debug//com.project.theProjectName-Signed.apk"
/Users/theusername/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_8.0.25/bin/java -jar /Users/theusername/Desktop/AndroidSdk/build-tools/27.0.3/lib/apksigner.jar sign --ks "/Users/theusername/.local/share/Xamarin/Mono for Android/debug.keystore" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android --min-sdk-version 18 --max-sdk-version 26  /Users/theusername/theProjectName/theProjectName/Droid/bin/Debug/com.project.theProjectName-Signed.apk
/Users/theusername/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_8.0.25/bin/java -jar /Users/theusername/Desktop/AndroidSdk/build-tools/27.0.3/lib/apksigner.jar sign --ks "/Users/theusername/.local/share/Xamarin/Mono for Android/debug.keystore" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android --min-sdk-version 18 --max-sdk-version 26  /Users/theusername/theProjectName/theProjectName/Droid/bin/Debug/com.project.theProjectName-Signed.apk
Signed android package 'bin/Debug/com.project.theProjectName-Signed.apk'

as you can see, on the two last lines in the snippet, it show me that the path for my debug.keystore is "/Users/theusername/.local/share/Xamarin/Mono for Android/debug.keystore"

A: I have run into the similiar problem. Please verify if the following path exist with a debug.keystore file:
/Users/theusername/.local/share/Xamarin/Mono for Android/debug.keystore

If it does not exist, create a new solution in Visual Studio and run it. This will create the keystore and you can afterwards return to your original project.


text:
Q: using - oneOf, anyOf in Schema I want to let user allow flexibility to provide only one of either ref_id or dataCenter. Could someone correct this schema ?
  kind: kind
    metadata:
      name: kind.v1
      namespace: system
    spec:
      descrption: This is an example specification
      schema:
        type: object
        properties:
          ref_id:
            type: string
            minLength: 25
            maxLength: 40
          dataCenter:
            type: string
            enum:
              - "abc"
              - "xyzzy"
          version:
            type: integer
            example: 1
        required:
          - ref_id
          - dataCenter
          - version

A: Because you have additional properties besides those two, a simple oneOf would be insufficient. Instead, nest a oneOf for ref_id and dataCenter inside an allOf.
(Example simplified for brevity)
properties:
  allOf:
    - version:
    - oneOf:
      - ref_id:
      - dataCenter:


text:
Q: Syntax error on python I'm trying to do a simple function to delete some cache files.
But I'm getting an syntax error, and I dont know why...
Code:
import xml.etree.ElementTree as ET
import os
import filecmp
import urllib
import shutil

def clean ():
    shutil.rmtree('/apks')
    os.remove('apk_cache')
    os.remove('info.xml')
    os.makedirs('apks')
    print "Cache - Clear"

    return menu ()

Error:
 File "C:\Users\Joao Carreira\ownCloud\Development\Python\Aptoide_Utils\utils.p
", line 14
   print "Cache - Clear"
                       ^

Thanks for the help! :)

A: If you use Python 3.x, you should write it as follow:
print("Cache - Clear")

print is a function in Python 3.x.

>>> print "Cache - Clear"
  File "<stdin>", line 1
    print "Cache - Clear"
                        ^
SyntaxError: invalid syntax
>>> print("Cache - Clear")
Cache - Clear
>>> print
<built-in function print>


text:
Q: HTML My css styles arent being outputted even though i have linked them Image of my website page code
Image of the css code
As you can see the background and font change are not showing up even though I have linked them and refreshed the page numerous times after saving.

A: try these
<link rel="stylesheet" href="main.css" />
<link rel="stylesheet" href="./styles/main.css" />

use only main.css if the css file is in the same folder as your index.html
use ./styles/main.css if the css file is in another folder.
send a ss with your root folder with the files you are using in this project if it doesn't work


text:
Q: System won't start Ubuntu 11.10 will not start when I boot to it. When I boot it, it shows the loading screen display, but then goes straight to the shutdown screen and is stuck there. I have tried the recovery mode to no avail. Does anyone have any ideas how to fix the problem?

A: I'd follow Mordoc's advice: Boot from a rescue system, mount /var/log and check the syslog out. Furthermore you should have a look at /boot - I have seen cases where this directory consumed 100 percent of the available partition space and therefore created the strangest errors.

A: To diagnose, I would boot from live-cd or usb and mount the drive. From there, I would navigate to the /var/log/ dir and hunt through the syslog and kern logs.


text:
Q: You must feed a value for placeholder tensor 'x' I'm a little blocked here.
I'm not new to tensorflow, even tho I did not work a lot with it.
But here's my problem :
I want to classify texts in 7 different categories, and for that I used the tfidf method to transform strings to numbers.
There, I transformed the sparse matrix into a dense one, which gives me a 2D matrix of shape (179, 482).
I split it into 150 obs training set and 29 obs testing set.
Then, I've setted up my model as follow :
'''
-------------------------------------------------------------------------
Convolution 2D avec RELU
-------------------------------------------------------------------------
'''
def conv1d(x, W, b, name_conv, name_bias, name_relu, strides=1):
    tensor = tf.nn.conv1d(x, W, strides, padding="SAME", name=name_conv)
    tensor = tf.nn.bias_add(tensor,b, name=name_bias)
    return tf.nn.relu(tensor, name=name_relu)

'''
-------------------------------------------------------------------------
Pooling max
-------------------------------------------------------------------------
'''
def maxpool2d(x, name, k=2):
    return tf.nn.max_pool(x, [1, k, k, 1], [1, k, k, 1], padding="SAME", name=name)

'''
-------------------------------------------------------------------------
Modele du reseau convolutif :
CONV1-RELU-CONV2-RELU-FCL-Prediction
-------------------------------------------------------------------------
'''
def conv_net(x, poids, biais):
    # Mise en forme de l'image d'entree
    x = tf.reshape(x, shape=[-1, 482, 1])

    conv1 = conv1d(x, poids['wconv1'], biais['bconv1'], name_conv='conv1', name_bias='bias1', name_relu='relu1')
    #conv1 = maxpool2d(conv1, k=2, name='pool1')

    conv2 = conv1d(conv1, poids['wconv2'], biais['bconv2'], name_conv='conv2', name_bias='bias2', name_relu='relu2')
    #conv2 = maxpool2d(conv2, k=2, name='pool2')

    # Mise en forme des activations de la seconde couche cachee pour l'entree de la couche completement connectee
    fcl = tf.reshape(conv2, [-1, poids['wfcl'].get_shape().as_list()[0]], name='reshape')
    fcl = tf.add(tf.matmul(fcl, poids['wfcl']), biais['bfcl'], name='fcl')
    fcl = tf.nn.relu(fcl, name='relu3')

    # Dropout
    #fcl = tf.nn.dropout(fcl, dropout, name='dropout')

    # Couche de sortie
    out = tf.add(tf.matmul(fcl, poids['out']), biais['out'], name='out')

    return out

if __name__ == '__main__':
    '''
    -------------------------------------------------------------------------
    Parametres du reseau
    -------------------------------------------------------------------------
    '''
    learning_rate = 0.00001
    num_epochs = 10
    batch_size = 1
    dropout = 0.75 # ici probabilite de garder le neurone

    logs_path = "tensorflow_logs"

    data, targets = getData()
    data = np.float32(data)
    targets = np.float32(targets)

    x_train = data[:150]
    y_train = targets[:150]

    x_test = data[150:]
    y_test = targets[150:]

    num_examples = x_train.shape[0]
    num_input =x_train.shape[1]
    num_classes = y_train.shape[1]

    # Affichage des informations par pas de temps
    display_step = 10

    # Espaces reserves qui vont etre remplis par les tenseurs representant l'ensemble des images et des labels lors de l'apprentissage
    x = tf.placeholder(tf.float32, [None, num_input], name='data')
    y = tf.placeholder(tf.float32, [None, num_classes], name='labels')
    #keep_prob = tf.placeholder(tf.float32, name='keep_prob')

    #Stockage des poids et biais dans des variables TF
    '''
    TODO : initialiser avec une loi normale des variables tensorFlow :
        - wconv1 et bcconv1 pour CONV1. wconv1 est un banc de 32 filtres 5*5*1. bconv1 a une taille adaptee
        - wconv2 et bconv2 pour CONV2. wcconv2 est un banc de 32 filtres 5*5*32*64. bconv2 a une taille adaptee
        - wfcl et bfcl pour la couche completement connectee : wfcl est un banc de filtres 7*7*64 a 1024 sorties. bfcl a une taille adaptee
        - out (poids et biais) ont une taille adaptee pour la classification des donnees MNIST
    '''

    poids = {
            'wconv1': tf.Variable(tf.random_normal([5, 1, 32])),
            'wconv2': tf.Variable(tf.random_normal([5, 32, 64])),
            'wfcl': tf.Variable(tf.random_normal([64, 1024])),
            'out': tf.Variable(tf.random_normal([1024, num_classes]))
    }

    biais = {
            'bconv1': tf.Variable(tf.random_normal([32])),
            'bconv2': tf.Variable(tf.random_normal([64])),
            'bfcl': tf.Variable(tf.random_normal([1024])),
            'out': tf.Variable(tf.random_normal([num_classes]))
    }

    # Construction du modele
    pred = conv_net(x, poids, biais)
    print(pred.shape)

    # Fonction de perte et procedure d'optimisation
    #TODO : entropie croisee avec logits, algorithme d'optimisation ADAM
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    # Evaluation du modele
    correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

    # Initialisation des variables
    init = tf.global_variables_initializer()

    tf.summary.scalar("cost", cost)
    tf.summary.scalar("accuracy", accuracy)

    merged_summary_op = tf.summary.merge_all()

    # Creation d'une session TF pour executer le programme
    with tf.Session() as sess:
        sess.run(init)

        train_writer = tf.summary.FileWriter(logs_path  + '/train', graph=tf.get_default_graph())
        test_writer = tf.summary.FileWriter(logs_path + '/test', graph=tf.get_default_graph())

        # Entrainement
        total_batch = int(num_examples/batch_size)
        for epoch in range(num_epochs):
            # Entrainement sur les batchs d'images
            for step in range (total_batch):
                perm = np.arange(num_examples)
                np.random.shuffle(perm)
                indices = perm[0:batch_size]
                batch_x = x_train[indices]
                batch_y = y_train[indices]
                _, summary = sess.run([optimizer, merged_summary_op], feed_dict={x: batch_x,
                                                 y: batch_y})
                train_writer.add_summary(summary, epoch*total_batch+step)
                if step % display_step == 0:
                    loss, acc, summaryt = sess.run([cost, accuracy, merged_summary_op], feed_dict={x: batch_x,
                                                                     y: batch_y})
                    test_writer.add_summary(summaryt, epoch*total_batch+step)
                    print("Iteration " + str(epoch * total_batch + step) + ", Precision  = " + "{:.5f}".format(acc))

        # Test

        print("Test:", sess.run(accuracy, feed_dict={x: x_test,
                                                     y: y_test}))

When I'm keeping my summaries, I get this error :

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'data' with dtype float and shape [?,482]

So, I'm a little lost, since when I remove the summaries as follow :
for step in range (total_batch):
            perm = np.arange(num_examples)
            np.random.shuffle(perm)
            indices = perm[0:batch_size]
            batch_x = x_train[indices]
            batch_y = y_train[indices]
            sess.run([optimizer], feed_dict={x: batch_x,
                                             y: batch_y})
            #train_writer.add_summary(summary, epoch*total_batch+step)
            if step % display_step == 0:
                loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                                 y: batch_y})
                #test_writer.add_summary(summaryt, epoch*total_batch+step)
                print("Iteration " + str(epoch * total_batch + step) + ", Precision  = " + "{:.5f}".format(acc))

My model is learning (it learns pretty much nothing, but still it's doing somthing)
Can anyone see what I'm doing wrong ?
I must confess that I've always worked with 4D arrays, mostly for image recognition, so this case is new for me.
Thanks for any good samaraitan that'll answer my question.
P.S. Sorry for french comments, but I'm sure you can still understand the code

A: Ok, there's something I forgot to mention : I'm working with Spyder.
The error must come from there for I executed my program directly in Ubuntu's console and everything works just fine.
Closing it here.


text:
Q: Bind Visibility to different source than DataContext I have two ViewModels:
public class CommandViewModel
{
    public string DisplayName { get; set; }
    public ICommand Command { get; set; }
}

and
public class SomeViewModel : INotifyPropertyChanged
{
    private bool someFlag;
    private CommandViewModel someCommand;

    public bool SomeFlag
    {
        get
        {
            return someFlag;
        }
        set
        {
            if (value == someFlag)
                return;
            someFlag = value;
            OnPropertyChanged("SomeFlag");
        }
    }

    public CommandViewModel SomeCommandViewModel
    {
        get
        {
            if (someCommand == null)
            {
                someCommand = new CommandViewModel();
                // TODO: actually set the DisplayName and Command
            }
            return someCommand;
        }
    }
}

And I have two corresponding Views:
<UserControl x:Class="ButtonView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="28" d:DesignWidth="91">
    <Button Content="{Binding Path=DisplayName}" Command="{Binding Path=Command}" />
</UserControl>

and
<UserControl x:Class="SomeView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" Height="125" Width="293" />

    <ViewButton
        Visibility="{Binding Path=SomeFlag, Converter={StaticResource BoolToVisibilityConverter}}"
        DataContext="{Binding Path=SomeCommandViewModel}" />
</UserControl>

I'm having a problem getting ButtonView's Visibility bound when its DataContext is also bound. If I leave the DataContext out, the Visibility works just fine (when SomeFlag switches value, the button's visibility changes with it) - but the display text and command don't work. If I bind the DataContext, the display text and command work, but the visibility doesn't. I'm sure it has to do with the fact that when I bind the DataContext to SomeCommandViewModel, it is expecting "SomeFlag" to exist within it. And of course, it doesn't.

A: If you set the DataContext of any given Element EVERY Binding (including children ones) of this element will use the DataContext as Source unless you explicitly give another source.
What you seem to do is specify 2 DataContext at once (UserControl.DataContext is NOT read as ViewButton.DataContext is set and the first source it finds counts).
You can either explicitly take the datacontext of a given element as Kent states
OR
you can specify the source explicitly.
e.g.
<ViewButton
    Visibility="{Binding Path=SomeFlag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Converter={StaticResource BoolToVisibilityConverter}}"
    DataContext="{Binding Path=SomeCommandViewModel}" />

A: I don't condone your design, but this will work around your immediate problem:
<UserControl x:Name="root"
    x:Class="SomeView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" Height="125" Width="293" />

    <ViewButton
        Visibility="{Binding Path=DataContext.SomeFlag, Converter={StaticResource BoolToVisibilityConverter}, ElementName=root}"
        DataContext="{Binding Path=SomeCommandViewModel}" />
</UserControl>


text:
Q: The Entity or complex type cannot be constructed in a Linq to Entity Query Good day to all.
Im Having Entity or complex type cannot be encountered
This is the first time i encountered this type of error
Someone Help me
    public IEnumerable<APPLICANT> GetApplicant()
    {
        IEnumerable<APPLICANT> applicantdata = Cache.Get("applicants") as IEnumerable<APPLICANT>;

        IEnumerable<Profile> profiledata = Cache.Get("profiles") as IEnumerable<Profile>;

        if (applicantdata == null)
        {

            var applicantList = (from a in context.Profiles
                                 join app in context.APPLICANTs
                                 on a.PROFILE_ID equals app.Profile_id
                                where app.APPLICANT_LogicalDelete == false
                                select new APPLICANT()
                                 {
               APPLICANT_LastName = a.Applicant_LASTNAME,
               APPLICANT_FirstName = a.Applicant_FIRSTNAME,
               APPLICANT_MiddleName = a.Applicant_MIDDLENAME,
               APPLICANT_Address = a.Applicant_ADDRESS,
               APPLICANT_City = a.Applicant_CITY,
               APPLICANT_Phone = a.Applicant_PHONE,
                APPLICANT_Email= a.Applicant_EMAIL
           });

            applicantdata = applicantList.Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName)).OrderBy(v => v.APPLICANT_ID).ToList();

            if (applicantdata.Any())
            {
                Cache.Set("applicants", applicantdata, 30);
            }
        }
        return applicantdata.ToList().Take(1000);

    }

And This is the line where i encounter the error
Thanks!
applicantdata = applicantList.Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName)).OrderBy(v => v.APPLICANT_ID).ToList();

AND THE ERROR IN THE LINE ABOVE IS
System.NotSupportedException: The entity or complex type 'Model.APPLICANT' cannot be constructed in a LINQ to Entities query.

A:
select new APPLICANT()

Entity Framework does not support this. It gets diagnosed when the query is used, not when the query is constructed, which is why the line where you get the exception is confusing.
You can construct any type that isn't also a database entity, including anonymous types, so you can do
select new
{
    a.Applicant_LASTNAME,
    a.Applicant_FIRSTNAME,
    a.Applicant_MIDDLENAME,
    a.Applicant_ADDRESS,
    a.Applicant_CITY,
    a.Applicant_PHONE,
    a.Applicant_EMAIL
}

and you can, if required, put those values back into APPLICANT objects after your query has finished executing.
Or, if appropriate, you can the APPLICANT directly:
select app

I'm not sure why you have Applicant_LASTNAME etc. in both Profile and APPLICANT, and I do not know if the values are the same. If they are not, this last suggestion won't be of use to you.

A: If I'm not wrong, you need to convert to Queryable objects.
applicantdata = applicantList.AsQueryable().Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName)).OrderBy(v => v.APPLICANT_ID).ToList();


text:
Q: Aggregate downstream test results I have a jenkins workflow configuration that is running several test jobs in parallel. What I would like to do, is aggregate all test results and display them on the 'workflow' job page.
Here is my current configuration:
node('git && linux') {
    // dome some stuff here
}

stage "Running unit tests for $REVISION"
build job: 'unit-tests', parameters: [[$class: 'StringParameterValue', name: 'REVISION', value: REVISION], [$class: 'StringParameterValue', name: 'REFSPEC', value: REFSPEC]]

stage "Running integration tests $REVISION"
def jobs = [:]
jobs['integration-tests-1']={build job: 'integration-tests-job-1', parameters: [[$class: 'StringParameterValue', name: 'REVISION', value: REVISION], [$class: 'StringParameterValue', name: 'REFSPEC', value: REFSPEC]]}
jobs['integration-tests-2']={build job: 'integration-tests-job-2', parameters: [[$class: 'StringParameterValue', name: 'REVISION', value: REVISION], [$class: 'StringParameterValue', name: 'REFSPEC', value: REFSPEC]]}
jobs['integration-tests-3']={build job: 'integration-tests-job-3', parameters: [[$class: 'StringParameterValue', name: 'REVISION', value: REVISION], [$class: 'StringParameterValue', name: 'REFSPEC', value: REFSPEC]]}

parallel jobs

// Here I would like to add something like
// aggregateDownstream('unit-tests', 'integration-tests-1', 'integration-tests-2', 'integration-tests-3'

Do you know if it would be possible to achieve this?