text:
Q: Realizar calculo de porcentagem Jquery Boa tarde pessoal.
Tenho um campo com valor readonly .
Esse campo já em preenchido com dado de meu banco.
Tenho um outro campo, onde irei digitar o valor da porcentagem.
Como faço para o valor do resultado ser apresentado no outro campo?

        Valor (R$)
        <input type="text" class="form-control" name="valor" id="valor" value="80.00" size="15" maxlength="25" placeholder="0.00" readonly>

        Percentual (%)
        <input type="text" class="form-control" name="percentual" id="percentual" title="Informe o percentual" size="15" maxlength="25" placeholder="0.00%">

        Resultado
        <input type="text" class="form-control" name="resultado" id="resultado" title="Informe o percentual" size="15" maxlength="25" placeholder="R$ 0.00">

A: Você pode fazer assim sem jquery:

document.getElementById('percentual').onkeyup = function() {
  var valor = parseFloat(document.getElementById('valor').value);
  document.getElementById('resultado').value = valor * (parseFloat(this.value)/100);
}

    Valor (R$)
    <input type="text" class="form-control" name="valor" id="valor"  value="80.00" size="15" maxlength="25" placeholder="0.00" readonly >

    Percentual (%)
    <input type="text" class="form-control" name="percentual" id="percentual" title="Informe o percentual"  size="15" maxlength="25" placeholder="0.00%"  >

    Resultado
    <input type="text" class="form-control" name="resultado" id="resultado" title="Informe o percentual" size="15" maxlength="25" placeholder="R$ 0.00"  >

A:

$("#percentual").on('input',function() {
 var Valor = $("#valor").val();
  var Porcentagem = $("#percentual").val();
  var resultado = (Valor * Porcentagem) / 100;
  $("#resultado").val(resultado)
});

                                        Valor (R$)
                                        <input type="text" class="form-control" name="valor" id="valor"  value="80.00" size="15" maxlength="25" placeholder="0.00" readonly >

                                        Percentual (%)
                                        <input type="text" class="form-control" name="percentual" id="percentual" title="Informe o percentual"  size="15" maxlength="25" placeholder="0.00%"  >

                                        Resultado
                                        <input type="text" class="form-control" name="resultado" id="resultado" title="Informe o percentual" size="15" maxlength="25" placeholder="R$ 0.00"  >

A: Seria algo assim

$(document).ready(function(){
    $("#percentual").change(function(){
      var valor = $("#valor").val();
      $("#resultado").val(valor * (parseInt($(this).val())/100));
    })
})

                                        Valor (R$)
                                        <input type="text" class="form-control" name="valor" id="valor"  value="80.00" size="15" maxlength="25" placeholder="0.00" readonly >

                                        Percentual (%)
                                        <input type="text" class="form-control" name="percentual" id="percentual" title="Informe o percentual"  size="15" maxlength="25" placeholder="0.00%"  >

                                        Resultado
                                        <input type="text" class="form-control" name="resultado" id="resultado" title="Informe o percentual" size="15" maxlength="25" placeholder="R$ 0.00"  >

A:

$("#percent").change(function() {
  if (parseFloat($(this).val()) <= 100) {
    var porcentagem = (parseFloat($("#valor").val()) * parseFloat($(this).val())) / 100;
    $("#resultado").val(porcentagem);
  }
});

    Valor (R$)
    <input id="valor" type="text" class="form-control" name="valor" id="valor" value="80.00" size="15" maxlength="25" placeholder="0.00" readonly>

    Percentual (%)
    <input id="percent" type="text" class="form-control" name="percentual" id="percentual" title="Informe o percentual" size="15" maxlength="25" placeholder="0.00%">

    Resultado
    <input id="resultado" type="text" class="form-control" name="resultado" id="resultado" title="Informe o percentual" size="15" maxlength="25" placeholder="R$ 0.00">


text:
Q: 'look along' the edges Vs 'look around' the edges I'm staring at a computer screen, looking at the edges of the glass.
I want to say:

"I looked around the edges and the screen looked fine to me."

Is it correct? The phrase, "looked around the edges", I mean? Or should I say:

"I looked along the edges and the screen looked fine."

And is there a difference between the two? If so, what is the difference?
Another example would be if I have a book, and I ask someone to find a particular word on a particular page, and I gave them a hint:

"Look along the edge and you will find it."

Should I say:

"Look around the edge you will find it."

I think 'look along' sounds correct to me in this context (correct me if I am wrong). But 'look around' sounds correct to me in my first example sentence.
I'm trying to understand the subtle differences between the two: look around Vs look along.

A: If what I meant was

I looked near the edge of the doorway

I might say

I looked along the edge of the doorway

to imply that my looking was very near the edge.
I would not say

I looked around the edge of the doorway

because it might be interpreted to mean that I looked into the next room.
It is certainly true that "around" is frequently used as a synonym of "near," but if you want to avoid ambiguity, it is a usage that I recommend avoiding.
The rules about the usage of prepositions are few, riddled with exceptions, and largely arbitrary. My suggestion is to see how they are used by good writers and learn by example.

A: I wouldn't use either.  Instead I would just say

I looked at the edges of the screen, and they look fine.

This suggests a detailed examination of that part of the screen.
Nevertheless, both "along" and "around" the edges are fine, but imply different actions.  "Along" suggests you followed the line of the edge with your eyes around the entire perimeter of the screen.  A similar example:

He walked along the edge of the park.

which suggests he followed the perimeter more or less exactly, without going too deeply into the park itself.
"Around" suggests you glanced at the edges in a more random pattern, without focusing too much on detail.  Example:

The mechanic looked around the inside of the car's engine compartment, but didn't see anything that looked too damaged.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the occurrence of a word in a string, and print it along with the next 4 characters C# I have a problem with this string = " Leeds United 1  Chelsea 0, Arsenal 1  Leeds United 1, Leeds United 3  Fulham 1, Liverpool 2  Leeds United 1, Swansea 2  Leeds United 4"
I want to be able to take each occurrence of the words "Leeds United" plus the score next to it and just print those scores out. I've tried using substrings, but Im unsure how to code it to make it go 4-5 places along as well

A: Question is not quite clear, but if you need to extract scores after Leeds United text - this can be easily done with regular expressions:
string source = "Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";

var matches = Regex.Matches(source, @"Leeds United \d+");
foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[0].Value);
}

Or, if you need score numbers only:
var matches = Regex.Matches(source, @"Leeds United (\d+)");
foreach(Match match in matches)
{
   Console.WriteLine(match.Groups[1].Value);
}

A: You could use a LINQ query with some String.Splits:
var leedsScores = str.Split(',')
    .Select(s => s.Split(new[] { "  " }, StringSplitOptions.RemoveEmptyEntries))
    .Where(arr => arr.Length >= 2)
    .Where(arr => arr.Any(team => team.Contains("Leeds United")))
    .Select(arr => arr.First(team => team.Contains("Leeds United")).Split(' ').Last());

foreach (string leedsScore in leedsScores)
    Console.WriteLine(leedsScore);

prints out:
1
1
3
1
4

A: Your question is unclear (provide the desired result); do you mean something like that (Linq):
String source = "Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";

String result = String.Join(Environment.NewLine, source
  .Split(',')
  .Where(line => line.Contains("Leeds United"))
  .Select(line => line.Trim()));

the result is
  Leeds United 1 Chelsea 0
  Arsenal 1 Leeds United 1
  Leeds United 3 Fulham 1
  Liverpool 2 Leeds United 1
  Swansea 2 Leeds United 4

A: Try this:
        var totalResults = new List<string>();
        var s = " Leeds United 1 Chelsea 0, Arsenal 1 Leeds United 1, Leeds United 3 Fulham 1, Liverpool 2 Leeds United 1, Swansea 2 Leeds United 4";
        var sarr = s.Split(',');
        foreach (var i in sarr)
        {
            var substring = i.Substring(i.IndexOf("Leeds United"),14);
            totalResults.Add(substring);
        }

It will not work for games having higher scores than 9, but with Leeds United, I doubt there is any danger :P (Edited to inlcude "Leeds United")


text:
Q: How to increase PHPStorm clipboard history size? By default Ctrl+Shift+V brings up a window with 5 last items copied, is there a way to increase that number?

A: Settings (Preferences on Mac) | Editor | Maximum number of contents to keep in clipboard.

A: At the time of 2021 y.
You should increase it from Registry.

*

*Press Shift + Shift

*Input clipboard.history.max.items

*Increase Value column

Registry view pic


