text:
Q: Can I modify a local javascript object? I have a stats object which is returned from firebase database
    var stats = await firebase
      .database()
      .ref("statistics")
      .child(currentUser.uid)
      .once("value");

The format of the object is like below:
stats  Object {
  "all": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "mtd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "qtd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "today": Object {
    "date": "Dec 7, 2019",
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
  "yesterday": Object {
    "date": "Dec 6, 2019",
    "pending": 0,
    "settled": 0,
    "vol": 0,
  },
  "ytd": Object {
    "pending": 1,
    "settled": 0,
    "vol": 100,
  },
}

Can I directly overwrite the stats.val().yesterday, say set the stats.val().yesterday to
    "date": "Dec 6, 2020",
    "pending": 1,
    "settled": 10,
    "vol": 1000,
  }

then use stats.val() with the latest changes? From what I did I still see old data before making changes to yesterday field. In this case, how can I get stats.val() with changes? Thanks!

A: val() returns a copy of the data in the snapshot, not the actual underlying object.  If you modify this copy, it won't change what's stored in the snapshot.  In this way, DataSnapshot is said to be "immutable" - it can't be changed.  So, what you're trying to do is not possible.
Typically, app code is supposed to call val() just once to get a copy of the data, then use that copy to populate the UI.


text:
Q: LWC Code not displaying data I am new to LWC. I am trying to print data fetched using Apex in LWC but it is neither printing data nor throwing error:
<template>
    <lightning-card title="Call Apex" icon-name="utility:announcement">

                <lightning-button variant="brand" onclick={buttonHandler} label="Show or Hide Data"></lightning-button>
                <template if:true={flag}>
                        <template for:each={accounts} for:item="account">

Name : {account.Name}

Industry : {account.Industry}

                        </template>
                </template>

    </lightning-card>

import { LightningElement } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class Wireapex11 extends LightningElement {
        flag = false;
        accounts = [];
        buttonHandler()
        {
                flag = true;
                getAccounts().then(function(result){
                        console.log(result);
                        this.accounts = result;
                }).catch(function(error){
                        console.error(error);
                });
        }
}

public class AccountController
{
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts()
    {
        return [SELECT Id, Name, Type, Industry FROM Account LIMIT 10];
    }
}

A: You have used this :
getAccounts().then(function(result){
    console.log(result);
    this.accounts = result;
    }).catch(function(error){
            console.error(error);
    });
}

