text:
Q: Unfortunately app has stopped in adt emulator I saw similar posts but none could help me out. I am making an android one to one voice chat app. However its getting stopped. I also set all the permissions in the manifest. Here is manifest code.
        <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bridgecall"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

  <uses-feature android:name="android.hardware.wifi" android:required="true" />
  <uses-feature android:name="android.hardware.microphone" android:required="true" />
   <uses-permission android:name="android.permission.USE_SIP" />
  <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.bridgecall.CallActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.bridgecall.sender" >
        </activity>
    </application>

</manifest>

Could i get any help in this matter?
Here is the log cat:
04-05 17:43:52.427: E/dalvikvm(1415): Could not find class 'javax.sound.sampled.AudioFormat', referenced from method com.bridgecall.CallActivity.getAudioFormat
04-05 17:43:52.427: W/dalvikvm(1415): VFY: unable to resolve new-instance 824 (Ljavax/sound/sampled/AudioFormat;) in Lcom/bridgecall/CallActivity;
04-05 17:43:52.427: D/dalvikvm(1415): VFY: replacing opcode 0x22 at 0x0007
04-05 17:43:52.537: I/dalvikvm(1415): Could not find method javax.sound.sampled.AudioSystem.getMixerInfo, referenced from method com.bridgecall.CallActivity.callStart
04-05 17:43:52.537: W/dalvikvm(1415): VFY: unable to resolve static method 5343: Ljavax/sound/sampled/AudioSystem;.getMixerInfo ()[Ljavax/sound/sampled/Mixer$Info;
04-05 17:43:52.537: D/dalvikvm(1415): VFY: replacing opcode 0x71 at 0x0025
04-05 17:43:52.607: D/dalvikvm(1415): DexOpt: unable to opt direct call 0x14dc at 0x09 in Lcom/bridgecall/CallActivity;.getAudioFormat
04-05 17:43:52.717: D/dalvikvm(1415): DexOpt: unable to opt direct call 0x14e0 at 0x35 in Lcom/bridgecall/CallActivity;.callStart
04-05 17:43:52.717: D/dalvikvm(1415): DexOpt: unable to opt direct call 0x14e0 at 0x61 in Lcom/bridgecall/CallActivity;.callStart
04-05 17:43:53.607: W/dalvikvm(1415): VFY: unable to resolve exception class 831 (Ljavax/sound/sampled/LineUnavailableException;)
04-05 17:43:53.607: W/dalvikvm(1415): VFY: unable to find exception handler at addr 0x10
04-05 17:43:53.617: W/dalvikvm(1415): VFY:  rejected Lcom/bridgecall/sender;.<init> ()V
04-05 17:43:53.617: W/dalvikvm(1415): VFY:  rejecting opcode 0x0d at 0x0010
04-05 17:43:53.617: W/dalvikvm(1415): VFY:  rejected Lcom/bridgecall/sender;.<init> ()V
04-05 17:43:53.637: W/dalvikvm(1415): Verifier rejected class Lcom/bridgecall/sender;
04-05 17:43:53.637: W/dalvikvm(1415): Class init failed in newInstance call (Lcom/bridgecall/sender;)
04-05 17:43:53.637: D/AndroidRuntime(1415): Shutting down VM
04-05 17:43:53.637: W/dalvikvm(1415): threadid=1: thread exiting with uncaught exception (group=0xb3a66ba8)
04-05 17:43:53.677: E/AndroidRuntime(1415): FATAL EXCEPTION: main
04-05 17:43:53.677: E/AndroidRuntime(1415): Process: com.bridgecall, PID: 1415
04-05 17:43:53.677: E/AndroidRuntime(1415): java.lang.VerifyError: com/bridgecall/sender
04-05 17:43:53.677: E/AndroidRuntime(1415):     at java.lang.Class.newInstanceImpl(Native Method)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at java.lang.Class.newInstance(Class.java:1208)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.os.Looper.loop(Looper.java:136)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at java.lang.reflect.Method.invokeNative(Native Method)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at java.lang.reflect.Method.invoke(Method.java:515)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-05 17:43:53.677: E/AndroidRuntime(1415):     at dalvik.system.NativeStart.main(Native Method)
04-05 17:43:57.027: I/Process(1415): Sending signal. PID: 1415 SIG: 9

and my CallActivity class
package com.bridgecall;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;

import javax.sound.sampled.TargetDataLine;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;

public class CallActivity extends Activity {
    boolean stopCapture = false;
    ByteArrayOutputStream byteArrayOutputStream;
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    AudioInputStream audioInputStream;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    Socket sock = null;
    SourceDataLine sourceDataLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call);
        Intent intent = new Intent(this, sender.class);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.call, menu);
        return true;
    }

    public void callStart()
     {
        try {
                        int port = 6039;
                        String host= "192.168.1.120";
            sock = new Socket(host, port);

            out = new BufferedOutputStream(sock.getOutputStream());
            in = new BufferedInputStream(sock.getInputStream());

            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();

            audioFormat = getAudioFormat();

            DataLine.Info dataLineInfo = new DataLine.Info(
                    TargetDataLine.class, audioFormat);

            Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

            targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);

            targetDataLine.open(audioFormat);
            targetDataLine.start();

            Thread captureThread = new CaptureThread();
            captureThread.start();

            DataLine.Info dataLineInfo1 = new DataLine.Info(
                    SourceDataLine.class, audioFormat);
            sourceDataLine = (SourceDataLine) AudioSystem
                    .getLine(dataLineInfo1);
            sourceDataLine.open(audioFormat);
            sourceDataLine.start();

        } catch (Exception e) {

        }
    }

    class CaptureThread extends Thread {

        byte tempBuffer[] = new byte[1000];

        public void run() {
            byteArrayOutputStream = new ByteArrayOutputStream();
            stopCapture = false;
            try {
                while (!stopCapture) {

                    int cnt = targetDataLine.read(tempBuffer, 0,
                            tempBuffer.length);

                    out.write(tempBuffer);

                    if (cnt > 0) {

                        byteArrayOutputStream.write(tempBuffer, 0, cnt);

                    }
                }
                byteArrayOutputStream.close();
            } catch (Exception e) {

            }
        }
    }

    private AudioFormat getAudioFormat() {
        float sampleRate = 8000.0F;
        int sampleSizeInBits = 8;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = false;
        return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
                bigEndian);
    }

}

and Sender class:
package com.bridgecall;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;

public class sender {

    ServerSocket MyService;
    Socket clientSocket = null;
    BufferedInputStream input;
    TargetDataLine targetDataLine;

    BufferedOutputStream out;
    ByteArrayOutputStream byteArrayOutputStream;
    AudioFormat audioFormat;

    SourceDataLine sourceDataLine;
    byte tempBuffer[] = new byte[1000];

    public sender() {
        try
        {
            mysender();
        }
        catch(LineUnavailableException e)
        {

        }
    }

    public void mysender() throws LineUnavailableException {

        try {
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo =  new DataLine.Info( SourceDataLine.class,audioFormat);
            sourceDataLine = (SourceDataLine)
                AudioSystem.getLine(dataLineInfo);
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                int port= 6039;

        MyService = new ServerSocket(port);
        clientSocket = MyService.accept();
        captureAudio();
        input = new BufferedInputStream(clientSocket.getInputStream());
        out = new BufferedOutputStream(clientSocket.getOutputStream());

            while(input.read(tempBuffer)!=-1){
                sourceDataLine.write(tempBuffer,0,1000);
            }
        } catch (IOException e) {

        }

    }

     private AudioFormat getAudioFormat(){
            float sampleRate = 8000.0F;
            int sampleSizeInBits = 8;
            int channels = 1;
            boolean signed = true;
            boolean bigEndian = false;
            return new AudioFormat(
                              sampleRate,
                              sampleSizeInBits,
                              channels,
                              signed,
                              bigEndian);
          }

    private void captureAudio() {
        try {

            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();

            audioFormat = getAudioFormat();

            DataLine.Info dataLineInfo = new DataLine.Info(
                    TargetDataLine.class, audioFormat);

            Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

            targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);

            targetDataLine.open(audioFormat);
            targetDataLine.start();

            Thread captureThread = new CaptureThread();
            captureThread.start();
        } catch (Exception e) {

        }
    }

    class CaptureThread extends Thread {

        byte tempBuffer[] = new byte[1000];

        public void run() {
            try {
                while (true) {
                    int cnt = targetDataLine.read(tempBuffer, 0,
                            tempBuffer.length);

                    out.write(tempBuffer);
                }

            } catch (Exception e) {

            }
        }
    }

        public static void main(String args[]) {

        new sender();
           }
}

A: You have not declared your sender Activity in AndroidManifest, which is causing here ActivityNotFoundException.

A: javax.sound.sampled.AudioFormat class not found
Include that class and app will start


text:
Q: Derivation of the Safety Stock Formula on Wikipedia There is a safety stock formula on Wikipedia but I've never found a step by step derivation or even a formal statement of the problem.
$$ SS = z_{\alpha } \sqrt{ E(L) \sigma_{D}^{2} + (E[D])^{2}\sigma_{L}^{2}} $$
https://en.wikipedia.org/wiki/Safety_stock
Below I provide a formal problem statement and show two ways to derive the SS formula. I'd love to get your feedback. Thank you!