text:
Q: Translation of a mathematical statement formulated in words to one formulated in predicate logic I want to express the fact that for all $x \in A$ that have the property that for all $y\in x$ $T(x,y)$ is true and there exists an $u \in B$ such that $P(y,u)$ is true AND for all $v\in C$, $Q(y,v)$ and $R(x,v)$ are also true, then $S(x)$ is true.
(Note that this statement is just a toy statement I have invented, because I was not sure I understood this transformation well, so I wanted to make it difficult, keeping with the idea, that if I got this difficult one right, that I probably understood how to do the transformations)
Formulated in a formal language of predicate logic, would this be
$$ \forall x ( x\in A \land \ \ \forall y (y\in x \rightarrow \ ( T(x,y) \land \ldots  $$
$$ \ldots \land ( \exists u ( u \in
B \land P(y,u) \land \forall v ( v\in C \rightarrow ( Q(y,v) \land R(x,v)))))))\rightarrow S(x) ) $$
(hope I didn't forget any paranthesis...)
?
Is there also a way to move the quantifiers "$\forall$" at the front, so that that string starts with $\forall x \forall y \ldots$ ?

A: As André said, you can move all of the quantifiers to the front; the result is an expression in what is called prenex normal form, and the conversion can be done quite mechanically. A formula can have more than one prenex normal form, but they will of course all be logically equivalent.
Edit: As Carl reminded me, logically equivalent prenex forms can (contrary to what I originally wrote) begin with different quantifiers: $\forall x \exists y(\phi(x) \land \psi(y))$ and $\exists y \forall x (\phi(x) \land \psi(y))$ are both prenex forms of $\forall x \phi(x) \land \exists x \psi(x)$. However, the order of the quantifiers can also matter: $\forall x \exists y \phi(x,y)$ and $\exists y \forall x \phi(y,x)$ are not logically equivalent. And it is certainly not possible in general to bring all of the universal quantifiers to the front.


text:
Q: Ubuntu 16.04 Error when restarting apache2 I tried restarting apache2 and I got this error:
root@vps50217:~# service apache2 restart
Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.
root@vps50217:~# systemctl
  UNIT                                    LOAD   ACTIVE     SUB       DESCRIPTION
  dev-simfs.device                        loaded activating tentative dev-simfs.device
  sys-devices-virtual-net-venet0.device   loaded active     plugged   /sys/devices/virtual/net/venet0
  sys-subsystem-net-devices-venet0.device loaded active     plugged   /sys/subsystem/net/devices/venet0
  -.mount                                 loaded active     mounted   /
  run-shm.mount                           loaded active     mounted   /run/shm
  systemd-ask-password-console.path       loaded active     waiting   Dispatch Password Requests to Console Directory Watch
  systemd-ask-password-wall.path          loaded active     waiting   Forward Password Requests to Wall Directory Watch
  init.scope                              loaded active     running   System and Service Manager
● apache2.service                         loaded failed     failed    LSB: Apache2 web server
  console-getty.service                   loaded active     running   Console Getty
  cron.service                            loaded active     running   Regular background program processing daemon
  dbus.service                            loaded active     running   D-Bus System Message Bus
  getty@tty2.service                      loaded active     running   Getty on tty2
  ifup@venet0.service                     loaded active     exited    ifup for venet0
  modules_dep.service                     loaded active     exited    LSB: modules.dep creation.
  mysql.service                           loaded active     running   MySQL Community Server
  networking.service                      loaded active     exited    Raise network interfaces
  php7.0-fpm.service                      loaded active     running   The PHP 7.0 FastCGI Process Manager
  postfix.service                         loaded active     running   LSB: Postfix Mail Transport Agent
  quota.service                           loaded active     exited    Initial Check File System Quotas
  rc-local.service                        loaded active     exited    /etc/rc.local Compatibility
  rpcbind.service                         loaded active     running   RPC bind portmap service
  rsyslog.service                         loaded active     running   System Logging Service
  saslauthd.service                       loaded active     running   LSB: saslauthd startup script
  ssh.service                             loaded active     running   OpenBSD Secure Shell server
  systemd-hwdb-update.service             loaded active     exited    Rebuild Hardware Database
  systemd-journal-flush.service           loaded active     exited    Flush Journal to Persistent Storage
  systemd-journald.service                loaded active     running   Journal Service
  systemd-random-seed.service             loaded active     exited    Load/Save Random Seed
  systemd-remount-fs.service              loaded active     exited    Remount Root and Kernel File Systems
● systemd-sysctl.service                  loaded failed     failed    Apply Kernel Variables
  systemd-tmpfiles-setup.service          loaded active     exited    Create Volatile Files and Directories
  systemd-udev-trigger.service            loaded active     exited    udev Coldplug all Devices
  systemd-udevd.service                   loaded active     running   udev Kernel Device Manager
  systemd-update-utmp.service             loaded active     exited    Update UTMP about System Boot/Shutdown
  systemd-user-sessions.service           loaded active     exited    Permit User Sessions
  xinetd.service                          loaded active     running   LSB: Starts or stops the xinetd daemon.
  -.slice                                 loaded active     active    Root Slice
  system-getty.slice                      loaded active     active    system-getty.slice
  system.slice                            loaded active     active    System Slice
  dbus.socket                             loaded active     running   D-Bus System Message Bus Socket
root@vps50217:~# systemctl status apache2
  Jun 28 15:05:14 vps50217 apache2[18059]:  *
  Jun 28 15:05:14 vps50217 apache2[18059]:  * The apache2 configtest failed.
  Jun 28 15:05:14 vps50217 apache2[18059]: Output of config test was:
  Jun 28 15:05:14 vps50217 apache2[18059]: apache2: Syntax error on line 7 of /etc/apache2/apache2.conf: Could not open configuration file /etc/phpmyadmin/apache.conf: No
  Jun 28 15:05:14 vps50217 apache2[18059]: Action 'configtest' failed.
  Jun 28 15:05:14 vps50217 apache2[18059]: The Apache error log may have more information.
  Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Control process exited, code=exited status=1
  Jun 28 15:05:14 vps50217 systemd[1]: Failed to start LSB: Apache2 web server.
  Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Unit entered failed state.
  Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Failed with result 'exit-code'.

Output of systemctl status apache2:
Jun 28 15:05:14 vps50217 apache2[18059]:  *
Jun 28 15:05:14 vps50217 apache2[18059]:  * The apache2 configtest failed.
Jun 28 15:05:14 vps50217 apache2[18059]: Output of config test was:
Jun 28 15:05:14 vps50217 apache2[18059]: apache2: Syntax error on line 7 of /etc/apache2/apache2.conf: Could not open configuration file /etc/phpmyadmin/apache.conf: No
Jun 28 15:05:14 vps50217 apache2[18059]: Action 'configtest' failed.
Jun 28 15:05:14 vps50217 apache2[18059]: The Apache error log may have more information.
Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Control process exited, code=exited status=1
Jun 28 15:05:14 vps50217 systemd[1]: Failed to start LSB: Apache2 web server.
Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Unit entered failed state.
Jun 28 15:05:14 vps50217 systemd[1]: apache2.service: Failed with result 'exit-code'.

A: The error message indicates that the file /etc/phpmyadmin/apache.conf is missing. This file is provided by the phpmyadmin package. It can be installed with:
sudo apt install phpmyadmin


text:
Q: How to edit a wordpress plugin without break its update process I would like to add some additional features/functionality with already available WordPress plugin.
Is it possible to carry over my customization while updating the plugin?

A: Probably not.
The recommended way to get your enhancements into the plugin is: Send your fixes to the developer and ask her to merge them into the original. If your changes are rather personal customizations, this won't happen.
If the plugin is written in a strict OOP style you can create a second plugin which extends just the classes from the original as you need it (sort of a child plugin). Unfortunately most plugin developers don't see this need and don't write their code accordingly. Be aware of the load order problem.
We could help better if you would describe which plugin you want to extend and what exactly you want to change.

A: Unfortunately it totally depends on the plugin (or more accurately, on the plugin author!) If the author was thinking pro-actively and created the plugin in such a way to make it extensible, then yes, you can create your OWN plugin that adds to the functionality in the existing plugin.
Do make note of what Toscho pointed out - that your plugin order matters (the link again is here).
Hooks
The most common way to make a plugin extensible is to add hooks (action and filter hooks) that you can then leverage with your own plugin. If you have a good code editor (right now I'm rocking out on NetBeans) you should do a search through the plugin source files for: do_action and apply_filters. If the plugin author has provided those hooks, this is a very convenient and easy way for you to over-ride defaults, or inject your own code.
Pluggable Functions
If the plugin author is savvy, but is using the global namespace for the plugin functions, he/she may have wrapped the plugin's functions within if ( function_exists() ) conditional statements. For this to work to your advantage, you have to make sure your plugin loads first (which may be a challenge). All you have to do is declare your function by the exact same name within the exact same namespace and then your function will replace the one used by the plugin.
Extension
If the plugin author is a good OOP coder, he/she may write the plugin code in a granular enough way that is open for extension (since, as the GOF would say, it is definitely closed for modification). Look for lots of granularity in the plugin class - that is to say methods that perform small, highly specific tasks - that can be overridden in your own class that extends the plugin's class. Of course, as Toscho mentions, the class needs to be architected in such a way that it can be overridden, and that its default implementation doesn't invoke itself completely.
Fork or Patch
If the plugin author is using gitHub, or has opened the source in some other way, you can either submit a patch to the author with your proposed modifications (your best bet is to modify the plugin to make it MORE flexible or powerful without removing or changing existing features or functionality), or you can just download the source, modify the plugin header to the extent that it will no longer be updated when the original author pushes an update out, and preferably submit your updated version to the author, or as its own entity directly to WordPress. Be aware that if you do submit the plugin to WP you will need to have a site for it and should be prepared to support it if others download it.

A: I know it's a very old question but I think I found the solution...
I've a plugin in which one of my client's developers have modified it to the limit of directories & sub directories, when updated the files get deleted and the plugin crashes. In order to make the original plugin independent of any core updates, I've moved the modified files and folders to a separate plugin in a directory named as extension.
Using the code found at https://gist.github.com/wpsmith/af206df2cf6a38e4e2f0
I added the class defined by Tarvis Smith in WPS_Extend_Plugin.php and included it in my plugin. Using the WPS_Extend_Plugin class I've pointed the extended files/folders directory to the target folder extension. There's no failure yet, but I not sure that is this the right way to extend a plugin or not!
// Require WPS_Extend_Plugin class
require_once( 'classes/WPS_Extend_Plugin.php' );

// Extend Sitepress Multilingual CMS
new WPS_Extend_Plugin( 'sitepress-multilingual-cms/sitepress.php', __FILE__, '3.9.0', 'CHERRY' );
// Extend AddThis
new WPS_Extend_Plugin( 'extension', __DIR__, '0.1', 'CHERRY' );

A: I understand this question is really old but I felt this might help someone.
If you feel the changes would help the community, please submit them to the developer. However, if the changes are unique to your installation, you can continue reading the following.
I had this issue about carrying over changes to updated version of a theme.
We did a recursive diff from old_version to modified_old_version and then applied the patch it created on the new version of the theme using the patch tool.
The patch tools create files with changes that could not be applied automatically. We had a few of those, and were easily able to identify and manually make those changes.
While making changes you have to make sure you don't change spacing for the entire file using editor features like auto-indent, etc. That is, make changes only where necessary. That would only make the process of carrying over the changes more time consuming later.


text:
Q: How could I get predictions for my PyTorch Image Classifier? I have implemented this code for My Keras model that worked accurately but now I wanna implement this for my PyTorch Model, but I am unable to configure it for making predictions, Below is my full code, I need help with the classify function:
# importing libraries

import tkinter as tk
from tkinter import *
# import PIL
from tkinter import filedialog

import numpy
from PIL import Image, ImageTk
import torch

# importing model

model=torch.load('corelK_model_0.pt')

classes = {
    0:'africa',
    1: 'beach',
    2: 'tallbuilding',
    3: 'buses',
    4: 'dinosaurs',
    5: 'elephants',
    6: 'Roses',
    7: 'horses',
    8: 'mountains',
    9: 'food'
}

def upload_image():
    file_path = filedialog.askopenfilename()
    uploaded = Image.open(file_path)
    uploaded.thumbnail(((top.winfo_width() / 2.25, (top.winfo_height() / 2.25))))
    im = ImageTk.PhotoImage(uploaded)
    sign_image.configure(image=im)
    sign_image.image = im
    label.configure(text=' ')
    show_classify_button(file_path)

def show_classify_button(file_path):
    classify_btn = Button(top, text="Classify Image", command=lambda: classify(file_path), padx=10, pady=5)
    classify_btn.configure(background="#364156", foreground="white", font=('arial', 10, 'bold'))
    classify_btn.place(relx=0.79, rely=0.46)

def classify(file_path):
    image = Image.open(file_path)
    image = image.resize((32, 32))
    image = numpy.expand_dims(image, axis=0)
    image = numpy.array(image)
    pred = model.predict_classes([image])[0]
    sign = classes[pred]

    print(sign)
    label.configure(foreground='#011638', text=sign)

# initialize GUI
top = tk.Tk()  # calling the constructor or creating the object of tk class
top.geometry('800x600')  # set height and width
top.title("Image Classification CIFAR10")
top.configure(background="#CDCDCD")

# set Heading

heading = Label(top, text="Image Classifier", pady=20, font=('arial', 20, 'bold'))
heading.configure(background="#CDCDCD", foreground='#364156')
heading.pack()

upload = Button(top, text="Upload an image", command=upload_image, padx=10, pady=5)
heading.configure(background="#364156", foreground='white', font=('arial', 10, 'bold'))
upload.pack(side=BOTTOM, pady=50)

# upload image
sign_image = Label(top)
sign_image.pack(side=BOTTOM, expand=True)

# predicted class

label = Label(top, background="#CDCDCD", font=('arial', 15, 'bold'))
label.pack(side=BOTTOM, expand=True)

top.mainloop()

The model I have used is VGG16 after transfer learning, I have saved it using the torch.save .

A: Can you try the following?

*

*After loading the model, set it to evaluation mode using this statement:

model=torch.load('corelK_model_0.pt')
model.eval()

*You're not applying the same image transformations (on the test image) that were used while model training. Your classify function should look like this:

def classify(file_path):
    image = Image.open(file_path)
    image = image.resize((32, 32))
    image = numpy.expand_dims(image, axis=0)
    image = numpy.array(image)

    # Start of transformations
    # .......................
    # End of transformations

    pred = model.predict_classes([image])[0]
    sign = classes[pred]

    print(sign)
    label.configure(foreground='#011638', text=sign)


text:
Q: Warning: session_start(): Setting option 'auto_start' failed Me aparece el siguiente error en la línea 10: Warning: session_start(): Setting option 'auto_start' failed
session_start([
    'use_only_cookies' => 1,
    'auto_start' => 1,
    'read_and_close' => true
]);

Que corresponde al 'auto_start' => 1, revise la documentación de PHP y esta bien escrita la directiva.
http://php.net/manual/es/session.configuration.php
Estoy utilizando PHP 7.0.10.

A: Fijate que en la tabla Opciones de configuración de sesión
Tienes lo siguiente:
Nombre               | Por defecto    | Cambiable
--------------------------------------------------------
session.auto_start   | "0"            |  PHP_INI_PERDIR

Si revisas el valor Cambiable (PHP_INI_PERDIR), veras que no se puede modificar en tiempo de ejecución:
Modo            | Significado
----------------------------------
PHP_INI_USER    | La entrada se puede establecer en scripts de usuario (como con ini_set()) o en el registro de Windows. Desde PHP 5.3, la entrada puede ser establecida en .user.ini
PHP_INI_PERDIR  | La entrada se puede establecer en php.ini, .htaccess, httpd.conf o .user.ini (desde PHP 5.3)
PHP_INI_SYSTEM  | La entrada se puede establecer en php.ini o en httpd.conf
PHP_INI_ALL     | La entrada se puede establecer en cualquier lugar

Por lo que esa directiva en concreto solo se puede modificar en php.ini, .htaccess, httpd.conf o .user.ini.
Igualmente no tendría ningun sentido hacer lo que pretendes, pues no tentendria sentido (en tiempo de ejecución) decirle a PHP que autoinicie sesión a la vez que inicias sesión.

A: Hola para habilitar el auto_start si estas usando xampp ve al panel en configuracion y abre el php.ini, luego busca auto_start y en el parametro 0 cambialo a 1 con eso quedara activo si luego vas a subir la aplicacion a un servidor debes estar seguro q podras modificarlo directamente en el php.ini para q este habilitado por lo tanto no necesitarias en el session_start de tu arreglo incluirlo xq ya estara activo te quedaria de esta forma, yo lo solucione de esa forma.. =)
session_start([
'use_only_cookies' => 1,
'read_and_close' => true

]);


text:
Q: If scalar and vector both are non zero then resulting vector is again non zero by scalar multiplication It seems easy but I am stuck a bit. Let V be a vector space over field F. Take x be non zero vector and a,b be different scalars then I want to show that ax and bx are different.
My try: let ax=bx . Multiplying both sides by inverse of a(say a'), we will get
              (1)x= x = (a'b)x. Now from here I can take things ahead if I show given any nonzero scalar c and non zero vector x we have cx again non zero vector. It seems obvious but I am just stuck to prove this. Thanks.

A: Let $x\in V$ with $x\ne 0$, and let $a,b\in F$ with $a\ne b$.

Suppose $ax=bx$.
\begin{align*}
\text{Then}\;\;&ax=bx\\[4pt]
\implies\;&ax-bx=0\\[4pt]
\implies\;&(a-b)x=0\\[4pt]
\implies\;&cx=0,\;\text{where}\;c=a-b\\[4pt]
\implies\;&c^{-1}cx=c^{-1}0\qquad\text{[$\,c^{-1}\;$exists since$\;a-b\ne 0\,$]} \\[4pt]
\implies\;&x=0\\[4pt]
\end{align*}
contradiction.

Therefore $ax\ne bx$.

A: There is no reason to involve $bx$ or $c$ in this. Assume $a\cdot x = 0$ (because "scalar multiplication that becomes zero" is the actual thing that this problem is about), and to basically the same argument from there. You get something along the lines of $$0 = a^{-1}\cdot 0 = a^{-1}a\cdot x = 1\cdot x = x$$ which is a contradiction, and you're done.

A: You just have stepped into the correct way. Let me explain further, let $V$ be a vector space over $\Bbb R$ and $x\in V$ be a non-null vector. Let $a,b\in \Bbb R$ be non-zero scalars.
Suppose that $ax=bx\implies x=a^{-1}bx\implies (1-a^{-1}b)x=0\implies 1-a^{-1}b=0\implies a^{-1}b=1$ if not then $(1-a^{-1}b)^{-1}$ exists and so $x=0(null-vector)$ which is not possible so, $a^{-1}b=1\implies a=b$. Hence if $a\ne b$ then $ax\ne bx$ for all non null $x\in V$.


text:
Q: PHP - Globalize namespace contents I can't find information related to it, the thing is that I have a namespace like this:
// foo.php

namespace foo;

function blah()
{

}

And then I include it / use it
require_once 'foo.php';

foo\blah();

Now I want to do the same but without specifying 'foo' all the time (something like using namespace in C++), is that possible?
require_once 'foo.php'

// using namespace foo;

blah(); // ?

Thank's!

A: Are you sure that the required file is in the same folder level with the file calling it? You can make some checks by throwing a simple if statement to verify.
$file_fnc = '/path/to/foo/file';

if(file_exists($file_fnc)) {
    require_once $file_fnc;
} else {
    echo "File not found";
}

This will help you determine if your file is truly existing. If it exists then we continue debugging from there. Test it and reply


text:
Q: How to create startup disk in ubuntu (Bootable Pendrive) I want to create a bootable pen drive of windows in ubuntu , but i don't have internet for downloading the software like usb disk creator. how can i do that ?

A: Sorry man but you can either build your own software or use existing softwares in which case you'll need to download. get winusb it's relatively small and easy to use

A: I think this steps works for you.

*

*Copy the windows image file on to the desktop and Insert a empty/formated USB stick.

*Open the dash and search for Startup Disk Creator.

*Select the Startup Disk Creator to launch the app.

*Click 'Other' to choose the downloaded ISO file.

*Select the file from desktop which you have copied and click 'Open'.

*Select the USB stick in the bottom box and click 'Make Startup Disk'.

*That's it! When the process completes, you'll be ready to install windows.

A: This will help you, Try installing the LTS , 12.04 is the Recent LTS Provided by Ubuntu
http://www.ubuntu.com/download/desktop/install-ubuntu-with-windows


text:
Q: GCTime Stamps Not printed I run the java application with following configuration
-Xmx512M
-Xms32M
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-Xloggc:Desktop/Gen/Gen/gc.log
-XX:+PrintGCTimeStamps
-XX:+PrintGCApplicationConcurrentTime
-XX:+PrintGC

But it is not printing GCTimeStamps in gc.log file..
The gc.log file contents are like below..
Application time: 0.0272860 seconds

2015-01-23T17:18:14.054+0100: 0.731: [GC [PSYoungGen: 94627K->58213K(108928K)] 226219K->217525K(287744K), 0.0607860 secs] [Times: user=0.35 sys=0.12, real=0.06 secs]
2015-01-23T17:18:14.115+0100: 0.792: [Full GC [PSYoungGen: 58213K->38649K(108928K)] [PSOldGen: 159312K->178815K(251904K)] 217525K->217465K(360832K) [PSPermGen: 4237K->4237K(21248K)], 0.1840190 secs] [Times: user=0.18 sys=0.01, real=0.19 secs]

Total time for which application threads were stopped: 0.2449170 seconds

Application time: 0.0107920 seconds

A: From your log
Application time: 0.0272860 seconds

Line above is produced by -XX:+PrintGCApplicationConcurrentTime, no date stamp
2015-01-23T17:18:14.054+0100: 0.731: [GC [PSYoungGen: 94627K->58213K(108928K)] 226219K->217525K(287744K), 0.0607860 secs] [Times: user=0.35 sys=0.12, real=0.06 secs]
2015-01-23T17:18:14.115+0100: 0.792: [Full GC [PSYoungGen: 58213K->38649K(108928K)] [PSOldGen: 159312K->178815K(251904K)] 217525K->217465K(360832K) [PSPermGen: 4237K->4237K(21248K)], 0.1840190 secs] [Times: user=0.18 sys=0.01, real=0.19 secs]

Lines above are produced by -XX:+PrintGCDetails, date stamps are they
Total time for which application threads were stopped: 0.2449170 seconds

Line above is produced by -XX:+PrintGCApplicationStopedTime, no date stamp
Application time: 0.0107920 seconds

Line above is produced by -XX:+PrintGCApplicationConcurrentTime, no date stamp
In summary
-XX:+PrintGCDateStamps works only with output produced by -XX:+PrintGCDetails
Output -XX:+PrintGCApplicationConcurrentTime and -XX:+PrintGCApplicationStoppedTime cannot be prefixed with date stamps unfortunately
You can find more details about GC diagnostic options here.


text:
Q: Network side updates to exchange personal address book I'm using @gautamsi ews-javascript-api to get my personal address book contacts programatically in my React/Redux app.  I can fetch my contacts using FindItems, but when I push a function to the OnChange array for an item, it never gets called when I update that contact from the outlook web interface.
First question, is it even possible to have a function called in my app when a contact is changed from network side?
Second question,
item.OnChange.push(function(data) { console.log(data) } );
Is this how I register a function to be called when item is changed on the network side.
Finally, is there a place I can register a callback to be notified whenever a contact is added or removed to my personal address book on the network side?
Cheers

A: Got a response from the author of this API and thought I'd answer it here for everyone else.
OnChange functions are only called for local changes to objects.  There isn't a way to get notified of network side changes to your objects.


text:
Q: Efficient way to fetch data from database I want to know which query style is better & efficient
I am using jdbc to fetch data from multiple tables(I am having more than 10 tables to fetch data). All data are related with keys
for that I am considering two ways
1) I am using joins to fetch data from database
Query s="select a.*,b.*,c.*......";//fetchin all data using joins in single query

Preparedstatement ps = con.prepareStatement(query);//con is a connection object
ResultSet res = ps.executeQuery();
//fetching data from resultset res
con.close();

2)I am taking data from each individual table
Query s="select from table a";
Preparedstatement ps = con.prepareStatement(s);
ResultSet res = ps.executeQuery();
//fetching data from resultset res
Query s1="select from table b";
Preparedstatement ps1 = con.prepareStatement(s1);
ResultSet res1 = ps1.executeQuery();
//fetching data from resultset res1
.............
//continue for all remaining tables
con.close();

I would like to know if there is any other/better method to it.
EDIT: I am using very large amount of data. What about hibernet other methods

A: The best way in my opinion is to handle all SQL stuff within one statement. As you proposed as version 1). If this is too complex for you in the Java sources, you could use a stored function in the database (I know only the Oracle/MySQL possibilities) and handle more complex statements in there. In Java you call just the stored function/procedure and handle the results in Java. This works fine for me.
The other possibility is to use ORM like Hibernate or whatever. But for small things this would be overkill :)
With 1), propably combined with stored functions but not really necessary, you let the database cache your statement and get the imho best performance. If you load table after table in your approach 2) and have to process the data and store it. That might be not that efficient.