You need to use arrow function instead. Only then this.accounts will refer to outer scope.
If you use this keyword inside function it tries to find the account reference within that function.
Also correct this: this.flag = true;
    getAccounts().then(result => {
        console.log(result);
        this.accounts = result;
    }).catch(function(error){
        console.error(error);
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot rename ifplugd in /usr/sbin folder how to uninstall ifplugd?
i try rename ifplugd ifplugd_old but it says Barewood "ifplugd not allowed while "strict subs in use.
looks like it's in use. How to bring it down and rename it or even delete it?

A: How to remove ifplugd depends on which kind of package management system (or Linux distribution) you are using:

*

*YUM (Fedora, RHEL, CentOS)
yum erase ifplugd

*APT (Debian, Ubuntu)
apt-get remove ifplugd

A: ps -aux|grep ifplugd

read the process id of ifplugd , and then
kill -9 process_id

Now, you should be able to uninstall it.


text:
Q: Multimarkdown to custom HTML Template How do I use MultiMarkdown 4 to take my markdown document and create a full custom HTML document.
As just using multimarkdown file.md > file.html would create the body of the HTML document I could just copy and paste this result into my HTML template, but if I want further control over it, such as ensuring the correct syntax for my code blocks to use prism.js syntax highlighter and other similar things how can this be achieved? The closest I have come is some information on using XSLT, however I can't find any documentation in using this with multimarkdown output.
If someone could point me in the right direction it would be a great help.

A: A very simple, somewhat hackish way would be to prepare a header.html file containing e.g
<html>
  <head>
    <title>my page</title>
  </head>
  <body>

and a footer.html containing e.g.
  </body>
</html>

then, you could do:
$ cat header.html > file.html
$ multimarkdown file.md >> file.html
$ cat footer.html >> file.html

Alternatively, you could use Pandoc instead of multimarkdown, which already includes a templating mechanism, or any other templating solution like mustache or even XSLT if you like that syntax.


text:
Q: How to do the same feature/function in jquery from mootools //new tmp element that contains the new div
var tmpDiv = new Element('div',{html:'

'});
//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $)
tmpDiv.getFirst().replaces($('video'));

$$('.showing').removeClass('showing');
$('thumb-' + id).addClass('showing');

How could I convert this to jquery?  I believe it is using the mootools dynamic library.
Thanks,

A: If I am reading this right, I think this is what you are looking for:
$("#video").replaceWith('

');

$('.showing').removeClass('showing');
$('#thumb-' + id).addClass('showing');


text:
Q: When an if case is true, it should run another if case I'm programming in Xojo and I want my computer to first run an if case and if that case is true, it should run another if case. How can I do that with Xojo ?

A: Below is an example of an If statement that includes the use of ElseIf and Else clauses:

Var theNumber As Double

If theNumber > 0 And theNumber < 100 Then
  MessageBox("The entered number is between 0 and 100")

ElseIf theNumber == 0 Or the number == 100 Then
  MessageBox("The entered number is either 0 or 100")

ElseIf theNumber < 0 Or theNumber > 100 Then
  MessageBox("The entered number is either below 0 or above 100")

Else
  MessageBox("Invalid input. Please try again...")
End If


text:
Q: Plotting an integral equation I would like to draw the solution of the following equation in a log-log plot of $\lambda$ against $M$.
$$10^{-10} = \frac{\lambda^{2}}{(4\pi)^{2}}\int_{0}^{1}dz\frac{(1-x)^{3}}{(1-x)^{2}+zM^{2}}$$
Here is my code:
table = Table[{Exp[M], λ /.
     NSolve[((λ^2)/(4 *Pi)^(2)) *
         NIntegrate[(((1-x)^3)/((1-x)^2 + Exp[2 M] x)), {x, 0, 1}] ==
                                    10^(-10), λ][[2]]},
     {M, -15, 15, 0.03}];
 ListLogLogPlot[table, Joined \[RightArrow] True,
 AxesOrigin \[RightArrow] {1, 1}]

With this code, I get a list of error messages and a list of the output values, but not the plot. How do I get the plot?

A: Why not make things easier and solve the integral exactly?
After making the integration variable consistently $\text{x}$ and changing it to $\text{x}\to 1-\text{x}$, the integral can be calculated explicitly. (In order to assist Mathematica in solving the integral we also assume temporarily that $\text{M}<-2$ such that the roots of the denominator are real.)
We get
f[M_] = Integrate[x^3/(x^2 + (1 - x) M^2), {x, 0, 1}, Assumptions -> M < -2] //
   FullSimplify

(* Out[111]= (Sqrt[-4 + M^2] (1 + 2 M^2) - M^2 Sqrt[-4 + M^2] (-1 + M^2) Log[M^2] -
 M^3 (-3 + M^2) Log[1/2 (-2 + M^2 - M Sqrt[-4 + M^2])])/(2 Sqrt[-4 + M^2]) *)

$$f(\text{M})=\int_0^1 \frac{x^3}{x^2+(1-x)M^2 } \, dx\\= \frac{1}{2} \left(\left(2 M^2+1\right)-M^2 \left(M^2-1\right) \log \left(M^2\right)\right)\\-\frac{\left(M^3 \left(M^2-3\right)\right) \log \left(\frac{1}{2} \left(M^2- M\sqrt{M^2-4}-2\right)\right)}{2 \sqrt{M^2-4}}$$
The result now holds for all real $\text{M}$.
At the special points it is
Limit [f[M], M -> 0]

(* Out[113]= 1/2 *)

{Limit [f[M], M -> 2], Limit [f[M], M -> -2]}

(* Out[115]= {17/2 - 12 Log[2], 17/2 - 6 Log[4]} *)

Series[f[M], {M, \[Infinity], 2}] // Normal

(* Out[148]= (-(11/6) - 2 Log[1/M])/M^2 *)

And here's the graph
Plot[f[M], {M, -10, 10},
 PlotLabel -> "The integral as a function of M"]

Now the function $\lambda $ is defined as
ld[M_] := 4 \[Pi] 10^-5/Sqrt[f[M]]

A log-log-plot (which is naturally confined to positive quantities) is then
LogLogPlot[ld[M], {M, .001, 15}, PlotLabel -> "Log-log-plot",
 AxesLabel -> {"Log[M]", "log[\[Lambda]]"}]

A: Here is your graph, once you delete the non-converged values:
ListLogLogPlot[table, AxesOrigin -> {1,1}]


text:
Q: how to control CSS file from the Java controller in JavaFX i've build an app with one theme and i use for that a CSS file when i finished it i m trying to give the User the choice of choicing colors that he prefer and the CSS file is included in the FXML files for each Stage
 *{
    -fx-primary :#2A2E37 ;
    -fx-secondary : #FFFF8D;
    -fx-primarytext : #B2B2B2;
    -fx-blue: #1976D2;
    -fx-red: #FF0000;
    -fx-green:#2E7D32;

}
.root{
    -fx-background-color: -fx-primary;
}

i wanna some methode that change the value of my -fx-primary for example and the color will be choosen from a pallette ( i can do that )
and for fxml i use the simple method
<AnchorPane fx:id="rootAnchoreFW" prefHeight="800.0" prefWidth="767.0" stylesheets="@../Style/myTheme.css" >

A: You can make several themes for this colors. For example, a file called themeRed.css, themeBlue.css
   .root{
    -fx-font-size: 14pt;
    -fx-font-family: "Tahoma";
    -fx-base: #DFB951;
    -fx-background: #A78732;
    -fx-focus-color: #B6A678;
}

And, you have a button that changes colors or themes.
You can set your themes in your app with something like this:
public String themeRed = getClass().getResource("themeRed.css").toExternalForm();
public String themeBlue = getClass().getResource("themeBlue.css").toExternalForm();
and in the button click action, or in the method triggered when a click happens, you can use:
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        scene.getStylesheets().remove(themeRed);
        scene.getStylesheets().add(themeBlue);
        System.out.println("Stylesheets: " + scene.getStylesheets());
        //You can see the stylesheet being used
    }
});

You can play with that to change themes.
The other option is if you just change let's say, one css line, like background in one button for example, you can use the setStyle method in every element you want.
For example:
btn.setStyle("-fx-background: #A78732;");

A: If for example you are using a ColorPicker colorPicker :
colorPicker.valueProperty().addListener((obs, oldValue, newValue) -> {
            yourAnchorPane.setStyle("-fx-primary : " + newValue);
});

So basically you need to use the setStyle function, add the attribute you want to change and its value like in CSS.
Or else (If you don't want to put an attribute) you can just do something like this to change the color of a label for instance :
label.setTextFill(colorPicker.getValue())

A: you can create an "CSS Editor"

you will have two css :
myTheme.css :
@import url("main.css");

*{
    -fx-primary :#2A2E37 ;
    -fx-secondary : #FFFF8D;
    -fx-primarytext : #B2B2B2;
    -fx-blue: #1976D2;
    -fx-red: #FF0000;
    -fx-green:#2E7D32;
}

main.css :
.root{
    -fx-background-color: -fx-primary;
}

you will have the same code for your fxml :
<AnchorPane fx:id="rootAnchoreFW" prefHeight="800.0" prefWidth="767.0"
            stylesheets="@../Style/myTheme.css" >

to edit the css you have two option :

*

*read the CSS file, export data, update it (delete the old CSS file and créate a new file)

*read a config file (txt, JSON, XLM...) to store data of you configaration and recreate the scc with it.
It will be a part of the anwser I think


text:
Q: How can I make tcpdump stop the capture after a certain number of packets captured? I am debugging a problem where two servers get stuck in a loop when communicates with each other. After a server restart the problem will start at some point, it can be in an hour
or in a day. I want to tcpdump the traffic when the problem starts so I can find out what
makes it happen.
My plan is to restart the servers then let tcpdump capture the traffic and then analyze the
result. However I would like tcpdump to stop after a few thousand packets captured to
avoid having to monitor it, since I don't know when the traffic will start.
Anyone having a suggestion?

A: See man tcpdump:

-c     Exit after receiving count packets.

A: Type the command below:
sudo tcpdump -i eno1 -c [size]

The argument -i eno1 tells tcpdump to listen only on the eno1 interface, and -c [size] tells tcpdump to stop capturing after [size] packages have been captured. So tcpdump -i eno1 -c 2048 will stop after 2048 packages.


text:
Q: How to convert a Scala anonymous trait implementation to Rust? I'm having difficulty converting this Scala trait to Rust
trait Inject[A, B] {
  self =>

  def inject(input: A): B

  def project(input: B): Try[A]

  def contraMap[AA](inj: Inject[AA, A]): Inject[AA, B] = new Inject[AA, B] {
    override def inject(input: AA) = self.inject(inj.inject(input))

    override def project(input: B) = self.project(input).flatMap(i => inj.project(i))
  }

  def map[BB](inj: Inject[B, BB]): Inject[A, BB] = new Inject[A, BB] {
    override def inject(input: A) = inj.inject(self.inject(input))

    override def project(input: BB) = inj.project(input).flatMap(i => self.project(i))
  }

}

Here is my Rust equivalent
pub trait Injection<A, B> {
    fn inject(input: A) -> B;
    fn project(input: B) -> Result<A, InjectionError>;
    fn contraMap<AA>(input: Injection<AA, A>) -> Injection<AA, B>;
    fn map<BB>(input: Injection<B, BB>) -> Injection<A, BB>;
}

pub struct InjectionError {
    msg: String,
}

I am getting:
error[E0038]: the trait `Injection` cannot be made into an object
 --> src/main.rs:4:5
  |
4 |     fn contraMap<AA>(input: Injection<AA, A>) -> Injection<AA, B>;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Injection` cannot be made into an object
  |
  = note: method `inject` has no receiver
  = note: method `project` has no receiver
  = note: method `contraMap` has no receiver
  = note: method `map` has no receiver

If I add a self reference, I still get the same error:
pub trait Injection<A, B> {
    fn inject(&self, input: A) -> B;
    fn project(&self, input: B) -> Result<A, InjectionError>;
    fn contraMap<AA>(&self, input: Injection<AA, A>) -> Injection<AA, B>;
    fn map<BB>(&self, input: Injection<B, BB>) -> Injection<A, BB>;
}

pub struct InjectionError {
    msg: String,
}

I am not sure how I can instantiate an anonymous Injection like I am doing in Scala. What would be the idiomatic way of converting this Scala trait to Rust?

A: In Rust, traits only describe behavior, not data. The compiler tells you your trait is not object-safe because you want to return anything that implements the trait, and that 'anything' has no single canonical known size at compile time.
You can Box your values to put them on the heap, or use references (which will require some scary lifetime juggling and be quite brittle, but avoid the allocation). You will also need to return a concrete type from map and contraMap. Look how Rust's Iterator trait does it: It returns a Map which is generic over the original iterator and the function type it maps, wraps both and implements Iterator.


text:
Q: Extensions of completely positive mappings I would like to ask the following two questions.
Let $1_{\mathcal{H}}\in \mathcal{A}\subset\mathcal{B}\subset\overline{\mathcal{A}}^{SOT}\subset\mathbb{B}(\mathcal{H})$ be a sequence of $C^{\ast}$-subalgebras and $\phi:\mathcal{B}\to\mathcal{A}$ a $*$-epimorphism such that $\phi^2=\phi$.

Question 1. Suppose that $\mathcal{A}$ is an $AW^*$-algebra and that $\{x_{\alpha}\}\subset\mathcal{B}_{sa}$ is a norm-bounded monotone increasing pairwise commuting net with strong limit $x\in\overline{\mathcal{A}}^{SOT}\setminus\mathcal{B}$. Since $\mathcal{A}$ is an $AW^*$-algebra, there exists a least upper bound $y$ for $\{\phi(x_{\alpha})\}$ in a maximal abelian $C^*$-subalgebra of $\mathcal{A}$ containing $\{\phi(x_{\alpha})\}$. Define $\tilde{\phi}:\operatorname{span}(\mathcal{B}\cup\{x\})\to\mathcal{A}$ to be the linear extension of $\phi$ such that $\tilde{\phi}(x)=y$, where $\operatorname{span}(\mathcal{B}\cup\{x\})$ is just the linear span (NOT taking products between $x$ and elements of $\mathcal{B}$). Is $\tilde{\phi}$ 2-positive? If not, how about if $\mathcal{A}$ is a monotone complete $C^*$-algebra?Question 2. Suppose that $\mathcal{A}$ is a monotone complete $C^*$-algebra and that $\{x_{\alpha}\}\subset\mathcal{B}_{sa}$ is a norm-bounded monotone increasing pairwise commuting net with strong limit $x\in\overline{\mathcal{A}}^{SOT}\setminus\mathcal{B}$, Define $\tilde{\phi}:\operatorname{span}(\mathcal{B}\cup\{x\})\to\operatorname{span}(\mathcal{A}\cup\{z\})$ to be the linear extension of $\phi$ such that $\tilde{\phi}(x)=z$, where $z$ is the strong limit of $\{\phi(x_{\alpha})\}$ in $\overline{\mathcal{A}}^{SOT}$. Is $\tilde{\phi}$ 2-positive? (Assuming $\mathcal{A}$ being monotone complete will not be essential in Question 2, but I did so since I am trying to solve the problem in this context.)

My feeling is that the answer to Question 2 is negative, while the answer to Question 1 could be positive at least in the monotone complete case.


text:
Q: Return function Angular 2 I have an issue with a asynchronous function. I've a service that provides me some data from a firebase database. One of those function returns a value:
historialDeConsumi() {
    this.item = this.af.database.object('/users/' + this.uid + '/admin', {
      preserveSnapshot: true
    });
    this.item.subscribe(snapshot => {
       this.hijosHistorialConsumi = snapshot.child('HisotialCons').val();

    });
    return this.hijosHistorialConsumi;
}

I call this function from a component:
ngOnInit() {
    this.consumi = this.servicioData.historialDeConsumi();
}

I want to match this.consumi to a value returned by function. I don't know the way to do this.

A: Your code won't work, of course, since you are trying to return something which doesn't exist yet. The most straightforward approach (but not the best, by any means) is to store the unwrapped observable in a service variable, then provide a way to retrieve it. In the below, I am using simplified/sample data:
// Keep data locally.
private data;

// Listen to observable in constructor, and store locally.
constructor() {
    this.item = this.af.database.object(path, {
      preserveSnapshot: true
    });
    this.item.subscribe(snapshot => {
       this.data = snapshot.val();
    });
}

// Retrieve the data.
getData() { return this.data; }

Note, however, that the entire idea of using snapshots is unnecessary. AngularFire returns observables which can be directly subscribed to. Therefore:
constructor() {
    this.item = this.af.database.object(path);
    this.item.subscribe(data => this.data = data);
}

or more simply, just
constructor() {
    this.af.database.object(path).subscribe(data => this.data = data);
}

However, this approach has a serious flaw. Whoever calls the accessor will get the latest value, but while they are holding onto that, if a new value arrives, they will never know about it, and will be left using the old one. Or, if someone calls the accessor before the observable has fired for the first time, which is entirely possible, they will end up getting undefined, with no way to then retrieve subsequent values.
Therefore, the service should simply return the observable, and the component would consume it.
// SERVICE
getData() { return this.af.database.object(path); }

// COMPONENT
public data;

ngOnInit() {
  this.service.getData().subscribe(data => this.data = data);
}

The data is {{data}}

In other words, we "unwrap" the observable in ngOnInit, and store its unwrapped value locally. This will sort of work like you want. However, the initial value of data will be undefined, until the observable emits its first value, so if you are trying to access a property on the data, assuming it's an object:

The name is {{data.name}}

You will get an error trying to access the name property on undefined. The most obvious way to deal with that is to use the ? operator, as in

 The name is {{data?.name}}

However, you may not want to have to do that everywhere in your template, and remember that AOT does not support the ?. The unpleasant alternative is to wrap this in
 everywhere.
Therefore, the preferred approach is to leave the observable as an observable until the last moment and unwrap it (subscribe to it) only when necessary, which you can do as follows (using the convention of naming variables holding observables with a final $ for clarity):
// COMPONENT
public data$: Observable<any>;

ngOnInit() {
  this.data$ = this.service.getData();
}

The data is {{data$ | async}}

using the async pipe, which subscribes implicitly. If you want to retrieve a property on data, then

The name is {{(data$ | async).name}}

and everything will work as expected. If you want to handle the case where the observable has not emitted yet, then
The name is

{{data.name}}

  <ng-template #loading>not loaded yet</ng-template>

If you want to somehow pre-process or manipulate the value of the observable, instead of unwrapping it either in the service or the component, and then performing the manipulation on the unwrapped value, manipulate the observable itself using map:
public firstName$;

ngOnInit() {
  this.firstName$ = this.service.getData().map(data => data.name.split(' ')[0]);
}

Then consume that mapped observable in your template as
The first name is

{{firstName}}

  <ng-template #loading>not loaded yet</ng-template>

In summary, the preferred pattern for working with AngularFire observables, and indeed all observables, is to leave them as observables for as long as possible, manipulate them by mapping (or filtering) them into new observables, avoid unwrapping them and storing their values locally if at all possible, and finally subscribe at the point where the value is actually needed, which is quite often in the template, where the subscription can be handled by the async pipe.
Using the async pipe has another major advantage. If you subscribe explicitly in the component logic, you will have to remember that subscription, and then unsubscribe in ngOnDestroy to avoid memory leaks. In contrast, Angular automatically cleans up any subscriptions done implicitly using the async pipe for you.

A: I suggest you to read up about how RXJS Observables work: RXJS Doc
Basically what you want to do is to subscribe on your Observable from your component. Your service should just return (or maybe manipulate the incoming data before returning) it.
This could look something like this:
myServiceFun(): Observable<any> {
    return doMyRequest().map((response: any) => {
          // manipulate it maybe here
          return response;
    });
}

In your component you subscribe to this Observable:
ngOnInit() {
    this.backendService.myServiceFunc().subscribe((response: any) => {
         this.myComponentProp = response;
    });
}

A: Another option is to use await and async to simplify the code:
import 'rxjs/add/operator/toPromise';

async historialDeConsumi(){
    let item = this.af.database.object('/users/' + this.uid + '/admin', { preserveSnapshot: true });
    let snapshot = await item.toPromise();
    return snapshot.child('HisotialCons').val();
}

async ngOnInit() {
    this.consumi = await this.servicioData.historialDeConsumi();
}

This way the code looks very much closer to how it would be if the database query was just an ordinary function call. Use toPromise() to convert an Observable into a Promise. Turn the methods into async methods and that lets you use await to wait for completion of any promise, it also means any value you return from the method will be wrapped into a promise, so the caller has to use await or treat it like a promise and call .then() on it.
Do remember that although it makes the code read like synchronous code everything is still happening asynchronously so the value won't be set until the asynchronous part completes. However as angular already knows how to handle an asynchronous ngOnInit() that shouldn't be a problem, it will wait for the result.


text:
Q: Android Gaming Frameworks I was considering creating a 2D game, and was wondering if there are any good open source or potentially paid (if not too expensive) frameworks for developing games.
Anything out there already?
Thanks.

A: AndEngine is for Android.
libgdx is desktop/android framework.

A: Check out Unity, it's rather nice, though the terms are a bit expensive.

A: I have heard good things about Corona.
http://www.anscamobile.com/
I have looked for a decent Android game framework and not been able to find many. The best I have found is the Cocos2D port for android but it is quite dated and you need to reference the IOS documents to learn how to use it and there is very little support.

A: If you want cocos2d for android the best solution is WiEngine


text:
Q: Error Installing NodeJS From Command Line To install NodeJS on a fresh copy of Linux on a virtual machine I'd type apt install nodejs
And I'd get the following output:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  javascript-common libc-ares2 libjs-highlight.js libnode72 libuv1 nodejs-doc
Suggested packages:
  npm
The following NEW packages will be installed:
  javascript-common libc-ares2 libjs-highlight.js libnode72 libuv1 nodejs nodejs-doc
0 upgraded, 7 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.7 MB of archives.
After this operation, 50.9 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://deb.debian.org/debian bullseye/main amd64 javascript-common all 11+nmu1 [6260 B]
Get:2 http://deb.debian.org/debian bullseye/main amd64 libc-ares2 amd64 1.17.1-1+deb11u1 [102 kB]
Get:3 http://deb.debian.org/debian bullseye/main amd64 libjs-highlight.js all 9.18.5+dfsg1-1 [397 kB]
Get:4 http://deb.debian.org/debian bullseye/main amd64 libuv1 amd64 1.40.0-2 [132 kB]
Get:5 http://deb.debian.org/debian-security bullseye-security/main amd64 libnode72 amd64 12.22.12~dfsg-1~deb11u1 [8319 kB]
Get:6 http://deb.debian.org/debian-security bullseye-security/main amd64 nodejs amd64 12.22.12~dfsg-1~deb11u1 [147 kB]
Get:7 http://deb.debian.org/debian-security bullseye-security/main amd64 nodejs-doc all 12.22.12~dfsg-1~deb11u1 [2547 kB]
Fetched 11.7 MB in 0s (42.8 MB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package javascript-common.
(Reading database ... 17840 files and directories currently installed.)
Preparing to unpack .../0-javascript-common_11+nmu1_all.deb ...
Unpacking javascript-common (11+nmu1) ...
Selecting previously unselected package libc-ares2:amd64.
Preparing to unpack .../1-libc-ares2_1.17.1-1+deb11u1_amd64.deb ...
Unpacking libc-ares2:amd64 (1.17.1-1+deb11u1) ...
Selecting previously unselected package libjs-highlight.js.
Preparing to unpack .../2-libjs-highlight.js_9.18.5+dfsg1-1_all.deb ...
Unpacking libjs-highlight.js (9.18.5+dfsg1-1) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../3-libuv1_1.40.0-2_amd64.deb ...
Unpacking libuv1:amd64 (1.40.0-2) ...
Selecting previously unselected package libnode72:amd64.
Preparing to unpack .../4-libnode72_12.22.12~dfsg-1~deb11u1_amd64.deb ...
Unpacking libnode72:amd64 (12.22.12~dfsg-1~deb11u1) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../5-nodejs_12.22.12~dfsg-1~deb11u1_amd64.deb ...
Unpacking nodejs (12.22.12~dfsg-1~deb11u1) ...
Selecting previously unselected package nodejs-doc.
Preparing to unpack .../6-nodejs-doc_12.22.12~dfsg-1~deb11u1_all.deb ...
Unpacking nodejs-doc (12.22.12~dfsg-1~deb11u1) ...
Setting up javascript-common (11+nmu1) ...
dpkg: error processing package javascript-common (--configure):
 installed javascript-common package post-installation script subprocess returned error exit status 1
Setting up libc-ares2:amd64 (1.17.1-1+deb11u1) ...
Setting up libuv1:amd64 (1.40.0-2) ...
Setting up libjs-highlight.js (9.18.5+dfsg1-1) ...
Setting up libnode72:amd64 (12.22.12~dfsg-1~deb11u1) ...
Setting up nodejs-doc (12.22.12~dfsg-1~deb11u1) ...
Setting up nodejs (12.22.12~dfsg-1~deb11u1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode
update-alternatives: warning: skip creation of /usr/share/man/man1/js.1.gz because associated file /usr/share/man/man1/nodejs.1.gz (of link group js) doesn't exist
Processing triggers for libc-bin (2.31-13+deb11u3) ...
Errors were encountered while processing:
 javascript-common
E: Sub-process /usr/bin/dpkg returned an error code (1)

Now, whenever I try to install anything I get an error. If I reset the machine and try to install other stuff it would work fine, but I always get the error when installing NodeJS.
What is the error and how can I fix it and move on?


text:
Q: Firebase Cloud Messaging request DeviceID without connecting to Firebase I am using ionic and firebasex to develop an app that uses Firebase Cloud Messaging. Is there a way to request the device id, without connecting to firebase? I need this, because to be compliant with GDPR, users have to be able to opt out of getting Push Notifications. I want to store the information about which device is opted out in my database though, for which it would be nice to know the device id, so that users could opt in to push notifications in other ways than through my app later.

A: The device ID that is used by FCM is generated on Google's servers. There is no way to get a device ID without the app communicating with those servers.


text:
Q: P2P on rtl8812au not working How to use P2P operations using rtl8812au driver?
I have tried almost every driver which are available out there in github and also in the linux home; none of them are actually working correctly.
The only driver which I found usable was aircrack-ng-rtl8812au

*

*https://github.com/aircrack-ng/rtl8812au
But for P2P group operations even that has some issues.

A: You can easily make the driver use p2p_group_interface by enabling the RTW_P2P_GROUP_INTERFACE macro to 1 in os_dep/linux/ioctl_cfg80211.h file. I hope this helps you in some way.


text:
Q: Beamer: page number without footer I am preparing a beamer presentation using the metropolis theme. In some slides, I would like to add text at the very bottom of the slide. This is done adding
\newcommand{\btVFill}{\vskip0pt plus 1filll}

in the preamble and
\begin{frame}
 framecontent

 \btVFill

 text at the bottom of the slide.
 \end{frame}

This works exactly as I suppose, as long as my footer is absent, i.e., as long as I define in the preamble
 \setbeamertemplate{footline}[]{}

I would like, however, to have the frame numbers from the footer environment put at the bottom right corner, such as resulting from
 \setbeamertemplate{footline}[frame number]{}

If I add the footer, the btVfill command will move the text just "above" the space occupied by the footer (being empty, considering my minimalistic definition of the footer).
Do you have any suggestion on how easily put text the very bottom of my slide keeping the minimal footer? A solutions which would not use the vspace command, as I would need to adjust it in each and every slide.
Thanks for your suggestions,
Leo

A: Misusing the navigation symbols, one could do the following:
\documentclass{beamer}

\usetheme{metropolis}

\setbeamertemplate{footline}{}
\setbeamertemplate{page number in head/foot}[totalframenumber]
\setbeamertemplate{navigation symbols}{\footnotesize\usebeamertemplate{page number in head/foot}}

\newcommand{\btVFill}{\vskip0pt plus 1filll}

\begin{document}

\begin{frame}
 framecontent

 \btVFill

 text at the bottom of the slide.
\end{frame}

\end{document}


text:
Q: Logic: Can you drop parentheses in a conjunction? In propositional logic, $p \land (q \land r) = (p \land q) \land r$ , where $p, q$ and $r$ are propositions.
Does this mean $p \land (q \land r) = p \land q \land r$ ? If so, why?

A: Yes, you are right: conjunction is associative. Thus, it doesn't matter where you put the parentheses. Hence, when you see "$p \land q \land r$", it means that you may insert the parentheses anywhere and you will get the same result.

A: I highly recommend avoiding "p∧q∧r" and the like when talking in a proof-theoretic context.  In a proof-theoretic context a proof is a sequence of well-formed formulas (wffs).  I can tell which wff p∧(q∧r) stands for and I can tell which wff (p∧q)∧r stands for (neither of those strings are wffs).  But, I can't tell which wff p∧q∧r stands for.  It could mean (p∧(q∧r)) or ((p∧q)∧r) or it could mean both (p∧(q∧r)) and ((p∧q)∧r).  And thus, in a proof-theoretic context p∧q∧r is meaningless.

A: Informally, one might say that if three things are true ($p \land q \land r$), then also one thing and two things — $p \land (q \land r)$ — and two things and one thing — $(p \land q) \land r$ — are true.
In a formal deductive system commonplace in symbolic logic, we want to be more formal. We usually deduce consequences from a set of premises. For example we deduce $p \land q$ from the set $\{p, q\}$. This is written:
$$\{p,q\} \vdash p \land q$$
where the braces are usually omitted, and $\vdash$ is voiced proves. Similarly:
$$p \land q \vdash p \qquad\qquad p\land q \vdash q$$
(where the premises thus are considered singleton sets) because this is simply throwing information away.
If we now allow chains of deduction, then, one easily obtains:
$$\begin{align*}\{p,q,r\} &\vdash p \land q& \{p \land q, r\} &\vdash (p \land q) \land r\\
\{p,q,r\}&\vdash q \land r&\{p, q \land r\}&\vdash p \land(q \land r)
\end{align*}$$
and from the rightmost conclusion the so-called $\land$-elimination rules  easily allow deriving $p, q$ and $r$ again. Thus either of the parenthesized expressions corresponds exactly to the truth of the three letters $p,q,r$. Thus we say they're (provably) equivalent:
$$p \land (q \land r) \dashv\vdash (p \land q) \land r$$
Thus we have demonstrated that the following definitions of $p \land q \land r$ are all equally sensible:

*

*As $p \land (q \land r)$;

*As $(p \land q) \land r$;

*By stating $p \land q \land r$ is true precisely when $p,q,r$ are all true.


text:
Q: Converting an Access Query to SQL Server I am trying to convert this query to a SQL Server view
SELECT
    IIF([tblStockMovementsDate] ! [LocationType] = 3, [tblShops] ! [Type], [tblLocationType] ! [LocationTypeDesc]) AS [LocationTypeDesc],
    tblStockMovementsDate.[Location],
    qryAllLocations.[WarehouseName],
    SUM (([tblStockMovementsdate] ! [MovementQtyHangers] + ([tblStockMovementsdate] ! [MovementQtyBoxes] * Iif(Isnull([qryGarmentsPerBox] ! [GarmentsPerBox]), 1, [qryGarmentsPerBox] ! [GarmentsPerBox]))) * [qryUnitPrice] ! [UnitPrice]) AS [TotalValue],
    IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType]) AS [LocationType]
FROM
    (((((tblStockMovementsDate
INNER JOIN
    tblLocationType ON tblStockMovementsDate.[LocationType] = tblLocationType.[LocationType])
INNER JOIN
    qryAllLocations ON tblStockMovementsDate.[Location] = qryAllLocations.[WarehouseRef])
LEFT JOIN
    qryGarmentsPerBox ON (tblStockMovementsDate.[Location] = qryGarmentsPerBox.[WarehouseRef])
                      AND (tblStockMovementsDate.[StockCode] = qryGarmentsPerBox.[StockCode]))
LEFT JOIN
    qryUnitPrice ON tblStockMovementsDate.[StockCode] = qryUnitPrice.[StockCode])
LEFT JOIN
    tblShops ON tblStockMovementsDate.[Location] = tblShops.[ShopRef])
INNER JOIN
    tblStock ON tblStockMovementsDate.[StockCode] = tblStock.[StockCode]
WHERE
    ((IIF ([tblShops].[Clearance] = 0, [tblStock].[DeadCode] = 0, [tblStock].[RemoveFromClearance] = 0) ) <> False)
GROUP BY
    IIF ([tblStockMovementsDate] ! [LocationType] = 3, [tblShops] ! [Type], [tblLocationType] ! [LocationTypeDesc]),
    tblStockMovementsDate.[Location],
    qryAllLocations.[WarehouseName],
    IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType])
ORDER BY
    IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType])

but it won't produce an output, instead I keep getting this error:

Error in list of function arguments: '=' not recognized.
  Error in list of function arguments: 'IS' not recognized.
  Unable to parse query text.

Any help would be appreciated.

A: This is a shot in the dark. I did my best to decipher the code you posted originally.
I would recommend getting rid of those nested views. They are going to cause you serious anguish at some point. You will likely have to grab the queries from those views and move that to this query.
Notice how much cleaner this is when you use aliases instead of the Access default of slapping the table in front of every column. I also removed dozens of parenthesis groups that did nothing but make this hard to see. I also converted all your IIF expressions to case expressions since I don't know what version of sql you are using.
SELECT
    case when smd.LocationType = 3
        then tblShops.Type
        else lt.LocationTypeDesc
    end AS LocTypeDesc
    , smd.Location
    , al.WarehouseName
    , Sum((smd.MovementQtyHangers + (smd.MovementQtyBoxes * Isnull(g.GarmentsPerBox, 1))) * qryUnitPrice.UnitPrice) AS TotalValue
    , case when sh.Type = 'Concession'
        then 4
        else smd.LocationType
    end AS LocType
FROM tblStockMovementsDate smd
INNER JOIN tblLocationType lt ON smd.LocationType = ll.LocationType
INNER JOIN qryAllLocations al ON smd.Location = al.WarehouseRef
LEFT JOIN qryGarmentsPerBox g ON smd.Location = g.WarehouseRef
                                AND smd.StockCode = g.StockCode
LEFT JOIN qryUnitPrice up ON smd.StockCode = up.StockCode
LEFT JOIN tblShops sh ON smd.Location = sh.ShopRef
INNER JOIN tblStock st ON smd.StockCode = st.StockCode
WHERE tblShops.Clearance <> 0
    OR tblStock.DeadCode <> 0
    OR tblStock.RemoveFromClearance <> 0
GROUP  BY case when smd.LocationType = 3 then tblShops.Type else lt.LocationTypeDesc end
    , smd.Location
    , al.WarehouseName
    , case when sh.Type = 'Concession' then 4 else smd.LocationType end
order by LocType


text:
Q: Catch move event in Clutter Actor but stay transparent for other interactions I want to build a Gnome shell extension that highlights the mouse cursor. I have a working prototype of a Clutter Actor that draws above all other windows, but mouse movements are only tracked when no other windows are behind the test canvas.
My impression is that the drawing is in the foreground but pointer signals are in the background. I would like to raise the move-signals to the very foreground in order to track the movement and update the position of the highlighting while staying transparent for all other UI interactions, so users can normally use the desktop while the mouse cursor highlighting is turned on.
Bonus question: is this even the right approach to do this?
Here is my prototype (https://github.com/tobias47n9e/MouseHighlight):
const St = imports.gi.St;
const Main = imports.ui.main;
const Tweener = imports.ui.tweener;
const Lang = imports.lang;
const PanelMenu = imports.ui.panelMenu;
const Clutter = imports.gi.Clutter;
const Mainloop = imports.mainloop;
const Cairo = imports.cairo;

let mouse_highlight;

/**
* Main shell extension object.
*/
const MouseHighlight = new Lang.Class({
    Name: 'MouseHighlight',
    Extends: PanelMenu.Button,

    /**
    * Initializes the shell extension object.
    */
    _init: function() {
        this.parent(0.0, "MouseHighlight");
        this.offset = [1000, 500];
        this.cnvs_size = [200, 200];

        this.label = new St.Label({
            text: "Choose Highlighting",
            y_expand: true,
            y_align: Clutter.ActorAlign.CENTER
        });

        this.actor.add_actor(this.label);

        this.cnvs_actor = new Clutter.Actor();

        this.setup_cnvs_actor();
    },

    /**
    * Sets the size, background and offset of canvas actor. Shows it and
    * adds it to the main uiGroup. Connects the signals of the actor.
    */
    setup_cnvs_actor: function () {
        let color = new Clutter.Color({
            red: 255,
            green: 0,
            blue: 0,
            alpha: 128
        });

        this.cnvs_actor.set_position(this.offset[0], this.offset[1]);
        this.cnvs_actor.set_width(this.cnvs_size[0]);
        this.cnvs_actor.set_height(this.cnvs_size[1]);
        this.cnvs_actor.set_background_color(color);
        this.cnvs_actor.show_all();
        this.cnvs_actor.set_reactive(true);
        this.cnvs_actor.connect("motion-event", this.mouse_move.bind(this));
        Main.uiGroup.add_actor(this.cnvs_actor);
    },

    /**
    * Draws a point at certain coordinates and offset. Called by
    * click events on the canvas.
    */
    draw_point: function(canvas, cr, width, height, coords, offset, draw) {
        let x = coords[0] - offset[0];
        let y = coords[1] - offset[1];

        cr.save();
        cr.setOperator(Cairo.Operator.CLEAR);
        cr.paint();
        cr.restore();
        cr.setOperator(Cairo.Operator.OVER);
        cr.setLineCap(Cairo.LineCap.ROUND);
        cr.setLineWidth(10);

        cr.translate(x, y);
        cr.arc(0, 0, 5, 0, Math.PI * 2);
        cr.stroke();

        return draw;
    },

    /**
    * Runs when the mouse moves over the canvas. Calls a function that
    * draw a highlight under the mouse cursor.
    */
    mouse_move: function(actor, event) {
        let coords = event.get_coords();
        let self = this;

        let canvas = new Clutter.Canvas();
        canvas.set_size(this.cnvs_size[0],this.cnvs_size[1]);

        canvas.connect("draw", function(canvas, cr, width, height) {
            self.draw_point(canvas, cr, width, height, coords, self.offset, false);
        });

        canvas.invalidate();

        this.cnvs_actor.set_content(canvas);
    },

    destroy: function() {
        this.parent();
        this.cnvs_actor.destroy();
    },
});

/**
* Initializes the shell extension.
*/
function init() {

}

/**
* Runs when the shell extension is enabled.
*/
function enable() {
    mouse_highlight = new MouseHighlight();

    Main.panel.addToStatusArea('mouse-highlight', mouse_highlight, 1, 'right');
}

/**
* Runs when the shell extension is disabled.
*/
function disable() {
    mouse_highlight.destroy();
}


text:
Q: Issues defining correct importJSON xpath In Google Sheets, I have the following importJSON function (taken from here):
function IMPORTJSON(url,xpath){
  try{
    var res = UrlFetchApp.fetch(url);
    var content = res.getContentText();
    var json = JSON.parse(content);

    var patharray = xpath.split("/");

    for(var i=0;i<patharray.length;i++){
      json = json[patharray[i]];
    }

    if(typeof(json) === "undefined"){
      return "Node Not Available";
    } else if(typeof(json) === "object"){
      var tempArr = [];

      for(var obj in json){
        tempArr.push([obj,json[obj]]);
      }
      return tempArr;
    } else if(typeof(json) !== "object") {
      return json;
    }
  }
  catch(err){
      return "Error getting data";
  }
}

I am trying to fetch the formatted marketcap from below:
{
    "quoteSummary": {
        "result": [
            {
                "price": {
                    "maxAge": 1,
                    "preMarketChange": {},
                    "preMarketSource": "FREE_REALTIME",
                    "postMarketChangePercent": {
                        "raw": 0.00015075946,
                        "fmt": "0.02%"
                    },
                    "regularMarketSource": "FREE_REALTIME",
                    "regularMarketOpen": {
                        "raw": 134.08,
                        "fmt": "134.08"
                    },
                    "strikePrice": {},
                    "openInterest": {},
                    "exchange": "NMS",
                    "volumeAllCurrencies": {},
                    "circulatingSupply": {},
                    "marketCap": {
                        "raw": 2255968796672,
                        "fmt": "2.26T",
                        "longFmt": "2,255,968,796,672.00"
                    }
                }
            }
        ],
        "error": null
    }
}

But I don't understand what xpath to use when calling the function. I have tried:
quoteSummary/result[0]/price/marketCap/fmt
/quoteSummary/result[0]/price/marketCap/fmt
quoteSummary/result/0/price/marketCap/fmt
/quoteSummary/result/0/price/marketCap/fmt

But I either get Node not Available or Error getting data.
What am I doing wrong?


text:
Q: Spark: What is the best way to do label encoding on a feature of variable length? For Spark, there is a StringIndexer in Spark ML that can do label encoding for a given column. However it cannot directly handle the situation where the column is variable length feature (or  multi-value feature). For example,
+-------+--------------------+--------------------+--------------------+--------------------+
|  jobid|        country_list|     typeofwork_list|             publish|              expire|
+-------+--------------------+--------------------+--------------------+--------------------+
|1636051|USA;Spain;China;A...|1441;1442;1443      |27/03/2017 2:00:0...|3/04/2017 1:59:59 PM|
|1636052|USA;Spain;Japan;A...|1441;1442           |27/03/2017 2:00:0...|3/04/2017 1:59:59 PM|
|1636053|UK;Spain;China;A....|1442;1443           |27/03/2017 2:00:0...|3/04/2017 1:59:59 PM|
|1636054|USA;Spain;China;A...|1443                |27/03/2017 2:00:0...|3/04/2017 1:59:59 PM|

The  country_list and typeofwork_list columns are variable length features. They can have more than a single value in one column, and the number of values is variant. When I wanna do label encoding on them, I cannot use StringIndexer directly on these columns.
Taking the country_list column for example, something like the following is the result I need:
+--------------------+
|        country_list|
+--------------------+
|0;1;2;3...          |
|0;1;4;3...          |
|5;1;2;3...          |
|0;1;2;3...          |

What is the best way to do label encoding on such columns in Spark?
One way I am thinking is first explode the country_list into a single-column dataframe, then do label encoding (StringIndexer) on this interim dataframe. After that, dropDulicate, then collect it, now I should have the mapping. Then I can broadcast the mapping to all worker machines. The original Dataframe can use a UDF which wraps the mapping to transform the country_list column. I'm wondering is there easier ways to do this?
Thank you.


text:
Q: Airflow does not launch my dags (activate a python environment and launch a python script) I would like to schedule a Python job to launch it every 15 minutes. I have already used airflow and haven't met any issues before.
I created a dag with a start date earlier today, a frequency of 15 minutes and two tasks which consist of activating a virtual Python environment and then launch a python script.
However, my dags do not execute itself so I started a web server to check its status and nothing happened. I, therefore, tried to launch it externally using the trigger_dag command but its status remain on running. I really do not understand what the problem is, any help would be appreciated. I attach two screenshots of the Airflow webserver which show the problem.

Edit : added the dags.py file, here is the definition of my dags :
import os
from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash_operator import BashOperator

default_args = {
    'owner': 'test',
    'depends_on_past': False,
    'start_date': datetime(2017,10,13,0,0,0,0),
    'email': ['test@gmail.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=15),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    #'end_date': datetime(2017, 9, 23),
}

dag = DAG('dbscan_integ', default_args=default_args)

t_dbscan = BashOperator(
    task_id='job_batch_dbscan',
        bash_command='/home/test/Documents/git_repo/analyser/algo_integ/integration_dbscan/python main_algo.py',
dag=dag)

t_virtual_dbscan = BashOperator(
    task_id='virtual_dbscan',
    bash_command='source activate integdb',
    dag=dag)
t_dbscan.set_upstream(t_virtual_dbscan)

A: I know this is stupid, but do you have the scheduler and worker up and running?

Edit 1:
Ok, I think the reason is that you do not have schedule_interval in your dag, instead you give timedelta(minutes=15) to retry_delay.


text:
Q: JWT Authentication in react-admin I am currently working on a react-admin project with the backend API server at localhost:8000/api using Django REST framework and django-rest-framework-simplejwt. The endpoints exposed from the backend API are admin/, api/, api/token/ and api/token/refresh/. I have tried to implement custom authProvider code similar as in this codesandbox following this github repo and this blogpost
Note that the codesandbox only serves as an example implementation of my frontend.
When I try to login with the correct credentials of Django admin, I am momentarily logged in to the dashboard page and instantly redirected to the login page. How do I get around this to work? Is there a simpler implementation to this, say using a third-party library/module?
P.S I can't change the backend code as I work only on the frontend. Also, I have not used drfProvider as data provider as it doesn't support react-admin@3.x.xand encountered too many errors when I downgraded to react-admin@2.x.x


text:
Q: How to edit a particular cell in listcontrol? I am having a listcontrol where I am supposed to edit cell's of second column.
And this should be a list control but not a gridcontrol.
Is it possible to edit cell's of particular column in listcontrol ? If any way exist please let me know how to achieve it.
Any suggestions is appreciated.

A: Look at CListCtrl::SetItemText
(MSDN)
Use the second parameter to specify the column.

A: CQuickList, a CListCtrl derived control, allows in-place edit of subitems.


text:
Q: How to property write characters in database I'm trying to write all iteam names and prices to database but I don't know why ★  is replaceing in database to ★ example ★ Bayonet to ★ Bayonet
I know code maybe is bad becouse I'm beginner
cost.json looks like these:
{
  "status" : "success",
  "prices" : [
    {
      "market_hash_name" : "★ Bayonet",
      "price" : "147.41",
      "created_at" : 1453784357
    },
    {
      "market_hash_name" : "★ Bayonet | Blue Steel (Battle-Scarred)",
      "price" : "112.28",
      "created_at" : 1453784518
    }, ...

Here are my code that I'm using:
<?php
@include_once ("pdocon.php");

$url = 'cost.json';
$api = file_get_contents($url);
$json = json_decode($api, true);

foreach($json['prices'] as $item) {
    $itemname = $item['market_hash_name'];
    $itemcost = $item['price'];

    $stmt = $dbh->prepare("SELECT * FROM items WHERE name=?");
    $stmt->execute(array($itemname));
    $rs = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!empty($rs)) {
        if(time()-$rs["lastupdate"] < 604800) die($rs["cost"]);
    }

    $stmt = $dbh->prepare("UPDATE items SET `cost` = ?,`lastupdate` = ? WHERE `name` = ?");
    $stmt->execute(array($itemcost, time(), $itemname));

    $stmt = $dbh->prepare("INSERT INTO items (`name`,`cost`,`lastupdate`) VALUES (?, ?, ?)");
    $stmt->execute(array($itemname, $itemcost, time()));

}

?>

A: Try to set your PDO connection options and pass it, when connecting to your database:
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$handle = new PDO(dns, user, pass, $options);


text:
Q: ej2 Syncfusion Sparkline component displays nothing Calling Component
 <SparkLine currentColor={"blue"} id="line-sparkline" type="Line" height="80px" width="250px" data={SparklineAreaData} color={"blue"} />

actuall Component
import React from 'react'
import {SparklineComponent,Inject,SparklineTooltip} from '@syncfusion/ej2-react-charts'
import {SparklineAreaData} from '../../data/dummy'
const SparkLine = ({id,height,width,color,data,type,currentColor}) => {

  return (

        <SparklineComponent
        id={"line-sparkline"}
        height={"80px"}
        width={"250px"}
        lineWidth={1}
        valueType="Numeric"
        fill={"blue"}
        border={{ color:"blue", width: 2 }}
        dataSource={SparklineAreaData}
        xName='x'
        yName='y'
        type={"Line"}
        >
          <Inject services={[SparklineTooltip]} />
        </SparklineComponent>

  )
}

export default SparkLine

Learning About syncfusion creating a simple Sparkline chart but it displays nothing on front-end to error also but when i inspect there is actually some elements tag but it shows nothing

A: This problem is arise due to wrong formatting of data. Your x-axes variable name and y-axes variable name  must be same as props xName and yName. If your dummy data look like this:
const dummyData = [{
  { xval: 1, yval: 6 },
  { xval: 2, yval: 7 },
  { xval: 3, yval: 4 },
  { xval: 4, yval: 8 },
  { xval: 5, yval: 10 },
}]

Props xName="xval" and yName="yval"
see Full example https://ej2.syncfusion.com/react/documentation/sparkline/getting-started/

A: I also experienced this problem. You can fix this by looking at the syncfusion documentation.
Correct the following.
change
xName='x' to xName = 'xval'
change
yName='y' to yName = 'yval'
Now it should work fine.

A: The value of your xName and yName props must be the same as your data Object property name
For example
if your data object is
const dummyData = [{
    { xvalue: 1, yvalue: 6 },
    { xvalue: 2, yvalue: 7 },
    { xvalue: 3, yvalue: 4 },
    { xvalue: 4, yvalue: 8 },
    { xvalue: 5, yvalue: 10 },
  }]

the xName and yName props value will be
    xName='xvalue'
    yName='yvalue'

like this:
 <SparklineComponent
    id={"line-sparkline"}
    height={"80px"}
    width={"250px"}
    lineWidth={1}
    valueType="Numeric"
    fill={"blue"}
    border={{ color:"blue", width: 2 }}
    dataSource={SparklineAreaData}
    xName='xvalue'
    yName='yvalue'
    type={"Line"}
    >


text:
Q: iOS: How to get the #define from a Constant.h ObjC in a Swift File? When I write this in the constant.h file:
#define WS_PLANNING_INFORMATION "registrations/"

It works when I call it from the Swift file.
But if I write this in the constant.h file:
#define WS_PLANNING_INFORMATION "registrations/" CRYPTOKEY

It doesn't work. The swift file doesn't see the WS_PLANNING_INFORMATION anymore.
Is there an easy way to concatenate two strings in the constant.h file to be well-retrieved by the swift file?
(The validate answer to this question is very useful and more simple than in that ticket, that doesn't suit me)

A: Use constants instead of macros.
in constant.h
extern const char *WS_PLANNING_INFORMATION;

in constant.m
const char *WS_PLANNING_INFORMATION = "registrations/" CRYPTOKEY;

If you mean to use NSString * instead of char *
in constant.h
extern const NSString *WS_PLANNING_INFORMATION;

in constant.m
const NSString *WS_PLANNING_INFORMATION = @"registrations/" CRYPTOKEY;


text:
Q: How to find grails Environment in grails java source package Greetings of the day !
I have a requirement to check the environment in grails project Java source package. Please help me.
I am trying to use this code, but not getting success.
String envName = System.getProperty(Environment.DEVELOPMENT);

A: Try this to get the current environment--
import grails.util.Environment;
...
Environment.getCurrent()

or test the environment --
Environment.getCurrent() == Environment.DEVELOPMENT


text:
Q: Find what domain is using the old Let's Encrypt ACME TLS-SNI-01 validation method before the EOL on February 13th, 2019 I just got this email. However, I host many wabsites (not all of them on the same server). I guess that one of the server is using an old version on the certbot client, but I'm not sure which. I however have a list of all the domains I host. Is there a command available to know which of them is using the old validation method ?
For reference, here is the email I got from Let's Encrypt on my contact email:

Hello,
Action is required to prevent your Let's Encrypt certificate renewals from breaking.
Your Let's Encrypt client used ACME TLS-SNI-01 domain validation to
  issue a certificate in the past 60 days.
TLS-SNI-01 validation is reaching end-of-life and will stop working on
  February 13th, 2019.
You need to update your ACME client to use an alternative validation
  method (HTTP-01, DNS-01 or TLS-ALPN-01) before this date or your
  certificate renewals will break and existing certificates will start
  to expire.
If you need help updating your ACME client, please open a new topic in
  the Help category of the Let's Encrypt community forum:
https://community.letsencrypt.org/c/help
Please answer all of the questions in the topic template so we can
  help you.
For more information about the TLS-SNI-01 end-of-life please see our
  API announcement:
https://community.letsencrypt.org/t/february-13-2019-end-of-life-for-all-tls-sni-01-validation-support/74209
Thank you,   Let's Encrypt Staff

A: I received the same email. After reviewing the information in a post titled, "How to stop using TLS-SNI-01 with Certbot" in the help link, they provided this command to determine if you need to:
grep '^pref_challs.*tls-sni-01' /etc/letsencrypt/renewal/*

They also suggested you update Certbot before running the command.

A: I tested my domain name on this site: https://letsdebug.net/ (mentioned on the let's encrypt forum : https://community.letsencrypt.org/t/third-party-tools-to-check-your-configuration/76272).
I tested these alternative methods of validation (HTTP-01, DNS-01 or TLS-ALPN-01) and all my domains are OK.
You can already do this manipulation.
Best regard.


text:
Q: Maven: Failed to load class for data source: com.databricks.spark.csv I have a Maven project and I can't make it run:
Exception in thread "main" java.lang.ClassNotFoundException: Failed to load class for data source: com.databricks.spark.csv.

How to fix this in Maven?

PS: I know about this question, but I cannot use any additional options to spark-submit, except --class and --master.

A: Try maven-shade-plugin in you pom it will create one shade jar with your all dependencies or classes. For more detail go through this link


text:
Q: How do I expand integer_sequence? I have a function which looks like this:
template <typename T, std::size_t... I>
std::ostream& vector_insert(std::ostream& lhs, const char* delim, const T& rhs, std::index_sequence<I...>) {
    std::ostream_iterator<float> it(lhs, delim);

    ((*it++ = at(rhs, I)), ...);
    return lhs;
}

This is my final attempt and I'm still failing on my expansion of the integer_sequence I'm hoping someone can tell me how to write a line that will effectively expand to:
*it++ = at(rhs, 0U), *it++ = at(rhs, 1U), *it++ = at(rhs, 2U)

Other things I've tried are:

*

**it++ = at(rhs, I...)

**it++ = at(rhs, I)...

*(*it++ = at(rhs, I))...
All of them are giving me the error:

error C3520: I: parameter pack must be expanded in this context

How do I expand this thing?
EDIT:
@AndyG has pointed out that this seems to be a visual-studio-2017 bug.

A: This seems like a compiler bug with Visual C++. I'm not aware of any easy fix for it other than simplifying the expression in which the parameter pack is expanded. Converting to a recursive approach seems to reliably work around the problem. For example :
#include <array>
#include <iostream>
#include <iterator>

template <typename T>
const auto& at(const T& v, size_t i) { return v[i]; }

// End of recursion
template<class T>
void vector_insert_impl(std::ostream_iterator<int> &, const char*, const T&)
{}

// Recursion case
template<class T, std::size_t N, std::size_t... I>
void vector_insert_impl(std::ostream_iterator<int> & iter, const char* delim, const T&rhs)
{
    *iter++ = at(rhs, N);

    // Continue the recursion
    vector_insert_impl<T, I...>(iter, delim, rhs);
}

template <typename T, std::size_t... I>
std::ostream& vector_insert(std::ostream& lhs, const char* delim, const T& rhs, std::index_sequence<I...>)
{
    std::ostream_iterator<int> it(lhs, delim);

    // Call the recursive implementation instead
    vector_insert_impl<T, I...>(it, delim, rhs);

    return lhs;
}

int main() {
    std::array<int, 5> v = { 1, 2, 3, 4, 5 };
    vector_insert(std::cout, " ", v, std::make_index_sequence<v.size()>());
}

Here, the parameter pack I is only expanded in the context of providing template parameters which VC++ has no trouble with.


text:
Q: Why isn't my element being emptied as expected? I'm sure this is very simple but I'm stuck.
I have an input, when a value is entered I would like to append this value to a  element. Once the value is deleted from the input, I would like to also remove it from the  element.
The issue i'm having is that the input value is removed, but the html 'Name' remains.
Fiddle link.
<input type="search" id="searchName" type="text">

$('#searchName').keyup(function() {
  if ($('#searchName').length > 0) {
    $("#filterName").text('Name: ' + $('#searchName').val());
  } else {
    $("#filterName").empty();
  }
});

Any help is appreciated.

A: Evaluate the length of the val(), not the element itself:
$('#searchName').keyup(function() {
  if ($('#searchName').val().length > 0) {
    $("#filterName").text('Name: ' + $('#searchName').val());
  } else {
    $("#filterName").empty();
  }
});

Fiddle

A: With a few modif. it's ok :-)

$('#searchName').on("keyup",function() {
  if ($('#searchName').val() != "") {
    $("#filterName").text('Name: ' + $('#searchName').val());
  } else {
    $("#filterName").text("");
  }
});

<input type="search" id="searchName" type="text">

A: Change the condition in the if to:
$('#searchName').val().length > 0

A: If you assign the keyup to the body element, not the input box itself then it will register the event and work -
$('body').keyup(function() {
  if($('#searchName').length > 0) {
    $("#filterName").text('Name: ' + $('#searchName').val());
  } else {
    $("#filterName").empty();
  }
});

Fiddle link - https://jsfiddle.net/age3nyph/4/

A: I would handle the 'search' and 'keyup' events to account for users clicking the 'x' and users typing in the field. See JSFiddle Example
$('#searchName').on('keyup', function() {
updateFilter(this);
});

$('#searchName').on('search', function(){
updateFilter(this);
});

function updateFilter(element){
if ($(element).val().length > 0) {
    $("#filterName").text('Name: ' + $(element).val());
 } else {
$("#filterName").empty();
 }
};

Edit: Updated link to point at JSFiddle setup to use JQuery. Original link excluded that update.


text:
Q: Laravel: How to hide/make user id uneditable in JS when using Brain Socket I have a universal used_id that will be used in brain socket (https://github.com/BrainBoxLabs/brain-socket) in Laravel like this:
window.userId = {{ $user->id }};
This will be used when receiving notifications,messages,etc. Problem is, since it is JS, window.userId can be edited in the DOM (like using firebug). So the user can get notifications from other users, which should not be.
Are there any countermeasures for this? (I'm using Sentry Package to get the user id)

*

*I've been thinking to use unique channels for each user instead, based on their ID, but will that be overkill? And i still have no idea how to do this in laravel?

A: You can't prevent users to edit javascript. You should use a specific kind of ID that we name "token", it's a key with a lot of every character, it's prevent users to guess the token of an other user.
You have "uniquid" who return a unique string, based on time, it can be guessed, but you can use it to assert unicity of your token. You can add informations such as user id, name, random string, maybe some salt, and then hash it.
You can use hash function
http://php.net/manual/en/function.hash.php
or mcrypt (you'd better use this one) :
http://php.net/manual/en/book.mcrypt.php


text:
Q: MYSQL Timezone support We are having a shared hosting plan and they are saying  that do provide MYSQL Timezone support in a shared hosting plan. I can create timezone related tables in our database and populate them with required data(data from from our local MYSQL Timezone related tables. How to view the code syntax for MySQL "CONVERT_TZ" function?
Thanks
Arun

A: In order to timezone support to be around, the hosting company should have executed this:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql ...

The mysql_tzinfo_to_sql utility should load the time zones. Please make sure the host company has done this. If they can't or won't,

*

*you could into Amazon EC2, you could have full access to MySQL and can run it yourself

*Find a willing hosting company

BTW Here is the MySQL Documentation for CONVERT_TZ : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz


text:
Q: Regarding memory and variable assignment in PHP Ive asked a similar question before but i was really unclear so ive decided to use a more concrete example.
Does php save the result of the variable or does it save the procedure to run it? Why im wondering is if i store a function in it, does it store the return value or just copies the procedure
say:
    function foo($something)
{

    for loop
        {
       echo 'Something';

       }

   return $something;
}

$b = foo(5);

from what i encountered just assigning the value executes the function. Which i dont want because i dont want to go through double the for loops and do double what could be inside.

A: PHP is a strict programming language, meaning that expressions are always completely evaluated. The line
$b = foo(5);

computes the value for foo(5) before the assignment; PHP does not leave it as a thunk to be evaluated when or if the variable $b is used.
If you want to you can achieve something similar to a thunk by creating a closure, like this:
$b = function() { return foo(5); };

This will not evaluate foo(5) until its value is needed, and then to get the value you must call the closure as $b().

A: In PHP you can have both (either store result, or function's code)
if you write:
function foo()
{
    return 5;
}
$a = foo();

this will mean - execute function foo and store result into $a
if you write:
$a = function()
{
    return 5;
};
$a();

this will mean - store function's code into variable $a, then execute function stored in $a


text:
Q: Bash: Replace strings in file with an array I want to replace strings in a file using a bash array.
e.g. the file example.txt:
A: Netherlands
B: Germany
C: United States
A: Netherlands
[Edit #2: In the file are also different strings without the format X:Y]
C, N: United States

Now I want to have a bash script to replace the letters (Edit: before the colons) so it becomes
A => Amsterdam
B => Berlin
C => Chicago
N => New York

So finally I want to have
Amsterdam: Netherlands
Berlin: Germany
Chicago: United States
Amsterdam: Netherlands
[Edit #2: In the file are also different strings without the format X:Y]
Chicago, New York: United States

And this using a bash script but it won't matter if we include other scripting languages like perl.
Thank you!

A: if A B C are the only cases:
awk 'BEGIN{FS=OFS=":";d["A"]="Am..";d["B"]="Berl..";d["C"]="Chica.."}
     {$1=d[$1]}7' file

if you have many A, B, C, ...A1..Ab...Ax.... I suggest you create a dictionary file in this format (dict.txt):
A:Am...
B:Berlin...
C:Cfoo
D:Dbar...
.....
....
Z:Zwhatever

Then you can:
awk -F':' -v OFS=":" 'NR==FNR{d[$1]:$2;next}{$1=d[$1]}7' dict.txt yourFile

Above codes were not tested, but my eye-compiler tells that it should go. ^_*
update according to the Question change
if there could be CSV in $1, you can first split() then get d[splitedElements] and concatenate the results. It is minor change, but you want to get hand dirty, I believe.

A: <?php
$source = file("/path/to/input/file.txt");
$lines = count($source);
$town = array();
$town["A"] = "Amsterdam";
$town["B"] = "Berlin";
$town["C"] = "Chicago";
$town["N"] = "New York";
for($i=0;$i < $lines; $i++)
{
  $line = $source[$i];
  if (strpos($line,":"))
  {
    foreach($town as $a => $v)
    {
      $c_town = explode(":",$line);
      $c_town[0] = str_replace($a,$v,$c_town[0]);
      $line = implode(":",$c_town);
    }
  }
  echo $line; # or do what you want with it
}

Finally I solved my problem by using an external php script. I know there are better ways because php is not always pre-installed on the operating system but it worked best.
Because the script parses the file line per line don't replace the echo with a write command (e.g. file_put_contents("/path/to/file",$line,FILE_APPEND); because it is slow and produces much traffic on your disk. I recommend to cache the output in an array and save it at the end of the script.
Thanks for the answers though, they work in most cases but weren't the solution for my problem because they mostly have problems with different contents in the file.


text:
Q: Get object from collection without iterating over it I'm trying to get the object from the collection beacons without having to iterate over that collection because that causes all get.rssi() values from the allBeacons list to get overwritten whilst only the values from the allBeacons list that are in the collection beacons have to be overwritten with their respective collection rssi value
how can I do this?
any help is greatly appreciated, this is my code:
MainActivity.java:
    @Override
        public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) {
            new java.util.Timer().schedule(
                    new java.util.TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    for (final Beacon beacon : beacons) {
                                        {
                                            if (!allBeacons.contains(beacon)) {
                                                allBeacons.add(beacon);
                                            }
                                        }
                                    }
                                    for (final Beacon allbeacons2 : allBeacons) {
                                        allbeacons2.setRssi(0);
                                    }

                                    for (final Beacon allbeacons3 : allBeacons) {
                                        if (beacons.contains(allbeacons3)) {
         //here the beacon of the allbeacons list should get the rssivalue of that beacon in the collection beacons
                               allbeacons3.setRssi(?.getRssi());
                                        }
                                    }
                                    arrayL.clear();
                                    arrayL.addAll(allBeacons);
                                    adapter.notifyDataSetChanged();

                                }
                            });

                        }
                    }
                    , 5000);

            //  }

        }

    });


text:
Q: Laravel functions arrays and datamodels I have been working on some old code that was given to me to play with and edit to get familar with and i was wondering if you can see if what i am doing is syntactly sound as im confusing myself with the laravel framework. i basically want to know if im close to what my comments are wanting to do and whether my code and comments marry up or a i missing the point? As im getting the following error message
The error message im getting when running this command through my terminal is
PHP Parse error:  syntax error, unexpected '$email' (T_VARIABLE), expecting '(' in /Libraryenter code here/WebServer/Documents/healthandsafetymonitoringsystem.local/app/commands/IncompleteReportsCommand.php on line 157

my code is as follows
// This function uses the parameters $data that is passed to this function each time
// the fire() function loops through and assigns and determines that there is a duereport
private function sendGeneralManagerEmail($data)
{
    // create an array called 'Park' that is poulated via the $data parameters
    // in the function and is specificly looking for the ParkName entries
    $data['Park'] = $Park->ParkName;
    //for each item in that array use $ParkName as a key and name each elements $name
    foreach($data['Park'] as $ParkName => $name)
    {
        // Every time i loop through this file get the element $name and
        // attach this prefix to it
        $email = $name."generalmanager@parkholidays.com";
    }
        // Then send an email with new $email variable as a reciepient and sending the $data passed
        // from the fire() function and used within this functions parameters
        Mail::send('emails.GeneralManager', $data, function($message) use $email
        {
            $message->to( $email, 'General Manager')->subject('[Urgent] Health & Safety Reports');
        });
}

Sorry for the dumb question if there are any articles regarding arrays/data models and php functions in laravel that you suggest reading thatll be great. This is a steep learnign curve as i have gone from plain php coding on notepad ++ to laravel 4 and i cant seem to find a nice tutorial that goes from the start to finish with a complete novice in mind.
Regards mike

A: Regarding your error
You just have a PHP syntax error. Here's the code you want:
// This function uses the parameters $data that is passed to this function each time
// the fire() function loops through and assigns and determines that there is a duereport
private function sendGeneralManagerEmail($data)
{
    // create an array called 'Park' that is poulated via the $data parameters
    // in the function and is specificly looking for the ParkName entries
    $data['Park'] = $Park->ParkName;
    //for each item in that array use $ParkName as a key and name each elements $name
    foreach($data['Park'] as $ParkName => $name)
    {
        // Every time i loop through this file get the element $name and
        // attach this prefix to it
        $email = $name."generalmanager@parkholidays.com";
    }
        // Then send an email with new $email variable as a reciepient and sending the $data passed
        // from the fire() function and used within this functions parameters
        Mail::send('emails.GeneralManager', $data, function($message) use ($email)
        {
            $message->to( $email, 'General Manager')->subject('[Urgent] Health & Safety Reports');
        });
}

See the use $email you had that I've changed to use ($email) in the closure at the end.
Regarding your more general question about coding
I can see a few things that don't look right to me. Is this code an exact replica of the function or have you removed some code?

A: It is hard to say more about you code, since it is taken out of context.
Writing new code as answer, will confuse you more.
So it is better to:
Subscribe to laracast and you will learn everything you need to know about Laravel. Also there is new, updated Laravel 4.1 documentation


text:
Q: Webview crashes on select box or any Dialog I have an application where clicking on an item in a list shows webview with javascript injected.I need to save the webview object so that when the user presses the same item again the existing webview is shown instead of reloading it and injecting the javascript again.I am able to save the webview object in Arraylist of webview inside the application class.
I check whether the item already exists in the Arraylist and if it do exists take the corresponding object and set the object as the content of the activity as shown below.
     temp_WebView=new WebView(this);
     temp_WebView=(WebView)application.getWebview(j);
     ViewGroup parent = (ViewGroup) application.getWebview(j).getParent();
     parent.removeView(application.getWebview(j));
     setContentView(temp_WebView);

This works fine but when clicking on any of the select box inside the webview where a dialog is populated it gets crashed  with the following error,

WARN/WindowManager(60): Attempted to add application window with unknown token HistoryRecord{4506d1e8 tabviewapp.com/.Webresults}.  Aborting.

 DEBUG/AndroidRuntime(500): Shutting down VM

 WARN/dalvikvm(500): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
 ERROR/AndroidRuntime(500): FATAL EXCEPTION: main
 ERROR/AndroidRuntime(500): android.view.WindowManager$BadTokenException: Unable to  add window -- token android.os.BinderProxy@45034510 is not valid; is your activity running?
 ERROR/AndroidRuntime(500): at android.view.ViewRoot.setView(ViewRoot.java:505)
 ERROR/AndroidRuntime(500): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)

 ERROR/AndroidRuntime(500):  at      android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)

 ERROR/AndroidRuntime(500):     at android.view.Window$LocalWindowManager.addView(Window.java:424)

 ERROR/AndroidRuntime(500):     at android.app.Dialog.show(Dialog.java:241)

 ERROR/AndroidRuntime(500):     at android.webkit.WebView$InvokeListBox.run(WebView.java:7095)

 ERROR/AndroidRuntime(500):     at android.os.Handler.handleCallback(Handler.java:587)

 ERROR/AndroidRuntime(500):     at android.os.Handler.dispatchMessage(Handler.java:92)

 ERROR/AndroidRuntime(500):     at android.os.Looper.loop(Looper.java:123)

 ERROR/AndroidRuntime(500):     at android.app.ActivityThread.main(ActivityThread.java:4627)

 ERROR/AndroidRuntime(500):     at java.lang.reflect.Method.invokeNative(Native Method)

 ERROR/AndroidRuntime(500):     at java.lang.reflect.Method.invoke(Method.java:521)

 ERROR/AndroidRuntime(500):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

 ERROR/AndroidRuntime(500):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

 ERROR/AndroidRuntime(500):     at dalvik.system.NativeStart.main(Native Method)

 WARN/ActivityManager(60):   Force finishing activity tabviewapp.com/.Webresults

I think the problem is with the context of the webview but not able to figure out how to set the context for the existing object or pass context to dialog generated inside the webview.
Thanks in advance.

A: I had a similar problem. In my case the webview was in an ActivityGroup. ActivityGroups and dialogs don't work out of the box. In my case I had to not use this as context, instead use getParent().
temp_WebView=new WebView(getParent());


text:
Q: What is the value of the series $\sum_{n\geq 1}\frac{1}{n^2+1}$? What is the value of $$\sum_{n=1}^{\infty}\frac1{1+n^2}$$
I don't know how to solve it.
I tried to solve it by power series, but I failed.

A: I will give an elementary solution based on the following lemmas:

Lemma 1. For any $n\in\mathbb{N}^+$,
  $$ \int_{0}^{+\infty}\frac{\sin(nx)}{n}e^{-x}\,dx = \frac{1}{1+n^2}.$$
  Proof: integration by parts.
Lemma 2. The following series is the Fourier series of a $2\pi$-periodic sawtooth wave $f(x)$, that over the interval $(0,2\pi)$ equals $\frac{\pi-x}{2}$:
  $$ f(x)=\sum_{n\geq 1}\frac{\sin nx}{n} $$
  Proof: direct computation of Fourier coefficients.

By Lemma 1 and Lemma 2,
$$\begin{eqnarray*}\sum_{n\geq 1}\frac{1}{n^2+1}&=&\int_{0}^{+\infty}f(x)e^{-x}\,dx\\(\text{periodicity of } f(x))\qquad&=&\left(1+\frac{1}{e^{2\pi}}+\frac{1}{e^{4\pi}}+\ldots\right)\int_{0}^{2\pi}f(x)e^{-x}\,dx\\[0.2cm]&=&\frac{e^{2\pi}}{e^{2\pi}-1}\int_{0}^{2\pi}\frac{\pi-x}{2}e^{-x}\,dx\\[0.2cm](\text{direct computation})\qquad &=&\color{red}{\frac{\pi\coth\pi-1}{2}}.\end{eqnarray*} $$

A: Hint:
$$\frac{\pi x}{2}\coth \pi x=\frac{1}{2}+\sum_{n=1}^{\infty }\frac{1}{\left ( \frac{n}{x} \right )^2+1}$$
at $x=1$
$$\sum_{n=1}^{\infty }\frac{1}{n^2+1}=\frac{\pi}{2}\coth \pi -\frac{1}{2}$$

A: Hint. It's well-known that
$$\pi\cot(\pi z)=\frac{1}{z}+2\sum_{n=1}^\infty \frac{z}{z^2-n^2}$$

A: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{n = 1}^{\infty}{1 \over n^{2} + 1} & =
{1 \over 2\ic}\sum_{n = 0}^{\infty}\pars{{1 \over n + 1 - \ic} -
{1 \over n + 1 + \ic}}
\\[5mm] & =
{1 \over 2\ic}\bracks{\vphantom{\Large A}\Psi\pars{1 + \ic} - \Psi\pars{1 - \ic}}\qquad
\pars{~\Psi:\ Digamma\ Function~}
\\[5mm] & =
{1 \over 2\ic}\braces{\vphantom{\LARGE A}%
{1 \over \ic} - \bracks{\vphantom{\Large A}\Psi\pars{1 - \ic} - \Psi\pars{\ic}}}\qquad
\pars{~\Psi\ Recurrence~}
\\[5mm] & =
-\,{1 \over 2} - {1 \over 2\ic}\,
\bracks{\vphantom{\large A}\pi\cot\pars{\pi\ic}}\qquad
\pars{~Euler\ Reflection\ Formula~}
\\[5mm] & =
-\,{1 \over 2} - {\pi \over 2\ic}\,\bracks{\vphantom{\large A}-\ic\coth\pars{\pi}} =
\bbx{\ds{\pi\coth\pars{\pi} - 1 \over 2}}
\end{align}

A: It is shown in this answer that
$$
\mathrm{PV}\sum_{n\in\mathbb{Z}}\frac1{n+z}=\pi\cot(\pi z)\tag{1}
$$
converges for all $z\in\mathbb{C}$.
Therefore,
$$
\begin{align}
\sum_{n=1}^\infty\frac1{n^2+z^2}
&=\frac i{2z}\sum_{n=1}^\infty\left(\frac1{n+iz}+\frac1{-n+iz}\right)\\
&=\frac i{2z}\left[\mathrm{PV}\sum_{n\in\mathbb{Z}}\frac1{n+iz}-\frac1{iz}\right]\\
&=-\frac1{2z^2}+\frac{\pi i}{2z}\cot(\pi iz)\\[6pt]
&=-\frac1{2z^2}+\frac\pi{2z}\coth(\pi z)\tag{2}
\end{align}
$$
Plugging in $z=1$ gives
$$
\sum_{n=1}^\infty\frac1{n^2+1}=-\frac12+\frac\pi2\coth(\pi)\tag{3}
$$


text:
Q: SSCCE: How to provide examples for programming questions I saw this today.
It's a description of Short, Self Contained, Correct (Compilable), Example. This would be a useful reference for many as a guideline for how to make code usable in questions on Stack Overflow.
It's based on these four points
* Short (Small) - Minimize bandwidth for your example, do not bore the audience.
* Self Contained - Ensure everything is included, ready to go.
* Correct - Copy, paste, (compile,) see is the aim.
* Example - Displays the problem you are trying to solve.

I thought it was pretty cool and could perhaps be worked into the Stack Overflow FAQ or wherever.
Is this a useful guideline, and what other code guidelines might be useful for Stack Overflow examples?

A: Eric Raymond wrote a whole bloody treatise on asking technical questions. The problem that became evident was that people who want to learn how to write a good question and people who can't write a good question are mutually exclusive groups.
I wouldn't mind seeing these four bullet points on the FAQ, though. Just to reinforce that we do, actually, like well-worded and well-thought out questions.

A: Personally I think using a fairly obscure acronym (I'd never heard about it before) doesn't help as much as making it explicit. I tend to say:

Please provide a short but complete example which demonstrates the problem.

I think that's clearer than even the expanded acronym. I have my own page about it which I sometimes reference: http://pobox.com/~skeet/csharp/complete.html - occasionally I've had to refer readers to a second page too: http://pobox.com/~skeet/csharp/incomplete.html


text:
Q: Logistic equation showing $L/2$ has the most rapid increase on the interval $0So the question goes as follows:
"Show that a solution $y(t)$ of the logistic equation having  $0<y(0)<L$ is increasing most rapidly when its value is $L/2$.(Hint: You do not need to use the formula for the solution to see this)"
So first of all I don't unnderstand how you would be able to see this without utilizing the formula:
$\frac{dy}{dt}=ky(1-\frac{y}{L})$
And also most important how would you see that the increase is as most rapid att $t=L/2$?
I was thinking about taking the difference between the slope at $t=L/2$ and the other $t$ values on the interval. But it does't seem right.
Any suggestions?
Thank you in advance!

A: Notice that we are only concerned about $$0<y<L$$ Since $$y'=ky(1-\frac{y}{L})>0$$ we have $$y''=ky'(1-\frac{2y}{L})$$  and $$y'''=\frac {-2k}{L}y'^2<0$$ Notice that the only critical point of $y'$ is at $$y=\frac {L}{2}$$This critical point is a maximum because $y'$ is concave down due to the fact that its second derivative, $y'''$ is negative.

A: The derivative $\frac{dy}{dt}$ is the rate of change of $y(t)$, so $y(t)$ is increasing most rapidly when $\frac{dy}{dt}$ has its maximum value. Since $\frac{dy}{dt}$ depends on $y$ only, we can use differentiation to find the maximum point:
$$
\left( ky\left(1-\frac{y}{L}\right) \right)'=k\left( 1-\frac{y}{L}+y\left(-\frac{1}{L}\right) \right)=k\left( 1-\frac{2y}{L} \right)
$$
We can see that $y=L/2$ is the only possible extremum point; $\frac{dy}{dt}$ strictly increases when $y<L/2$ and strictly decreases when $y>L/2$, thus $L/2$ is the maximum point.


text:
Q: PHP not working correctly? I have this PHP code here, which should sent the Names, Email and comment of the user to an email. Although it doesn't seem to be working any more. I've been using this code as a basis for my contact form for many years. Now they're just not working.
Your message is being sent...
<?php

$emailSubject = 'A message from: '.$_POST['name'] .' '.'-'.' ' .'Email Adress: ' .$_POST['email'];
$webMaster = 'webmaster@gmail.com';

$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$email = $_POST['email'];
$sub = $_POST['sub'];
$comments = $_POST['comments'];

$body = <<<EOD

First Name: $name1

Last Name: $name2

Email: $email

Subject: $sub

Comments: $comments

EOD;

$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailSubject, $body,
$headers);

$theResults = <<<EOD

<title>Your message is being sent...</title>
<meta http-equiv="refresh" content="4;URL=http://www.google.co.uk">

EOD;
echo "$theResults";
?>

It's very confusing and annoying. Messages when sent to Hotmail don't even appear, so that'll force the clients to get a new email because of it, and when sent to Google... Does it not accept $_POST or something?

As you can see, the SCRIPT does work, it's just with G-mail none of the important information seems to show up, and on Hotmail the messages don't even send/appear!! Thanks for your help. Here is the HTML if needed.

CONTACT US

<form action="Scripts/contact.php" method="post">

<input name="text1" type="text" class="inputstyle" id="name1" value="First Name"     size="5" maxlength="5" />

<input name="text2" type="text" class="inputright" id="name2" value="Last Name" />

<input name="text3" type="text" class="inputstyleBelow" id="email" value="E-mail Address" />
Invalid format.

<input name="text4" type="text" class="inputrightBelow" id="sub" value="Message Subject" />

<textarea name="textarea1" cols="45" rows="5" class="inputstyleMsg" id="comments">Message Here</textarea>
     Minimum number of characters not met.Exceeded maximum number of characters.

<input name="Submit message" type="submit" class="submitmail" value="" />

</form>

A: Your form fields are incorrect. id is NOT used in form submission. the name parameter is. Since you've named your form fields as text1, text2, etc... but are looking for name1 and similar in your PHP code, you're trying to retrieve non-existent fields.
e.g. you have:
<input name="text1" type="text" class="inputstyle" id="name1" value="First Name"     size="5" maxlength="5" />
$_POST['name1'];

no, that field will actually be $_POST['text1'].


text:
Q: Direct python output to linux file I have a script written in python which I am running on ubuntu. I would like the output of this command to be directed into the file.
print str(kFx) + ',' + str(kFy) + ',' + str(kFz)
I would ideally use the python.py > file.txt but the script has some interactive parts which I won't be able to use if I redirect the output to a file.
I tried changing the code to this but I get syntax errors. I literally use python for the first time so excuse my lack of knowledge.
print (str(kFx) + ',' + str(kFy) + ',' + str(kFz) , file=open("output.txt", "a"))

Any ideas on how to do that?
Thank you,
Alex

A: you can open the file with file=open("output.txt", "a")) like you did. then instead of printing you would use
file.write(str(kFx) + ',' + str(kFy) + ',' + str(kFz))

becasue you opened the file in append mode (denoted by the "a" in open) it would add this string to the end of the file. you might also need to add a new line after your string:
file.write("\n")

when you are done writing:
file.close()

A: On Python 3, it could look like:
with open("output.txt", "a") as file:  # append to the file
    print(*kF, sep=', ', file=file)
    # etc...

I've added space after the comma for readability. See What does ** (double star) and * (star) do for parameters?
On Python 2, you could add from __future__ import print_function at the top of your script and convert to string manually ", ".join(map(str, kF)) or just:
print(kFx, kFy, kFz, sep=', ', file=file)

You could use kF object instead of kFx, kFy, kFz e.g., a tuple/list:
kF = "kFx value", "kFy value", "kFz value"

or for readability, you could use collections.namedtuple to create a custom class:
from collections import namedtuple

Point3D = namedtuple("Point3D", "x y z")

kF = Point3D("kFx value", "kFy value", "kFz value")
# -> Point3D(x='kFx value', y='kFy value', z='kFz value')

It enables kF.x, kF.y, kF.z syntax. If you need a mutable object, you could use types.SimpleNamespace:
from types import SimpleNamespace

kF = SimpleNamespace(x="kFx value", y="kFy value", z="kFz value")
kF.x += " modified"
# -> namespace(x='kFx value modified', y='kFy value', z='kFz value')

On Python 2, you could partially emulate it using class Point3D: pass.
For a richer functionality, you could try attrs package:
#!/usr/bin/fades
import attr  # fades.pypi attrs

Point3D = attr.make_class("Point3D", ["x", "y", "z"])

kF = Point3D("kFx value", "kFy value", "kFz value")
kF.x += " modified"
# -> Point3D(x='kFx value modified', y='kFy value', z='kFz value')

To run this and other code examples that require third-party Python packages from PyPI, you could use fades for convenience (to install, run: sudo apt-get install fades). Though it is not necessary, you could just install dependencies manually instead: pip install attrs (make sure to run your script with the same python executable as pip: head -1 $(command -v pip)).
To print kF to the file:
print(*attr.astuple(kF), sep=', ', file=file)
# -> kFx value modified, kFy value, kFz value

To save it in JSON format:
import json

with open("kF.json", "w", encoding='utf-8') as json_file:  # overwrite the file
    json.dump(attr.asdict(kF), json_file)
    # -> {"x": "kFx value modified", "y": "kFy value", "z": "kFz value"}

A: If you use with-keyword; the file-stream will only stay open inside the block. Then you dont have to remember closing it when you are done.
with open('test.output', 'w') as f:
    f.write('{0},{1},{2}\n'.format(kFx, kFy, kFz))

If you meant to append to file like echo "test" >> test.txt and not echo "test" > test.txt
Then just change the open mode to 'a' instead of 'w'


text:
Q: How to communicate between JavaScript and Python in a CGI script I have a CGI script which runs on local host. It has a Python function named compute(argument 1) and prints html tags along with a JavaScript function called onClick which gets called when a button is clicked on the browser. I am not sure how to communicate between JavaScript and Python here.
Here is a snippet of the CGI file
   import cgi

   def worker():
      #Does something here and returns an python list called data
   def compute(index)
       #Does something with data[index] and returns another python list called data2
   print ("Content-type: text/html")
   print ()
   print ("")
   print ("")
   print ("<title>Worker</title>")
   print("""""")
   print ("")
   print ("")
  <button  type = "button" class  = "next" onclick = "onClick()" >Next → </button>
   print("""Count:
 0
""")
   print ("")
   print ("")

My question here is how do I make the JavaScript function OnClick() call the python function compute() by passing variable count as a parameter and then storing the resulting list returned by compute() as a JavaScript variable. It would be better if worker function does not have to be called again. It would be fine to even return a single variable in compute(index) rather than a python list and pass it to JavaScript. Thanks in advance :).

A: AJAX/JQUERY can send the data, JSON for instance, to your python endpoint. But your script is not a server. You need a server a.k.a middleware like apache. POST via AJAX to your server adress:
    $(function(){
    $.ajax({
    url: "ServerAdress/cgi-bin/" + service.py,
    type: "POST",
    async:true,
    data: {key_vehicule: 'mercedes'},
    success: function(response){

        },
    error: function(){

        },
    complete: function(){

        }
    });

Be sure to have your server configured to execute the python script with the python interpeter and all the right it needs. In the python script, just importing the cgi is not enought, you need the to receive the data:
     form = cgi.FieldStorage()
     vehicule = form.getvalue('key_vehicule')


text:
Q: How can I unlock a paragraph when co-authoring a Word document? I've never encountered this before upgrading to Office 2016, so it may be related. A coworker edited a paragraph in a Word document that is on a Sharepoint server, but then saved the change and closed the document (even restarted his computer). However, the paragraph still shows as locked:

To avoid conflicts, you cannot edit in this area until USER finishes editing it and uploads to the server.

Both of us have cleared the Office file cache as described towards the end of this article, but it did not unlock that paragraph. Also, it does not show that user as one of the users editing the document. This paragraph is also locked to users opening the document in Word 2013.
So my thoughts are that this must require some work on the SharePoint server itself (the paragraph lock information must be held there somewhere)...anyone know what that work would be?

A: I had the same issue. In my case the document section was mistakenly blocked for editing by a user. Following steps helped to resolve the issue:

*

*Select the locked section

*Click on review tab on MS word ribbon

*Click Block Authors icon ( if its greyed out)

I hope this will resolve the issue.


text:
Q: C++ overloading operators for matrix structure I am trying to make matrix structure with overloading operators '+' and '='.
Matrix structure:
struct Matrix{
    int rows;
    int cols;
    std::vector<int> data;
    Matrix(int rows, int cols, int val);    //creates matrix row*col and fills every position with val
    Matrix(const Matrix &m);    //copy constructor
    Matrix(int rowcol = 0);    //creates matrix rowcol*rowcol filled with zeros
    Matrix & operator=(const Matrix &m);
    void printMatrix();    //prints the matrix
    ...
};

Operators:
Matrix & Matrix::operator=(const Matrix &m) //assings matrix m to the new matrix
{

}

Matrix operator+(const Matrix &a, const Matrix &b) //sums two matrices
{
    //I know how to make the algorithm for summing two matrices, however i don´t know how
    //to return the result into existing matrix
}

And main function:
int main(){
    Matrix A(3,3,1);
    Matrix B(3,3,2);
    Matrix C(3,3,0);

    C = A + B;
    C.printMatrix();
    ...

    return 0;
}

I don´t know how to make it work. I tried something like this for the '=' operator:
Matrix & Matrix::operator=(const Matrix &m)
{
    static matrix d(m);    //using copy constructor
    return d;
}

but it didn´t work. It created new matrix with dimensions 0x0. Any advice on how to implement it?

A: A working way to implement that operator= would be as follows:
Matrix& Matrix::operator=(const Matrix &m)
{
    this->rows = m.rows;
    this->cols = m.cols;
    this->data = m.data;

    return *this;
}

I won't approach the algorithm needed for operator+, but the surrounding machinery is also surprisingly simple:
Matrix operator+(const Matrix &a, const Matrix &b) //sums two matrices
{
    Matrix result(<num of rows>, <num of cols>, 0);

    // do things with result here, using your algorithm, a, and b
    // e.g. result.data[?] = a.data[?] ? b.data[?]

    return result;
}

To make this easier, since your data is one-dimensional (good! this is efficient!), you may want to implement an accessor that takes x and y dimensions and returns an index into data. For example:
int& Matrix::val(const int x, const int y)
{
    assert(x < cols);
    assert(y < rows);

    return data[x + y*cols];
}

The result of this may be both read and written, like this:
result.val(x1, y1) = a.val(x2, y2) + b.val(x3, y3);

Where those co-ordinates and the + are just things I made up, and should come from your algorithm.

If you also want an operator+=, to affect an existing matrix, then:
Matrix& Matrix::operator+(const Matrix &b) //sums two matrices
{
    // do things with your object here, using your algorithm and b

    return *this;
}

Where I return *this for the member operators, that's not strictly necessary, though it is conventional, and it allows for easy chaining of operations (if you're into that kind of thing). You can find more information on operator overloading in your book.