Background
First let's talk about the problem we're trying to solve. Imagine you're a Supply Chain Manager of a candy factory in charge of inventory levels for raw materials (ie sugar, honey, etc). Now if you ever run out of a raw material, say sugar, then the plant will shut down and everyone will yell at you.
You may be tempted to maintain extremely high inventory levels so there's never a chance you run out. A billion tons of sugar in the warehouse at all times. Unfortunately this takes up space and ties up money in inventory. Therefore, it is your job to come up with the minimal amount of safety stock needed to maintain a certain service level.
As the Supply Chain Manager you're faced with two uncertainties. First is the amount of material needed in a given time frame. This quantity is uncertain because it is impossible to perfectly forecast things like customer demand. For example, next week do we need three or four tons of sugar to support production for Halloween sales? The second uncertainty is not knowing exactly when new deliveries will arrive. Suppliers are not always on time.
Formalizing the problem
Let $D_1,D_2,...,D_n$ be a sequence of independent and identically distributed random variables. Each $D_i$ represents your demand quantity in one time period. For example, say we choose one time period to be a week. Then $D_1$ and $D_2$ are quantities that represent your total raw material needs in week one and two respectively.
Let $T \in [1,2,...]$ be a random variable that represents the time between deliveries. For example, let's say the supplier delivers every two weeks and is never late. Then $T=2$ always and in this situation $T$ is a constant random variable. In the real world however $T$ can vary depending on how unreliable the supplier is.
Therefore the quantity we are interested in for this paper is:
$$D(T) = \sum_{i=1}^{T} D_i = D_1 + D_2 + ... + D_T$$
As you can see the two unknowns are the demand quantities within each time period (the $D_i$'s) and the amount of time periods until the next delivery. Therefore, $D(T)$ is a random variable that represents your total demand needed between deliveries. Therefore the amount of safety stock we keep is some multiple $C$ of the standard deviation of $D(T)$. That is,
$$Safety \,\, Stock = C \sqrt{\mu_L \sigma_D^2 + \mu_D^2 \sigma_L^2} = C \sqrt{Var(D(T))}$$
For example, let's say that $D(T) \sim Normal(\mu, \sigma^2)$ then by keeping $C=3$ standard deviations on top of the mean you have a $\Phi(3) = 99.8$ percent chance of not running out. Note that $D(T)$ will not always be normally distributed. But by Chebyshev's Theorem, regardless of how $D(T)$ is distributed if you set $C=3$ you have at least an $89$ percent chance of not running out.
Super Fast Derivation
It turns out this already a well known problem, just not necessarily in the context of supply chains or safety stock. Note that $D(T)$ is the sum of a random number of random variables that are independent and identically distributed. Note that $T$ is a non negative integer and for this problem we are assuming that $T$ is independent of the sequence $D_i$. Using the law of total variance
$$Var(X) = E[Var(X|Y)] + Var(E[X|Y])$$
we can condition the sum of the $D_i$'s on $T$ and after using the linearity of expectations and the fact that the variance of a sum of independent RVs is the sum of each variance, get
$$Var\bigg(\sum_{i=1}^{T} D_i \bigg) = E[T] Var(D) + (E[D])^2 Var(T)$$
Therefore one standard deviation of $D(T)$ is
$$\sqrt{Var(D(T))} = \sqrt{\mu_L \sigma_D^2 + \mu_D^2 \sigma_L^2}$$
and the final safety stock formula is a multiple $C$ of one standard deviation of $D(T)$.
Another Derivation
Here's another way of deriving the formula. Again let $T$ be a random variable that gives the duration of time between deliveries.  Let $D(T)$ be a random variable that represents the total demand during an interval of length $T$. In the end what we want to derive is $\sqrt{Var(D(T))}$ which is the standard deviation of $D(T)$.
Let's first condition on the expected value of $D(T)$
$$E[D(T) | T = t] = E[D_1 + D_2 + ... + D_t] = \sum_{i=1}^{t} E[D_i] = tE[D_i] = t\mu_D $$
Remember in the assumptions that each $D_i$ is independent. Similarly,
$$Var(D(T)|T=t) = Var(D_1 + D_2 + ... + D_t) = \sum_{i=1}^t Var(D_i) =  t\sigma_D^2$$
Therefore
$$E[D(T)|T] = T\mu_D$$
and
$$Var(D(T)|T) = T\sigma_D^2$$
Now we use the property
$$Var(X|Y) = E[X^2|Y] - (E[X|Y])^2$$
which can be rearranged into
$$E[X^2|Y] = Var(X|Y) + (E[X|Y])^2$$
For our problem $X$ is $D(T)$ and $Y$ is $T$. Plugging in we get
$$ E[D(T)^2|T]  = Var(D(T)|T) + (E[D(T)|T])^2$$
$$= T\sigma_D^2 + T^2\mu_D^2$$
Now we use the following property to get the unconditional expectations.
$$E[X] = E[E[X|Y]]$$
Therefore,
$$E[D(T)] = E[E[D(T)|T]] = E[T\mu_D] = \mu_D E[T] = \mu_D \mu_L$$
and
$$E[D(T)^2] = E[E[D(T)^2)|T]] = E[T\sigma_D^2 + T^2\mu_D^2] =E[T\sigma_D^2] + E[T^2\mu_D^2] $$
$$= \sigma_D^2 E[T] + \mu_D^2 E[T^2] = \sigma_D^2 \mu_L + \mu_D^2 E[T^2] = \sigma_D^2 \mu_L + \mu_D^2 (\sigma_L^2 + \mu_L^2)$$
And the last equality follows because $Var(T) = E[T^2] - (E[T])^2$ which gives us $E[T^2] = \sigma_L^2 + \mu_L^2$
Finally,
$$Var(D(T)) = E[D(T)^2] - (E[D(T)])^2 = \sigma_D^2 \mu_L + \mu_D^2 (\sigma_L^2 + \mu_L^2) - (\mu_D \mu_L)^2$$
$$ = \mu_L \sigma_D^2 + \mu_D^2 \sigma_L^2$$
And one standard deviation of $D(T)$ is
$$\sigma_{D(T)}=\sqrt{Var(D(T))} = \sqrt{\mu_L \sigma_D^2 + \mu_D^2 \sigma_L^2}$$
So our safety stock should be some multiple of the above based on our risk tolerance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out whether a string include digit(s) How do I find out whether a string has digit(s). For example, "Te6st1" has digits (6 and 1).

A: You can use re.findall:
>>> re.findall(r'\d+', "Te6st1")
['6', '1']

If you want them as integers, you can then call int on the result:
>>> [int(n) for n in re.findall(r'\d+', "Te6st1")]
[6, 1]

A: You can use the isdigit() function with something like this
>>> s = "Te6st1"
>>> results = [(char,char.isdigit()) for char in s]
>>> results
[('T', False), ('e', False), ('5', True), ('s', False), ('t', False), ('1', True)]

You can also use the filter operator to get all the digits
>>> digits = filter(lambda x:x.isdigit(), s)
>>> digits
'51'

Hope it helps


text:
Q: Problem with MULTPLE SETTINGS File. Django/Python I am trying to run a Django project on my windows machine. I am getting nomodulefounderror. The project consists of multiple settings files for prod, Development, and Test.
I am using a virtual environment, Python 2.7 and Django 1.10 versions
I need help to run this project on my local machine.
Python manage.py runserver --settings=settings_dev_sai

It throws me an error. Here is my error log

     python manage.py runserver --settings=bg.settings.settings_dev_sai
Traceback (most recent call last):
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute
    super().execute(*args, **options)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle
    if not settings.DEBUG and not settings.ALLOWED_HOSTS:
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__
    self._setup(name)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "F:\brdge\bridge_sai\bridge\settings.py", line 38, in <module>
    from settings_dev_sai import *
ModuleNotFoundError: No module named 'settings_dev_sai'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv
    connections.close_all()
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 225, in close_all
    for alias in self:
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 219, in __iter__
    return iter(self.databases)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 153, in databases
    self._databases = settings.DATABASES
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__
    self._setup(name)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "F:\brdge\bridge_sai\bridge\settings.py", line 38, in <module>
    from settings_dev_sai import *
ModuleNotFoundError: No module named 'settings_dev_sai'

manage.py File
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bg.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Error log Updated
 Traceback (most recent call last):
      File "manage.py", line 10, in <module>
        execute_from_command_line(sys.argv)
      File "F:\brdge\env1\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
        utility.execute()
      File "F:\brdge\env1\lib\site-packages\django\core\management\__init__.py", line 316, in execute
        settings.INSTALLED_APPS
      File "F:\brdge\env1\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
        self._setup(name)
      File "F:\brdge\env1\lib\site-packages\django\conf\__init__.py", line 41, in _setup
        self._wrapped = Settings(settings_module)
      File "F:\brdge\env1\lib\site-packages\django\conf\__init__.py", line 97, in __init__
        mod = importlib.import_module(self.SETTINGS_MODULE)
      File "C:\Python27\Lib\importlib\__init__.py", line 37, in import_module
        __import__(name)
    ImportError: No module named settings_dev_sai

A: i think that you just need run it
python manage.py runserver --settings=bridge.settings_dev_sai

because bridge.settings is a file not a package

A: It seems your project dir name is 'bg', so I think while importing modules you should do
from bg import settings_dev_sai

or
from bg.settings_dev_sai import *

also make sure settings_dev_sai is in same dir 'bg'

A: I think i need to answer my question, The problem of nomodulefounderror, due to incomplete data in my Postgres database. I had dumped .sql file into the Postgres database which was given by my manager and later configured the settings file according to the database name and run command python manage.py runserver --settings=bg.settings_dev_sai. It worked perfectly.