A: Are your data actually linked?  Or are they distinct conceptual data sets, e.g. you're loading Products in query1, and say, Sizes, Colours, Towns int queries 2, 3 and 4?  If the latter, then distinct queries could well be best, avoiding problems arising from aritificial JOIN constructs.
Edit - if tables are indeed related, then JOINing sounds appropriate, provided you use an efficient query. In your SELECT be sure to pull back only fields you need (ignore "extra" ones) to aid performance.


text:
Q: Do Spark Streaming and Spark Structured Streaming use same micro-batch engine? Do Spark Streaming and Spark Structured Streaming use the same micro-batch scheduler engine? Does Spark Structured Streaming have lower latency than Spark Streaming?

A:
Do Spark Streaming and Spark Structured Streaming use same micro-batch scheduler engine

Certainly not. They're different internally, but share the same high-level concepts of a stream and a record.
While in Spark Structured Streaming you can get as close to how it was in Spark Streaming using DataStreamWriter.foreach or DataStreamWriter.foreachBatch methods.
The main difference is how to describe a streaming pipeline. In Spark Structured Streaming you use Spark SQL's Dataset API while Spark Streaming bet on Spark Core's RDD API. Both end up as a RDD-based computation, but Spark SQL uses higher-level abstractions (e.g. Dataset API).
Do they both use a "micro-batch scheduler engine"? Yes, but Spark Structured Streaming is trying to leverage some data sources that can be queried continuously (and no micro-batching).

