text:
Q: change image gallery function how i can to make these changes in below code?

*

*show thumbnail image title for
 when we click, thumb image.

*show thumbnail image title below of

*set URL thumbnail image for "blank.gif" ( i mean when we click thumb image,
 get URL of that thumb image, also. i want make this change for use full-screen of any image)

code here:

$(".productthumbs img").click(function() {
    // calclulate large image's URL based on the thumbnail URL (flickr specific)
    var url = $(this).attr("src");
    // get handle to element that wraps the image and make it semitransparent
    var wrap = $("#main").fadeTo("medium", 0.5);
    // the large image from flickr
    var img = new Image();
    // call this function after it's loaded
    img.onload = function() {
        // make wrapper fully visible
        wrap.fadeTo("fast", 1);
        // change the image
        wrap.find("img").attr("src", url);
    };
    // begin loading the image from flickr
    img.src = url;
// when page loads simulate a "click" on the first image
}).filter(":first").click();

A: I get my answer, put it here for anyone have same asking...

...

and add these lines :
wrap.find('h5').html(title);
wrap.find("a").eq(1).attr("href", url);

after :
    wrap.find("img").attr("src", url);

Good luck.


text:
Q: Ripple emulator is not working with Ionic on Mac OSX I am getting an error: Error: static() root path required when using the Ripple emulator with the Ionic Framework.
ripple emulate

A: I found a way to get this to work, I added a path to the apps www folder its working perfectly now.
ripple emulate --path /Users/user/Desktop/app/www

More here: https://www.npmjs.com/package/ripple-emulator

redpajama_set_name: RedPajamaStackExchange


text:
Q: Concerning the existence of a basis corresponding to the dual basis $\phi_1,\phi_2,...,\phi_n\in V'$ Is the following Proof Correct?

Theorem. Given that $V$ is finite dimensional and $\phi_1,\phi_2,...,\phi_n$ is a basis for $V' = \mathcal{L}(V,\mathbf{F})$ i.e. the dual of $V$. Show that there exists a basis of $V$ whose dual basis is $\phi_1,\phi_2,...,\phi_n$.

Proof.  Let $I_n = \{i\in\mathbf{Z^+}|i\leq n\}$. Since $\phi_1,\phi_2,...,\phi_n$ is a basis for $V'$ we can affirm that $\forall j\in I_n$ $\phi_j$ is not the zero linear functional consequently there exist a list of vectors $v_1,v_2,...,v_n$ such that $\forall j\in I_{n}(\phi_j(v_j)\neq 0)$.
Since $\dim V = \dim V'$ in order to show that $v_1,v_2,...,v_n$ is a basis it is sufficient for  us to show that $v_1,v_2,...,v_n$ is linearly independent.
Assume that for some $c_1,c_2,...,c_n\in\mathbf{F}$ $$c_1v_1+c_2v_2+\cdot\cdot\cdot+c_nv_n = 0\tag{1}$$
and that $i\in I_n$, applying $\phi_{i}$ to $(1)$ yields the equation $0 = c_i\phi(v_i)$ since $\phi_i(v_i)\neq 0$ it follows that $c_i = 0$ and since our choice of $i$ was arbitrary it follows that $c_1 = c_2 = ...  = c_n = 0$ .

A: No, the proof is not correct.
It is not enough that $\phi_i(v_i)=1$; you also need information about $\phi_i(v_j)$ when $i\neq j$.
In your computation for linear independence you assumed that $\phi_i(v_j)=0$ when $i\neq j$, but this does not follow from your choice of $v_i$s.
If you can find a basis $w_1,\dots,w_n$ of $V$ so that $\phi_i(w_j)=\delta_{ij}$, then your proof works, but you need to elaborate on why such a basis exists.
For example, if $w_i$s are such a good basis, in your proof nothing prevents you from choosing
$$
v_1=v_2=\dots=v_n=w_1+w_2+\dots+w_n.
$$
Now all the $v_i$s are equal but $\phi_i(v_i)=1$.
The problem is that $\phi_i(v_j)=1$ for all $i,j\in I_n$, and no terms vanish in the sum.


text:
Q: Trouble with _RCTReconnectingWebSocket with ExpoKit I'm experimenting an issue since some days ago, and I don't know what I made to have my project under a bad configuration. I hope explain it in a good way:
If I configure my scheme with build configuration set to Release, the build is ok. But when I changed the build configuration to Debug, the build is failed with the following error:
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_RCTReconnectingWebSocket", referenced from:
  objc-class-ref in libReact.a(RCTPackagerConnection.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

My project is a react native ejected with ExpoKit:
"expo": "^19.0.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-19.0.0.tar.gz",

Plus, the project has CocoaPods as a dependency manager (so I open the project with the xcworkspace file).
Any ideas what do I have wrong?


text:
Q: Why is swedish letters not working with fancyhdr for laTex pandoc conversion? Does anyone know why this decoding error happens when I try to convert a markdown file to pdf? Everything works fine except when I use Swedish letters in fancyhdr. If i remove the letter 'å' it works (the letter is in the YAML below).
pandoc-script:
pandoc  main_temp.md default.yaml  -o main.pdf --bibliography library.bib -V lang=sv

Error:
UTF-8 decoding error in default.yaml at byte offset 454 (e5).
The input must be a UTF-8 encoded text.

my YAML:
---
start-page: 2 # start pagenumbering on page 2
geometry: #
- top=2cm
- bottom=2cm
- left=2.4cm
- right=2.4cm
pagesize: a4
indent: true
font: Times New Roman
fontsize: 12pt
header-includes:
- \usepackage{setspace}
- \setstretch{1.5}

- \usepackage{fancyhdr} # for header and footer (ej sv tecken)
- \pagestyle{fancy} # not sure what this is
- \fancyhead[LO,LE]{myname}
- \fancyfoot[CO,CE]{Perspektiv pa politik 2020}
- \fancyfoot[LE,RO]{\thepage} # not sure what this is.

# Change size of header:
- \usepackage{sectsty}
- \sectionfont{\small}

# Change spacing left/before/after header:
- \usepackage{titlesec}
- \titlespacing*{\section}{0pt}{5pt}{2pt} #{left}{before}{after}
---
````

A: For some reason I missed that my files where ANSI and not UTF-8. Notepad first showed UTF-8 for some reason. Probably user error :)
This line fixed my problem:
- \usepackage[utf8]{inputenc}


text:
Q: Wigner transform of a thermal density matrix (Schrödinger Hamiltonian) I am interested in computing the Wigner transform in $R^{2n}$ of $$e^{-\beta H}$$
where
$$H = \sum_{k=1}^n P_k^2 + V(x_1, \ldots,x_n)$$
I am assuming that $V$ is a polynomial bounded below  and obviously $$P_k= -i\hbar \frac{\partial}{\partial x^k}$$
I am not necessarily interested in the exact result.  In particular, I would like to know if the Wigner function tends to the corresponding classical exponential for $\hbar \to 0$. Some references on these issues would be welcome.

A: Your question completely outranges my competence, but Balescu's famous book might be addressing it, at some level. In your shoes, I might choose an oscillator potential and resolve your hamiltonian to decoupled normal modes, which should be tractable with the celebrated (by dint of its non-triviality!) result for just one oscillator, I thought I might review below. It would only be useless if it were universally in mind.
Work in natural units of the problem, $m=1, ~~\omega=1$, i.e. absorb $\sqrt{m\omega}$ into x and 1/p, and $1/\omega$ into H,
rendering it as $H=(p^2+x^2)/2$. The quantum hamiltonian is then $\hat H=(\hat p^2+\hat x^2)/2$, whose Wigner transform is $H=(p^2+x^2)/2$.
The Groenewold-Moyal correspondence of QM operators to phase space variables x and p dictates that the Weyl transform of $\exp(-\beta \hat H)$ is $\exp_\star (-\beta H)$, the star exponential representing formally the power expansion of the exponential with powers supplanted by $\star$-powers.
$$
\exp_\star \left ( -\beta   H \right )
= \exp_\star \left ( -\beta H \right ) \star 1 \nonumber \\
=\exp_\star \left ( -\beta H \right )\star 2\pi\hbar \sum_n f_{n}
=2\pi\hbar \sum_n e^{-\beta E_n  }f_{n} ~,   \label{spectral}
$$
which is thus a generating function for the stargenfunctions $f_n$.
Of course, for $\beta =0$, the obvious  identity resolution  is recovered.
This Wigner transform, then, is directly seen (Bartlett-Moyal) to sum to
\begin{equation}
\exp_\star \left (-\beta  H  \right )=
\left ( \cosh\left(\frac{ \beta \hbar}{2}\right)\right ) ^{-1}
\exp\left ( \frac{-2}{\hbar} \tanh\left(\frac{\beta\hbar}{2}\right) H\right ) ,
\end{equation}
which is to say just a Gaussian
in phase phase,  with the proper classical $\hbar\to 0$ limit, the starting point.
Details and clarifications could be found in our short booklet, section 0.14 (time evolution).