text:
Q: run Powershell command line in ASP Classic I need to run PowerShell command lines in Classic ASP and return the search result.
I found a code, but it's not working
    <%
Set objShell = server.CreateObject("WScript.Shell")
Set objExec = objShell.Exec("powershell.exe -Command dir")
Set objStdOut = objExec.StdOut

While Not objStdOut.AtEndOfStream
   Response.write objStdOut.ReadLine
Wend

objExec.StdIn.Close()

%>

Does not generate error and page returns blank.
Can someone help me?


text:
Q: Import scipy into pycharm, already changed project interpreter, unused import statement I have imported numpy in properly but can't seem to get scipy working. I am using anaconda as the python interpreter.

A: You may want to be more specific. You can:

*

*Post your code

*Explain what you are trying to do with the code

*Post the error
There are thousands of ways a module can not properly work. Your question is simply impossible to understand.


text:
Q: How to implement a form with nested fields? There are two related models
class Skill(models.Model):
    """Information about an employee's skills."""

    LEVELS = (
        ('basic', 'Basic'),
        ('intermediate', 'Intermediate'),
        ('advanced', 'Advanced'),
        ('expert', 'Expert'),
    )

    employee = models.ForeignKey(
        Employee, on_delete=models.CASCADE, related_name="employee_skills")
    technology = models.ForeignKey(Technology, on_delete=models.CASCADE)
    year = models.CharField('common year using amount ', max_length=4)
    last_year = models.CharField('Last year of technology using ', max_length=4)
    level = models.CharField("experience level", max_length=64, choices=LEVELS)

class Technology(models.Model):
    """Technologies."""

    name = models.CharField('technology name', max_length=32, unique=True)
    group = models.ForeignKey(Techgroup, on_delete=models.CASCADE, related_name="group")

The point is that each technology has its own meaning for the level of ownership, years of experience and when it was last used.
I made a form that allows  to edit one technology at a time.
forms.py
class SkillEditForm(forms.ModelForm):
    YEAR_CHOICES = [(r, r) for r in range(1, 11)]
    LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)]
    year = forms.CharField(
        widget=forms.Select(choices=YEAR_CHOICES),
    )
    last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES))

    class Meta:

        model = Skill
        fields = ['technology', 'level', 'last_year', 'year']

There are dozens of technologies in the database. Now I want to implement the ability to edit all the technologies in one window at once, so that the user does not have to press the button to add technology 10 times.
Smth like:
technology1   level last_year  year
......
......
technology_N   level last_year  year

<button>

And that's where I'm stuck on how to implement it. I would be grateful for the advice.

A: To edit multiple models in a single view, you will have to render and process multiple ModelForms based on those models.
A common solution for create/update operations on multiple model instances is django's formsets.
I would advise you to use inline formsets and inlineformset_factory, as it does make things a lot easier.
Don't forget to include the management form in your templates as that can cause a lot of trouble when processing formsets.
On the front-end side of things something like django-dynamic-formset can do the job, if you don't want to write much JavaScript.


text:
Q: Max # of threads per CPU I'm currently using Visual Studio Test Suite load tester to simulate a load against on of our web apps on a different server. (No, I'm not testing against production). I believe it is creating a thread per simulated user.
While I was doing this, I experienced a blue screen which may have been unrelated.
But that brought up the question.
How many threads can I use before my CPU can't handle GENERATING that many requests?
Specs:
Intel Core 2 Duo CPU T7700 @ 2.40 GHz 2.40 GHz (32 bit)
Is there any other information or context I need to provide?

A: It depends on the version of .NET you're running.  You can 250 worker thread for processor on .NET 3.5.
Check out this MSDN article.

A: You can monitor these performance counters while you're running this test.  It'll give you an idea of what your practical limits are as you increase the concurrency:

*

*System \ "Processor Queue Length".

Processor Queue Length is the number
  of threads in the processor queue.
  Unlike the disk counters, this counter
  counters, this counter shows ready
  threads only, not threads that are
  running.  There is a single queue for
  processor time even on computers with
  multiple processors. Therefore, if a
  computer has multiple processors, you
  need to divide this value by the
  number of processors servicing the
  workload. A sustained processor queue
  of less than 10 threads per processor
  is normally acceptable, dependent of
  the workload.

This is similar to the Unix load average, in that it indicates threads waiting to execute.  This is not the same as CPU utilization %, which only tells you how much time is spent working vs. idling.

*

*System \ "Context Switches/sec".

Context Switches/sec is the combined
  rate at which all processors on the
  computer are switched from one thread
  to another.  Context switches occur
  when a running thread voluntarily
  relinquishes the processor, is
  preempted by a higher priority ready
  thread, or switches between user-mode
  and privileged (kernel) mode to use an
  Executive or subsystem service.  It is
  the sum of Thread\Context
  Switches/sec for all threads running
  on all processors in the computer and
  is measured in numbers of switches.
  There are context switch counters on
  the System and Thread objects. This
  counter displays the difference
  between the values observed in the
  last two samples, divided by the
  duration of the sample interval.

This number is relative to each system.  But, with some benchmarking you can use this counter to correlate to the upper limits of your processing capacity.

A: Some limiting factors to consider:

*

*Time spent context switching between threads can outweigh benefit of having multiple threads. Generally, unless your threads spend a lot of time waiting, the benefit of more threads per core is a degredation, not improvement, in performance - see next point:

*Is there any point in having more than one thread? Unless each thread spends a lot of time waiting for something to happen - if you have one core - then you can only do one thing at once. Throwing more threads at it is not going to help. For 2 cores 2 threads...

*Running out of stack memory is a possibility - as the os can no longer keep track of all your threads.


text:
Q: running individual packages from eclipse (not running on the server) Currently, on the project I'm working on we're running jboss as the server. All code in the repository branch is setup to run on the jboss server. However, my work doesn't require that I run the server yet - it's just a Java class I need to test.
How do I run my code as a java project and not as Jboss?

A: Assuming it has an appropriate main method, in the editor for the class, you can just right-click, select "Run As" then "Java Application" (or use the appropriate shortcut, e.g. Alt-Shift-X J).
Alternatively, go to the "Run" button, click on the drop down arrow and go to "Run Configurations" where you can create a new configuration.


text:
Q: Get Value From Realtime Firebase Inside Child Greeting everyone, im working a project right now and need help for firebase realtime database.

My firebase Project

As you guys can see in the above picture, inside student, I have matric number, and inside matric number have block and department.
I have a barcode scanner which scan the value of department and return to get the matric number. Any solution.
Below code is my progress.
mCodeScanner.setDecodeCallback(new DecodeCallback() {
        @Override
        public void onDecoded(@NonNull final Result result) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    r = result.getText();
                    Query s = ref.equalTo("JTMK", "department");
                    name.setText(r);
        }});}});

A: If you don't know the matric number of the student, indeed a query is required. Assuming that result.getText() returns JTMK, please use the following lines of code:
mCodeScanner.setDecodeCallback(new DecodeCallback() {
    @Override
    public void onDecoded(@NonNull final Result result) {
        String department = result.getText();
        DatabaseReference db = FirebaseDatabase.getInstance().getReference();
        DatabaseReference studentRef = db.child("Student");
        Query queryByDepartment = studentRef.orderByChild("department").equalTo(department).limitToFirst(1);
        queryByDepartment.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (task.isSuccessful()) {
                    for (DataSnapshot ds : task.getResult().getChildren()) {
                        String block = ds.child("block").getValue(String.class);
                        name.setText(block);
                        Log.d("TAG", block);
                    }
                } else {
                    Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
                }
            }
        });
    }
});

Things to notice:

*

*There is no need to use runOnUiThread when reading data from the Realtime Database.

*Firebase API is asynchronous. So I recommend you read the following resource:

*

*How to read data from Firebase Realtime Database using get()?

*When you run the code, you should see in the logcat BESTARI 4, which will also be set to name TextView.


text:
Q: @fortawesome/angular-fontawesome and unicode I am upgrading font-awesome in my angular application earlier we were having hardcoded the URL of font-awesome (from CDN ) in style.scss file, now we got to have an angular package which is as below:
ng add @fortawesome/angular-fontawesome@3.0.0 and also similar SVG icons.
and we have changed the approach from
<i class="fa fa-lock"><i> to <fa-icon icon="faLock"></fa-icon>
Now the challenging stuff here is that in my existing application we have used unicode as below:
ui li:before {
content: '\f138';
font-family: FontAwesome;
}

I have changed the above to below
ui li:before {
    content: '\f01';
    font-family: Font Awesome 5 Free;
    }