does Spark Structured Streaming have lower latency than Spark Streaming?

That'd be hard to answer. The creators of Spark Streaming decided to develop Spark Structured Streaming and hope to get better at query performance and expressiveness. Spark Streaming is no longer recommended.

A: Structered Streaming is mostly a higher-level abstraction that allows you to define your streaming logic then it uses Spark SQL engine for execution on the same micro-batch engine.
By default Structured Streaming uses micro-batch engine, however if you are using Spark 2.3+, then you can have the continuous mode where you can get down to 1 millisecond latency


text:
Q: How to Transfer data from JavaScript to Model using AJAX call My implementation
Model
namespace Game.Models
{
    public class Lev_model
    {
        public static string GetJsonFile(string Level)
        {
                string Data;
                string selectedLevel = "One";
                string one = System.Web.HttpContext.Current.Server.MapPath(@"~/Data//lvl-one.json");
                string two = System.Web.HttpContext.Current.Server.MapPath(@"~/Data//lvl-two.json");
                if (selectedLevel == "One")
                {
                    Data = File.ReadAllText(one);
                }
                else if (selectedLevel == "Two")
                {
                    Data = File.ReadAllText(two);
                }
                else
                {
                    Data = "Default";
                }

                return Data;
        }
    }
}

View
//AJAX call to change the selectedLevel to "one" or "two"

 var lvlData = "One"

        $.ajax({
            url: '@Url.Action("GetLevelData", "Home")',
            type: "POST",
        data: {strLvl: lvlData},
        success: function(response) {
            response ? alert("It worked!") : alert("It didn't work.");
        }

Controller
[RequireHttps]
        public ActionResult GetLevelData(string strLvl)
        {
            var data = Lev_model.GetJsonFile(strLvl);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

My question
How can I add a View/ AJAX call to change the value of my model. Notice that I hard code selectedLevel to "One" but I want to make it dynamic which means I can change the value so that it can load only one JSON file.

A:  $.ajax({
        type: "POST",
        url: serviceUrl,
        data: { strLvl: YourData},
        success: function (response) {
             //Do some thing
        },
        error: function () {
             //Error message
        }
    });

A: Try this -
        $.ajax({
            type: "POST",
            url: '/controller/GetLevelData',
            data : JSON.stringify({ 'strLvl': lvlData }),
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
            },
            error: function () {
            }
        });


text:
Q: Prevent a program adding itself to startup programs automatically I find my dropbox auto adds itself to startup programs, even after I unchecked it from the startup prefrences. However, when I manually started dropbox sometime, it automatically added itself to startup. Here is the experiment I did. (Ubuntu 14 LTS)

*

*Uncheck dropbox from startup.

*Exit dropbox

*Manually start dropbox

*Then dropbox is checked in the startup.

How to disable a program (e.g., dropbox) adding itself to startup programs?

A: The startup preferences is stored at ~/.config/autostart/. Take dropbox for example, it auto adds itself to startup by adding/editing the ~/.config/autostart/dropbox.desktop file. So a simple solution change that file and make it root-editable only.

*

*vim ~/.config/autostart/dropbox.desktop. Then change Exec=dropbox start -i to Exec=

*chmod 600 ~/.config/autostart/dropbox.desktop. This makes the file only accessible by its user.

*sudo chown root:root ~/.config/autostart/dropbox.desktop. This changes the user of the file to root.

A: Changing preferences to prevent dropbox changing login items is good.
Yet simpler is changing dropbox preferences and deselecting "Start dropbox on system startup".


text:
Q: Appending Date in SQL Function I am trying to get the correct year based on the current date and append to the fiscal year months date part but I am getting an error that it is not an integer.  Ideas or thoughts?
`ALTER FUNCTION [dbo].[fn_CS_IssuedMODs] (@currentDate DATE)
RETURNS TABLE
AS
RETURN
(SELECT cs.Specialist, CASE WHEN COUNT(mn.mod_number_id) IS NULL
        THEN 0 ELSE COUNT(mn.mod_number_id) END AS IssuedMODS,
        cs.user_certificateSerialNumber
FROM    dbo.tbl_modificationNumbers AS mn RIGHT OUTER JOIN
        dbo.vw_ContractSpecialists AS cs ON mn.mod_specialist_id =     cs.user_certificateSerialNumber
WHERE    (mn.statusID = 10)  AND effective_date between '10/1/'+DATEPART(YEAR,@currentDate)
                            + CASE WHEN DATEPART(MONTH, @CurrentDate) >= 10 THEN -1 ELSE 0 END AND '09/30/'+DATEPART    (YEAR,@currentDate)
GROUP BY cs.Specialist, cs.user_certificateSerialNumber`

A: lets create some variables for testing:
DECLARE @currentDate DATETIME = '4/2/2014'

DECLARE @FiscalYearStart DATETIME
DECLARE @FiscalYearEnd DATETIME

Now we are going to check whether the current date is before or after October 1 and if so, we are going to start the fiscal year using the previous year, otherwise we are in the new fiscal year.
SELECT @FiscalYearStart =
(
    CASE
        WHEN DATEPART(MONTH, @currentDate) < 10 THEN
            DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate) - 1, 0))
        ELSE
            DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate), 0))
    END
),
@FiscalYearEnd =
(
    CASE
        WHEN DATEPART(MONTH, @currentDate) < 10 THEN
            DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate), 0))
        ELSE
            DATEADD(MONTH,9, DATEADD(YEAR, DATEDIFF(YEAR, 0, @currentDate) + 1, 0))
    END
)