text:
Q: Shell script moving incoming files in to folder depending on prefix file name I am a total newbie and can't pass a problem.
I have a process that transcode movie files to a folder. The files have a file name with two different prefixes.
I want to make all incoming NT_*.mp4 to be moved to one other predefined folder and all ET_*.mp4 to another predefined folder. They predefined with path and name.
Tried a simple if $fname=NT_*.mp4 then mv file to folder1 elif $fname=ET_*.mp4 mv that file to folder2. And that doesn't work, it just move all files in the folder to folder1, so that is obviously wrong way.
So what do I need to do for checking each file for it prefix and then move them based on the prefix to predefined folders?

A: Spaces are important. It looks like you used something like
fname="wrong"
if [[ $fname=="right" ]]; then
  echo "Equal"
fi

You should add spaces around the equal sign:
fname="wrong"
if [[ $fname == "right" ]]; then
  echo "Equal"
fi


text:
Q: Is it possible to include Runtime Directives in a .NET Core library? I am currently getting a MissingRuntimeArtifactException from a UWP app that is referencing a DNX library that I also wrote.  I have the following .rd.xml file included in the DNX xproj:
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata>
<Library Name="BinarySerializer">
<Type Name="BinarySerialization.BinarySerializer">
  <Method Name="Deserialize">
    <TypeParameter Name="type" Serialize="Required All" />
  </Method>
</Type>

If I convert the DNX xproj to a UWP library the runtime directive appears to be included and appears to resolve the exception in the UWP app.

A: It turns out this is possible by embedding the .rd.xml as a resource with the project.json file.
  "resource": [
    "BinarySerializer.rd.xml"]


text:
Q: ¿Cómo colocar saltos de línea en un JTextArea en Java? tengo un editor de texto en java :v en este puedes abrir y guardar archivos colocando la ruta del archivo mas el formato... pero cuando guardas un archivo los saltos de lineas que colocas no se guardan aquí una parte de mi código cuando preciosas el botón de guardar

        String archivo=new String(rutas.getText());//aqui se guarda en una variable el texto de la ruta
        String archivo2=new String(editor.getText());//aqui se optiene el texto que tiene el editor
        try {
            PrintWriter writer = new PrintWriter(archivo);
            String saltos = editor.getText().replace("\n", "\r\n");
            writer.println(archivo2);

            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

GRACIAS por la ayuda

A: iniciemos por entender que significa un Salto de linea Wikipedia en Ingles sobre "new line" o si no puedes entender bien el ingles Wikipedia en español sobre "new line" (el link en español eso es es muy pobre a lo cual minimo suguiero usar google translate en la version en ingles...)
en sintesis existen varias formas de demostrar una nueva linea dependiendo del applicativo y/o Systema Operativo. los mas comunes son:
Unix like:'\n'
Windows & DOS: '\r'+'\n'
'\r'– Macs (OS 9 y anteriores)
donde '\n' significa "Line Feed" y '\r' Carriage return
con lo anterior claro, recordemos que Java es Independiente de la plataforma y puede utilizar o no el mismo caracter. en los elementos como el JTextArea los saltos de linea por defecto son representados como '\n'
por tanto cuando usas editor.getText() este retorna in String. que muy probablemente sus lineas son separadas por '\n' para guardar el String a un archivo y conservar las "nuevas lineas" con el mismo formato del systema Operativo en donde se ejecuta la applicacion se debe realizar una de las siguientes acciones:
A:
String salto = System.lineSeparator(); //java 6 para atras se utiliza: System.getProperty("line.separator");
String towrite= editor.getText().replace("\n",salto);
writer.println(towrite);
writer.flush();
writer.close();

B:
String salto = System.lineSeparator(); //java 6 para atras se utiliza: System.getProperty("line.separator");
editor.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, salto);
editor.write(writer);
writer.flush();
writer.close();

mas sobre este metodo ver este link
particularmente en tu codigo el problema que tienes es el siguiente:
new String() es redundante Y ademas un gasto de memoria innesesario los String en java son Immutables!

   String archivo=new String(rutas.getText());

debe ser
    String archivo=rutas.getText();

esta linea esta de mas y/o la variable esta mal nombrada

    String archivo2=new String(editor.getText());//aqui se optiene el texto que tiene el editor

modificarlo a algo mas significativo:
String texto_editor= editor.getText();

Y el mayor offensor! saltos es el texto que remplazo '\n' por "\r\n" pero no se hace nada con el por que la siguiente linea lo que hace es guardar archivo2 que se hace con la variable saltos

        String saltos = editor.getText().replace("\n", "\r\n");
        writer.println(archivo2);
        ...
    }

recuerda, los String son immutables. si lee un texto del UI y lo modifica, este no se refleja en el UI, debe re ingresar el texto, y aun si ese fuera el caso archivo2 no es una referencia al texto de editor por tanto igual esta mal.


text:
Q: Let the minimum edit length depend on a post's age and answered status For a very old post (especially a question that has accepted/upvoted answers, or any answer to such a question) there is not much point fixing minor spelling errors at the expense of putting it back to front page.
On the other hand, a question that is only a couple of minutes old is on front page anyway, so in this case a minor bump due to something simple yet severe like a missing semicolon in a MWE (assuming that is not the origin of the question's problem) should be much more acceptable.
Therefore I propose the minimum edit length starting at 1 char during the first few minutes and increase it in an adequate manner (to be elaborated upon) to a rather high number for questions older than a specific age.

A: An example could be something like this:
Post Age | Min. edit length
---------+----------------------
< 5 min  |  1
5-30 min |  2
.5-2 h   |  4
---------+----------------------
         |    | min. edit length
Question |    | in presence of
  Age    |    | upvoted/accepted
         |    | answers
---------+----+-----------------
2-24 h   |  8 |  16
1-7 d    | 16 |  32
1-4 w    | 32 |  64
> 4 w    | 64 | 128

Note that in this example, for answers younger than 2 hours their own age is considered (they caused a bump due to their mere creating anyway), while after that the question's age (always larger than the answer's age) is considered even for answer edits in order to make unnecessary edits/bumps less likely.


text:
Q: How to iterate this array to match all possible connections As a person that couldn't grasp recursion, I'm getting an array that has unlimited depth on parent <> child id links. This is a category list from an ecommerce platform (Shopee). And I'm trying to build a relationship list between all the categories and subcategories from the array below.
How to get this

Women's Clothing -> Tshirt -> Trending
                           -> Promotion

Shoes -> Hiking Shoe -> Winter Shoe

From the array below

$category = Array(
  [0] => Array
                (
                    [category_id] => 16
                    [parent_id] => 0
                    [category_name] => Women's Clothing
                    [has_children] => 1
                 )
  [1] => Array
                (
                    [category_id] => 18
                    [parent_id] => 16
                    [category_name] => Tshirt
                    [has_children] => 1
                 )
  [2] => Array
                (
                    [category_id] => 901
                    [parent_id] => 18
                    [category_name] => Trending
                    [has_children] => 0
                 )
  [3] => Array
                (
                    [category_id] => 23
                    [parent_id] => 0
                    [category_name] => Shoes
                    [has_children] => 1
                 )
  [4] => Array
                (
                    [category_id] => 100
                    [parent_id] => 23
                    [category_name] => Hiking Shoe
                    [has_children] => 1
                 )
  [5] => Array
                (
                    [category_id] => 120
                    [parent_id] => 100
                    [category_name] => Winter Shoe
                    [has_children] => 0
                 )
  [6] => Array
                (
                    [category_id] => 1400
                    [parent_id] => 18
                    [category_name] => Promotion
                    [has_children] => 0
                 )
)