but icons are not coming up, do we still need to define the .css file in angular.json to work for Unicode (the path of fort-awesome of node_modules )?
Please note that my version of fortawesomesupportsfont-awesome version 5+`.
ADDED packages
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.0",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",

Angular version :6;

A: Ok, if you inspect your code where you use you new icons, you should see something like that :

That means that you don't have the css way to display FA icons :
.fa, .fas {
    font-family: "Font Awesome 5 Pro";
    font-weight: 900;
}

So you can't use the unicode trick to display an icon anymore.
Unless, on top of the angular svg FA library, you install the "web" way :
https://fontawesome.com/v5/docs/web/setup/get-started. You will then have a regular font-family that you will be able to use.
Tell me if the part about the SVG makes sense to you if I expressed it correctly.
Cheers.


text:
Q: How to get the visual length of a text string in python Similar to this question, I'm not asking how to find the number of characters in a string.  I would like to determine the visual length of a string as rendered or compare it to another string.
For example, both 'iiii' and 'WWWW' have four characters.  However, 'iiii' is shorter visually.  I'm aware that this is determined by font, and I'm not working with monospaced fonts.  So, for the purposes of this problem, I'll be using Arial 10pt.
Are there any built-in modules which will provide the visual dimensions of a string given a font?

A: If you are using Windows, then the following approach could be used.
It uses the current screen as the output context and calculates the dimensions needed to display the given font at the given point size. It returns a tuple holding the text width and text height:
import ctypes

def GetTextDimensions(text, points, font):
    class SIZE(ctypes.Structure):
        _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

    hdc = ctypes.windll.user32.GetDC(0)
    hfont = ctypes.windll.gdi32.CreateFontA(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
    hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
    size = SIZE(0, 0)
    ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))
    ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
    ctypes.windll.gdi32.DeleteObject(hfont)
    return (size.cx, size.cy)

for text, font in [
    ('....', 'Arial'),
    ('WWWW', 'Arial'),
    ('WWWW', 'Arial Narrow'),
    ('....', 'Courier New'),
    ('WWWW', 'Courier New'),
    ("Test", "Unknown font"),
    ('Test', 'Calibri')]:

    print '{:8} {:20} {}'.format(text, font, GetTextDimensions(text, 12, font))

This would display the following output:
....     Arial                (12, 15)
WWWW     Arial                (44, 15)
WWWW     Arial Narrow         (36, 16)
....     Courier New          (28, 15)
WWWW     Courier New          (28, 15)
Test     Unknown font         (24, 15)
Test     Calibri              (23, 14)

Arial being a proportional font shows different dimensions for .... and WWWW but Courier New being fixed width gives the same results. Arial Narrow gives 36 compared to 44 for Arial.
In the case of Unknown font, the Windows font mapper has automatically picked a default font.
Tested on Python 2.x.

Note for Python 3.x
As this is calling GetTextExtentPoint32A() in Windows, this expects ANSI text to be passed to it, as such the call could be changed as follows to fix this:
ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text.encode('cp1252'), len(text), ctypes.byref(size))

Alternatively, switch the code to use the wide versions, replace with these two:
hfont = ctypes.windll.gdi32.CreateFontW(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
ctypes.windll.gdi32.GetTextExtentPoint32W(hdc, text, len(text), ctypes.byref(size))

A: Instead of rendering into an image buffer and counting pixels, you can calculate width directly by using the font metrics. There doesn't seem to be a font API distributed with core python, but there are plenty of third-party ones in various packages. Here's a pretty complete solution for Adobe font metrics, using matplotlib:
>>> from matplotlib import rcParams
>>> import os.path

>>> afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm', 'ptmr8a.afm')
>>>
>>> from matplotlib.afm import AFM
>>> afm = AFM(open(afm_filename, "rb"))
>>> afm.string_width_height('What the heck?')
(6220.0, 694)

The metrics are reported in units of 1/1000 of the scale factor (point size) of the font being used. (Thanks @JacobLee for digging up this information.)
Another possibility is the tkFont module of tkinter.  This page documents the function tkFont.Font.measure("some string"), but it seems you need a Tk window before you can use it; so I don't know how practical it is:
# Python 3 names -- see Note below
import tkinter
from tkinter import font as tkFont

tkinter.Frame().destroy()  # Enough to initialize resources
arial36b = tkFont.Font(family='Arial', size=36, weight='bold')
width = arial36b.measure("How wide is this?")
print(width)  # Prints: 404

Note: In python 2 (and in the page I mentioned above), tkinter is known as Tkinter, and tkinter.font is a top-level module, tkFont:
import Tkinter
import tkFont

A: Use a graphic / font library like ImageFont.  Draw the string and then use the getsize to get the width.
Note that some text like "AWAY" may be narrower than the sum of the individual letters due to kerning.  So it would be difficult to lookup widths of each letter and add them.

A: Just a small improvement of the answer of @alexis with tkinter.
I find that method easy and reliable, except that it opens a tkinter window which you have to close manually.
I modified the code so you don't have the window anymore, and made a function with a few more options.
from tkinter import Tk
from tkinter.font import Font

def get_text_size(text: str, font_family: str = 'Arial', font_size: int = 10, bold: bool = False) -> int:
    """Get the screen width of a text based on Font Type, Font Size and Font Weight

    Args:
        text (str): Text for which to calculate the screen width
        font_family (str, optional): Font family. Defaults to 'Arial'.
        font_size (int, optional): Font size. Defaults to 10.
        bold (bool, optional): If bold or not. Defaults to False.

    Returns:
        int: Screen width of the text
    """
    root = Tk()  # Needed to estimate the width.
    font_weight = 'bold' if bold else 'normal'
    font_var = Font(family=font_family, size=font_size, weight=font_weight)
    width = font_var.measure(text)
    root.destroy()  # Destroy the created window
    return width


text:
Q: Is it possible to Create an Array of type typeof(T).getElementOf(), and initialize it within a generic method of ? I have a generic method, and wish to create an instance of the type T in question after verifying that it is an array:
public static T Ins<T>(string s, int delim) {
    if (typeof(T).IsArray) {

        char d = d_order[delim];
        string[] part = s.Split(d);
        Array temp = Array.CreateInstance(typeof(T).GetElementType(), part.Length);
        T tot = (T)temp; // doesn't work (can't convert from array to T)

        var genMethod = typeof(InputFunctions).GetMethod("Ins").MakeGenericMethod(typeof(T).GetElementType());

        //Calling genMethod on substrings of s to create the elements
    }
    else {
        //defining the function for non array types
    }

InputFunctions is the current class, and d_order is a character array defined elsewhere.
The idea is to perform recursion to initialize this. For example, if T is int[][][], and s is the string parameter,
I want to create an instance of int[s.Split(d).Length][][] and then fill it with this function called on int[][] and so on.
The above didn't work due to a casting error. I have another attempt below:
replace the array declaration with:
object[] temp = new object[part.Length]

and putting the cast to T after filling in the elements with recursion.
The problem with this is that object[] is not convertible to T so even though I know that every element in the array is of the proper type, I can't convert it to T. If there is a way around that, that would also solve my problem.
Thank you for your help.

A: You can cast temp to T like Guru Stron has shown, but that doesn't allow you to use the resulting T like an array. If you want to use it as an array, you should not cast temp to T and keep using temp instead, because temp is of type Array. You can do just about everything you can do on "normal" arrays like int[] or string[] on an Array, except you lose some type safety. But you are using reflection here, so no type safety in the first place.
To set the index i of temp to something, just do:
temp.SetValue(something, i);

You should cast temp to T before returning, of course:
return (T)(object)temp;

Here is an example of how you'd write this method with a constant length:
public static T Ins<T>() {
    const int length = 10;
    if (typeof(T).IsArray) {
        Array temp = Array.CreateInstance(typeof(T).GetElementType(), length);

        var genMethod = typeof(InputFunctions).GetMethod("Ins").MakeGenericMethod(typeof(T).GetElementType());
        for (int i = 0 ; i < length ; i++) {
            temp.SetValue(genMethod.Invoke(null, null), i);
        }
        return (T)(object)temp;
    }
    else {
        return default(T);
    }
}

A: Try casting temp to object first and then to T:
T tot = (T)(object)temp;


text:
Q: Difference between $("#id") and $("[id=]") In my page, due to some reason (which I do not find relevant to the topic hence not explaining) a div gets duplicated and two divs with same id are generated in my html. While writing jquery code to remove all divs except topmost, I found that $("#id") was returning me just 1 element(note: there are two divs with same id now) whereas $("[id=]") was returning me 2. So finally my code worked with $("[id=]") but not with $("#id").
Any reason why? Is it that $("#id") returns only the first element it finds with specified id?
Please note that I have already come across a thread which has a similar question but does not answer my query

A: The thing is $("#id") will always gives you single result like document.getelementById() however when you do $("[id=]") you are finding all elements with a given attibute as id so it returns you multiple elements since it doesn't use the javascript document.getelementById() now.
$("[id=]") is something that you use when you want to select some elements form your document that follow some rules like

Attribute Contains Selector [name*="value"]

Selects elements that have the specified attribute with a value containing a given substring.

Attribute Contains Word Selector [name~="value"]

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

Attribute Ends With Selector [name$="value"]

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
etc.
For more information see https://api.jquery.com/category/selectors/
However in you HTML you should ideally keep the id to be unique. If you want multiple elements to have same id then use class instead.


text:
Q: compare $x^{y^{z}}$ and $y^{x^{z}}$ (help) the problem goes like this :
let $(x,y,z)  \in \mathbb{R^3}_{+}$ and $0<x<y<z$
compare $ x^{y^z}$ ;$x^{z^y}$; $y^{x^z}$ ; $y^{z^x}$ ; $z^{y^x}$ ; $ z^{x^y}$
how can we compare the values ?

A: Without any additional assumptions it is impossible to compare these numbers, since for example $x^{y^z}>x^{z^y}$ for $(x,y,z)=(3,4,5)$ and $x^{y^z}<x^{z^y}$ for $(x,y,z)=(\frac{1}{2},4,5)$.

If $a>b>e$, then $b^a>a^b$, using this fact, you can do some general work for $e<x<y<z$.


text:
Q: I am not getting last location in android I am learning Android Google API. I am creating an app to get the last location through Google Play Services. After trying many tutorials I am getting null in location. I am running application on my mobile which is API 23. I keep location and data setting on in my mobile. Below is my code.
Gradle dependencies:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:7.5.0'
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

MainActivity code
package com.lab.locationawareapp;

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {

    protected static final String TAG = "MainActivity";

    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mGoogleApiClient;

    /**
     * Represents a geographical location.
     */
    protected Location mLastLocation;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLatitudeLabel = getResources().getString(R.string.latitude_label);
        mLongitudeLabel = getResources().getString(R.string.longitude_label);
        mLatitudeText = (TextView) findViewById((R.id.latitude_text));
        mLongitudeText = (TextView) findViewById((R.id.longitude_text));

        buildGoogleApiClient();
    }

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
                    mLastLocation.getLatitude()));
            mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
                    mLastLocation.getLongitude()));
        } else {
            Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }

    @Override
    public void onConnectionSuspended(int cause) {

        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
}

A: With Android Marshmallow, you have to explicitly request permission from the user although you have specified those in Manifest file.
So, you have to request for location permissions this way :
First you create a request code for location
public static final int LOCATION_REQUEST_CODE = 1001; //Any number

And then check if already permission is granted or not, if not then the code will request for permission which will show a native popup asking to deny/allow the location permission
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
        } else {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }

The above code should be written before requesting any location preferably in onCreate() of the activity. Then based on the action taken by the user on the popup , you'll get a callback where you can perform according to your requirement.
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                   mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                }
            }
        }
    }

Also, wherever you are trying to fetch the location, you should check whether the location permission has been granted to your application or not and then fetch the location.
 if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                          mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    }

You can request Manifest.permission.ACCESS_FINE_LOCATION or  Manifest.permission.ACCESS_COARSE_LOCATION or both. It depends upon your requirement.

A: getLastLocation will return null if the system doesn't have a location cached.  Which is anytime that the location wasn't recently requested by another program.  You either need to check it for null, or you need to request locations rather than get the last location (note that requesting location takes time and may never call your callback, if you can't get GPS lock and you want high accuracy).

A: try from this link which i was faced i put there some code also so you can try it
Get Current Location 0 in marshmallow where below 23 API its give exact current Location using fused Location
check your Device in which you tested app it Have updated google Play services ?? if not then update it it should be match with your gradle play service version


text:
Q: Running a javascript function in global scope In order to be GDPR compliant I wrapped all affiliate scripts on our webshop inside functions and add them to a job queue.
After the user accepts our privacy policy I run all queued jobs. I want to run them in global scope so all declared variables are accessible in global scope because some affiliate scripts are depending on global variables (I know that's ugly ;) ).
I know, I could rewrite all the javascript code and declare the varibales in global scope and wrap the rest of the code inside a function.
But then I would need to edit a lot of external modules (we are running a magento webshop and use external modules for including the affiliate scripts)
my current approach:
var jobQueue = [];
var add = function (fn) {
    jobQueue.push(fn);
    console.log("function pushed to queue");
};
var execute = function () {
    while ((curJob = jobQueue.pop()) !== undefined) {
        curJob();
        console.log("executed job");
    }
};

my problem is that some external scripts are depending on the variables declared inside my jobs. Is there any possibility to run the functions like the code was run globally?
I already found something like this but I could not make it work:
Javascript eval on global scope?
(this does not work with functions)
eval.call(window, x, y, z)

A: I found a possible solution but it is ugly:
I save the body of the function (How to get function body text in JavaScript?) to a string and evaluate it in window scope
var execute = function () {
    while ((curJob = jobQueue.pop()) !== undefined) {
        var entire = curJob .toString();
        var body = entire.slice(entire.indexOf("{") + 1, entire.lastIndexOf("}"));
        eval.call(window, body);
        console.log("executed job");
    }
};

A: Variables in Javascript have 'function scope', meaning that if you declare a variable inside a function, it won't be accessible from outside that function.
But when a variable doesn't exist inside a function, Javascript will look for that variable outside that function until it reaches the global object.
So variables declared in the global object are visible everywhere.
You can assign variables to the global scope just by declaring them in the global scope.
var pushing = "function pushed to queue";
var executed = "executed job";
var jobTitle = "... programing ...";

var jobQueue = [];
var add = function (fn) {
    jobQueue.push(fn);
    console.log( pushing );
};
var execute = function () {
    while ((curJob = jobQueue.pop()) !== undefined) {
        curJob();
        console.log( executed );
    }
};

// Lets add a Job
add( function(){ console.log( jobTitle ); } );

execute();

JS Bin
As you can see, the job added has access to the variable jobTitle that is declared in the global scope.
Hope it helps


text:
Q: Pushing a xmm register into the stack without affecting flags Moving a xmm register to the stack can be done by
sub rsp,16
movdqu  xmmword [rsp], xmm0

Problem here is sub add modify rflags.
How can I achieve this without use of expensive pushfq popfq?


text:
Q: Website JPGs appear very pixelated on an iPad Our website appears fine on a Mac. However, on an iPad, the home page slider images appear very very pixelated.
I've had a look at [this article][2] and changed the JPGs to progressive, and cleared the server cache, and the iPad Safari cache, yet the issue remains.
Help appreciated.

A: From this answer, using background-attachment: fixed with background-size: cover causes issues on most mobile browsers. You can try using background-attachment: scroll. This won't give your desired effect, but you'll see the images at least. You could use a media-query or two to limit it to devices that are tablets or phones by using @media screen and (max-device-width: 1024px){}
OR
You can use background-position: scroll and include some javascript that will keep the image at the scrolled position (keeping it at the top of the window): DEMO

A: Maybe try to convert the image to a PNG or SVG and see if this helps. If you have a graphic designer have him do this or use one of the image converters on the web. JPEGs are compressed each time they're saved and this is a lossy compression so the image will artifact giving the pixelated look you're describing. If this solves the problem then you know it was a problem with the image itself. If it still appears pixelated then this may be a problem with the Ipad instead. I would then see if you can get a developer to set up an emulator for a different Ipad device, with Genymotion or with the built in emulator that comes with Android Studio, and visit your site on the emulator and see if the problem still persists. Hopefully this helps!


text:
Q: Display different content based on domain I currently run two domains on the same server.  Both websites use the same files.
Is it possible to utilize javascript or jquery or something else to display certain page content based on which domain the user is accessing from?
For example.  If user arrives from "www.site1.com" can I make the page display a different css template than if they access from "www.site2.com".
I hope this makes sense. Thanks.

A: In PHP: Get current domain
In JavaScript: Get The Current Domain Name With Javascript (Not the path, etc.)
Then you can do some if/else statements in either PHP or JavaScript and display your content accordingly.

A: use $_SERVER['SERVER_NAME']
and you can also check $_SERVER variable
var_dump($_SERVER);
PHP manual:$_SERVER

A: You can check the $_SERVER['HTTP_REFERER'] value to try to learn where from your user has came (it has nothing to do with the domain name of application he has came to). This value might be useful but you shouldn't depend on it, because it can be easily changed (it's one of the headers web browser may set when following a link).


text:
Q: How can I remove an empty space in a footer? In my footer I can't remove the empty space between image and bottom border of footer.
Can anyone help me?
(See snippet for understand the problem)

.news-footer {
  border-style: solid;
  bottom: 0;
  left: 0;
 position: fixed;
  right: 0;

 }

.image-footer {
  height: 100%;
  width: 100%;

}

A: You can use display:block.

Another method like flexbox is not compatible with all browsers.
In IE you need use -ms prefix. Learn more here or here.

.news-footer {
  border-style: solid;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;

 }

.image-footer {
  height: 100%;
  width: 100%;
  display:block;

}

A: Use display: flex; on , like:
footer {
  display: flex;
}

Have a look at the snippet below:

.news-footer {
  display: flex;
  border-style: solid;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;
 }

.image-footer {
  height: 100%;
  width: 100%;
}

Hope this helps!

A: Set your image with display: block.

.news-footer {
  border-style: solid;
  bottom: 0;
  left: 0;
 position: fixed;
  right: 0;

 }

.image-footer {
  height: 100%;
  width: 100%;
  display: block;

}


text:
Q: Why thermal printer is called as 'thermal' I always wonder when I see "thermal printer" written in printer's datasheet. Why its called as 'thermal". What is the difference between Graphic and thermal printer?
Thank you.

A: Thermal printers have tiny heating elements in the print head.  They require a specially-coated paper that will turn black when heated (then fade over time).  I think most thermal printers can print graphics as well as text.  Most printers in cash registers and credit card terminals seem to be thermal.
A graphic printer can print graphics as well as text.  It may use any printing technology - inkjet, laser, thermal, or whatever...

A: Thermal printers use a special paper that is heat sensitive, and the printhead heats up to print onto the paper. That lets you print without a separate ink supply.
"Graphic" generally means that a printer can print both text and graphics.

A: Thermal printers are used to print on Thermal Papers which are usual paper sheet covered with very thin thermosensitive film.
When subjected to heat, the film melts, while coloring matter and reagent that has been in the solid state reacts with the film. In order the paper changed its color, it should be heated up to 150-200 oС.
A graphical image on the paper is printed by means of a number of heating elements that are placed in such a manner that they are perpendicular to the direction of the paper feed.
When feeding the voltage to the thermoelement, the corresponding area of the media gets heated and then consequently changes its color and gets darker.
To heat the paper, it is stretched out along the line of thermoelements. Heating and cooling down of the paper takes place pretty quick hence leaving marks in the necessary places of the tape. The image that will be typed by the printer is made of such marks arranged by lines.


text:
Q: Do I have to clean up an element if I replace it with another in the DOM? What happens to the div in this example? Do I have to delete it or clean it up?
var div = document.getElementById('myDiv');
var span = document.createElement('span');
span.textContent = 'hello world';
div.replaceWith(span);

Or is it garbage collected or something?

A: Assuming you release your reference to it once you're done, it's garbage collected; there's no explicit "delete" or similar in the DOM.
So at the end of your code, if the div variable isn't going out of scope or is being retained by a closure, you'll want to do
div = undefined;

...to make sure you don't retain a reference to the div. But if it's going out of scope and isn't retained by a closure, that's not necessary.

Side note: The DOM's replaceWith is quite new and support for it may be spotty.


text:
Q: kubeadm init fails when it can't find runc I installed containerd and runc to /opt and I believe that's why kubeadm init is failing. Here is an error I see in the kubelet systemd log.
unable to retrieve OCI runtime error (open /run/containerd/io.containerd.runtime.v2.task/k8s.io/c242a3c3dbb9b0d35489ae3f99b1cd79d12a45dcf5d4a39abcd4fd045e61dc3a/log.json: no such file or directory): exec: \"runc\": executable file not found in $PATH: unknown"" pod="kube-system/etcd-cp0" podUID=4b344419cbf991a1f149e60ac0841c36
How do I tell kubeadm where the runc binary is? Do I need to write a kubeadm-config.yaml file or can I generate one somehow?
Thanks in advance.
/opt/cni
/opt/cni/bin
/opt/cni/bin/flannel
/opt/cni/bin/tuning
/opt/cni/bin/bridge
/opt/cni/bin/static
/opt/cni/bin/ipvlan
/opt/cni/bin/bandwidth
/opt/cni/bin/host-local
/opt/cni/bin/loopback
/opt/cni/bin/vlan
/opt/cni/bin/firewall
/opt/cni/bin/ptp
/opt/cni/bin/sbr
/opt/cni/bin/macvlan
/opt/cni/bin/host-device
/opt/cni/bin/portmap
/opt/cni/bin/dhcp
/opt/sbin
/opt/sbin/runc
/opt/containerd
/opt/containerd/lib
/opt/containerd/bin
/opt/bin
/opt/bin/containerd-shim-runc-v1
/opt/bin/containerd-shim
/opt/bin/containerd-shim-runc-v2
/opt/bin/ctr
/opt/bin/containerd-stress
/opt/bin/containerd

A: Oh. I had removed apparmor. Now that I have reinstalled apparmor I can initialize my controlplane node.


text:
Q: Neumorphic / neomorphic design in Flutter I've seen several articles recently about neomorphic design in Flutter. How do I implement that in my own project?

I know it is something about the decoration, but what specifically do I add?
Container(
  width: 100,
  height: 100,
  decoration: BoxDecoration(
    ???
  ),
),

A: You can play around with the actual colors but here is a light and dark example. If you see a different color scheme you like better then just take a screenshot and use Gimp or some other image editing software to get the hex colors from it.
Neumorphic light

*

*Background color: Color(0xFFEFEEEE)

*Light shadow: Colors.white.withOpacity(0.8),

*Dark shadow: Colors.black.withOpacity(0.1)
Code
Container(
  width: 100,
  height: 100,
  decoration: BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.white.withOpacity(0.8),
        offset: Offset(-6.0, -6.0),
        blurRadius: 16.0,
      ),
      BoxShadow(
        color: Colors.black.withOpacity(0.1),
        offset: Offset(6.0, 6.0),
        blurRadius: 16.0,
      ),
    ],
    color: Color(0xFFEFEEEE),
    borderRadius: BorderRadius.circular(12.0),
  ),
),

Neumorphic dark

*

*Background color: Color(0xFF292D32)

*Light shadow: Colors.white.withOpacity(0.1),

*Dark shadow: Colors.black.withOpacity(0.4)
Code
Container(
  width: 100,
  height: 100,
  decoration: BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.white.withOpacity(0.1),
        offset: Offset(-6.0, -6.0),
        blurRadius: 16.0,
      ),
      BoxShadow(
        color: Colors.black.withOpacity(0.4),
        offset: Offset(6.0, 6.0),
        blurRadius: 16.0,
      ),
    ],
    color: Color(0xFF292D32),
    borderRadius: BorderRadius.circular(12.0),
  ),
),

Pub packages

*

*flutter_neumorphic

*clay_containers

*neumorphic

*nm_generators
See also
These articles and code were helpful in researching this.

*

*Neumorphism in user interfaces

*Neumorphism (Soft UI) in User interface design - Tutorial

*Dark Neumorphism UI Trend 2020

*Neumorphic designs with Flutter

*neuomorphic_container Pub package


text:
Q: jQuery trigger click after changing url I have a function that records clicks on a link with a data tag. The code hides a telephone number until the link has been clicked, then it reveals the number. The problem I'm having is I am unable to get that revealed number to fire without user interaction once it has loaded.
I had to prevent the default event for when the button is clicked for the first time as the url does not yet contain the real data and also I don't want the page to jump.
Once clicked the new link's html will change to, example: "☎ 0123456789"
and the href will change to, example: "tel:0123456789"
This data is obtained from JSON sent from AJAX PHP file.
After this I want to programatically click the URL but I can't seem to get it to fire and keep getting a console error message saying "Uncaught TypeError: event is undefined" ~ presumably to do with the event prevent default?
Info: there will be multiple phone numbers loaded via PHP so I need to access each one individually.
HTML for the link;
 ☎ Click to call

JS code (jQuery 3.4.1);
 $(document).on('click','.telephone',function(event) {
     event.preventDefault(); // Prevent page jump
     var num = $(this).data("num");
     $.ajax({
         url: "myserverfile.php",
         method: "POST",
         data: {num: num},
         dataType: "json",
         success: function(a) {
             var b = (a[0]['status']); // True or false
             var c = (a[0]['tel']); // Number or error
             // If result found change URL and click it to call number
             if (b == true) {
                 $('.telephone[data-num="' + num + '"]').html("☎ " + c); // Change link text
                 $('.telephone[data-num="' + num + '"]').attr("href", "tel:" + c); // Change link href
                 $('.telephone[data-num="' + num +'"]').click(); // Update: This causes a loop because it runs the code again. I need to hide the original a tag and create a new one then trigger it.
             }
         }
     });
 });

Any suggestions?

A: Calling the .click() method doesn't create an event. The event is created when the user actually clicks something. If you console.log(event) it'll be undefined when called by .click(), which is where you're getting the error from. To get around that you could
if (event) { event.preventDefault(); }

But then you're going to run into recursion since you're basically
$(document).on('click', '.telephone', function() { $('.telephone').click(); });

To get around that you could add something like a loaded class
$(document).on('click', '.telephone:not(.loaded)', function() {
  $('.telephone[data-num="' + num +'"]')
    .addClass('loaded')
    .attr(...)
    .html(...)
    .click();
});

Also, you'll thank yourself later for using a little more descriptive variable names. And for those unaware, jquery is chainable.

A: Figured it out. I was creating a loop so the click wouldn't work so I hid the first link after the click and loaded a new hidden one. I used a different column value from the table for the data tag on this new link to avoid any possible conflicts.
Apart from the loop issue the major part I was missing was [0] before assigning .click.
Thanks for the suggestions along the way.
Working code below;
 $(document).on('click', '.telephone', function(event) {
     event.preventDefault();
     var num = $(this).data("num");

     $.ajax({
         url: "myserverfile.php",
         method: "POST",
         data: {num: num},
         dataType: "json",

         success: function(a) {
             var b = (a[0]['status']);
             var c = (a[0]['id']);
             var d = (a[0]['tel']);

             if (b == true) {
                 $('.telephone[data-num="' + num + '"]').hide(200);
                 $(document).ready(function() {
                     $(".telephone-reveal");
                     $('.telephone-reveal[data-id="' + c + '"]').show(200);
                     $('.telephone-reveal[data-id="' + c + '"]').html("☎ " + d);
                     $('.telephone-reveal[data-id="' + c + '"]').attr("href", "tel:" + d);
                     $('.telephone-reveal[data-id="' + c + '"]')[0].click();
                 });
             }
         }
     });
 });


text:
Q: Linq select between 2 values for a list of id I have a linq query that works in the singular - here it is:
public static AmountRange GetAmountRange(int term)
{
     return amountTable
        .Where(x => term.IsBetween(x.MinTerm, x.MaxTerm))
        .Select(x => new AmountRange(term, x.MinAmount, x.MaxAmount))
        .First();
}

The IsBetween function is a simple 'int' extension method, which does exactly what it says.
What I would like to do is to make another variant that accepts an array of 'int[]' as the initial param so that I'm not calling the query several times.
If this was an array of single values, I would simply use the .Contains functionality, but it doesn't.
Here's an example that uses .Contains - however, it doesn't allow for a range - only a single value. It needs to be converted so thateach term IsBetween MinAmount and MaxAmount.
public static IEnumerable<AmountRange> SelectAmountRange(int[] terms)
{
    var termList = terms.ToList();

    return amountTable.Where(t => termList.Contains(t.MinAmount))
        .Select(x => new AmountRange(term would go here, x.MinAmount, x.MaxAmount))
        .ToList();
}

So, in a nutshell, I want to achieve the following:

*

*Pass an array of int[] (terms) as the parameters.

*Select all rows where each term value falls between the table values
MinAmount and Max Amount.

A: Given the object:
public class AmountRange
{
    public AmountRange(int term, int minAmount, int maxAmount)
    {
        Term = term;
        MinTerm = minAmount;
        MaxTerm = maxAmount;
    }

    public int Term { get; }
    public int MinTerm { get; }
    public int MaxTerm { get; }
}

I think what you're looking for then is a join on passed terms and the terms in the object and then applying the filter accordingly:
    public static IEnumerable<AmountRange> GetAmountRange(int[] terms)
    {
        return amountTable
            .Join(terms,
                range => range.Term,
                term => term,
                (range, term) => new { range, term })
           .Where(x => x.term.IsBetween(x.range.MinTerm, x.range.MaxTerm))
           .Select(x => new AmountRange(x.term, x.range.MinTerm, x.range.MaxTerm));
    }

A:
What I would like to do is to make another variant that accepts an array of 'int[]' as the initial param so that I'm not calling the query several times.

You can use a dictionary of int to AmountRange. That is, each distinct int is mapped to a single AmountRange.
public static Dictionary<int, AmountRange> GetAmountRanges(int[] terms)
{
     return terms.Distinct().ToDictionary(
                 key => key,
                 term => amountTable
                 .Where(x => term.IsBetween(x.MinTerm, x.MaxTerm))
                 .Select(x => new AmountRange(term, x.MinAmount, x.MaxAmount))
                 .First());
}

in order to access dictionary items.
var ranges = GetAmountRanges(terms);

foreach(var kvp in ranges)
{
    var index = kvp.Key;
    var range = kvp.Value;

    // do stuff
}

If terms can contain duplicates, then you should access items in this way.
var ranges = GetAmountRanges(terms);

foreach(var i in terms)
{
    var kvp = ranges[i];
    var index = kvp.Key;
    var range = kvp.Value;

    // do stuff
}

A: public static AmountRange GetAmountRange(int[] terms)
{
     return amountTable
        .Where(x => terms.All(y => y.IsBetween(x.MinTerm, x.MaxTerm)))
        .Select(x => new AmountRange(terms, x.MinAmount, x.MaxAmount))
        .ToList();
}

Another approach
public static List<AmountRange> GetAmountRange(int[] terms)
{
     return amountTable
        .Select(x => new {Item=x, Terms=terms.Where(z => z.IsBetween(x.MinTerm, x.MaxTerm))})
        .SelectMany(x => x.Terms.Select(term => new AmountRange(term, x.Item.MinAmount, x.Item.MaxAmount)))
        .ToList();
}


text:
Q: $_FILES["file"]["type"] VS pathinfo($file_name, PATHINFO_EXTENSION) how best and what different $_FILES["file"]["type"] VS pathinfo($file_name, PATHINFO_EXTENSION) how best are these two,and what's difference in both ?
I've asked this question because I found $_FILES["file"]["type"] not good with images, and it can't define image type which I take by my D-camera. However the pathinfo($file_name, PATHINFO_EXTENSION) can so easily define any type of file, but I see all developers use $_FILES["file"]["type"].
So please tell me when I should use them and what is good for security purpose.

A: You should never rely on $_FILES["file"]["type"] (because this data is provided with browser and is not checked by php at all).
Choose either file extension or image type got from getimagesize

A: $_FILES['files']['type'] is actually the file type the browser thinks the file is. It can be interesting, but it can also be unreliable.


text:
Q: Converting a list of ints to a byte array I tried to use the List.ConvertAll method and failed. What I am trying to do is convert a List<Int32> to byte[]
I copped out and went this route, but I need to figure out the ConvertAll method...
List<Int32> integers...

internal byte[] GetBytes()
{
    List<byte> bytes = new List<byte>(integers.Count * sizeof(byte));
    foreach (Int32 integer in integers)
        bytes.AddRange(BitConverter.GetBytes(integer));

    return bytes.ToArray();
}

A: How about
var bytes = integers.Select(i => BitConverter.GetBytes(i)).ToArray();

totally untested BTW, but seems reasonable.
This should actually give you an Array of arrays of bytes...which may or may not be what you need.  If you want to collapse it into a single array, you can use SelectMany
var bytes = integers.SelectMany(i => BitConverter.GetBytes(i)).ToArray();

A: The ConvertAll method is flawed because it expects there to be a 1:1 mapping from the source to the destination. This is not true when converting integers to bytes. You are much better off going with a solution such as what @SLaks has suggested with the SelectMany extension method.

A: Since you don't want a byte[][] where each integer maps to an array of four bytes, you cannot call ConvertAll.  (ConvertAll cannot perform a one-to-many conversion)
Instead, you need to call the LINQ SelectMany method to flatten each byte array from GetBytes into a single byte[]:
integers.SelectMany(BitConverter.GetBytes).ToArray()

A: To use the ConvertAll method you can do the following...
Assuming that you have a list of ints that are really byte values and you do not actually want the bytes required to make up an int, i.e. byte[][]:
public static class Utility {

   public static byte IntToByte(int i) {
       if(i < 0)
           return (byte)0;
       else if(i > 255)
           return (byte)255;
       else
           return System.Convert.ToByte(i);
   }
}

... to convert ...
byte[] array = listOfInts.ConvertAll(
                    new Converter<byte, int>(Utility.IntToByte) ).ToArray();

or you could use an anonymous delegate...
byte[] array = listOfInts.ConvertAll( new Converter<byte, int>(
                   delegate(int i) {
                       if(i < 0)
                          return (byte)0;
                       else if(i > 255)
                          return (byte)255;
                       else
                          return System.Convert.ToByte(i);
                   })).ToArray();


text:
Q: CommandLine using ProcessBuilder in Java and pipe between programs I've looking to run the following Unix command from Javas' ProcessBuilder (in Windows).
$ gensky 1 21 11 | genskyvec -m 1 > skyvec_1-21-11_1.skv

So I've written this:
String cmd = String.format("C:\\Radiance4.2\\bin\\gensky 1 21 11 | %s -m 1 > %s\n", "C:\\Radiance4.2\\bin\\genskyvec", "C:\\Radiance4.2\\temp\\output_test.skv");

And this:
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream(true);
Process process = null;
try {
    process = builder.start();
    System.out.println("Started Processing!");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

But continue to get error - that program not found. Any ideas what I'm doing wrong?

A: use directory() to set working directory to C:\\Radiance4.2\\bin\\ and pass List<String>
List cmd = new ArrayList();
cmd.add("genskyvec");
cmd.add("1");
cmd.add("21");
cmd.add("11");
// all parameters
and use redirectOutput() to file you are passing with >


text:
Q: Cloud Firestore emulator not running when testing Cloud Functions locally I've been trying to implement some Cloud Functions that reads data from Cloud Firestore. I want to test these locally, however I cannot get the Cloud Firestore emulator to run. My assumptions are that it's where the problem is, but it might be somewhere else - if that's the case please let me know.
Here is my function:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'

admin.initializeApp()

//Functions to fetch the documents in the user collection and send them to the client.
export const getUserDocs = functions.https.onRequest((request, response) => {
    admin.firestore().doc('/Users/{documentId}').get()
    .then(snapshot => {
        const data = snapshot.data()
        response.send(data)
    })
    .catch(error => {
        response.status(500).send(error)
    })
})

This is the error I get when I run the command firebase serve --only functions :
Carlo@Carlos-Air-2 functions % firebase serve --only functions
⚠  Your requested "node" version "8" doesn't match your global version "13"
✔  functions: functions emulator started at http://localhost:5000
i  functions: Watching "/Users/Carlo/app/functions" for Cloud Functions...
✔  functions[getUserSports]: http function initialized (http://localhost:5000/app/us-central1/getUserSports).
i  functions: Beginning execution of "getUserSports"
⚠  functions: The Cloud Firestore emulator is not running, so calls to Firestore will affect production.
⚠  External network resource requested!
   - URL: "http://179.252.163.233/computeMetadata/v1/instance"
 - Be careful, this may be a production service.
⚠  External network resource requested!
   - URL: "http://metadata.google.internal./computeMetadata/v1/instance"
 - Be careful, this may be a production service.
i  functions: Finished "getUserSports" in ~9s

I've tried starting from scratch again and uninstalling and reinstalling but with no success.
I've also watched the tutorial series on YouTube but for some reason my code doesn't work.
Any help is greatly appreciated.

A: I was getting the following error when trying to run firebase for local testing:
The Cloud Firestore emulator is not running, so calls to Firestore will affect production.
What I did wrong was no select both Firestore and Functions (see image).
then there are a number of commands available to spin up local testing:

*

*firebase serve

*firebase serve --only functions

*firebase emulators:start --only=functions

*firebase emulators:start

The last one (#4) resolved the issue for me.

A: There is no error in your output console.
It's just a warning saying that you are not running Firestore locally, which is totally normal since you run the command with --only functions and thus started only the cloud functions part (without firestore, rules, etc)


text:
Q: Custom spinner style How can I style/customize spinner like shown below using xml?
I can make white background with border, but i can't set icon on the left and arrow on the right.

A: If your problem is with a layout that sets the icon to the left and arrow to the right, the following should work.
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/icon" />

    <ImageView
        android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

</RelativeLayout>

I'm at work, so I can't test this out, but I think it should work.


text:
Q: Maximum number of iterations must be positive ERROR when using Logistic Regression (python)     x_train, x_test, y_train, y_test =
    sklearn.model_selection.train_test_split(X, y, test_size=0.2,
    shuffle=False)
    return(x_train, x_test, y_train, y_test)

    logisticR = LogisticRegression(random_state=0, max_iter = '800',
    solver='saga', multi_class='multinomial')
    logisticR.fit(x_train, encoded_ytrain)

    acc = logisticR.score(x_test, encoded_ytest)
    print(acc)

When run it gives the following Error: ValueError: Maximum number of iteration must be positive; got (max_iter='800')
As max_iter is 100 by default, is there another way to change the size of iteration?

A: Actually the max_iter should be an int, it should not be a str
Can you try the following:
logisticR = LogisticRegression(random_state=0, max_iter=800,
    solver='saga', multi_class='multinomial')

A: Why have you put your max_iter object value inside a ''. You are creating a Str. You need to feed an int. Just put it equal to 800.


text:
Q: C++ OpenMP Fibonacci: 1 thread performs much faster than 4 threads I'm trying to understand why the following runs much faster on 1 thread than on 4 threads on OpenMP. The following code is actually based on a similar question: OpenMP recursive tasks but when trying to implement one of the suggested answers, I don't get the intended speedup, which suggests I've done something wrong (and not sure what it is). Do people get better speed when running the below on 4 threads than on 1 thread? I'm getting a 10 times slowdown when running on 4 cores (I should be getting moderate speedup rather than significant slowdown).
int fib(int n)
  {
    if(n == 0 || n == 1)
        return n;
    if (n < 20) //EDITED CODE TO INCLUDE CUTOFF
        return fib(n-1)+fib(n-2);
    int res, a, b;
    #pragma omp task shared(a)
    a = fib(n-1);
    #pragma omp task shared(b)
    b = fib(n-2);
    #pragma omp taskwait
    res = a+b;
    return res;
  }

int main(){
  omp_set_nested(1);
  omp_set_num_threads(4);
  double start_time = omp_get_wtime();
  #pragma omp parallel
  {
    #pragma omp single
    {
      cout << fib(25) << endl;
    }
  }
  double time = omp_get_wtime() - start_time;
  std::cout << "Time(ms): " << time*1000 << std::endl;
  return 0;
}

A: Have you tried it with a large number?
In multi-threading, it takes some time to initialize work on CPU cores. For smaller jobs, which is done very fast on a single core, threading slows the job down because of this.
Multi-threading shows increase in speed if the job normally takes time longer than second, not milliseconds.
There is also another bottleneck for threading. If your codes try to create too many threads, mostly by recursive methods, this may cause a delay to all running threads causing a massive set back.
In this OpenMP/Tasks wiki page, it is mentioned and a manual cut off is suggested. There need to be 2 versions of the function and when the thread goes too deep, it continues the recursion with single threading.
EDIT: cutoff variable needs to be increased before entering OMP zone.

the following code is for test purposes for the OP to test
#define CUTOFF 5
int fib_s(int n)
{
    if (n == 0 || n == 1)
        return n;
    int res, a, b;
    a = fib_s(n - 1);
    b = fib_s(n - 2);
    res = a + b;
    return res;
}
int fib_m(int n,int co)
{
    if (co >= CUTOFF) return fib_s(n);
    if (n == 0 || n == 1)
        return n;
    int res, a, b;
    co++;
#pragma omp task shared(a)
    a = fib_m(n - 1,co);
#pragma omp task shared(b)
    b = fib_m(n - 2,co);
#pragma omp taskwait
    res = a + b;
    return res;
}

int main()
{
    omp_set_nested(1);
    omp_set_num_threads(4);
    double start_time = omp_get_wtime();
#pragma omp parallel
    {
#pragma omp single
        {
            cout << fib_m(25,1) << endl;
        }
    }
    double time = omp_get_wtime() - start_time;
    std::cout << "Time(ms): " << time * 1000 << std::endl;
    return 0;
}

RESULT:
With CUTOFF value set to 10, it was under 8 seconds to calculate 45th term.
co=1   14.5s
co=2    9.5s
co=3    6.4s
co=10   7.5s
co=15   7.0s
co=20   8.5s
co=21 >18.0s
co=22 >40.0s

A: I believe I do not know how to tell the compiler not to create parallel task after a certain depth as: omp_set_max_active_levels seems to have no effect and omp_set_nested is deprecated (though it also has no effect).
So I have to manually specify after which level not to create more tasks. Which IMHO is sad. I still believe there should be a way to do this (if somebody know, kindly let me know). Here is how I attempted it, and after input size of 20 parallel version runs a bit faster than serial (like in 70-80% time).
Ref: Code taken from an assignment from course (solution was not provided, so I don't know how to do it efficiently): https://www.cs.iastate.edu/courses/2018/fall/com-s-527x
#include <stdio.h>
#include <omp.h>
#include <math.h>

int fib(int n, int rec_height)
{
  int x = 1, y = 1;
  if (n < 2)
      return n;
  int tCount = 0;

  if (rec_height > 0)   //Surprisingly without this check parallel code is slower than serial one (I believe it is not needed, I just don't know how to use OpneMP)
  {
   rec_height -= 1;
  #pragma omp task shared(x)
  x = fib(n - 1, rec_height);
  #pragma omp task shared(y)
  y = fib(n - 2, rec_height);
  #pragma omp taskwait
  }
  else{
    x = fib(n - 1, rec_height);
    y = fib(n - 2, rec_height);
  }
  return x+y;

}

int main()
{
  int tot_thread = 16;
  int recDepth = (int)log2f(tot_thread);
  if( ((int)pow(2, recDepth)) < tot_thread) recDepth += 1;
  printf("\nrecDepth: %d\n",recDepth);
  omp_set_max_active_levels(recDepth);
  omp_set_nested(recDepth-1);

  int n,fibonacci;
  double starttime;
  printf("\nPlease insert n, to calculate fib(n): %d\n",n);
  scanf("%d",&n);
  omp_set_num_threads(tot_thread);
  starttime=omp_get_wtime();
  #pragma omp parallel
  {
   #pragma omp single
   {
    fibonacci=fib(n, recDepth);
   }
  }
  printf("\n\nfib(%d)=%d \n",n,fibonacci);
  printf("calculation took %lf sec\n",omp_get_wtime()-starttime);
  return 0;
}


text:
Q: Java opens URL to save file to specific folder I'm trying to code based on the manual operation.  For manual, I have a URL and when I paste the URL to the Chrome browser, the browser automatically downloads the PDF file from that URL and save to folder "download" without prompting any user input.  With Code, I'm able to accomplish the same thing as the manual operation.  However I would like the code to save the PDF into specific folder instead of default folder "download".  Is it possible to do that?
    public static void browseURL() {
    try {

        String url ="mycompanyURL";
        System.out.println("url " + url );

        Desktop desktop = Desktop.getDesktop();
        URI uri = new URI (url);
        desktop.browse(uri);

    }catch(Exception err) {

        System.out.println("exception " + err.getMessage());
    }
  }

A: When I had to do that in old versions of Java, I used the following snippet (pure Java, source: Baeldung).
public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
    File file = new File(filePath);
    try (BufferedInputStream in = new BufferedInputStream(new URL(downloadUrl).openStream());
         FileOutputStream fileOutputStream = new FileOutputStream(file)) {
        byte[] dataBuffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
            fileOutputStream.write(dataBuffer, 0, bytesRead);
        }
    }
}

The above opens an input stream on the URL, and outputs the bytes of such stream into a file output stream (where the file is wherever you wish).
Alternatively, there are many libraries doing that in one/two liners (the article I posted shows some of those alternatives).
Also, starting from more recent versions of Java, there are other shorter options:
public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
    try (InputStream in = new URL(downloadUrl).openStream()) {
        Files.copy(in, Paths.get(new File(filePath)), StandardCopyOption.REPLACE_EXISTING);
    }
}

Depending on the version of Java you have, you may pick one of those. Generally speaking, I suggest you reading through the Baeldung's article and check the one that best suits for you.

A: Here you go. Handles redirects and so on can use and modify as you wish. Have fun with it. All in native Java. Did write this to download some media easily. This can also download media like images, videos and documents.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Path;

public class Downloader {
    public static void download(String url) {
        final HttpClient hc = HttpClient.newHttpClient();
        final Builder requestBuilder = HttpRequest.newBuilder().version(HttpClient.Version.HTTP_1_1);

        Path path = Path.of("myfilepath");
        handleGet(hc, "myfile.pdf", "myurl.com", path, requestBuilder);

    }

    private static void handleGet(
                final HttpClient hc,
                final String fileName,
                final String url,
                final Path filePath,
                final Builder requestBuilder
                ) {

            final HttpRequest request = requestBuilder.uri(URI.create(url)).build();
            hc.sendAsync(request, BodyHandlers.ofInputStream())
            .thenApply(resp -> {
                int sc = resp.statusCode();
                System.out.println("STATUSCODE: "+sc+" for url '"+url+"'");
                if(sc >= 200 && sc < 300) return resp;
                if(sc == 302) {
                    System.out.println("Handling 302...");
                    String newUrl = resp.headers().firstValue("location").get();

                    handleGet(hc, fileName, newUrl, filePath, requestBuilder);
                }
                return resp;
            })
            .thenAccept(resp -> {
                int sc = resp.statusCode();
                if(sc >= 200 && sc < 300) {
                    try {
                        System.out.println("Im fine here");
                        Files.copy(resp.body(), filePath);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.err.println("STATUSCODE: "+ sc +" for file "+ fileName);
                }
            }).join();
        }
}