SELECT @FiscalYearStart As FiscalYearStart, @FiscalYearEnd As FiscalYearEnd

Output:
FiscalYearStart         FiscalYearEnd
2013-10-01 00:00:00.000 2014-10-01 00:00:00.000

Now you can use effective_date >= @FiscalYearStart AND effective_date < @FiscalYearEnd in your query to pull the correct data for the year.

A: Instead of datepart() use either datename().  Or, do an explicit cast() to a string.
The + operator is overloaded in SQL Server.  When it encounters a number, it is treated as addition -- and you can't add strings.
I can't figure out what your code is supposed to be doing.  There are probably better ways to accomplish what you want.  For starters, you should use ISO standard date formats (YYYYMMDD or YYYY-MM-DD) for constants.

A: Try this:
ALTER FUNCTION [dbo].[fn_CS_IssuedMODs] (@currentDate DATE)
RETURNS TABLE
AS
RETURN
(SELECT cs.Specialist, CASE WHEN COUNT(mn.mod_number_id) IS NULL
    THEN 0 ELSE COUNT(mn.mod_number_id) END AS IssuedMODS,
    cs.user_certificateSerialNumber
FROM    dbo.tbl_modificationNumbers AS mn RIGHT OUTER JOIN
    dbo.vw_ContractSpecialists AS cs ON mn.mod_specialist_id = cs.user_certificateSerialNumber
WHERE    (mn.statusID = 10)  AND effective_date between Cast(DATEPART(YEAR, DateAdd(Year, CASE WHEN DATEPART(MONTH, @CurrentDate) >= 10 THEN -1 ELSE 0 END, @currentDate)) as varchar) + '-10-1'
                        AND Cast(DATEPART(YEAR,@currentDate) as varchar) + '-09-30'
GROUP BY cs.Specialist, cs.user_certificateSerialNumber


text:
Q: Mac OS X, Java 7: createNewFile filename encoding I'm trying to update a application, running mainly on Mac OSX, from Java6 to Java7.
It occurs that files beeing creating with some special characters in the filename e.g. "föhn.txt" are beeing created as "f?hn.txt" with Java7.
If you run this sort example on a Mac
File file = new File("föhn.txt");
file.createNewFile();

*

*with Java6: föhn.txt

*with Java7: f?hn.txt

I know there're simular threads for this topic:

*

*Encoding of file names in Java

*Setting the default Java character encoding?
and I've tryed to set JVM argument: -Dfile.encoding=UTF8 but this has no effect to the filename. Compiler and source are set to utf-8. I've no idea why this is not working with Java7 on OS X.
Update:
I've tried the example within eclipse and Netbeans and the final application is bundled with the jdk (appbundler).
Mac OS X uses a decomposed UTF-8 format:
File.listFiles() mangles unicode names with JDK 6 (Unicode Normalization issues)
And a blog about this topic:
http://shlrm.org/blog/2012/10/04/osx-java-utf-8-oh-my/
This helps reading filenames but I've not found a solution for creating new files with the correct encoded filename.

A: Thanks @Duralumin for the right hint.
From eclipse, netbeans or a bundled app with JRE (appbundle) the java binary of Java7 is used directly. Calling java from the command line will use the binary under /usr/bin which is a file from Apple. For that reason it works from command line.
In eclipse or netbeans you have to set the Environment in the run configurations, just add:
LC_TYPE = "UTF-8"

In the Appbundle I added
setenv("LC_CTYPE","UTF-8",1);

to the native (Objective-C) JavaAppLauncher I'm using.


text:
Q: Angular 2 - error handling Angular 2 -  I have many pages in my application and where in each page I am calling the backend services. Here my query was how to create a common error-popup component where it will take error message and show the popup when ever it required my application. Can you please help to find the solution on this. Thank you.

A: This is how I did it in Angular 5, you can do it similar in Angular2, since it is not that different. I hope this will help you.
In my app.component.html, I added this:

      <button type="button" class="close" (click)="errorMessage=''">
                          ×
                      </button>
       {{ errorMessage}}

      <button type="button" class="close" (click)="busyinfoMessage=''">
                          ×
                      </button>
       {{ busyinfoMessage}}

      <button type="button" class="close" (click)="infoMessage=''">
                          ×
                      </button>
       {{ infoMessage}}

    <button type="button" class="close" (click)="warningMessage=''">
                        ×
                    </button>
     {{ warningMessage}}

in my CSS file I added this:
.messages {
  float: left;
  top: 10px;
  right: 10px;
  width: 100;
  height: 20;
  padding: 6px;
  position: fixed;
  border-radius: 8px;
  z-index: 9999;
}

This css code will place this toast like message in right upper corner of page.
Then I cretated action.service.ts which is used for showing this messages and to toggle my loader-spinner:
import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class ActionService {
    public autoloader = true;
    public _toggleLoader: EventEmitter<any>;
    public _errorMessage: EventEmitter<any>;
    public _busyinfoMessage: EventEmitter<any>;
    public _warningMessage: EventEmitter<any>;
    public _infoMessage: EventEmitter<any>;
    public timeoutInfo: any;
    public timeoutWarning: any;

    constructor() {
        this._toggleLoader = new EventEmitter<any>();
        this._errorMessage = new EventEmitter<any>();
        this._busyinfoMessage = new EventEmitter<any>();
        this._warningMessage = new EventEmitter<any>();
        this._infoMessage = new EventEmitter<any>();
    }

    toggleLoader(toggle: boolean) {
        this._toggleLoader.emit(toggle);
    }

    errorMessage(errorMessage: string) {
        this._errorMessage.emit(errorMessage);
    }

    busyinfoMessage(busyinfoMessage: string) {
        this._busyinfoMessage.emit(busyinfoMessage);
    }

    warningMessage(warningMessage: string, timeout: number) {
        if (timeout === 0) {
            this._warningMessage.emit(warningMessage);
            return;
        }
        this.timeoutWarning = setTimeout(() => {
            this._warningMessage.emit('');
        }, 1000 * timeout);
        this._warningMessage.emit(warningMessage);
    }

    infoMessage(infoMessage: string, timeout: number) {
        if (timeout === 0) {
            this._infoMessage.emit(infoMessage);
            return;
        }
        this.timeoutInfo = setTimeout(() => {
            this._infoMessage.emit('');
        }, 1000 * timeout);
        this._infoMessage.emit(infoMessage);
    }

    stopTimeout(tip: string) {
        if (tip === 'w') {
            clearTimeout(this.timeoutWarning);
        } else {
            clearTimeout(this.timeoutInfo);
        }
    }
    }
}

Im my app.component.ts file I added this lines of code:
import { Component, OnInit, OnDestroy } from '@angular/core';

import { Subject } from 'rxjs/Subject';