A: You could first group the items by their parent key, and then perform a depth-first traversal through the data:
function dfs(&$childrenfor, $id, $path) {
    if (isset($childrenfor[$id])) {
        foreach($childrenfor[$id] as $item) {
            yield from dfs($childrenfor, $item["category_id"], [...$path, $item["category_name"]]);
        }
    } else {
        yield $path;
    }
}

// first group the items by parent key
foreach ($category as $item) {
    $childrenfor[$item["parent_id"]][] = $item;
}
// ...then use depth-first traversal to collect the root-to-leaf paths in the tree
$result = [...dfs($childrenfor, 0, [])];

The $result would have the following for your example data:
[
    ["Women's Clothing", "Tshirt", "Trending"],
    ["Women's Clothing", "Tshirt", "Promotion"],
    ["Shoes", "Hiking Shoe", "Winter Shoe"]
]

I guess you can take it from there to generate a format that suits you.


text:
Q: Is it possible to see the code generated by Macwire Is it possible to see what is the code generated by wire macro
lazy val securedRequestHandler : SecuredRequestHandler = wire[DefaultSecuredRequestHandler]

In the above example, I want to know what arguments were passed when DefaultSecuredRequestHandler was created. DefaultSecuredRequestHandler is not my class. It is part of Silhouette library.
I am trying to create an instance of DefaultSecuredRequestHandler and I need to pass BodyParser.Default to it but I dont know from where to get it. However, I found some code online which us using Macwire to create instance of DefaultSecuredRequestHandler. Thus I want to know how DefaultSecuredRequestHandler was created.
new DefaultSecuredAction(requestHandler: SecuredRequestHandler, bodyParser: Default) //I don't know how to create a bodyParser of type Default


text:
Q: UIStackview `fillProportionally` distribution issue I have a container stack view and it has 2 other stackviews lets call them stackview 1 and stackview 2. Stackview 2 have a custom UIView with some label.
My issue is with stackview 1 and it has 2 arranged subviews. Axis of this UIStackView is vertical.  These subviews are custom UIView. These custom view may contain text or image and height of these custom views is not predefined and they are based on the content (i.e based on the height of the text).
Custom view 1 and custom view 2 are added in stackview 1. Stack view 1 and stack view 2 are added inside another container stack view.
My issue is I'm not able to display both these custom views (which are inside stackview 1) even if I return intrinsicContentSize (based on intrinsicContentSize of textviews) for these custom views in fillProportionally distribution.
If I return a constant width and height in intrinsicContentSize for customview then both views are displayed properly.
Inside my custom view
override var intrinsicContentSize: CGSize {
    let size = CGSize.init(width: 100, height: 100)
    return size
   }

Screenshot shows this behaviour.

But if I return size based on the intrinsicContentSize of UITextView (subview of customView, I have disabled scroll for textview) then only customview 2 is displayed and another view (customview 1) is not displayed.
Inside my Custom view
  override var intrinsicContentSize: CGSize {
       let size = textView.intrinsicContentSize
       return size
       }

Screenshot shows this behaviour.

I want fillProportionally behaviour but I cannot make it to work as I want which is to display both views (custom view 1 and custom view 2).
 According to documentation fillProportionally uses intrinsicContentSize to fill views proportionally. But why isn't that working in my case even after I overrided intrinsicContentSize var?
Why custom view 1 have zero hight even after overriding it's intrinsic content size?
I want both of these custom views to be displayed inside stack view 1.
I have been stuck here so I would greatly appreciate any help.

A: The .fillProportionally property of UIStackView is (from my experience) one of the most misunderstood elements of auto-layout.
So, I'm not entirely sure this is going to give you what you want, but give it a try.

Tapping the Text button will change the "description" text and tapping the Height button will change the height of the "container" view, so you can see how it looks with different amounts of text.
The Report button will print the resulting heights and proportional ratios of the views.
All via code - no @IBOutlet or @IBAction connections - so just start with a new view controller and assign its custom class to ProportionalStackViewController:
class ProportionalHeightView: UIView {

    let myNonScrollTextView: UITextView = {
        let v = UITextView()
        v.isScrollEnabled = false
        v.setContentHuggingPriority(.required, for: .vertical)
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() -> Void {

        let padding: CGFloat = 0.0
        addSubview(myNonScrollTextView)
        myNonScrollTextView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myNonScrollTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
            myNonScrollTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding),

            // if we want the text top-aligned
            //myNonScrollTextView.topAnchor.constraint(equalTo: topAnchor),

            // if we want the text vertically=sentered
            myNonScrollTextView.centerYAnchor.constraint(equalTo: centerYAnchor),
        ])

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        myNonScrollTextView.sizeToFit()
        invalidateIntrinsicContentSize()
    }

    override var intrinsicContentSize: CGSize {
        return myNonScrollTextView.bounds.size
    }
}

class TitleView: ProportionalHeightView {

    override func commonInit() {
        super.commonInit()
        myNonScrollTextView.font = UIFont.systemFont(ofSize: 22.0, weight: .bold)
        myNonScrollTextView.backgroundColor = .cyan
        backgroundColor = .blue
    }

}
class DescView: ProportionalHeightView {

    override func commonInit() {
        super.commonInit()
        myNonScrollTextView.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
        myNonScrollTextView.backgroundColor = .yellow
        backgroundColor = .orange
    }

}

class ProportionalStackViewController: UIViewController {

    var titleView: ProportionalHeightView = {
        let v = ProportionalHeightView()
        v.myNonScrollTextView.font = UIFont.systemFont(ofSize: 22.0, weight: .bold)
        v.myNonScrollTextView.backgroundColor = .cyan
        v.backgroundColor = .blue
        return v
    }()
    var descView: ProportionalHeightView = {
        let v = ProportionalHeightView()
        v.myNonScrollTextView.font = UIFont.systemFont(ofSize: 16.0, weight: .regular)
        v.myNonScrollTextView.backgroundColor = .yellow
        v.backgroundColor = .orange
        return v
    }()