import { ActionService } from './action.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  private ngUnsubscribe: Subject<any> = new Subject();
  public loader = false;
  public errorMessage = '';
  public warningMessage = '';
  public busyinfoMessage = '';
  public infoMessage = '';

  constructor(
    private _router: Router,
    private _actionService: ActionService
  ) {
  }

  ngOnInit() {
    this._actionService._toggleLoader
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        setTimeout(() => this.loader = res, 0);
      });

    this._actionService._errorMessage
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.errorMessage = res;
      });

    this._actionService._warningMessage
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.warningMessage = res;
      });

    this._actionService._busyinfoMessage
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.busyinfoMessage = res;
      });

    this._actionService._infoMessage
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.infoMessage = res;
      });

  }

  stopTimeout(tip: string) {
    this._actionService.stopTimeout(tip);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

Since I'm using Angular 5 I created this error interceptor for showing error messages after every call:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { ActionService } from './action.service';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

    constructor(
        private _actionService: ActionService,
        private _router: Router) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request)
            .catch((err: HttpErrorResponse, caught) => {
                if (err.status === 0) {
                    this._actionService.errorMessage('Check you connection to interent!');
                    return Observable.empty<HttpEvent<any>>();
                }
                if (err.status === 500) {
                    this._actionService.errorMessage('Server error : ' + err.error.ExceptionMessage);
                    return Observable.empty<HttpEvent<any>>();
                }
                if (err.status === 401 || err.status === 403) {
                    this._router.navigateByUrl('prijava');
                    return Observable.empty<HttpEvent<any>>();
                }
                this._actionService.errorMessage('Unknown error. Error message: ' + (err.error.ExceptionMessage || err.error.Message));
                return Observable.empty<HttpEvent<any>>();
            })
    }
}

export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true
};

Since you are using Angular 2, my suggestion to you would be to create HTTP.Service and to implemet calls for errors in that service. Something like this:
import { Injectable, ReflectiveInjector } from '@angular/core';
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '@angular/http';
import { LocatorService } from './locator.service';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { ActionService } from './action.service';

import { Url } from './global';

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

@Injectable()
export class HttpService extends Http {
    private currentRequests: number;
    private _router: Router;
    private _actionService: ActionService;

    constructor(backend: XHRBackend, options: RequestOptions, router: Router) {
        let token = localStorage.getItem('token'); // your custom token getter function here
        options.url = Url + (options.url == null ? '' : options.url);
        options.headers.set('Authorization', `Bearer ${token}`);
        super(backend, options);
        this._actionService = LocatorService.injector.get(ActionService);
        this._router = router;
        this.currentRequests = 0;
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        let token = localStorage.getItem('token');
        if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
            if (!options) {
                // let's make option object
                options = { headers: new Headers() };
            }
            options.headers.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
            options.url = Url + url;
        } else {
            // we have to add the token to the url object
            if (!options) {
                // let's make option object
                options = { headers: new Headers() };
            }
            options.headers.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
            url.url = Url + url.url;
        }
        if (this._actionService.autoloader) { this._actionService.toggleLoader(true); }
        return super.request(url, options)
            .catch(
            this.catchError(this)
            )
            .finally(() => {
                setTimeout(() => {
                    if (this._actionService.autoloader) { this._actionService.toggleLoader(false); }
                }, 100);
            }
            );
    }

    private catchError(self: HttpService) {
        // we have to pass HttpService's own instance here as `self`
        return (res: Response) => {
            console.log(res);
            switch (res.status) {
                case 0:
                    this._actionService.errorMessage('Check your internet connection!');
                    return Observable.throw(null);
                case 500:
                    this._actionService.errorMessage('Server error : ' + res.json()['ExceptionMessage']);
                    return Observable.throw(null);
                case 401:
                case 403:
                    this._router.navigateByUrl('prijava');
                    return Observable.throw(null);
                default:
                    this._actionService.errorMessage('Unknown error. Error message: ' + (res.json()['ExceptionMessage'] || res.json()['Message']));
                    return Observable.throw(null);
            }
        };
    }
}

I hope that is all. If you need any clarification please ask. I hope this will help you.

A: For user notification on errors, i use Angular Material. On running an http query. I handle errors from http observables using the error=> arrow function in the Observable result. Forexample this is an auth login query to my restful API.
...
constructor(private _dialogService: TdDialogService,
              private _viewContainerRef: ViewContainerRef,
              private authenticationService: AuthenticationService){}
       login() {
    this.authenticationService.login(this.formLogin.value.email, this.formLogin.value.password)
      .subscribe(
        data => {
          // Handle any 200 result
        },
        error => {
          // Handle any http errors, 401 UnAuthorized or 500 or any other
          this.openAlert('Invalid username or password'); // You can pass in your error message
        });
  }

  openAlert(message: string) {
    this._dialogService.openAlert({
      message,
      disableClose: true,
      viewContainerRef: this._viewContainerRef,
      title: 'Error',
      closeButton: 'Ok'
    });
  }
}

Result


text:
Q: inferred type is not accepted when included A function which compiles and cabal repl even indicates what a specific type  should be (rel) produces an error if the inferred type is included in the code.
coords2faces  :: (MorphsHQ rel, Eq rel, Eq obj,   Ord obj)  => State (Store obj rel)  [(obj, obj)]
coords2faces = do
    f <- rel3 (hqFace :: rel)
    return  f

How to include a type in code in such a case?
The error message is
app/TheMain.hs:107:16: error:
    • Could not deduce (MorphsHQ rel1) arising from a use of 'hqFace'
      from the context: (MorphsHQ rel, Eq rel, Ord obj)
        bound by the type signature for:
                   coords2faces :: forall rel obj.
                                   (MorphsHQ rel, Eq rel, Eq obj, Ord obj) =>
                                   State (Store obj rel) [(obj, obj)]
        at app/TheMain.hs:105:1-98
      Possible fix:
        add (MorphsHQ rel1) to the context of
          an expression type signature:
            forall rel1. rel1
    • In the first argument of 'rel3', namely '(hqFace :: rel)'
      In a stmt of a 'do' block: f <- rel3 (hqFace :: rel)
      In the expression:
        do f <- rel3 (hqFace :: rel)
           return f
    |
107 |     f <- rel3 (hqFace :: rel)

A: This is because the rel in the type declared for coords2faces is not the same as the rel in the type declared for hqFace. To make this more obvious, you can see that the compiler renamed the type variable to rel1 in the error message. By default, type variables in separate signatures are always independent.
In order to make the code compile, you can either remove the type signature for hqFace,
coords2faces :: (MorphsHQ rel, Eq rel, Eq obj, Ord obj) => State (Store obj rel) [(obj, obj)]
coords2faces = do
    f <- rel3 hqFace
    return f

or you can enable the ScopedTypeVariables language extension and declare the rel type variable in a forall to specify the scope.
{-# LANGUAGE ScopedTypeVariables #-}

coords2faces :: forall rel obj. (MorphsHQ rel, Eq rel, Eq obj, Ord obj) => State (Store obj rel) [(obj, obj)]
coords2faces = do
    f <- rel3 (hqFace :: rel)
    return f


text:
Q: Probability of letter transmitting and receiving
One of the sequences of letters $AAAA, BBBB,CCCC$ is transmitted over a communication channel with respective probabilities $p_1,p_,p_3$ where $(p_1 + p_2 + p_3 = 1)$. the probability that each transmitted letter will be correctly understood is $\alpha$ and the probabilities that the letter will be confused with two other letters are $\frac{1}{2} (1 − \alpha)$ and $\frac{1}{2}(1 −\alpha)$. It is assumed that the letters are distorted independently. find the probability that $AAAA$ was transmitted if $ABCA$ was received.

A: I abbreviate $AAAA$, $BBBB$ etc as just $A$ and $B$.
Use Bayes' Theorem.
$$
P(A \mid ABCA) = \frac{P(ABCA\mid A)P(A)}{P(ABCA)}
$$
The demoninator can be expanded as
$$
P(ABCA) = P(ABCA\mid A)P(A) + P(ABCA \mid B)P(B) + P(ABCA \mid C)P(C)
$$


text:
Q: Flask marshmallow remove key from nested dict I have the following schema:
class PublisherSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        fields = ('name',)
        model = Publisher

class JournalSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        fields = ('title', 'publisher')
        model = Journal
        ordered = True

    publisher = ma.Nested(PublisherSchema)

When I dump the JournalSchema I want the result to be:
{
  "title": "hello",
  "publisher: "bye"
}

But right now it dumps as:
{
  "title": "hello",
  "publisher": {
    "name": "bye"
  }
}

How can I nest the publisher value but not display the key?

A: Actually I figured it out. The way to do it is:
class JournalSchema(ma.SQLAlchemyAutoSchema):
    publisher = fields.String(attribute="publisher.name")

    class Meta:
        fields = ('title', 'publisher')
        model = Journal
        ordered = True

This considers that 'publisher' is a relationship of the referenced model.


text:
Q: Increase of ubuntu entries on startup I am new to Ubuntu and have just installed it on my HP envy dv6 laptop, as a dual OS alongside windows 10(I newly installed both OS's). I have 2 problems at the moment:

*

*On startup, the GRUB menu does not show. Instead it will boot into
Windows by default. If I want to launch into Ubuntu, I need to press
ESC key, launch boot options and launch Ubuntu from
there. I have already tried disabling Fast Startup on Windows, and
have re-registered GRUB in my firmware. How do I get the GRUB
menu to show?

*The more pressing issue is that the number of Ubuntu entries that
show on the boot manager keeps increasing with time. As of now I
have roughly 10-15 Ubuntu entries in the boot manager (see in the
picture bellow), and there is no difference in these unwanted Ubuntu
options. How do I fix this issue?

A: I suspect your grub is configured for a "quiet" boot.
You can edit grub at /etc/default.
Run "info -f grub -n 'Simple configuration'" in the terminal to get the manual on what to change and how to get your desired effect.
Don't forget to run "update-grub" after you've saved your changes.


text:
Q: add-apt-repository now broken after python was updated Add-apt-repository no longer works after an update.  I see a python3.8 folder now and I had 3 python modules updated.
I have spent a couple of days so far trying various suggested fixes with symbolic links and reinstalling most of python.  Nothing has worked.  Most of the suggested fixes are from several years ago and not pertinent to the python versions installed now.
The modules that were updated and probably the root cause are:
python3-distutils:amd64 (3.6.8-1~18.04, 3.6.9-1~18.04)
python3-lib2to3:amd64 (3.6.8-1~18.04, 3.6.9-1~18.04)
python3-gdbm:amd64 (3.6.8-1~18.04, 3.6.9-1~18.04)
I had used the add-apt-repository recently, only a couple of weeks ago to add a new repository with no issues.  Never had any issues before either.
I have python2.7, python3, python3.6, python3.7 and now python3.8  None were manually installed.  All came from automatic updates.
python3 -V yields Python 3.6.8
This is the error that I get with the add-apt-repository command:
keith@Serenity:/usr/lib/python3/dist-packages$ sudo add-apt-repository ppa:sicklylife/gnucash
^CTraceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 136, in <module>
    shortcut = shortcut_handler(line)
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 868, in shortcut_handler
    ret = factory(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 398, in shortcut_handler
    return PPAShortcutHandler(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 355, in __init__
    info = get_ppa_info(self.shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 326, in get_ppa_info
    ret = get_ppa_info_from_lp(user, ppa)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 101, in get_ppa_info_from_lp
    return get_info_from_lp(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 95, in get_info_from_lp
    return get_info_from_https(lp_url, True)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 88, in get_info_from_https
    data = _get_https_content_py3(url, accept_json)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 120, in _get_https_content_py3
    lp_page = urllib.request.urlopen(request, cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/usr/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/usr/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/usr/lib/python3.6/urllib/request.py", line 1318, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/usr/lib/python3.6/http/client.py", line 1254, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1300, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1249, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1036, in _send_output
    self.send(msg)
  File "/usr/lib/python3.6/http/client.py", line 974, in send
    self.connect()
  File "/usr/lib/python3.6/http/client.py", line 1407, in connect
    super().connect()
  File "/usr/lib/python3.6/http/client.py", line 946, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
KeyboardInterrupt
keith@Serenity:/usr/lib/python3/dist-packages$


text:
Q: Error while showing map in an Android app of a user location derived from GPS I'm generating Google map by using the code below. What I am doing here is just get the longitude/lat from GPS. The output I get is just black screen with Google written below. The key and manifest(also layout) are correct as I tried the same code by hardcoding lon/lat and it worked. What might be the error?

A: You are using Location location = lm.getLastKnownLocation(strLocationProvider); Try launching an app with location. I had this same issue, you are getting a dead location. If this doesn't work then try logging you results with logcat. Find out if the you are actually getting a location or not.

A: Are you getting an NPE?  You are checking if location is null, but then -- even if it is -- you are using it's methods.


text:
Q: Podcast App Subscription Doesn't Match iTunes Store I have a podcast that shows the latest episodes and updates when I go to the iTunes Store (Desktop and iPhone), however, after I subscribe to the podcast on the Podcast App (iPhone), it shows my old podcast feed that I had before I moved my podcast to another domain.

*

*Yes, I did do a 301 redirect to the new RSS feed

*Yes, I did do a new itunes feed tag

*Yes, this only affects the Podcast app on the iPhone

The Podcast in question is called Super Coach by Coach Micheal Burt.
Any suggestions?
Brandon

A: This ended up being fixed by changing the feed URL inside of the new Podcast Connect dashboard on podcastconnect.apple.com website.

A: You can manually reset the iTunes feed at the site listed above. Here is mine; verify (highlighted) that the 'cast is "active" and click on "refresh feed" also highlighted. It can never hurt to run an RSS feedreader test. w3c provides excellent QA.


text:
Q: Program will not exit a do-while loop I'm trying to make a simple calculator in C++. Here is a portion of the code:
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
    int math;
    int a1;
    int a2 = 0;
    int a3 = 1;
    int answer;
    int amount = 0;
    int achecker = 1;

    cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, "
            "type '3' to multiply, type '4' to divide, and type '5' to exit."
         << endl;
    cin >> math;

    while (math = 1)
    {
        cout << "Input how many numbers you wish to add:" << endl;
        cin >> amount;
        achecker = amount;
        do
        {
            cout << "Input the number you wish to add:" << endl;
            cin >> a1;
            answer = a1 + a2;
            a2 = a1;
            achecker = achecker - achecker + 1;
        } while (achecker < amount);
        cout << answer;
    }

The problem I am encountering is that when the program gets into the do-while loop, it never comes out, it just keeps on asking for the user to input a number. I have gone over this several times and I have no idea what the problem is. Can someone help?

A: You have wrong condition check in the while loop.
match=1 is assignment operation and not equality check, which is what you are trying to do. The assignment will always return 1(true) so you have an infinite loop.
replace match=1 with match==1 for your code to work

A: achecker = achecker - achecker + 1; is always equal to 1. So I think you have an error in that line.

A: First of all , you should be writing while(math==1) sicnce math=1 is an assignment operator not a check operator.
Secondly, instead of while , use if since you want to do the calculation for addition only once , putting it in while loop will make it an infinite loop.
Thirdly , in the do - while loop , the condition should be while(achecker>=0), because your condition will always give a true value.So, actually , there is no need of achecker, simply keep decrementing amount by one for each loop run and keep the condition as while(amount>=0) .
One, more improvement i would like to suggest , though not required -
declare answer as int answer = 0;. For each loop run , accept a new value in a1 and then for adding , write answer=answer+a1. This should serve your purpose.
So, edited code according to me should be -
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
  int math;
  int a1;
  int a3 = 1;
  int answer = 0;
  int amount = 0;
  int achecker = 1;

  cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, type '3' to      multiply, type '4' to divide, and type '5' to exit." << endl;
  cin >> math;

  if(math == 1){
  cout << "Input how many numbers you wish to add:" << endl;
  cin >> amount;
  do{
  cout << "Input the number you wish to add:" << endl;
  cin >> a1;
  answer = answer + a1;
  amount = amount - 1;
  }while(amount>=0);
  cout << answer;
  }


text:
Q: Java won't run my eclipse program after being exported I am trying to use eclipse to write a simple text-based game, but whenever I export it, The executable jar file pulls up an error of "could not find or load main class." I'm a bit of a noob, so if I'm doing something stupid, please don't hesitate to point it out. I've searched for hours trying to figure it out, but haven't come up with anything. Any help would be greatly appreciated.
Here's my code:
package dsadsa;
import java.util.Scanner;
public class UserInput {
public static void main(String args[]) {
      Scanner Jameson = new Scanner(System.in);
  double fans, sans, tans, foans, fians, sians;
  System.out.println("You are walking down a road when a mysterious character exits an alleyway and proceeds to follow you.");
  System.out.println("Do you 0:run or 1:fight ?");
  fans = Jameson.nextDouble();
  if (fans == 0) {
      System.out.println("You break in to a run down the road, but no matter how fast you go, the man seems to keep pace with you.");
      System.out.println("Do you 0:keep running or 1:turn and ask why he is following you ?");
      sans = Jameson.nextDouble();
      if (sans == 0) {
          System.out.println("You continue to try to escape the man, but he is faster then you, he eventually catches up to you and tackles you.");
          System.out.println("Do you 0:Scream for help or 1:Fight back ?");
          tans = Jameson.nextDouble();
          if (tans == 0) {
              System.out.println("You scream for help, but there is nobody near to hear you, the man puts a bag over your head and carries you into the alley he originally came out of.");
              System.out.println("Game Over.");
          } else {
              System.out.println("You make an attempt to throw the man off you, but he is incredibly heavy. He raises a fist and puches you in the head, knocking you out. Game Over.");
          }
      } else {
          System.out.println("You turn and ask the man why he is following you, he does not respond. His hoodie is completely covering his face, so that none of his features are visible.");
          System.out.println("Do you 0:Ask him again or 1:Walk up to him and pull back his hood ?");
          tans = Jameson.nextDouble();
          if (tans == 0) {
              System.out.println("You ask the man again why he was following you, he once again says nothing. Are you deaf? You ask him.");
              System.out.println("The man proceeds to pull a shining blade from within his cloak. You did not expect this. He walks forward to you and promptly slays you.");
              System.out.println("Game Over.");
          } else {
              System.out.println("You walk forward and pull back his hood. You immediately scream in horror, his face is blank except for a slit that must be his mouth.");
              System.out.println("He has no lips and his skin is completely white. You break into a sprint, adrenaline rushing through your body. You make it home, and the creature seems to have stayed behind.");
              System.out.println("Do you 0:lock the doors or 1:grab a weapon ?");
              foans = Jameson.nextDouble();
              if (foans == 0) {
                  System.out.println("You immediately turn and lock the door, terrified by your encounter. You walk upstairs and get into your bed, you lie awake for hours before you finally drift off to sleep.");
                  System.out.println(" You awake well-rested, but you soon realise that you are no longer in your own house, but in a completely different one. You walk around the house and find nothing unusual,");
                  System.out.println(" but as you look out the door, you realise there is nothing there. You have been trapped in a simulation by an alien race. Game Over.");
              } else {
                  System.out.println("You run to your room and grab a shotgun that you keep in a gun locker under your bed. You walk to the window and see the creature slowly approaching your door.");
                  System.out.println("Do you 0:run to lock the door  or 1:shoot the creature from your room ?");
                  fians = Jameson.nextDouble();
                  if (fians == 0) {
                      System.out.println("You run to the door and bolt it shut, trapping the creature outside. After a minute, you hear the door handle shaking.");
                      System.out.println("Do you 0:shoot the creature throught the door or 1:call the police ?");
                      sians = Jameson.nextDouble();
                      if (sians == 0) {
                          System.out.println("You shoot the creature through the door, but this only aggravates it, it bashes through the door and slays you. Game Over.");
                      } else {
                          System.out.println("You call the police, telling them that there is a man outside the door trying to get in, so that they won't think you're insane. The End.");
                          System.out.println(" They come promptly and once they realise that the creature is not really a man, they request permission from the government to shoot, permission is granted, and the creature is killed.");
                          System.out.println(" You have just stopped a large-scale alien invasion on planet earth, of which the creature was leader, the government thanks you and you are awarded $10,000.");
                          System.out.println("Congratulations! You have beaten the game! Thanks for playing!");
                      }
                  } else {
                      System.out.println("You shoot the creature through the window and it collapses onto the porch. Unfortunately, the glass shatters back into your face and you eventually bleed out. Game Over.");
                  }
              }
          }
      }
  } else {
      System.out.println("You turn and punch the man, but he does not seem to be effected by it, he proceeds to fight back, nailing you in the face and knocking you out clean.");
      System.out.println("You awake in a trash bin in the middle of nowhere. Game Over.");
  }
  Jameson.close();}
 }

A: You have coded your text-based game to run in the command line therefore you cannot package it as a jar because default your os will run javaw.exe which won't support the command line it needs to be run from java.exe, if you look in your project>bin there should be a file called UserInput.class you have will have to open cmd to this folder and run java UserInput(without the '.class' extension). If, however, you want to package it for someone a little less technical then your solution will be to make a simple GUI using Swing and a ConsoleWindow which I found here. Once you have made you can use it as follows:
    //This makes our console object which we can get input or write to, the class mentioned in the link must be in the same directory in Eclipse as this one
    try {
        Console console = new Console();
    }catch (IOException e) {}

    //Our input scanner we use console.piOut instead of System.in
    Scanner s = new Scanner(console.piOut);

    String sample = s.nextLine(); //Gets some input

    //Makes a printer where we can write to the console:
    PrintWriter printer = new PrintWriter(console.poOut);

    //Simple HelloWorld same usage as System.out.println() etc
    printer.println("Hello");

    printer.println("You said: " + sample);

A: Your code is fine, might be something silly
On eclipse there is the option to export your project to jar
1. select "Runnable JAR file", then next
On the screen "Runnable JAR File Specification"
1. On launch configuration select UserInput -
2. Select destination file. Eg c:\game.jar
3. Library handling -> package required libraries into generated JAR
4. finish
The you run your code via command line:
java -cp game.jar dsadsa.UserInput


text:
Q: Applying formula based on condition in numpy array I have numpy array:
wk = np.array([1, 0, 3, -4])
how to apply a formula based on certain condition, like how to sum all positive value in wk. I've tried
if wk.all > 0:
    np.sum(wk)

But it threw an error.

A: np.sum(wk[wk > 0])

is what you are looking for. wk > 0 creates a boolean array of the same size as wk that is true everywhere where wk > 0. wk[wk > 0] then evaluates to an array that only contains those elements of wk where the former array is true and finally np.sum sums up those values.

A: for the positive values you can use:
import numpy as np
wk = np.array([1, 0, 3, -4])
sum = wk[wk>0].sum() # returns array of elements which are positive and then adds them

similarly you can put conditions inside wk[condition_here]


text:
Q: How to combine my two const in my handle changer in react & filter my array I'm using React hooks for this and when typing it doesn't get its values what I entered and it gets reset. Below one is my handle changer:
//handle changer for inputs
    const handleChange = (event) => {
        setPerson({ ...person, [event.target.name]: event.target.value });

    // an array of non-empty fields
    const fields = Object.entries(person).filter(person => person);
    const state = Object.fromEntries(fields);
    setPerson(state);
    console.log(state);

}

I would like to know about a method to get filter my empty values in an array and pass my values to array.

A: First of all, React hook's set state is asynchronous.
If you expect the setState method to be called multiple times per render, use this pattern:
setPerson(person => ({ ...person, [event.target.name]: event.target.value }))

Then, this filer: filter(person => person) makes no sense, you should use some attribute such as id to filter by and if you want only one record, use find() instead.
If you want more concrete answer, you should provide the data structure person contains.


text:
Q: How to get systemd "socket" unit to automatically restart? specifically dropbear.socket On my BeagleBone Black Angstrom system, the dropbear.socket UNIT seems to spontaneously die after a while. The effect is that I can not ssh into the machine without restarting the dropbear.socket UNIT.  This fixes the problem in the short term:
systemctl restart dropbear.socket

I tried adding Restart=always to the /lib/systemd/system/dropbear.socket file, but that is not allowed (I get an error in the system log).
[Unit]
Conflicts=dropbear.service

[Socket]
ListenStream=22
Accept=yes
Restart=always

[Install]
WantedBy=sockets.target
Also=dropbearkey.service

What's the correct way of getting dropbear.socket to restart automatically? It would be nice to fix the root cause, but this seems like an easy workaround and will make the system more robust.
Update
Here is the list of failed units (I didn't filter it, in case the music service (which I am not using) is a suspect).

% systemctl list-units --failed --full
UNIT                                                  LOAD   ACTIVE SUB    DESCRIPTION
dropbear@1-192.168.0.43:22-192.168.0.40:55370.service loaded failed failed SSH Per-Connection Server
mpd.service                                           loaded failed failed Music Player Daemon

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

2 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

Also here is /lib/systemd/system/dropbear@.service

[Unit]
Description=SSH Per-Connection Server
Requires=dropbearkey.service
After=syslog.target dropbearkey.service

[Service]
ExecStart=-/usr/sbin/dropbear -i -r /etc/dropbear/dropbear_rsa_host_key -p 22
ExecReload=/bin/kill -HUP $MAINPID
StandardInput=socket
KillMode=process

A: Have you tried setting the OnFailure flag? Example:
[Unit]
Conflicts=dropbear.service
OnFailure=dropbear.socket

[Socket]
ListenStream=22
Accept=yes
Restart=always

[Install]
WantedBy=sockets.target
Also=dropbearkey.service


text:
Q: select Image from gallery and show in an ImageView? i am developing an application which requires the user to select a photo from the gallery and set it as the profile picture. Now the below code is working properly on most of the devices( i have checked on Motorola Moto G, One plus X, MI 4i and some other). whenever i run it on redmi prime it is giving an error stated below:
Stacktrace

Process: com.example.lordvoldemort.imagepicker, PID: 23291
  java.lang.RuntimeException: Failure delivering result
  ResultInfo{who=null, request=1, result=-1, data=Intent {
  dat=file:///storage/emulated/0/DCIM/Camera/IMG_20160807_003845_HDR.jpg
  typ=image/jpeg }} to activity
  {com.example.lordvoldemort.imagepicker/com.example.lordvoldemort.imagepicker.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke interface method
  'boolean android.database.Cursor.moveToFirst()' on a null object
  reference
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3595)
                                                                                at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:3638)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:154)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke interface
  method 'boolean android.database.Cursor.moveToFirst()' on a null
  object reference
                                                                                at
  com.example.lordvoldemort.imagepicker.MainActivity.onActivityResult(MainActivity.java:104)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6241)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3591)
                                                                                at
  android.app.ActivityThread.handleSendResult(ActivityThread.java:3638)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:154)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

the code i am using on ActivityResult-
Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };

                    Cursor cursor = getContentResolver()
                            .query(selectedImage, filePathColumn, null,
                                    null, null);
                    assert cursor != null;
                    cursor.moveToFirst();

                    int columnIndex = cursor
                            .getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();

                    newbitmap = BitmapFactory.decodeFile(filePath);
                    ImageView ivImage = (ImageView)findViewById(R.id.image);
                    ivImage.setImageBitmap(newbitmap);

 public String getPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

the error is -
Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference

A:
Now the below code is working properly on most of the devices

I suspect that it will work reliably on very few devices. It would depend a bit on where the Uri is coming from.

the error is - Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference

That is because MediaStore does not recognize the Uri. Your getPathFromURI() will work for few Uri values on few devices (though, again, it depends a bit on where the Uri is coming from).
A Uri is not a file. There is no requirement for there to be any "real path" for a Uri, any more than there has to be a file on the stackoverflow.com Web server at the path /questions/39355114/select-image-from-gallery-and-show-in-an-imageview (which is the path portion of the URL for this question).


text:
Q: Wrong output using g++ on linux and correct on windows I am learning c++ and decided to write a small program to practice on variable scopes. The problem is that I am getting a different (and wrong in my opinion) output on Linux after compiling and executing, while on windows everything is correct. Here is the code:
/*main.cpp*/
#include <iostream>
using namespace std;

extern int x;
int f();

int main() {
    cout << " x = " << x << endl;
    cout << "1st output of f() " << f() << endl;
    cout << "2nd output of f() " << f() << endl;

    return 0;
}

/*f.cpp*/
#include<iostream>
using namespace std;

int x = 10000;
int f() {
    static int x = ::x;
    {
        static int x = 8;
        cout << x++ << endl;
    }
    cout << x++ << endl; return x;
}

the command I am typing on linux is $g++ main.cpp f.cpp && ./a.out
Desired output (windows output):
x = 10000
8
10000
1st output of f() 10001
9
10001
2nd output of f() 10002

Given (Linux) output:
x = 10000
1st output of f() 8
10000
10001
2nd output of f() 9
10001
10002

As I can tell it seems like the Linux program skips the cout of the int f() function, any ideas why such a thing happens?

A: After help from the comments I understood that the problem had to do with how the code executes in different compilers, I managed to solve the "bug" by explicitly calling the function f(), execute it's commands first, and then getting the return value. I explained it as good as I could so here is the code:
int main() {
    cout << " x = " << x << endl;
    int temp=f();
    cout << "1st output of f() " << temp << endl;
    temp=f();
    cout << "2nd output of f() " << temp << endl;

    return 0;
}