    let containerView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }()

    let proportionalStackView: UIStackView = {
        let v = UIStackView()
        v.axis = .vertical
        v.distribution = .fillProportionally
        return v
    }()

    let changeTextButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Text", for: .normal)
        return b
    }()
    let changeHeightButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Height", for: .normal)
        return b
    }()
    let reportButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Report", for: .normal)
        return b
    }()
    let btnStack: UIStackView = {
        let v = UIStackView()
        v.distribution = .fillEqually
        v.spacing = 20
        return v
    }()

    var nLines = 0

    var containerH = NSLayoutConstraint()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .systemTeal

        btnStack.translatesAutoresizingMaskIntoConstraints = false
        proportionalStackView.translatesAutoresizingMaskIntoConstraints = false
        containerView.translatesAutoresizingMaskIntoConstraints = false

        // add a horizontal stack view with buttons at the top
        btnStack.addArrangedSubview(changeTextButton)
        btnStack.addArrangedSubview(changeHeightButton)
        btnStack.addArrangedSubview(reportButton)

        view.addSubview(btnStack)

        // set text for titleView
        titleView.myNonScrollTextView.text = "Pleasanton Panthers"
        descView.myNonScrollTextView.text = "A one stop destination for all the Panthers fans! Experience our new futuristic techology-enabled fan experience an much more!" // "Single line"

        proportionalStackView.addArrangedSubview(titleView)
        proportionalStackView.addArrangedSubview(descView)

        containerView.addSubview(proportionalStackView)
        view.addSubview(containerView)

        // respect safe area
        let g = view.safeAreaLayoutGuide

        containerH = containerView.heightAnchor.constraint(equalToConstant: 240.0)

        NSLayoutConstraint.activate([

            // buttons stack 20-pts from top / leading / trailing
            btnStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            btnStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            btnStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            // container view 20-pts from bottom of buttons, 20-pts from leading / trailing
            containerView.topAnchor.constraint(equalTo: btnStack.bottomAnchor, constant: 20.0),
            containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            // container view height
            containerH,

            // constrain stack view 20-pts from top/bottom/leading/trailing to container
            proportionalStackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20.0),
            proportionalStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20.0),
            proportionalStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20.0),
            proportionalStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20.0),

        ])

        changeTextButton.addTarget(self, action: #selector(changeText), for: .touchUpInside)
        changeHeightButton.addTarget(self, action: #selector(changeHeight), for: .touchUpInside)
        reportButton.addTarget(self, action: #selector(report), for: .touchUpInside)

        [titleView, titleView.myNonScrollTextView, descView, descView.myNonScrollTextView].forEach {
            v in
            // un-comment next line to clear background colors
            //v.backgroundColor = .clear
        }
    }

    @objc func report() -> Void {

        let titleTextH = titleView.myNonScrollTextView.frame.size.height
        let descTextH = descView.myNonScrollTextView.frame.size.height

        let titleViewH = titleView.frame.size.height
        let descViewH = descView.frame.size.height

        let tRatio = titleTextH / descTextH
        let vRatio = titleViewH / descViewH

        print("text heights:\t", titleTextH, descTextH)
        print("view heights:\t", titleViewH, descViewH)
        print("Text view ratio: \(tRatio) view ratio: \(vRatio)")

    }

    @objc func changeHeight() -> Void {
        if containerView.frame.origin.y + containerView.frame.size.height > view.frame.size.height - 20 {
            containerH.constant = 220
        }
        containerH.constant += 20
    }

    @objc func changeText() -> Void {
        nLines += 1
        if nLines > 10 {
            descView.myNonScrollTextView.text = "A one stop destination for all the Panthers fans! Experience our new futuristic techology-enabled fan experience an much more!" // "Single line"
            nLines = 0
            return
        }
        var s = ""
        for i in 1..<nLines {
            s += "Line \(i)\n"
        }
        s += "Line \(nLines)"
        descView.myNonScrollTextView.text = s
    }

}


text:
Q: Html/Php como alterar o conteudo da pagina de acordo com o final inserido Tenho um HTML aqui que uso para gerar Players em Meu Site
Porém tenho que ficar mudando o conteudo do arquivo para acessar Videos Diferentes
Gostaria de Sabe se há uma forma de Mudar a Area:
De acordo com a url inserida Exemplo

www.site.com.br/Player.html?video=video.mp4;img=img.png

Teria que mudar o Arquivo para Php?
Por Favor me Ajude não tenho experiencia com Programação WEB

HTML:
<video id="my_video_1" class="video-js vjs-default-skin" width="640px" height="267px"
      controls preload="none" poster='https://image.tmdb.org/t/p/w780/fVcZErSWa7gyENuj8IWp8eAfCnL.jpg'
      data-setup='{ "aspectRatio":"640:267", "playbackRates": [1, 1.5, 2] }'>
    <source src="" type='video/mp4' />

  </video>

A: Você pode apenas usar as variáveis $_GET do endereço. Seguindo seu exemplo (consertei o separador de ; para &:
www.site.com.br/Player.php?video=video.mp4&img=img.png

Você tem dois atributos, "video" e "img", e os valores deles. Então o PHP fica bem simples:
<video id="my_video_1" class="video-js vjs-default-skin" width="640px" height="267px"
  controls preload="none" poster='<?= $_GET['img'] ?>'
  data-setup='{ "aspectRatio":"640:267", "playbackRates": [1, 1.5, 2] }'>
<source src="<?= $_GET['video'] ?>" type='video/mp4' />

O resultado seria:
<video id="my_video_1" class="video-js vjs-default-skin" width="640px" height="267px"
  controls preload="none" poster='img.png'
  data-setup='{ "aspectRatio":"640:267", "playbackRates": [1, 1.5, 2] }'>
<source src="video.mp4" type='video/mp4' />

Dá pra depois você melhorar o código pra não mostrar o vídeo se, por exemplo, não tiver nenhum argumento, mas aí seria melhor você sentar e aprender a programar mesmo.


text:
Q: How do I initialize radius in this instance? I don't know how to initialize radius so that the user can input the radius when prompted to instead of having a set value to radius. I think I have everything else pretty much right here but I cannot for the life of me figure this out.
 What am I missing here? Please help
import java.util.Scanner;
import java.text.DecimalFormat;

public class CircleCalc
{
  public static void main(String[]args)
   {
  Scanner keyboard = new Scanner(System.in);
  double radius;
  double area = Math.PI * radius * radius;
  double circum = 2 * radius * Math.PI;
  DecimalFormat formatter = new DecimalFormat("#.0000");
  int choice;

  System.out.println("CIRCLE CALCULATOR MENU");
  System.out.println("1) Calculate the Area of a Circle");
  System.out.println("2) Calculate the CIrcumference of a Circle");
  System.out.println("3) Quit the Program");
  System.out.println("Make a selection by choosing a number:");
  choice = keyboard.nextInt();

  if (choice == 1)
  {
     System.out.println("What is the radius of the Circle?");
     radius = keyboard.nextInt();
     System.out.println(" The Area of the Circle with radius " + radius + " is " + area);
  }

  else if (choice == 2)
  {
     System.out.println("What is the radius of the Circle?");
     radius = keyboard.nextInt();
     System.out.println("The Circumference of the Circle with radius " + radius+ " is " + formatter.format(circum));
  }

  else if (choice == 3)
  {
  System.out.println("You have chosen to quit the program.");
  }

  else if (choice >3)
  {
  System.out.println("You have made an invalid selection.");
  }
   }

}

A: Here is your problem.
Scanner keyboard = new Scanner(System.in);
  double radius;
  double area = Math.PI * radius * radius;
  double circum = 2 * radius * Math.PI;
You have not initialized the radius value but at the same time you're using it in calculating area and circumference. Get the input from user first. Do this first radius = keyboard.nextInt();.
You can do the calculation after you have got the radius value from the user.
Hope that helps

A: It looks like you want to define functions that calculate the circumference and the area for any radius (since you don't know the concrete radius at the point where you know how to calculate those)
public static double area(double radius) {
    return Math.PI * radius * radius;
}

public static double circum(double radius) {
    return 2 * radius * Math.PI;
}

Then later when you need to calculate the results you invoke these methods:
System.out.println(" The Area of the Circle with radius " + radius + " is " + area(radius));

And
System.out.println("The Circumference of the Circle with radius " + radius + " is "
                   + formatter.format(circum(radius)));


text:
Q: i am trying to make a pong game in android but i am stuck ,i dont know why ball isnt moving here is the class which extends surface view , in its run method i've called the method to animate ball but the ball isnt animating
 public  class OurView extends SurfaceView implements Runnable
{
    Canvas c;
    Thread t = null;

    SurfaceHolder holder;
    boolean isItOk = false;
    Rect racketTop,racketBottom;

    int TopLeft ;
    int TopRight ;
    int TopTop ;
    int TopBottom;

    int bottomLeft;
    int bottomRight;
    int bottomTop;
    int bottomBottom;

    GameState state;

    public OurView(Context context) {
        super(context);
        holder = getHolder();
        state = new GameState();
    }

    @Override
    public void run() {

        while (isItOk == true) {

            if (!holder.getSurface().isValid())
                continue;

            c = holder.lockCanvas();
            c.drawARGB(0, 0, 0, 0);
            TopLeft = ((c.getWidth() / 2) / 2) + 50;
            TopRight = (c.getWidth() / 2) + ((c.getWidth() / 2) / 2) - 50;
            TopTop = getTop();
            TopBottom = 10;

            bottomLeft = ((c.getWidth() / 2) / 2) + 50;
            bottomRight = (c.getWidth() / 2) + ((c.getWidth() / 2) / 2) - 50;
            bottomTop = getBottom() - 10;
            bottomBottom = getBottom();

            racketTop = new Rect();                                                                  // for top racket
            racketTop.set(TopLeft, TopTop, TopRight, TopBottom);                                      //left = ((c.getWidth()/2)/2)+50
                                                                                //top = getTop()
                                                                                //right = (c.getWidth()/2)+((c.getWidth()/2)/2)-50
                                                                                //bottom = 10

            racketBottom = new Rect();                                                         // FOR BOTTOM RACKET
            racketBottom.set(bottomLeft, bottomTop, bottomRight, bottomBottom);                                                 //left = ((c.getWidth()/2)/2)+50
                                                                                // top = getBottom()-10
                                                                                // right = (c.getWidth()/2)+((c.getWidth()/2)/2)-50
                                                                                // bottom = getBottom()

            Paint white = new Paint();
            white.setColor(Color.WHITE);
            white.setStyle(Paint.Style.FILL);

            c.drawRect(racketTop, white);
            c.drawRect(racketBottom, white);

here i called the method
            state.update();

            state.draw(c,white);
            holder.unlockCanvasAndPost(c);

        }
    }
     public void pause()
    {
        isItOk = false;
        while(true)
        {
            try
            {
                t.join();
            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }

            break;
        }

        t = null;
    }

    public void resume()
    {
        isItOk = true;
        t = new Thread(this);
        t.start();

    }

here is the class where ball is defined
     public class GameState {

int ballx,bally;        //ball x and y position
int ball_size = 20;          // size of ball
static int ballvelx = 3;    // velocity x of ball
static int ballvely = 3;    // velocity y of ball

public GameState() {

}

public void update()
{
    ballx += ballvelx;
    bally += ballvely;

}

public void draw(Canvas canvas, Paint paint)
{
     //objects color
    paint.setColor(Color.WHITE);

    ballx = canvas.getWidth()/2;
    bally = canvas.getHeight()/2;

    //ball
    canvas.drawCircle(ballx,bally,ball_size,paint);
}

}
help me this is my first android game

A: Without judging on the rest of your code:
ballx = canvas.getWidth()/2;
bally = canvas.getHeight()/2;

This resets the position of your ball every time you draw it.
No wonder it does not move, when you reset its position.
Call update() instead, so the ball is moved.


text:
Q: How to compare and then concatenate information from two different rows using python pandas data frames I have written this code:
import pandas as pd
import numpy as np

input_table = {'W' : pd.Series([1.1,2.1,3.1,4.1,5.1,6.1], index = ['1','2','3','4','5','6']),
     'X' : pd.Series([7.,8.,9.,10.,11.,12.], index = ['1','2','3','4','5','6']),
     'Y' : pd.Series(['A','B','C','D','E','E'], index = ['1','2','3','4','5','6']),
     'Z' : pd.Series(['First',' ','Last','First',' ','Last'], ['1','2','3','4','5','6'])}

output_table = pd.DataFrame(input_table)

output_table['Previous_Y'] = output_table['Y']

output_table.Previous_Y = output_table.Previous_Y.shift(1)

def Calc_flowpath(x):
    if x['Z'] == 'First':
        return x['Y']
    else:
        return x['Previous_Y'] + x['Y']

output_table['Flowpath'] = output_table.apply(Calc_flowpath, axis=1)

print output_table

And my output is (as expected):
     W     X  Y      Z Previous_Y Flowpath
1  1.1   7.0  A  First        NaN        A
2  2.1   8.0  B                 A       AB
3  3.1   9.0  C   Last          B       BC
4  4.1  10.0  D  First          C        D
5  5.1  11.0  E                 D       DE
6  6.1  12.0  E   Last          E       EE

However, what I'm trying to do with the Flowpath function is:

If Column Z is "First", Flowpath = Column Y
If Column Z is anything else, Flowpath = Previous Flowpath value + Column Y
Unless Column Y repeats the same value, in which case skip that row.

The output I am targeting is:
     W     X  Y      Z Previous_Y Flowpath
1  1.1   7.0  A  First        NaN        A
2  2.1   8.0  B                 A       AB
3  3.1   9.0  C   Last          B      ABC
4  4.1  10.0  D  First          C        D
5  5.1  11.0  E                 D       DE
6  6.1  12.0  E   Last          E       DE

To give context, these lines are steps in a manufacturing process, and I'm trying to describe the path materials take through a job shop.  My data is a large number of customer orders and every step they took in the manufacturing process.  Y is the manufacturing step, and column Z indicates the first and last step for each order.  I'm using Knime to do the analysis but I can't find a node that will do this, so I'm trying to write a python script myself even though I'm quite the programming novice (as you can probably see).  In my previous job, I would have done this in Alteryx using the Multi-Row node but I no longer have access to that software.  I've spent a lot of time reading the Pandas documentation and I feel the solution is some combination of DataFrame.loc, DataFrame.shift, or DataFrame.cumsum, but I can't figure it out.
Any help would be greatly appreciated.

A: Iterate over the rows of your DataFrame and set the value of the Flowpath column following the logic you outline in the OP.
import pandas as pd

output_table = pd.DataFrame({'W' :[1.1, 2.1, 3.1, 4.1, 5.1, 6.1],
                             'X': [7., 8., 9., 10., 11., 12.],
                             'Y': ['A', 'B', 'C', 'D', 'E', 'E'],
                             'Z': ['First', ' ', 'Last', 'First', ' ', 'Last']},
                            index=range(1, 7))

output_table['Flowpath'] = ''

for idx in output_table.index:
    this_Z = output_table.loc[idx, 'Z']
    this_Y = output_table.loc[idx, 'Y']
    last_Y = output_table.loc[idx-1, 'Y'] if idx > 1 else ''
    last_Flowpath = output_table.loc[idx-1, 'Flowpath'] if idx > 1 else ''

    if this_Z == 'First':
        output_table.loc[idx, 'Flowpath'] = this_Y
    elif this_Y != last_Y:
        output_table.loc[idx, 'Flowpath'] = last_Flowpath + this_Y
    else:
        output_table.loc[idx, 'Flowpath'] = last_Flowpath

A: You can calculate a group variable by cumsum on the condition vector where Z is first to satisfy the first and second conditions and replace the same value as previous one with empty string so that you can do cumsum on the Y column which should give the expected output:
import pandas as pd
# calculate the group varaible
grp = (output_table.Z == "First").cumsum()

# calculate a condition vector where the current Y column is the same as the previous one
dup = output_table.Y.groupby(grp).apply(lambda g: g.shift() != g)

# replace the duplicated process in Y as empty string, group the column by the group variable
# calculated above and then do a cumulative sum
output_table['flowPath'] = output_table.Y.where(dup, "").groupby(grp).cumsum()

output_table

#     W X   Y       Z   flowPath
# 1 1.1 7   A   First          A
# 2 2.1 8   B                 AB
# 3 3.1 9   C   Last         ABC
# 4 4.1 10  D   First          D
# 5 5.1 11  E                 DE
# 6 6.1 12  E   Last          DE

Update: The above code works under 0.15.2 but not 0.18.1, but a little bit tweaking with the last line as following can save it:
output_table['flowPath'] = output_table.Y.where(dup, "").groupby(grp).apply(pd.Series.cumsum)

A: for index, row in output_table.iterrows():
   prev_index = str(int(index) - 1)
   if row['Z'] == 'First':
       output_table.set_value(index, 'Flowpath', row['Y'])
   elif output_table['Y'][prev_index] == row['Y']:
       output_table.set_value(index, 'Flowpath', output_table['Flowpath'][prev_index])
   else:
       output_table.set_value(index, 'Flowpath', output_table['Flowpath'][prev_index] + row['Y'])

print output_table

     W     X  Y      Z Previous_Y Flowpath
1  1.1   7.0  A  First        NaN        A
2  2.1   8.0  B                 A       AB
3  3.1   9.0  C   Last          B      ABC
4  4.1  10.0  D  First          C        D
5  5.1  11.0  E                 D       DE
6  6.1  12.0  E   Last          E       DE

A: So bad things will happen if Z['1']!='First' but for your case this works. I understand you want something more Pandas-ish so I'm sorry that this answer is pretty plain python...
import pandas as pd
import numpy as np

input_table = {'W' : pd.Series([1.1,2.1,3.1,4.1,5.1,6.1], index = ['1','2','3','4','5','6']),
     'X' : pd.Series([7.,8.,9.,10.,11.,12.], index = ['1','2','3','4','5','6']),
     'Y' : pd.Series(['A','B','C','D','E','E'], index = ['1','2','3','4','5','6']),
     'Z' : pd.Series(['First',' ','Last','First',' ','Last'], index =['1','2','3','4','5','6'])}

ret = pd.Series([None,None,None,None,None,None], index = ['1','2','3','4','5','6'])
for k in [str(n) for n in range(1,7)]:
    if(input_table['Z'][k]=='First'):
        op = input_table['Y'][k]
    else:
        if(input_table['Y'][k]==input_table['Y'][str(int(k)-1)]):
            op = ret[str(int(k)-1)]
        else:
            op = ret[str(int(k)-1)]+input_table['Y'][k]
    ret[k]=op

input_table['Flowpath'] = ret
output_table = pd.DataFrame(input_table)
print output_table

Prints::
  Flowpath    W   X  Y      Z
1        A  1.1   7  A  First
2       AB  2.1   8  B
3      ABC  3.1   9  C   Last
4        D  4.1  10  D  First
5       DE  5.1  11  E
6       DE  6.1  12  E   Last


text:
Q: Cannot initialize public static class when the DLL is placed in a remote server This question derives another question "DLL cannot find AppConfig file on remote location" As at first I wasn't able to get detail stack trace on Powershell, but later when I find out a way to see the stack trace, I realize the question may not be accurate and may be a new question.
I have a DLL in a network shared folder, and after I import it to PowerShell by using Import-Module, calling the DLL's methods shows this error:

The type initializer for Configuration.AppConfiguration threw an exception

and the exception is a TypeInitializationException.
The exception is thrown for the class:
namespace Configuration
public static class AppConfiguration
{
    private static Configuration Configuration = ConfigurationManager.OpenExeConfiguration(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);
    public static string name {...}
    public static int timeout {...}
}

If I copy the DLL to my local folder, the error will not happen and everything works correctly, however on that remote location, it just doesn't work.

A: you class does not have the default constructor , add a default static/non static constructor to class that is throwing this error


text:
Q: Protocol buffer objects generated at runtime a colleague of mine came with an idea of generating protocol buffers classes at runtime. Meaning:

*

*There is C++ server application and Java client application communicating over TCP/IP via protocol buffers messages.

*The C++ application may have different schema in different versions and this is not necessarily backward compatible

*There is Java application communicating with this server which should support all possible server versions.

The idea is that the server sends the protocol buffer's definition as part of the initial handshake and the java application generates the class at runtime and use it for communication with the server.
I wonder whether this is even vital idea and if there is possibly some utility for such use case.
Thanks

A: What you describe is actually already supported by the Protocol Buffers implementations in C++ and Java.  All you have to do is transmit a FileDescriptorSet (as defined in google/protobuf/descriptor.proto) containing the FileDescriptorProtos representing each relevant .proto file, then use DynamicMessage to interpret the messages on the receiving end.
To get a FileDescriptorProto in C++, given message type Foo that is defined in that file, do:
google::protobuf::FileDescriptorProto file;
Foo::descriptor().file()->CopyTo(&file);

Put all the FileDescriptorProtos that define the types you need, plus all the files that they import, into a FileDescriptorSet proto.  Note that you can use google::protobuf::FileDescriptor (the thing returned by Foo::descriptor().file()) to iterate over dependencies rather than explicitly name each one.
Now, send the FileDescriptorSet to the client.
On the client, use FileDescriptor.buildFrom() to convert each FileDescriptorProto to a live Descriptors.FileDescriptor.  You will have to make sure to build dependencies before dependents, since you have to provide the already-built dependencies to buildFrom() when building the dependents.
From there, you can use the FileDescriptor's findMessageTypeByName() to find the Descriptor for the specific message type you care about.
Finally, you can call DynamicMessage.newBuilder(descriptor) to construct a new builder instance for the type in question.  DynamicMessage.Builder implements the Message.Builder interface, which has fields like getField() and setField() to manipulate the fields of the message dynamically (by specifying the corresponding FieldDescriptors).
Similarly, you can call DynamicMessage.parseFrom(descriptor,input) to parse messages received from the server.
Note that one disadvantage of DynamicMessage is that it is relatively slow.  Essentially, it's like an interpreted language.  Generated code is faster because the compiler can optimize for the specific type, whereas DynamicMessage has to be able to handle any type.
However, there's really no way around this.  Even if you ran the code generator and compiled the class at runtime, the code which actually uses the new class would still be code that you wrote earlier, before you knew what type you were going to use.  Therefore, it still has to use a reflection or reflection-like interface to access the message, and that is going to be slower than if the code were hand-written for the specific type.
But is it a good idea?
Well, this depends.  What is the client actually going to do with this schema it receives from the server?  Transmitting a schema over the wire doesn't magically make the client compatible with that version of the protocol -- the client still has to understand what the protocol means.  If the protocol has been changed in a backwards-incompatible way, this almost certainly means that the meaning of the protocol has changed, and the client code has to be updated, schema transmission or not.  The only time where you can expect the client to continue working without an update is when the client is only doing a generic operation that only depends on the message content but not the message meaning -- for example, the client could convert the message to JSON without having to know what it means.  But this is relatively unusual, particularly on the client end of an application.  This is exactly why Protobufs doesn't send any type information by default -- because it's usually useless, since if the receiver doesn't know the meaning, the schema is irrelevant.
If the issue is that the server is sending messages to the client which aren't intended to be interpreted at all, but just sent back to the server at a later time, then the client doesn't need the schema at all.  Just transmit the message as bytes and don't bother parsing it.  Note that a bytes field containing an encoded message of type Foo looks exactly the same on the wire as a field whose type is actually declared as Foo.  You could actually compile the client and server against slightly different versions of the .proto file, where the client sees a particular field as bytes while the server sees it as a sub-message, in order to avoid the need for the client to be aware of the definition of that sub-message.
      ``

A: For Java you may find following wrapper API ("protobuf-dynamic") easier to use than the original protobuf API:
https://github.com/os72/protobuf-dynamic
For example:
// Create dynamic schema
DynamicSchema.Builder schemaBuilder = DynamicSchema.newBuilder();
schemaBuilder.setName("PersonSchemaDynamic.proto");

MessageDefinition msgDef = MessageDefinition.newBuilder("Person") // message Person
    .addField("required", "int32", "id", 1)     // required int32 id = 1
    .addField("required", "string", "name", 2)  // required string name = 2
    .addField("optional", "string", "email", 3) // optional string email = 3
    .build();

schemaBuilder.addMessageDefinition(msgDef);
DynamicSchema schema = schemaBuilder.build();

// Create dynamic message from schema
DynamicMessage.Builder msgBuilder = schema.newMessageBuilder("Person");
Descriptor msgDesc = msgBuilder.getDescriptorForType();
DynamicMessage msg = msgBuilder
    .setField(msgDesc.findFieldByName("id"), 1)
    .setField(msgDesc.findFieldByName("name"), "Alan Turing")
    .setField(msgDesc.findFieldByName("email"), "at@sis.gov.uk")
    .build();

Dynamic schemas can be useful in some applications to distribute changes without recompiling code (say in a more dynamically typed system). They can also be very useful for "dumb" applications that require no semantic understanding (say a data browser tool)


text:
Q: Replace content via scripting in batch of smart objects(Replace layers) in photoshop cc 20.0.0 So I have these 28 *.tif image files as 28 layers (smart objects) I have arranged in a .psd file and wish to replace each layer with another .tif file. I wish to run some script(jsx) with loop something like this :
for (i=1;i<=28;i++) {
  for j in (start,end) {
     for k in (a,b,c,d,e,f) {
            file = 'chr' + $i + '_' + $j + '_' + $k;
                     }}}

update July2020: sorry for this late, I had found one solution and was like this, you first should download json2.js :
// replace smart object's content and save psd;
#target photoshop
#include json2.js
if (app.documents.length > 0) {
  var myDocument = app.activeDocument;
  var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
  var thePath = myDocument.path;

  psdOpts = new PhotoshopSaveOptions();
  psdOpts.embedColorProfile = true;
  psdOpts.alphaChannels = true;
  psdOpts.layers = true;
  psdOpts.spotColors = true;

//lists for desired filename input
    var ppath = "c:/here/goes/file/path/for/taking/input/file";
// (you can implement using json too)
       var num = [
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "X",
      "Y"
    ];
    var nnum = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "X"
    ];
    var lletter = [
      "q",
      "p",
      "o",
      "n",
      "m",
      "l",
      "u",
      "t",
      "k",
      "j",
      "i",
      "h",
      "g",
      "f",
      "d",
      "c",
      "b",
      "ae",
      "ad",
      "ac",
      "ab",
      "aa",
      "a",
      "z",
      "y",
      "x",
      "w",
      "v"
    ];
    var letter = [
      "q",
      "p",
      "o",
      "n",
      "m",
      "l",
      "u",
      "t",
      "k",
      "j",
      "i",
      "h",
      "g",
      "f",
      "d",
      "c",
      "b",
      "ae",
      "ad",
      "ac",
      "ab",
      "aa",
      "a",
      "z",
      "y",
      "x",
      "w",
      "v"
    ];

// main code starts here :

      for (var i in num) {
        saveJPEG(thNamer);
        alert("saved Jpeg");
        myDocument.saveAs((new File("D:\\thesis-bioinformatics" + '/vol-ID/' + thNamer + "_" +".psd")),psdOpts,true);
        alert("saved psd");

          for (var k in letter) {
            var TitleGroup = myDocument.layerSets.getByName('chr_place_plot_');
            var TitleGroup2 = myDocument.layerSets.getByName('chr_text');

            var thNamer = 'chr' + num[i] + '_start' + '_plot_';
            var thNames = 'chr' + num[i] + '_start' + '_plot_' + letter[k];
            var thprevNames = 'chr' + nnum[i] + '_start' + '_plot_' + letter[k];
            VolLayer = TitleGroup.artLayers.getByName(thprevNames);
            VolLayer2 = TitleGroup2.artLayers.getByName('Chr1');

            myDocument.activeLayer = VolLayer;
            var theFiles = ppath + thNames + '.tif';

          if (theFiles && thprevNames != thNames)
          {
            VolLayer = replaceContents(theFiles);
            VolLayer2.textItem.contents = thNamer;
            }

      }
    }
};

A: Try This Code
It'll loop through all layers and will replace it with the .tiff file you'll choose
var doc = app.activeDocument;

function editContent() {

cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };

function Rename() {
  // Edit Contents
  function step1(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    executeAction(sTID('placedLayerEditContents'), desc1, dialogMode);
  };

  step1();      // Edit Contents
};

Rename.main = function () {
  Rename();
};

Rename.main();

    }

function merge() {
    var fileRef = File.openDialog ('Choose File', ['*.tif;*tiff'], true);
    app.open( new File( fileRef ) );
    if(app.activeDocument.activeLayer.isBackgroundLayer ) app.activeDocument.activeLayer.name = 'From Background';
    app.activeDocument.selection.selectAll();
    app.activeDocument.selection.copy();
    app.activeDocument.selection.deselect();

    var idMk = charIDToTypeID( "Mk  " );
    var desc8946 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var ref1324 = new ActionReference();
        var idBckL = charIDToTypeID( "BckL" );
        ref1324.putClass( idBckL );
    desc8946.putReference( idnull, ref1324 );
    var idUsng = charIDToTypeID( "Usng" );
        var ref1325 = new ActionReference();
        var idLyr = charIDToTypeID( "Lyr " );
        var idOrdn = charIDToTypeID( "Ordn" );
        var idTrgt = charIDToTypeID( "Trgt" );
        ref1325.putEnumerated( idLyr, idOrdn, idTrgt );
    desc8946.putReference( idUsng, ref1325 );
executeAction( idMk, desc8946, DialogModes.NO );

    app.activeDocument.close(SaveOptions.SAVECHANGES);
    app.activeDocument.artLayers.add();
    app.activeDocument.paste();
    app.activeDocument.flatten();
    app.activeDocument.close(SaveOptions.SAVECHANGES);
    }

for (var i=0;i<doc.layers.length;i++){
    doc.activeLayer=doc.layers[i];
    editContent();
    merge();
    }

A: This will take input in JSON and replace text and similarly can be made to replace images giving the file path.
What it does is simply look for the layer group and then replace the content with the text or the file of your choice then save the jpg and PSD file in an output folder.
You can see the code here: https://github.com/avialxee/photoshop-jsx

#target photoshop
#include json2.js // json to js parser

if (app.documents.length > 0) {
    var myDocument = app.activeDocument;
    var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
    var thePath = myDocument.path;
    var outpath = thePath+'/output/';

    psdOpts = new PhotoshopSaveOptions();
    psdOpts.embedColorProfile = true;
    psdOpts.alphaChannels = true;
    psdOpts.layers = true;
    psdOpts.spotColors = true;

    var obj = loadInput('inputs.json')

    function loadInput(relpath){
        var input = new File($.fileName);
        var jsoninput = new File(input.path + '/' + relpath);

        jsoninput.open('r');
        var name = jsoninput.read();
        jsoninput.close();

        return JSON.parse(name);
    }

    for (var i in obj.name) {

        var TitleGroup = myDocument.layerSets.getByName('baseImage');
        var TitleGroup2 = myDocument.layerSets.getByName('text');
        var thNamer = obj.name[i];
        VolLayer = TitleGroup2.artLayers.getByName('participantName');
        myDocument.activeLayer = VolLayer;
        //var theFiles = ppath + thNamer + '.tif';

        if (thNamer) {
            //VolLayer = replaceContents(theFiles);
            VolLayer.textItem.contents = thNamer;
            saveJPEG(thNamer);
            alert("saved Jpeg");
            myDocument.saveAs((new File(outpath+ thNamer + "_" + ".psd")), psdOpts, true);

        }
    }
};

function getFiles(theFile) {
    if (theFile.name.match(/\.(psd|tif)$/i)) {
        return true
    };
};

function replaceContents(newFile) {
    var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents");
    var desc3 = new ActionDescriptor();
    var idnull = charIDToTypeID("null");
    desc3.putPath(idnull, new File(theFiles));
    var idPgNm = charIDToTypeID("PgNm");
    desc3.putInteger(idPgNm, 1);
    executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
};

function saveJPEG(name) {
    var doc = app.activeDocument;
    var file = new File(outpath + name + '.Jpg');
    var opts = new JPEGSaveOptions();
    opts.quality = 10;
    doc.saveAs(file, opts, true);
}


text:
Q: Python date of birth Hi I just started to learn python from scratch and stumbled upon this recently
birth_year = input('Birth Year: ')
age = 2022 - float(birth_year)
print(age)

In the above lines of code used to determine the age of a person if I replace float with bool(just for experimenting) it returns the value 2021 no matter what the inputted birth year is. Can someone please explain why is it doing so?

A: well what are you even expecting bool only has two values 0 or 1.
when you pass some value to 'birth_year' the bool value becomes 1 cause in bool anything except 0 returns 1.
I hope you are following me, and in the end it's like this, (2022-1)=2021

A: True evaluates to 1 in python. When you call bool() on an integer that does not equal 0, you will get True. You are basically subtracting 1 from 2022 here.

A: I believe a bool can have only two values: 1 (true) or 0 (false) Anything that isn't zero is considered to be true. So when you say 2022 - bool(birth_year), you're really saying 2022 - 1, which will equal 2021.


text:
Q: Adding browserstack functionality to beginner behat web test tutorial As a behat (and browserstack) beginner, I have followed the beginner behat web feature tutorial.  I had one issue, that was solved by adding "fabpot/goutte": "1.*@stable" to the mix as recommended in a stackoverflow post. Now with a working tutorial, I would like to get this to run on browserstack. However the various guides I have followed, have all resulted in various and different errors when modifying my behat.yml. (I was able to get a git example working, but unable to adapt my tutorial example to work). Here are my behat files at present.
composer.json:
{
    "require": {
        "behat/behat": "~2.5",
        "behat/mink-extension": "~1.3",
        "behat/mink-goutte-driver": "~1.2",
        "behat/mink-selenium2-driver": "~1.2",
        "fabpot/goutte": "1.*@stable"
    },
    "config": {
        "bin-dir": "bin/"
    }
}

behat.yml:
default:
    extensions:
        Behat\MinkExtension\Extension:
            base_url:
            goutte: ~
            selenium2: ~

testscenario.feature:
Feature: ...

@javascipt
scenario: ...
steps...

FeatureContext.php
<?php

use Behat\Behat\Context\ClosuredContextInterface,
    Behat\Behat\Context\TranslatedContextInterface,
    Behat\Behat\Context\BehatContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;

use Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext
{...working functions...}

Now here's an example of a git behat.yml that works (for me) with the out of the box git repo:
default:
    extensions:
        Behat\MinkExtension:
            sessions:
                my_session:
                    browser_stack:
                        username: "username"
                        access_key: "accesskey"
                        capabilities: {"browser" :"Chrome", "os": "OS X", "os_version": "Yosemite", "browserstack-debug": true}

But if I try to use the git behat.yml in my project I get the error:
PHP Warning:  require(Behat\MinkExtension): failed to open stream: No such file or directory

And if I modify the behat.yml to state:
extensions:
Behat\MinkExtension\Extension:

then I get:
 [Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
 Unrecognized option "sessions" under "behat.extensions.behat_minkextension_extension"

What do I need to change to resolve this and get my behat tutorial project working with Browserstack? Much appreciated.

A: This is what is working for me(behat 2.4):
default:
 extensions:
   Behat\MinkExtension\Extension:
    base_url: my_url
    goutte: ~
    selenium2:
     capabilities: { "capability_name": "cap_value" }

Please not that some of the BS capabilities might not be recognized by selenium.
Also you can take a look at this repo: behat-mink-browserstack


text:
Q: Parse xml response with XElement into Model class I have the following class:
public class Location
{
    public string Name { get; set; }
    public long Latitude { get; set; }
    public long Longitude { get; set; }
    public string AddressLine { get; set; }
    public string FormattedAddress { get; set; }
    public string PostalCode { get; set; }

}

And the following XML response from my RESTful request:
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>xxx</TraceId>
<ResourceSets>
<ResourceSet>
  <EstimatedTotal>1</EstimatedTotal>
  <Resources>
    <Location>
      <Name>L4 0TH, Liverpool, Liverpool, United Kingdom</Name>
      <Point>
        <Latitude>53.431259840726852</Latitude>
        <Longitude>-2.9616093635559082</Longitude>
      </Point>
      <BoundingBox>
        <SouthLatitude>53.427397123156176</SouthLatitude>
        <WestLongitude>-2.9702530969854752</WestLongitude>
        <NorthLatitude>53.435122558297529</NorthLatitude>
        <EastLongitude>-2.9529656301263412</EastLongitude>
      </BoundingBox>
      <EntityType>Postcode1</EntityType>
      <Address>
        <AdminDistrict>England</AdminDistrict>
        <AdminDistrict2>Liverpool</AdminDistrict2>
        <CountryRegion>United Kingdom</CountryRegion>
        <FormattedAddress>L4 0TH, Liverpool, Liverpool, United Kingdom</FormattedAddress>
        <Locality>Liverpool</Locality>
        <PostalCode>L4 0TH</PostalCode>
      </Address>
      <Confidence>High</Confidence>
    </Location>
  </Resources>
</ResourceSet>

How can I get the value of Name, Latitude, Longitude, AddressLine, FormattedAddress and PostalCode into my properties?
My method is:
internal Location ListLocations()
    {
        Location loc = new Location();
        string query = "L40TH";
        string key = "MyBingMapsKey";
        string url = string.Format("http://dev.virtualearth.net/REST/v1/Locations/{0}?o=xml&key={1}", query, key);
        XElement elements = GetResponse(url);

        // stuck here!

    }

A: I would do it like this:
static readonly XNamespace Ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

static Location LocationFromXml(XElement element)
{
    var point = element.Element(Ns + "Point");
    return new Location
    {
        Name = (string)element.Element(Ns + "Name"),
        Latitude = (long)(float)point.Element(Ns + "Latitude"), // probably not exactly what you want
        Longitude = (long)(float)point.Element(Ns + "Longitude"),
        AddressLine = null, // not sure what do you want here
        FormattedAddress = null, // ditto
        PostalCode = (string)element.Element(Ns + "Address").Element(Ns + "PostalCode")
    };
}

And then in ListLocations():
var location = elements.Element(Ns + "ResourceSets")
                       .Element(Ns + "ResourceSet")
                       .Element(Ns + "Resources")
                       .Element(Ns + "Location");
return LocationFromXml(location);

A: You can probably use XPath to easily get to the right data and manually fill in the Location properties (or even better, add the code to the Location class). The key is the XPath extension methods for Linq to XML. Particularly look at XPathSelectElement and XPathEvaluate:
loc.Name = elements.XPathSelectElement("//Name").Value;
loc.Latitude = Convert.ToInt64(elements.XPathSelectElement("//Latitude").Value);
loc.Longitude = Convert.ToInt64(elements.XPathSelectElement("//Longitude").Value);
//loc.AddressLine = ??? (Not sure what the intended value is here...)
loc.FormattedAddress = elements.XPathSelectElement("//FormattedAddress").Value;
loc.PostalCode = elements.XPathSelectElement("//PostalCode").Value;


text:
Q: I have difficulty in making a fragment trigger an alarm. here is my Activity and the fragment Here is my Activity Class that initiate the Alarm Manager and on pressing the button found on my fragment gives error!
Activity -
public class Schedule extends AppCompatActivity
{
    CardView cardView = null;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;
    Context context;

    private int[] tabIcons = {
            R.drawable.ic_timeline_icon,
            R.drawable.ic_schedule_icon,
            R.drawable.ic_explore_icon
    };

    public Schedule() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);

        //initilize this variable
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        cardView = (CardView) findViewById(R.id.cv);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(new Profile(), "PROFILE"); // `new Profile()` should be in `FragmentPagerAdapter.getItem()`
        viewPagerAdapter.addFragment(new Scope(), "SCOPE");  // `new Scope()` should be in `FragmentPagerAdapter.getItem()`
        viewPagerAdapter.addFragment(new Explore(), "EXPLORE");  // `new Explore()` should be in `FragmentPagerAdapter.getItem()`
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        this.context = this;
    }

    public void alarmHouse() {
        Calendar cal = Calendar.getInstance();
        Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    }`

//here is the Fragment class for the Alarm
public class Scope extends Fragment {

    protected static Button txtDate, txtDateEnds, txtTimeIn, txtTimeOut; // static View references are an anti-pattern
    Context context;

    public Scope() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_scope, container, false);

    txtDate = (Button) view.findViewById(R.id.btn_termBegins);
    txtDateEnds = (Button) view.findViewById(R.id.btn_termEnds);
    txtTimeIn = (Button) view.findViewById(R.id.time_in);
    txtTimeOut = (Button) view.findViewById(R.id.time_out);
    assert txtDate != null;
    assert txtDateEnds != null;
    assert txtTimeIn != null;
    assert txtTimeOut != null;
    termBegins();
    termEnds();
    periodTimeIn();
    periodTimeOut();

    return view;

}

public void termBegins() {
    txtDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SectionEndsDate mDatePicker = new SectionEndsDate();
            mDatePicker.show(getFragmentManager(), "Select date");
        }
    });
}

public void termEnds() {
    txtDateEnds.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SectionBeginsDate mDatePicker = new SectionBeginsDate();
            mDatePicker.show(getFragmentManager(), "Select date");
        }
    });
}

public static class SectionEndsDate extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar cal = Calendar.getInstance();
        int year_x = cal.get(Calendar.YEAR);
        int month_x = cal.get(Calendar.MONTH);
        int day_x = cal.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), this, year_x, month_x, day_x);
    }

    public void onDateSet(DatePicker view, int year_x, int month_x, int day_x) {
        txtDate.setText("Section Begins: " + String.valueOf(day_x) + " - " + String.valueOf(month_x + 1) + " - " + String.valueOf(year_x));
    }
}

public static class SectionBeginsDate extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar cal = Calendar.getInstance();
        int year_x = cal.get(Calendar.YEAR);
        int month_x = cal.get(Calendar.MONTH);
        int day_x = cal.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, year_x, month_x, day_x);
    }

    public void onDateSet(DatePicker view, int year_x, int month_x, int day_x) {
        txtDateEnds.setText("Section Ends: " + String.valueOf(day_x) + " / " + String.valueOf(month_x + 1) + " / " + String.valueOf(year_x));
    }
}

public void periodTimeIn() {
    txtTimeIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Schedule schedule = new Schedule();
            schedule.alarmHouse();
            TimeInPicker mTimePicker = new TimeInPicker();
            mTimePicker.show(getFragmentManager(), "Select time");

        }
    });
}

public void periodTimeOut() {
    txtTimeOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TimeOutPicker mTimePicker = new TimeOutPicker();
            mTimePicker.show(getFragmentManager(), "Select time");
        }
    });
}

public static class TimeInPicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
        txtTimeIn.setText("Time In: " +
                String.valueOf((hourOfDay == 0 || hourOfDay == 12) ? 12 : hourOfDay % 12) + " : "
                + String.valueOf((minute < 10) ? "0" + minute : minute) + " " + (hourOfDay < 12 ? "AM" : "PM"));

    }
}

public static class TimeOutPicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
        txtTimeOut.setText("Time Out: " +
                String.valueOf((hourOfDay == 0 || hourOfDay == 12) ? 12 : hourOfDay % 12) + " : "
                + String.valueOf((minute < 10) ? "0" + minute : minute) + " " + (hourOfDay < 12 ? "AM" : "PM"));

    }
}

A: You are creating a new instance of your Activity class  and trying to call its method like a normal Java class.
Schedule schedule = new Schedule();
schedule.alarmHouse();

In this case, you'll not have the application context which is needed to set the alarm in alarmHouse().
You need to use getActivity() to call any public method of the container activity from your fragment.
So it would be like -
`getActivity().alarmHouse();`