text:
Q: Database design: users and guests I have two types of people on my site, users and guests. Virtually they are the same, except for creation/auth processes.
At the moment I have two tables:
t_users

userId[PRIMARY, AUTOINC] username[UNIQUE]

t_guests

guestId[PRIMARY, AUTOINC] userId

When somebody enters the site, script does the following:
1) creates new guest record by inserting a new row to t_guests
2) adds new record to t_users, using guestId generated on previous step (guest username = "Guest guestId")
3) updates guest record setting userId assigned on step 2
I feel this database design to be just awful, because it contains many vulnerabilities. For example, if username "Guest xyz" already exists in t_users table, step 2 will fail and step 3 will assign wrong value to the userId (depending on implementation it'll be 0 or guestId, assigned on step 1).
Actually I only need t_guests table for its auto increment feature to generate unique usernames for guests. Is there a way to use just one consolidated table and register guests using single query?
UPDATE: I can do the following to insert guests in a single table:
SELECT @mg := IFNULL(MAX(guestId), 0) + 1 FROM t_users;

INSERT INTO t_users (guestId) VALUES(@mg);

But I can't be sure, that nobody inserts a new guest record in t_users between execution of those two statements. And I can't make guestId unique, because real users will have it equal to zero.

A: If you just have 1 table with"
userID, username, type
for the username you could use your script to generate a Guid and use that as the username, or someother random variable.  If you use a GUID it is virtually impossible that you get 2 guids that collide.
Also if you do have 2 usernames that collide if you make sure that the username column has to be unique then the insert will fail and you could just try again.
You definitely aught to just have 1 table here.


text:
Q: Dockerize and deploy the Spring App that has Kafka consumer on AKS? At present, we have a Java spring boot application deployed on the VM which consumers the message from Kafka.
We have an Enterprise Kafka Cluster deployed on the VMs. It uses the standard ports - eg: 9092 & 2181.
Requirement:
We want to deploy this application Azure Kubernetes Services (AKS).
Ask : Is there anything specific (eg: port ) needs to be done in the dockerfile or kubernetes manifest yaml?
I would assume that as long as the AKS can connect (VNET - VNET) with the Kafka Cluster that should be sufficient.
please suggest.

A: Kafka clients don't need to expose any port mappings
Your assumption is correct, that given the proper VPC settings, then communicate should be fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ошибка при создании виртуальной среды в python Пытаюсь создать виртуальную среду в python (на windows 7) и вылезает ошибка: Error: [Errno 2] No such file or directory:
Почитал в интернете, говорят, что проблема может быть в переменной PATH + в неправильной установке python. Python у меня установлен в двух местах:
Подскажите, как решить проблему?

A: Попробуйте создавать виртуальное окружение следующей командой:
$ virtualenv venv


text:
Q: Can we use 2 or more SoftwareSerial in Arduino? So I have a project that need ESP-01 (ESP8266) and Fingerprint Sensor (FM10A), both of it would be connected to Arduino UNO. Both of the component need to communicate from SoftwareSerial. For some project-related reason I can't use the hardware-serial.
The programs works like this:

*

*The fingerprint sensor is going to capture a fingerprint and give it an ID (String)

*The ID is going to be sent to firebase database using ESP-01

Is it possible to make them work using 2 SoftwareSerial?
ESP-01 Pins | Fingerprint Sensor FM10A Pins
Any helpful response would be appreciated, thank you!

A: The  ESP-01 (ESP8266)is only a WiFi module with 2 gpios available.
It should be used together with a micro-controller board and not stand alone.
Better is to get a micro-controller board like esp32.

A: My answer is not a good answer: I am not sure.
You can certainly use 2 SoftwareSerial and make use of them with no problem but that library comes with limitations as per the official documentation
Quoting from what I've linked:

SoftwareSerial library has the following known limitations:

*

*It cannot transmit and receive data at the same time.

*If using multiple software serial ports, only one can receive data at a time.

*Not all pins on the Mega and Mega 2560 boards support change interrupts, so only the following can be used for RX: 10, 11, 12, 13,
14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12
(66), A13 (67), A14 (68), A15 (69).

*Not all pins on the Leonardo and
Micro boards support change interrupts, so only the following can be
used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

*On Arduino or Genuino 101 boards the current maximum RX speed is 57600bps.

*On Arduino or Genuino 101 boards RX doesn't work on digital pin 13.

*If your project requires simultaneous data flows, see Paul
Stoffregen's AltSoftSerial library.

Of course this library was built for Arduino and you might have to deal with other stuff if you're planning on to program the ESP8266.
I also remember having to deal with extra noise when using the SoftwareSerial at some higher baud-rates. So keep that in mind!


text:
Q: VB.net real-time time elapsed feature I already have created a real time clock that synchronizes with the computer time and is being displayed in a label.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub

I want to make a real-time time elapsed feature that keeps on counting the seconds/minutes/hours elapsed from the time it started till the time it stops and it would be basing on the real-time clock i have created. I would be creating a start and stop button for this. Is this possible? Thanks in advance.

I am now able to complete everything and i added a feature that records the starting and ending time based on my real time clock. Here is my working code:
Dim hr, min, sec As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Start.Text = ""
    EndLbl.Text = ""
    Elapse.Text = ""
    Timer2.Enabled = True
    Start.Text = Time.Text
End Sub

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick

    sec = sec + 1
    If (sec = 60) Then
        sec = 0
        min = min + 1
    ElseIf (min = 60) Then
        min = 0
        hr = hr + 1
    ElseIf (hr = 24) Then
        hr = 0
        min = 0
        sec = 0
    End If

    Elapse.Text = String.Format("{0}hr : {1}min : {2}sec", hr, min, sec)
    Timer2.Interval = 1000
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Timer2.Enabled = False
    EndLbl.Text = Label4.Text

    hr = 0
    min = 0
    sec = 0
    Timer2.Interval = 1
End Sub

Credits to the starting code given by NeverHopeless. Thanks alot.

A: I suggest you use only 1 timer:
Public Class Form2

Private _elapseTimerRunning As Boolean = False
Private _elapseStartTime As DateTime

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
    Timer1.Interval = 1000
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    txtTime.Text = Now.ToString("h:mm:ss tt")
    If _elapseTimerRunning = True Then
        Dim elapsedtime = DateTime.Now.Subtract(_elapseStartTime)
        txtElapsed.Text = String.Format("{0}hr : {1}min : {2}sec", elapsedtime.Hours, elapsedtime.Minutes, elapsedtime.Seconds)
    End If
End Sub

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    _elapseStartTime = DateTime.Now
    _elapseTimerRunning = True
End Sub

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    _elapseTimerRunning = False
End Sub

End Class

A: An example for displaying the elapsed time the application has run.
Public Class Form1
    'shows elapsed time that the app has run
    '
    Dim elapTimer As New Threading.Timer(AddressOf tick, Nothing, 1000, 1000)
    Dim stpw As Stopwatch = Stopwatch.StartNew

    Private Sub tick(state As Object)
        If stpw.IsRunning Then
            'format - http://msdn.microsoft.com/en-us/library/ee372287.aspx
            Me.Invoke(Sub()
                          Label1.Text = stpw.Elapsed.ToString("d\ \ hh\:mm\:ss\.ff")
                      End Sub)
        End If
    End Sub

End Class

To add start/stop functionality using buttons:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'start the elapsed timer
    stpw.Start() 'continue
    'or
    'stpw.Restart() 'restart
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    stpw.Stop()
End Sub

A: Something like this would help you: (untested, but will give you a starter)
Dim hr, min, sec As Integer 'msec;

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Enabled = True
    Timer2.Enabled = True
End Sub

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    'msec++;
    'if(msec == 60)  { msec = 0; sec++; }

    sec+=1;
    if(sec  = 60) Then
      sec = 0 : min+=1
    end if
    if(min  = 60) Then
      min = 0 : hr+=1
    end if
    if(hr = 24)  Then
      hr  = 0 : min = 0 : sec = 0
    end if

    'TimeElapsed.Text = String.Format("{0}:{1}:{2} {3}", hr, min, sec, msec)
     TimeElapsed.Text = String.Format("{0}:{1}:{2}", hr, min, sec)
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Time.Text = Date.Now.ToString("h:mm:ss tt")
End Sub

NOTE: Timer2 will run for every second.


text:
Q: InflateException: Error inflating class Button - Crash through play store I have spent a long time looking for an answer to this issue and seem unable to figure it out.
An app I created through "Android Studio" has been working perfectly fine when I create an APK in debug mode, however if I create a bundle and upload it to play store then it crashes on 5 out of 11 devices (including my own) due to the exact same error:

Issue: java.lang.RuntimeException: Unable to start activity ComponentInfo{maxmansung.finaljudgement/maxmansung.finaljudgement.MainScreen}: android.view.InflateException: Binary XML file line #65: Binary XML file line #65: Error inflating class Button

What appears to be happening is that the app is unable to open any Buttons at all for some reason. I have tried deleting the button at the point of error but it simply changes to crashing on another button instead.

Error Log

FATAL EXCEPTION: main
Process: maxmansung.finaljudgement, PID: 20309
java.lang.RuntimeException: Unable to start activity ComponentInfo{maxmansung.finaljudgement/maxmansung.finaljudgement.MainScreen}: android.view.InflateException: Binary XML file line #65: Binary XML file line #65: Error inflating class Button
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6524)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
Caused by: android.view.InflateException: Binary XML file line #65: Binary XML file line #65: Error inflating class Button
Caused by: android.view.InflateException: Binary XML file line #65: Error inflating class Button
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=58; index=309
    at android.content.res.StringBlock.get(StringBlock.java:65)
    at android.content.res.AssetManager.getPooledStringForCookie(AssetManager.java:642)
    at android.content.res.TypedArray.loadStringValueAt(TypedArray.java:1279)
    at android.content.res.TypedArray.getString(TypedArray.java:219)
    at android.widget.TextView.(TextView.java:1157)
    at android.widget.Button.(Button.java:109)
    at android.widget.Button.(Button.java:105)
    at android.support.v7.widget.AppCompatButton.(AppCompatButton.java:71)
    at android.support.v7.widget.AppCompatButton.(AppCompatButton.java:67)
    at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
    at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
    at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:738)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:869)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:832)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at maxmansung.finaljudgement.MainScreen.onCreate(MainScreen.java:24)
    at android.app.Activity.performCreate(Activity.java:6910)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6524)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)

Game Code
If I keep the OnClickListener parts then the crash continues
package maxmansung.finaljudgement;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

import maxmansung.finaljudgement.savedVariables.saveSettings;

public class MainScreen extends AppCompatActivity {

@Override
public void onBackPressed() {
    System.exit(0);
}

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

    saveSettings settings = new saveSettings(this);
    settings.updateFromSave(this);
    Boolean currentTrue = settings.getCurrentTrue();

    Button mainScreenNew = findViewById(R.id.mainScreenNew);
    Button mainScreenCont = findViewById(R.id.mainScreenCont);
    Button mainScreenAchievements = findViewById(R.id.mainScreenAchieve);

    if (currentTrue){
        mainScreenCont.setVisibility(View.VISIBLE);
    } else {
        mainScreenCont.setVisibility(View.GONE);
    }

    if (settings.achievementsGained()){
        mainScreenAchievements.setVisibility(View.VISIBLE);
    } else {
        mainScreenAchievements.setVisibility(View.GONE);
    }

    final Animation clickAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_click);

    mainScreenNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Animation.AnimationListener listener = new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    Intent gamePage = new Intent(getApplicationContext(),GamePage.class);
                    gamePage.putExtra("continue", false);
                    startActivity(gamePage);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            };
            clickAnimation.setAnimationListener(listener);
            view.startAnimation(clickAnimation);
        }
    });

XML Page
If I remove the drawableLeft and drawableStart parts then the crash changes to what appears to be an identical crash but further back in the XML code
I have removed the previous code as it does not impact the crash
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="maxmansung.finaljudgement.MainScreen">

<Button
    android:id="@+id/mainScreenAchieve"
    style="@style/Widget.AppCompat.Button.Borderless.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:drawableStart="@drawable/achievement_icon"
    android:drawableLeft="@drawable/achievement_icon"
    android:text="@string/mainScreenAchievements"
    android:textAllCaps="true"
    android:textColor="@color/colorText"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/mainScreenCont" />

A: This type of error sometimes happens because there is a drawable involved.
I see in your xml this @drawable/achievement_icon is used for the Button with id mainScreenAchieve.
Is there a case that you have stored this drawable in a folder like drawable-v24 only and not in the main drawable folder?
If this is the case then copy and paste it in the main drawable folder too.
Otherwise in the devices with lower version this drawable is unavailable and this leads to an app crash.

A: It looks like it's related to the text setting. Is your strings.xml malformed? Or is it missing from certain build types?
Also - Having a + in this line: app:layout_constraintTop_toBottomOf="@+id/mainScreenCont" can cause problems. It doesn't need the +.


text:
Q: Extracting text from any web page with Jsoup I am trying to extract the text from web page http://www.zomato.com/mumbai/starbucks-coffee-fort including any newlines, spaces in the original. For that I have written following piece of code with the help of answer at Jsoup - extracting text :
Document doc = Jsoup.connect("http://www.zomato.com/mumbai/starbucks-coffee-fort").get();
Elements div = doc.select("div");
for (Element d : div) {
  for (Node nd : d.childNodes()) {
    System.out.println(nd.toString());
  }
}

But it's not working as expected. Actually it should print text of  as well as text
of all its child nodes. Also I want this code a bit generalized so that it can
extract text from any web page. Please help.

A: Jsoup is generalized tool for scraping text from any web page ;)
Solution for this case:
Document doc = Jsoup.connect("http://www.zomato.com/mumbai/starbucks-coffee-fort").get();
Elements div = doc.select("div.res-review-body > div > p");
for (Element paragraph : div) {
    System.out.println(paragraph.text());
}

Result:
Firstly I would say it was tough to even start writing a review for a brand like 'Starbucks'.
(...)


text:
Q: How to include items in credit memo transactional email It seems that the product level items aren't available in the Magento credit memo transactional email, nor is a balance displayed - it gets you to login via My Account to view it.
Is there a reason behind this? What would be required to achieve this - would the information be available at a transactional email template or, would I need to extend Magento?


text:
Q: Blur image using Opencv in JAVA I am working on image blur functionality. To achieve this I am using opencv with JAVA. But the blur ratio of the image is according to the quality of the uploaded image, means if I upload low quality image, then it blurs the image as expected, but if I upload high quality image, then it blurs the image in very minor proportion. How can I set the parameters to this line so that the blur effect is same for all images(means it is independent of the uploaded image quality)
 Imgproc.GaussianBlur(source, destination,new Size(39,39),0);

A: Recently even i have been working on something very similar.
In your case you are working with kernel size of 39*39.
So if i assume you are getting best result when you use the image of size 500*500 (width and height of source image).
So in your case if your image is 500 use kernel size of 39 (ratio of 500/39=12.82)
Now if you increase the image size (high resolution image) also try to increase the kernel size with same proportionality.
For example now if you feed an image of size 1000*1000 then make the kernel size as 78.
So basically use dynamic kernel size for blurring.
If you can be specific about the case where you are implmenting it, you can get much better answer specific to your situation.
Hope that helps. Dont forget to upvote.

A: Try to convert all images in consistent size.
example:If you have image with dimension 455x550 convert it into 300x300.Likewise you have one consistent dimension.convert all images in same dimension before applying blur effect.


text:
Q: php flock behaviour when file is locked by one process Let's consider a sample php script which deletes a line by user input:
$DELETE_LINE = $_GET['line'];
$out = array();
$data = @file("foo.txt");
if($data)
{
    foreach($data as $line)
        if(trim($line) != $DELETE_LINE)
            $out[] = $line;
}
$fp = fopen("foo.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line)
    fwrite($fp, $line);
flock($fp, LOCK_UN);
fclose($fp);

I want to know if some user is currently executing this script and file "foo.txt" is locked, in same time or before completion of its execution, if some other user calls this script, then what will happen?
Will second users process wait for unlocking of file by first users? or line deletion by second users input will fail?

A: If you try to acquire an exclusive lock while another process has the file locked, your attempt will wait until the file is unlocked. This is the whole point of locking.
See the Linux documentation of flock(), which describes how it works in general across operating systems. PHP uses fcntl() under the hood so NFS shares are generally supported.
There's no timeout. If you want to implement a timeout yourself, you can do something like this:
$count = 0;
$timeout_secs = 10; //number of seconds of timeout
$got_lock = true;
while (!flock($fp, LOCK_EX | LOCK_NB, $wouldblock)) {
    if ($wouldblock && $count++ < $timeout_secs) {
        sleep(1);
    } else {
        $got_lock = false;
        break;
    }
}
if ($got_lock) {
    // Do stuff with file
}


text:
Q: excel - Multiple units in single pivot table column I am trying to combine multiple units into a single column of my pivot table. I need all the units (ea,hr,m2,t,wk) to populate under a single column adjacent to the QUANTITY column. Before I add the 'units' field to the table I get the BEFORE and i just want to add the quantity the corresponds to each item to populate in a single column rather than how it does in the AFTER
BEFORE + AFTER

A: Move your units to the rows area and then set your pivot table design to Tabular.


text:
Q: Newtons's Method If when you are using Newton's method and your results are just going back and forth between two values, say $0$ and $1$.  It is $f(x)=x^3 -2x+2$ starting with $x=1$. What is the reasoning behind this?

A: In terms of the theorem about convergence of Newton's method, this is simply one of the issues that can occur if your initial guess for the root is not good enough. We are only guaranteed convergence for initial guesses which are already sufficiently close to the root.
In terms of what it means about the function, it doesn't mean very much analytically. It can be interpreted geometrically, if you want. The tangent line to $f$ at $0$ is $y=-2x+2$ while the tangent line to $f$ at $1$ is $y=(x-1)+1=x$. These have their roots at $1$ and $0$ respectively. Newton's method finds the root of the tangent line, so starting at $0$ sends you to $1$, then back to $0$, etc. This geometric observation correctly suggests that we may see cycles if we start out relatively close to an extremum of $f$ (since the derivative changes sign between the two values that are being hit).

A: For illustration, see https://en.wikipedia.org/wiki/Newton%27s_method#Starting_point_enters_a_cycle
with the picture

A Newton fractal with discussion of this example can also be found in https://www.math.sunysb.edu/~scott/Newton.ps.gz


text:
Q: Pick a random picture from a directory This is my current code:
const superagent = require("snekfetch");
const Discord = require('discord.js')
const random = require('random')
const os = require('os')

module.exports.run = async (client, message, args) => {
     if (!message.channel.nsfw) {
        message.react('');
        return message.channel.send({embed: {
                color: 16734039,
                description: "CO TY ROBISZ! TE ZDJENCIA SA TYLKO DLA DOROSLYCH! (idz na kanal NSFW)"
            }})
    }
    superagent.get('https://nekos.life/api/v2/img/ero')
        .end((err, response) => {
      const embed = new Discord.RichEmbed()
      .setTitle(":smirk: Eevee")
      .setImage(random.choice(os.listdir("./app/eevee")))
      .setColor(`RANDOM`)
      .setFooter(`Tags: eevee`)
      .setURL(response.body.url);
  message.channel.send(embed);
    }).catch((err) => message.channel.send({embed: {
                color: 16734039,
                description: "Something is wrong... :cry:"
            }}));

}

module.exports.help = {
    name: "eevee",
    description: "Fajno zdjencia",
    usage: "eevee",
    type: "NSFW"
}

When I try to run it, I get this error message:

TypeError: os.listdir is not a function

Is there anything I can do to fix this problem?

A: I don't really know the os package but after a bit of researching I've found no readdir function. If you want to get all files of a directory you also can do it like this:
const fs = require('fs')

const allMyFiles = fs.readdirSync();

Also you are creating your embed with RichEmbed() which is outdated. Since v12 you have to use MessageEmbed():
const exampleEmbed = new Discord.MessageEmbed()
   .setTitle('Test')
   [...]


text:
Q: How does Translate inline work How does translate inline work? I'm trying to change a previous translation in the checkout "Proceed to checkout" button. ATM all our websites have the same translation of the button but I need to change it for store specific to something else.
When I activate translate inline and find the word I want to change I do check the box for "for this store view only" And I can change it, however when I disable translate Inline it changes back to the original word. Is there a file where all the translates from translate inline save to?
Or do anyone know why I can't change the word?

A: Documentation says :

Magento 2 Inline Translation is theme specific, if you change the store theme, you need to do it again.

I would say it's a non technical solution to add translation but, the way it should be handled is using i18n
In your magento code you should have a file like this one
app/design/theme/default/i18n/us_US.csv
It's on that csv file that you would put all your theme translation
You have one file per language
app/design/theme/default/i18n/fr_FR.csv
"Hi","Salut"


text:
Q: restatables and \listoftheorem I am using the restatable environment from the thm-restate package ofthmtools.
I am also using \listoftheorems command to give me a list of the theorems.
However, my restatable theorem is appearing twice in the list of theorems, even when I used the starred version.
My feeling is that it should only be in the list of theorems once.
Here is a mwe:
\documentclass{article}
\usepackage{thmtools}
\usepackage{thm-restate}

\declaretheorem[name=Theorem,numberwithin=section]{thm}

\begin{document}

\listoftheorems[ignoreall,show={thm}]

\section{First}

\begin{restatable}[Goldbach's conjecture]{thm}{goldbach}
\label{thm:goldbach}
Every even integer greater than 2 can be expressed as the sum of two primes.
\end{restatable}

\begin{thm}
Some other theorem
\end{thm}

Lets look at the first one again
\goldbach*

\end{document}

I've tried using the ignoreall key and to show just thm environments, but I guess the restatable is a thm too so this doesn't work.
Any ideas appreciated, thanks!

A: This solution requires some customisation of the thmtools files.
Copy the file thm-listof.sty into the same directory as your document and alter it; I was doing this anyway in order to reformat the list of theorems. If you try to override the format in your preamble, it does not work due to the packages use of \AtBeginDocument.
In this file, find the block which starts \addtotheorempostheadhook{% and modify it to read:
\newif\ifdontputthminlist
\dontputthminlistfalse
\addtotheorempostheadhook{%
  \ifdontputthminlist\else
  \thmtlo@chaptervspacehack
  \addcontentsline{loe}{\thmt@envname}{%
    \csname ll@\thmt@envname\endcsname
  }%
  \fi
}

Then, when you restate your theorem with \oldtheorem* just write it as follows:
\dontputthminlisttrue
\oldtheorem*
\dontputthminlistfalse

This may also come in handy if there's some random theorem you don't want to show up in the list for any other reason.
If you want, you could adopt this approach but flip the flag automatically by modifying the code in thm-restate.sty, but I haven't tried that since this sufficed.

A: There are two options: The first, simpler option is to write additional code into the *.loe file (which is where the list of theorems is stored) to prevent the superfluous lines to be printed. This can simply be achieved like this:
\addtocontents{loe}{\protect\iffalse}
\goldbach*
\addtocontents{loe}{\protect\fi}

All theorems between the two \addtocontents commands will be omitted from the list of theorems.
The other option would be to prevent the restated theorems from writing the additional \contentslines to the *.loe file in the first place. However, this is likely to be more complicated, as the thm-listof.sty package uses \addtotheorempostheadhook to make theorems automatically write to the *.loe file, and this command is already executed when you load the package. It should be possible to locally redefine \addcontentsline, which is used inside the hook, to be a no-op.


text:
Q: Are there any serious investigations of whether "mathematicians do their best work when they're young"? There is no shortage of anecdotes and conjectures on both sides of this widespread belief, but good supporting data either way is harder to find. Can anyone provide any references for serious (preferably academic rather than journalistic) research that actually crunched the data and produced interesting conclusions about whether this bit of folklore is reality-based?
I put "mathematicians do their best work when they're young" in quotes because this is clearly not a well-posed question--it is only intended to be shorthand for any of a number of questions on this topic.
Historical studies (Évariste Galois, etc.) are OK, but studies on people born after, say, 1950, would be of greater interest and relevance.

A: If everybody assumes mathematicians to be "a different cup of tea" or that "they cook themselves apart from the rest of scientists" (or that they are not scientists at all, if you will), then I would have nothing to add to what has already been said. However, let us suppose for a moment that mathematics is comparable to any other scientific endeavor. Then we have this article of Packalen & Bhattacharya, 2015, "Age and the trying out of new ideas" (http://www.nber.org/papers/w20920.pdf) which I would say is closely related to your question. Not in the sense of bulk production, but in terms of originality, which in my humble opinion, it is also very, very important for mathematicians (perhaps even more than size of production). They studied biomedical articles since 1946, and one of the conclusions they arrive at, is that the best possible team in order to obtain an original paper, is a young scientist coupled with a "more experienced" one (read it as "older", maybe "much older").

A: I hope it's OK to post an answer to my own question since it's community-wiki. Here are a couple of things I found down this rabbit-hole.
Dean Simonton at UC Davis has done some work claiming that there is a slow age-related decline in quality and quantity of creative output, but the relevant variable is career age, not biological age. He also makes it clear that although he believes there is a clear aggregate trend, the individual variability is much greater than the aggregate variability. Furthermore, he attributes the decline mostly to factors other than biological aging.
Simonton, D. K. (1997). Creative productivity: A predictive and explanatory model of career trajectories and landmarks. Psychological Review, 104, 66-89.
This paper is behind a subscription paywall (but there is a link below in the comments), so instead I'm posting this link to the PowerPoint (sorry) of his 2005 talk at the Max Planck International Research Network on Aging:
http://psychology.ucdavis.edu/Simonton/MxAgCrProd.ppt
I couldn't find a good sound bite from Simonton's paper. Here is a quote from Arne Dietrich's 2004 paper The cognitive neuroscience of creativity:

Simonton (1997) has convincingly demonstrated that
  "creative productivity is a function of career age, not
  chronological age" (p. 70). Although career age and
  chronological age are highly correlated, latecomers to a
  discipline show the same career trajectories and landmarks,
  as well as conformity to the 10-year rule (Simonton,
  1997, 2003). For instance, mathematicians peak on
  average at 26.5 years of career age, while historians peak
  at 38.5 (Simonton, 1997). Because prefrontal-dependent
  mental functions do not significantly decline until old
  age, the distinction between chronological and career age
  can be accommodated as long as the creator's career onset
  is not at an advanced chronological age.

A: As I originally said as a comment, the following paper provides perhaps one attempt at approaching a similar question. Namely the authors explore what effect winning the Fields medal has on mathematicians productivity. To do this they examine publication and citation rates of a select group of mathematicians over time. The authors' note, "It turns out that Fields medalists are not only publishing fewer papers in the post-medal period, and that those papers are relatively less important, but they are also accepting fewer mentees under their wing."
"Prizes and Productivity: How Winning the Fields Medal Affects Scientific Output"
George J. Borjas and Kirk B. Doran

A: These two studies arrive at what seems to be a more sensible conclusion:
Age and Scientific Performance, Stephen Cole (1976).

The long-standing belief that age is negatively associated with scientific productivity and creativity is shown to be based upon incorrect
  analysis of data. Analysis of data from a cross-section of academic
  scientists in six different fields indicates that age has a slight
  curvilinear relationship with both quality and quantity of scientific
  output. These results are supported by an analysis of a cohort of
  mathematicians who received their Ph.D.'s between 1947 and 1950.
  There was no decline in the quality of work produced by these
  mathematicians as they progressed through their careers.

Age and Achievement in Mathematics: A Case-Study in the Sociology of Science, Nancy Stern (1978).

The claim that younger mathematicians (whether for physiological or
  sociological reasons) are more apt to create important work is
  unsubstantiated... I have found no clear relationship between age and
  achievement in mathematics.

For anecdotes and "advice to aging mathematicians", I might recommend Mathematical menopause, or, a young man's game?, by Reuben Hersh (The Mathematical Intelligencer, 2001).

Until we find a consensus about which advances are "major," we can't
  refute Hardy's claim that no major advance has been made by a
  mathematician over 50. But his slogan, "Mathematics is a young man's
  game," is misleading, even harmful.

A: Jordan Ellenberg (JSE on MO)
wrote a nice article after Perelman announced his solution of the
Poincaré conjecture:

"Is Math a Young Man's Game? No. Not every mathematician is washed up at 30."
  Slate, May 2003.
  (article link.)

The article ends with this:

"It's only in the presence of both conditions—deduction and inspiration, long experience and youthful audacity—that new math gets made, as it was made by Perelman, and as it was made on the day Poincaré wrote down his conjecture. He was 50 years old."

A: This misconception that mathematics is a young person's game seem to have been pushed most forcefully by Hardy, but the list of examples he gives is very misleading because they all died young and so obviously could not go on to contribute anything further anyway!  He also conveniently forgets some famous counterexamples like Euler and Weierstrass.  Cramer, for example, could be classed as a young prodigy, since he obtained his PhD equivalent at age 20, but the work for which he is known today was done when he was into his 40s.
The question asks for research on this question so I will provide two physics examples from my own reading.
1.) In 1988, Aharonov and colleagues published an influential PRL article on quantum mechanics.  In 2020, Aharonov and Rohlich published a PRL article on quantum mechanics which looks set to be just as influential and is no different in quality or insight to the 1988 paper.
2.) In 1974, Georgi and Glashow published a PRL article on field theory which has been very influential.  In 2020, Georgi published a PRL article on field theory which does not look to differ from the paper published forty-five years earlier in terms of quality and insight.


text:
Q: Increasing the cross entropy loss instead of decreasing it Is there a way to flip the effect of the cross-entropy loss?
I have a language model, and I want to train the model in a way that doesn't generate a specific text. Thus, I have two losses, one that I want to reduce (loss1) and another that I want to increase (loss2):
loss1 = outputs['loss1']
loss2 = 1-outputs['loss2']
loss = loss1 + loss2

My question is, is it correct to subtract loss2 from 1? in this way it increases instead of decreasing.


text:
Q: Evolution dismissed as "less secure app" by Google I know this issue has been discussed countless times before, but I am still baffled. I have tried switching to Evolution many times, and setting up the Google email and calendar account, looks so straight forward, yet no go, Google just keeps asking for password again and again (And yes, I have enabled imap forwarding.)
I am using Ubuntu 16.04.
I downloaded Evolution 3.15.5 from the repositories.
I downloaded syncevolution, likewise from repositories (v. 1.05)
I was denied access to my google contacts and calendar (receiving the usual apologetic mail from Google today.)
I see there are a lot of people on the net saying they have no problem. But I cannot fathom what they are doing (apart from enabling "less secure apps"). The following link seems very detailed: https://help.ubuntu.com/community/SyncEvolution/synchronize-google-contacts-with-evolution-addressbooks, but it is far too (!) complicated. Could somebody please spell it out for me.
I do really wish to switch to Evolution.

A: I have second factor auth turned on on my google account. I ran into this problem with Thunderbird and posted on gmail forums, but the answer turned out to be simple. Try using an app-specific password, if you are already using app-specific passwords, then make sure you type your standard password correctly. For me, it was just the fact that I needed to type my actual password in, and not use a generated one when I was trying to use a generated one without typing in my regular password first.


text:
Q: Inserir marcação em progress bar Não consegui encontrar uma forma de inserir uma marcação na barra, estou tentando mostrar uma média.
Como é:

Como eu gostaria de mostrar a média:

Alguém sabe como posso fazer isso com bootstrap?

A: Uma sugestão de implementação com "Stacked", exemplo:
Demo: JSFiddle

Resultado:

Outra maneira seria criar uma classe e posicionar sobre o progress-bar, exemplo:
Demo: JSFiddle
HTML

CSS
.marcador{
    display:inline-block;
    position:relative;
    top:0;
    left:10%;
    width:5px;
    height:80px;
    background-color:red;
}

Resultado:


text:
Q: Netgear A6210 (Mediatek MT7612U). & Ethernet Realtek RTL8111/8168/8411 devices not found above kernel 5.4.0-42- LTS 20.04.2 Netgear A6210 (Mediatek MT7612U). & Ethernet Realtek RTL8111/8168/8411 devices are not found after higher kernel 5.4.0-42 on LTS 20.04.2
Both devices work under 5.4.0-42-lowlatency
In the syslog under NetworkManager it should say ~:-
NetworkManager[729]:   [16127] device (enp24s0): ...
NetworkManager[729]:   [16127] device (wlxb0b98a580d83): driver supports Access Point (AP) mode
NetworkManager[729]:   [16127] manager: (wlxb0b98a580d83): new 802.11 Wi-Fi device ..
NetworkManager[729]:   [16127] device (wlxb0b98a580d83): ...

A: This has been fixed in Ubuntu kernel 5.4.0-65
There is a fix released for this bug but I am not sure when a new kernel will have the fix, for now check in terminal mokutil --sb-state as Secure Boot needs to be disabled, then in terminal do
sudo apt install git build-essential
git clone https://github.com/jeremyb31/mt76.git
cd mt76
make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo cp mt76x02-lib.ko /lib/modules/$(uname -r)/kernel/drivers/net/wireless/mediatek/mt76/
make -C /lib/modules/$(uname -r)/build M=$(pwd) clean
Reboot, if after another kernel update it fails to work do
cd mt76
make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo cp mt76x02-lib.ko /lib/modules/$(uname -r)/kernel/drivers/net/wireless/mediatek/mt76/
make -C /lib/modules/$(uname -r)/build M=$(pwd) clean


text:
Q: Knockout asyncCommand / Ajax MVC ActionResults I am pretty new to front end development and also the project I'm working on (bug fixes). I am using Knockout/MVC ActionResults.
I have been tasked to alter a form so that it doesn't allow double click submission, I added basic Jquery to disable to button, but have been told it needs to use asyncCommand.
What I have noted about it however is that all examples using this they return a Json result etc. where mine will be an action result.
I was wondering if I need to alter the MVC actionresult or whether there is another way that I'm just not seeing.
I was hoping I could do something like:
HTML
<button class="btn btn-action" data-bind="command: create, activity: create.isExecuting">Create</button>

JS
 model.create = ko.asyncCommand({
        execute: function (complete) {
            $.ajax({
                type: 'POST',
                url: "/account/create",
                data: ko.toJSON(data),
                contentType: 'application/json; charset=utf-8',
            });
        complete();
        },
        canExecute: function (isExecuting) {
            return !isExecuting;
        }
    });

CONTROLLER
        public ActionResult Create(Model model, int versionId)
        {

if (success)
                {
                    return Redirect("/accounts");
                }
else
                {
                    return View(model);
                }
}

Can this actually happen or not?
Thanks,
Clare

A: The solution for me was to alter the ActionResult to return a value to AJAX.


text:
Q: Trying to create javascript out put loop for various tasks I am trying to use javascript to create tasks with a counter.  The script will lookup task entries and then create depending on what is within the DB.  For example -

task 1 [timer 1]
task 2 [timer 2]
task 3 [timer 3]

Currently my output is like so

task 1 [timer 3]
task 2 [timer 3]
task 3 [timer 3]

My code is as follows -
{% if tasks %}

    {% for task in tasks %}

        <button class="button";>Complete!</button>
{{ task.task_name }}

I appreciate any help, thanks

A: A few things to point out:

*

*Setting all these vars in the body of the document means they're all scoped to the global window object, which means each loop overwrites the same variable. This is why you're seeing the results of timer3 in all three slots.

*(Minor issue) You've got extraneous semicolons in a few places in your HTML. No need for semicolons in HTML tags, unless they're inside the quotes of an attribute that accepts them (such as the style="" attribute).

*(Minor issue) Be consistent with quote marks. A good general style principle is "double quotes" for HTML attributes, 'single quotes' for strings in Javascript.

*You're creating duplicate javascript code for every iteration of your for task in tasks loop. You should instead think of that loop as a place to trigger the start of timers and display the results of timers, but that shouldn't be where all that timer-creation code lives.

*To fix (4), you'll want to make a reusable function out of the timer-creating code. This is a good test case to think about what function arguments you need to pass to a timer-creating function. In looking over your code, I see that you're using task.id and task.task_due in the code that creates the timer. Looks like we would just need to pass those two values to a createTimer() function.

Try something like this:

{% if tasks %}
  {% for task in tasks %}
    <button class="button">Complete!</button>

      {{ task.task_name }}

  {% endfor %}
{% endif %}


text:
Q: adding group with usergroup in Debian 10 doesn't seem to work I'm trying to add a user to a group but it doesn't seem to work:
sudo usermod -a -G wireshark nicolas

But when I check my id, I get
uid=1000(nicolas) gid=1000(nicolas) groupes=1000(nicolas),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev),112(bluetooth),115(scanner)

Or, simplier, groups
nicolas cdrom floppy audio dip video plugdev netdev bluetooth scanner

I checked that wireshark group existed with
$ sudo groupadd wireshark
groupadd: group 'wireshark' already exists

Has anyone got an idea?
Thanks

A: If you're currently logged in as the user you're modifying, make sure to log out and log back in again to see your updates.
For what it's worth, in the terminal you can also "switch" user to the same user with su <username>. (Although, that effectively nests a new login inside your current session, so if you exit you'll end up in your original, unmodified, session.)
More details on Unix Stack Exchange.


text:
Q: Starting jQuery width: 'toggle' with a value of zero I have the following jQuery code:
jQuery(document).ready(function(){
    $('#logo').hover( function() {
      $('#logo span').stop(true, true).animate({
        width: 'toggle'
      }, 1000, function() {
        // Animation complete.
      });
    });
});

This takes a span within #logo and animates its width. It's perfect, except that I want the  span to start with zero width and then toggle. I could pass the function another function that toggles the width on page load, but I don't want an ugly flicker when the page first loads.
I've tried adding width: 0px; but that completely breaks it.
Here's my jsfiddle: http://jsfiddle.net/s6WYr/2/
Thanks in advance for your help.

A: What if you do this:
a#logo span {
 display: inline-block;
}

then right after the #logo div in your page, add a script section and do
<a id="logo" href="<?php bloginfo('url');?>">my.logo

don't wait for document ready as it will fire after.
This should happen quick enough that you won't see it (at least for me it did).
I actually couldn't see the flicker even when using $(document).ready() but YMMV.
Give it a try.

A: Would this be acceptable: jsFiddle
jQuery:
$('#logo span').hide();
$('#logo').hover(
    function(){
        $('#logo span').show(1000);
    },
    function(){
        $('#logo span').hide(1000);
    }
);

Small CSS change:
a#logo span {
    display:inline-block;
}


text:
Q: Is the poetic phrase "Time stumbled and fell" considered a Juxtaposition? In the poem "People on the Bridge" written by Wislawa Szymborksa (Translated by Joanna Trzceiak) the phrase "Time stumbled and fell" is used. Is this an example of a juxtaposition used by the poet?

A: Chambers online defines juxtaposition as

placing or being placed together.

Lexico goes a bit further and provides the definition

The fact of two things being seen or placed close together with
  contrasting effect.

I don't see any of that in the sentence you give us.  Perhaps you are searching for the word metaphor which is probably a fair description of the idea of time stumbling as if it were a legged animal rather than, well, something rather more abstract.


text:
Q: jQuery get local time, then use AJAX to give to php I need my php file f-eval.php to receive the hour time from a javascript / jQuery file time.js through $_GET and AJAX, but it isn't working. My code is as follows.
f-eval.php
<?php
$totalflightscore = 100;
// Something is wrong weather
if (isset($_GET['drizzle'])) {
    $totalflightscore = $totalflightscore - 10;
}
if (isset($_GET['rain'])) {
    $totalflightscore = $totalflightscore - 30;
}
if (isset($_GET['thunder'])) {
    $totalflightscore = $totalflightscore - 50;
    // selecting this option alone will trigger a red alert.
}
// Something is wrong wind
if ($_GET['windspeed'] > 30) {
    $totalflightscore = $totalflightscore - 50;
} elseif ($_GET['windspeed' > 15]) {
    $totalflightscore = $totalflightscore - 25;
} elseif ($_GET['windspeed' > 10]) {
    $totalflightscore = $totalflightscore - 5;
} else {
    if ($_GET['windspeed'] <= 12) {
        // wind speed is less than 12 mph. do nothing.
    }
}
// Something is wrong day night
if (isset($_GET['am-day'])) {
    // some users of this site may hold Part 107, so do not trigger a red alert.
} else {
    $totalflightscore = $totalflightscore - 20;
}
// Something is wrong airmap
if (isset($_GET['am-green'])) {
    $totalflightscore = $totalflightscore + 10;
    // adding because green indicates there are no controlled airspace zones nearby
}
if (isset($_GET['am-orange'])) {
    $totalflightscore = $totalflightscore - 25;
    // indicates you are in airport 5 mile zone, near heliport, or near tfr.
}
if (isset($_GET['am-red'])) {
    $totalflightscore = $totalflightscore - 75;
    // indicates you are in an airport or on a runway, in tfr, or in controlled airspace. will trigger a red alert.
}
// reCaptcha code
            echo "TFS was $totalflightscore";
          if ($totalflightscore <= 40) {
              echo '<meta http-equiv="Refresh" content="0;url=https://apps.roen.us/safeflight/hs/hs-dnto.html">';
        } elseif ($totalflightscore <=60) {
              echo '<meta http-equiv="Refresh" content="0;url=https://apps.roen.us/safeflight/hs/hs-calert.html">';
          } elseif ($totalflightscore <=100) {
              /*echo '<meta http-equiv="Refresh" content="0;url=https://apps.roen.us/safeflight/hs/hs-nalert.html">'; */
              echo "This is executing!";
              if ($_GET['n']) {
                  echo 'I am recieveing AJAX.';
              }
          }

index.html
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link href="https://use.fontawesome.com/releases/v5.0.4/css/all.css" rel="stylesheet">
    <title>SafeFlight</title>

      SafeFlight
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

      </button>

          Home
          About
          Acknowledgments

Welcome to SafeFlight.

Not sure if it's safe to fly? Welcome to SafeFlight - your go-to resource for preflight planning and on-site risk assesment for flying your sUAS. Simply enter current weather conditions, and SafeFlight will notify you if it's safe to fly.

 If you aren't sure whether it's legal to fly, you are able to find out using SafeFlight through an embedded version of AirMap, an open source webapp that makes airspace laws easy to understand and follow.

Legal Disclaimer
 Neither SafeFlight, nor AirMap should be used exclusively to determine whether it is safe to fly. Unfroseen circumstances affecting the safety of flight can arise, and neither SafeFlight nor AirMap (or any similar apps, for that matter)
              can help you with those. Please use common sense and good judgement when piloting sUAS. They are not toys and are extremely dangerous if misused or mishandled.

            <form class="form-horizontal" role="form" method="GET" action="f-eval.php">

Get Started

How's the weather?

                  <input type="radio" name="options" id="sunny" autocomplete="off"> Clear

                  <input type="radio" name="options" id="cloudy" autocomplete="off"> Overcast

                  <input type="radio" name="drizzle" id="drizzle" autocomplete="off"> Drizzle

                  <input type="radio" name="rain" id="rain" autocomplete="off"> Heavy Rain

                  <input type="radio" name="thunder" id="thunder" autocomplete="off"> Thunder

              <input class="form-control" name="windspeed" type="number" placeholder="Wind speed in MPH...">

Is it daytime?

                      <input type="radio" name="day" id="day" autocomplete="off" checked> Day

                      <input type="radio" id="night" autocomplete="off"> Night

Go to this page and move to the area that your flight will be taking place. Then, look at the top left for the color of the "Warning" symbol. (triangle with "!") Please record that color below.

                      <input type="radio" name="am-greenNC" id="green" autocomplete="off"> Green

                      <input type="radio" name="am-yellow" id="yellow" autocomplete="off"> Yellow

                      <input type="radio" name="am-orange" id="orange" autocomplete="off"> Orange

                      <input type="radio" name="am-red" id="red" autocomplete="off"> Red

              <button type="submit" onSubmit="ajax();" class="btn btn-primary">Calculate Conditions</button>
            </form>

time.js
$(document).ready(function() {
    var d = new Date();
    var n = d.getHours();
    alert("jQuery loaded!");
    function ajax() {
        $.ajax({
            type: 'GET',
            url: 'https://apps.roen.us/safeflight/beta/f-eval.php',
            data: 'time=' + n
        })
    }
})

The site is at https://apps.roen.us/safeflight/beta/

A: If the ajax function is designed/intended to run at page load then the nested function needs to be called so I guess(?!) either
$(document).ready(function() {
    var d = new Date();
    var n = d.getHours();
    alert("jQuery loaded!");
    function ajax() {
        $.ajax({
            type: 'GET',
            url: 'https://apps.roen.us/safeflight/beta/f-eval.php',
            data: 'time=' + n
        })
    }
    ajax.call( this );
})

or
$(document).ready(function() {
    var d = new Date();
    var n = d.getHours();
    alert("jQuery loaded!");
    $.ajax({
        type: 'GET',
        url: 'https://apps.roen.us/safeflight/beta/f-eval.php',
        data: 'time=' + n
    })
})


text:
Q: How much health does the tank have? In some waves of the Mann vs Machine gamemode, a tank slowly rumbles towards you to deliver its own bomb.  How much damage does it take to destroy this monstrosity?

A: The health of Tanks is not fixed, it is based on the current mission and wave. This is defined within *.pop files in \tf\scripts\population.

*

*Mannworks

*

*Mission 1

*

*Wave 2: 20,000

*Wave 7: 22,500 x2

*Mission 2

*

*Wave 4: 18,000 x2

*Wave 7: 18,000 x2, 20,000 x2

*Mission 3

*

*Wave 1: 18,000 x2

*Wave 3: 20,000 x2

*Coal Town

*

*Mission 1

*

*Wave 3: 28,000

*Wave 4: 30,000

*Wave 6: 33,000

*Mission 2

*

*Wave 2: 30,000

*Wave 5: 25,000 x2

*Wave 7: 20,000 x2, 35,000 x1

*Mission 3

*

*Wave 4: 35,000

*Wave 6: 30,000 x1, 20,000 x2

*Decoy

*

*Mission 1

*

*Wave 3: 20,000

*Wave 8: 20,000

*Mission 2

*

*Wave 6: 25,000

*Wave 8: 25,000 x2

*Mission 3

*

*Wave 4: 25,000 x2

*Wave 6: 32,000 x1, 30,000 x2

Info about *.pop files: http://forums.steampowered.com/forums/showthread.php?t=2884318


text:
Q: Indenting Bash Script Output I am attempting to write a bash script and I am having difficulty making the output look neat and organized. I could fall back on just using newlines, but I would much rather have output that was easy to read. For instance, when I run git clone ..., I want to first echo "Cloning repository" and then have the output of git indented. Example output:
Cloning repository...
    Initialized empty Git repository in /root/client_scripts/jojo/.git/
    remote: Counting objects: 130, done.
    remote: Compressing objects: 100% (121/121), done.
    remote: Total 130 (delta 13), reused 113 (delta 6)
    Receiving objects: 100% (130/130), 176.07 KiB, done.
    Resolving deltas: 100% (13/13), done.

Currently, it's all compressed with no indentation. Does anyone know how to do this? I attempted with sed and awk but it didn't seem to show any more output than just Initialized empty Git repository in /root/client_scripts/jojo/.git/. I would greatly appreciate any comments.

A: A different solution that doesn't require sed:
command | (while read; do echo "    $REPLY"; done)

A: The problem with piping the output of git through any command is that git will detect that the output is not a terminal so it won't output messages which are progress messages because (typically) it is not useful to pipe a whole lot of terminal characters and progress updates to something that isn't a terminal.
To get the progress messages anyway you need to provide the --verbose option to git clone. The progress messages appear on stderr so you are likely to need a pipe something like 2>&1 | ....
Be aware the the progress messages won't appear line by line, but you'll get a lot of terminal escape codes which are designed to clear the same line. Trying to indent this output by piping through a line based tool like sed is likely to prove difficult, if not impossible. For a program that can handles input unbuffered, it should be fairly possible to look for a ^M in the output and add some spaces (or a tab) immediately aftwards, flushing as often as each batch of data is received.

A: You can filter the output from the command you want to indent through sed.
/tmp/test>cat script
#!/bin/sh

echo "Running ls -l"
ls -l 2>&1 | sed 's/^/\t/'

/tmp/test>sh script
Running ls -l
        total 4
        -rw-rw-r-- 1 hlovdal hlovdal 55 2009-11-03 23:36 script
/tmp/test>

The sed command will replace the beginning of the line (before the first character) with a tabulator, i.e. insert a tabulator at the very beginning of the line.
Updated to also indent stderr.

A: Pipe through
sed "s/^/    /g"

This will replace the (zero-width) anchor for line start by four spaces, effectively adding four spaces at the start of the line.
(The g does this globally; without it, it will only do it once, which would do the first line.)

A: Since the awk solution wasn't posted yet:
$ echo -en "hello\nworld\n"
hello
world
$ echo -en "hello\nworld\n" | awk '{print "    "$0}'
    hello
    world


text: Q: Perforce Integrate files from another server I was reading this How to create private remote perforce branches and push to it? so I thought this would be a good place to post and talk about my issue. I have a p4 server hosted on a physical machine in my office. However, I'm trying to migrate it to the cloud running Ubuntu 20.04. It's currently running on Windows Server. I've read this guide: https://community.perforce.com/s/article/3080 however, the problem here is that this completely overrides the current data on p4. What I want to do is simply merge the data or append it from my other server to my new master server. Does anyone know if this is possible? The goal is to migrate from windows to linux, without overriding the default depots on a linux setup.


text:
Q: How to handle analytics on PWA when it is deployed both as an web app and an TWA in Play Store How should I integrate analytics into a PWA webapp ? if I add analytics from google analytics into webapp and publish it in a server, then later, if I want to publish it on Google Play Store, how should I track the use?
here's the scenario:

*

*I'm deploying the PWA from a subdomain.

*then I'm publishing the PWA from Google Play Store as a TWA.

My concerns:
Should I use the google analytics snippet for web to track the subdomain-based pwa and firebase analytics for my Google Play Store app?
Or,
Can I use a single method to track both versions at the same time?
I have found this faq of chrome developer about use of google analytics

The CPA library follows the basic usage pattern of Google Analytics and will feel familiar to existing users of Google Analytics. However, unlike the web-centric official Google Analytics JavaScript libraries, the CPA library uses an "app-centric" model that is better suited for Packaged Apps. Among other features, the library provides methods for specific types of hits, such as "event" and "appView", and it can be used in both Closure-based and traditional JavaScript projects.

I am using Vuejs as frontend with pwa template, not sure if it is applicable for my use case. Any suggestion or direction would be much appreciated.

A: I am using THIS - Web + App configuration.
Using this you can track both at the same time.
You can configure it easily in firebase - see HERE for more


text:
Q: A page has multiple UITextField the keyboard cannot be hidden There is a UIScrollView, contentView of scrollView have a UINibView, UINibView have three UITextField:
Action of first UITextField: display a custom view;
Action of second UITextField: show system keyboard;
Action of third UITextField: display a custom view.
Click the second one first, then click the first, the keyboard cannot be hidden at this time.
kehuiInfoView.dateInput.rx.controlEvent(.editingDidBegin)
            .subscribe { _ in
                weakSelf?.view.endEditing(true)
                weakSelf?.kehuiInfoView.dateInput.resignFirstResponder()
                weakSelf?.datePicker.show()
            }
            .disposed(by: bag)

A: If your text field is supposed to use a date picker for its input, you can consider using this: https://github.com/danielt1263/CLE-Architecture-Tools/blob/main/Tools/UITextField%2BWheeledDatePicker.swift
With the above, you could for example call:
let date = textField.wheeledDatePicker(initial: Date(), formatter: dateFormatter) { $0.datePickerMode = .date }

Which will handle bringing up and dismissing the date picker for you.


text:
Q: TtlExpired status while trying to ping the server I am using below code to check whether server is available or not
bool isReachable = false;

        Ping pinger = new Ping();
        try
        {
            PingOptions opt = new PingOptions(255, false);
            PingReply reply = pinger.Send("www.stackoverflow.com", 1000, new byte[32], opt);

            isReachable = reply.Status == IPStatus.Success;
        }
        catch (PingException)
        {
            // Discard PingExceptions and return false;
        }

I am not getting Success status from server instead I am getting as System.Net.NetworkInformation.IPStatus.TtlExpired.
I tried different hosts like www.google.com, www.wikipedia.org, but not getting success status from server. I am able to ping without any problem in command prompt
I tried without ttl option, but same response only.
PingReply reply = pinger.Send("www.stackoverflow.com");
isReachable = reply.Status == IPStatus.Success;

A:             PingReply reply = pinger.Send("www.google.com/");

should be
            PingReply reply = pinger.Send("www.google.com");


text:
Q: Python wrong SSL version using requests I have been struggling with this problem since I installed python on a new PC.
Basically, I have the https request:
import requests
import ssl

proxies = {
    'https': "https://myproxyhere"
}

r = requests.get('https://example.com', proxies=proxies, timeout=10)
print(r.text)

On the other PC it works fine, but on this one it gives that error:
```(Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1122)')))```

I had openssl 1.1.1h installed and python 3.9 had openssl version 1.1.1g. However, I downgraded my openssl to 1.1.1g, and still the error persists, I'm not able to do SSL requests, using proxies.
Keep in mind that the proxies are not the cause, as i have the same exact piece of code working fine on my other laptop, however i bought a Windows Surface Pro and when i did this fresh install, im not able to make this work. Ive tried everything so far, from trying other versions of openssl and python.
Does someone have a clue on how to fix this?
Full Error Traceback:
Traceback (most recent call last):
  File "C:\Users\gonca\Desktop\debug.py", line 9, in <module>
    r = requests.get('https://example.com', proxies=proxies, timeout=10)
  File "C:\Users\gonca\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\gonca\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\gonca\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\gonca\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\gonca\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1122)')))

Edit:
For people that face this error, the solution was down-grading the requests module, it was bugged.

A: There is a bug in requests-2.25.1. I have to downgrade to 2.24.0
pip install requests==2.24.0


text:
Q: Bind List to combobox I cannot create a class or my own object so I thought I would use a List<KeyValuePair> to store two properties and then bind this object to a combobox.
However, I cannot see how I can set the valueField and TextField in the combobox.
The code.
List<KeyValuePair<int, string>> kvpObject =
 new List<KeyValuePair<int, string>>();

foreach (User u in m_users) {

    kvpObject.Add(new KeyValuePair<int, string>(u.ID, u.Name));
}

// Bind Add Users combobox
cmboBox.DataSource = kvpObject;
cmboBox.ValueField = "????" // Maybe something like kvpObject[0]..
cmboBox.TextField  = "????";
cmboBox.DataBind();

Does anyone know what I need to put inside the ????.

A: I think it should be like this:
cmboBox.ValueField = "Key";
cmboBox.TextField  = "Value";

Because you are using the KeyValuePair. The properties is Key and Value
Update:
I also have a suggestion. Instead of using a for loop. Then you can use Linq to bind it to the datasource of the combobox. Something like this:
cmboBox.DataSource = m_users
                      .Select (s =>new KeyValuePair<int,string>(s.ID,s.Name))
                      .ToList();
cmboBox.ValueField = "Key";
cmboBox.TextField  = "Value";
cmboBox.DataBind();

Remember to include System.Linq;


text:
Q: Authorizations for editing and (re)processing IDocs I'm looking into the risk of unauthorized transactions through access to editing existing IDocs and reprocessing them.
In below scenarios, the following characteristics are applicable:

*

*User Y belongs to the finance department and has access to financial
transactions in SAP.

*User Y has created the IDOC (related to financial transaction).

*User X belongs to the HR department and has NO access to financial transcations in SAP.

*User X has T-code level access to changing IDOCS.

My question is, which of these scenarios is the correct one and what is the technical reasoning behind it?

*

*User X can edit an existing IDOC and reprocess it successfully because the IDOC/system checks the authorization of the IDOC creator (in this case: User Y).

*User X can edit an existing IDOC and reprocess it successfully because the IDOC is in the queue and does not check for additional authorization.

*User X can edit an existing IDOC but can NOT reprocess it because the IDOC/system checks the authorization of the IDOC changer (in this case: User X).

A: You can create authorization object for IDOC message type, so user can not edit or send unauthorized message type. Otherwise user can 1,2 or 3. Details are here: http://sambitsapbasis.blogspot.com.tr/2009/08/special-authorization-object-for-idoc.html

A: Assuming User X created outbound IDoc and User Y received this inbound IDoc, the following endings will be real for your scenarios:

*

*False

*False

*True

You have to get it clearly: sender has nothing to do with processor of the IDoc, only processor matters. SAP even recommends to cut sender's authorizations to minimum and process IDocs collectively in background in order to eliminate need for granting additional authorizations.
Generally, IDocs authorizations model is run around these objects, the most important from which are S_IDOCMONI and S_IDOCCTRL, and the general rule is:

if user has authorization to disply IDocs (which is controlled by
  S_IDOCMONI), he also able to send it.

If you want to restrict certain IDoc types for viewing and processing in BD87, you have to implement SAP note 1269516.


text:
Q: MySQL Regexp, ignore letters inside parentheses I need to check whether a string contains all caps. However, it should ignore anything inside parentheses. Any non-letters are OK, too.
These should give true:
select binary  "ALL CAPS"         regexp "the expr"  from dual;
select binary  "CAPS (in paren)"  regexp "the expr"  from dual;
select binary  "ALL 1:,? CAPS "   regexp "the expr"  from dual;

This should give false:
select binary  "Not All CAps"     regexp "the expr"  from dual;

I thought about first doing a replace to remove anything in parentheses, but there doesn't seem to be a way to do a replace with regular expressions.

A: This allows anything inside a parenthesis pair, caps only outside.
^[^a-z]*(\(.*\))?[^a-z]*$

EDIT: some asterisks were missing.


text:
Q: Android 13 ..Lab SIM device boots with a Operator XAA, not the PLMN as defined on SIM IMSI PLMN I have a specific issue. The Device SIMs used  in Lab tests have ICCD ..includes a PLMN usually 001 or 002 this is the PLMN or operator ID ..Android 11 or later loads( after reboot)  the operator profile with PLMN 002..I notice this change,  earlier the profile loaded was extracted from the PLMN defined on the IMSI e.g say 311 311 ( MNC)..is there any Telephony check or any way to disable via ADB commands to load the profile as defined by IMSI PLMN and not ICCID..? The device is a late Samsung ..
rebooted a Samsung device with Lab( Test) SIMs..


text:
Q: How to recover a messed-up git submodule? I git submodule add'ed a submodule at a wrong directory.
I git rm'ed the submodule and then git submodule summary returned fatal: Not a git repository: '<path to the deleted submodule>.git'.
I used grep -r '<path to the deleted submodule>' to remove all references to the deleted directory.
There was only one reference left to the deleted directory, which was in .git/index (binary file).
But git submodule summary still gives fatal: Not a git repository: '<path to the deleted submodule>.git'.
How should I fix it?

A: Double-check:

*

*the content of your .gitmodules file

*the content of .git/modules subfolder

If you remove any reference of the submodule you git rm'ed, that should be better.
Also, make sure you try again a git rm mysubmodule, without any trailing slash.


text:
Q: Get data with publish unpublish date using mysql? I have pubish and unpublish date for news. Now I want to dynamically select all news whose current date lies in between publish date and unpublish date.
I have description, publish_date and unpublish_date as table columns.
Do I have to do mysql union or is there some other simple ways

A: You should go for the between operator:
WHERE 'current date' BETWEEN publish_date AND unpublish_date

This only works if your publish_date and unpublish_date are of type date!
In case you are using TEXT or VARCHAR as column type you could use:
TO_DATE(publish_date, 'DD/MM/YYYY')

To convert from Text to date with specified format


text:
Q: Почему раскрывающийся список остается пустым, хотя переменная инициализирована Изучаю Vue js, возникла необходимость инициализировать массив (listProductType) с помощью запроса на бекэнд до открытия страницы с последующим отображением в виде раскрывающегося списка. Переменная инициализирована, в консоль выходит, но список остается пустым.
Просьба сказать что я делаю не так, где ошибка?
HTML:

Введите тип продукта

        <input id="idProductType" v-model="nameOfProductType" placeholder="Введите тип продукта">
        <button id="sendProductType" @click="getAlert">Сохранить</button>

Выберите тип продукта

        <select>
            <option selected="selected" disabled>Выберите тип продукта</option>
            <option v-for='index in listProductType'>{{index.id}} / {{index.name}}</option>
        </select>

main.js:
var vm = new Vue({
    el: "#sendForm",
    data:{
        nameOfProductType: "",
        listProductType: []
    },
    beforeCreate:() => {
        new Promise((resolve, _) => {
            axios
            .get('http://localhost/admin/getListProductType')
            .then(response => {
                resolve(this.listProductType = response.data);
                console.log(listProductType);
                });
        })
    },
    methods:{
        getAlert(){
            var productType = {
                    name: this.nameOfProductType
                };
            //console.log(productType)
            axios({
                method: 'post',
                url: 'http://localhost/admin/addProductType',
                data: productType
            });
        }
    }
});

A:
Не используйте стрелочные функции в свойствах экземпляра и в коллбэках, например created: () => console.log(this.a)

Помогло:
beforeMount(){
    axios.get('http://localhost/admin/getListProductType')
    .then(response => {
        this.listProductType = response.data
    })
}


text:
Q: Unable to locate words in phrases in text files using python I am trying to locate words and phrases contained in multiple text files.  My code will locate the words but it is completely missing the phrases.  Can anyone suggest a better way of doing this?  Regular expressions may taker too long given that I have several thousand txt files.
My code is as follows.
import glob

work_list = ['at least', 'from time to time', 'in effect', 'greater than', 'lower than',
'more than', 'up to', 'approximate', 'approximately', 'at the same time']

path = 'D:/Testing10'

context_d = {} # this will be used later
for filename in glob.glob(os.path.join(path, '*.txt')):
    # if filename.endswith('.txt'):
        f = open(filename)
        file = f.read()
        txt = file.lower()
        txt = txt.split()
        txt = [item.replace('May', '') for item in txt] # locate and replace all months of May before lowering
        txt = [item.replace('\n', '') for item in txt]
        txt = [item.replace('\\n', '') for item in txt]
        txt = [item.replace('\\', '') for item in txt]
        txt = [item.replace('\\s', '') for item in txt]
        y = range(len(work_list))
        for i in y:
            if work_list[i] in txt:
              print(work_list[i], "found in filename", filename)
            else:
              print("not found")```

A: You can iterate through your work_list and look in the text file without chopping up the text file into words and phrases, assuming that the text file contains one continuous piece of text.  You may have to eliminate line returns if you have any in your text file:
work_list = ['at least', 'from time to time', 'in effect', 'greater than', 'lower than',
'more than', 'up to', 'approximate', 'approximately', 'at the same time']

path = 'D:/Testing10'

context_d = {} # this will be used later
for filename in glob.glob(os.path.join(path, '*.txt')):
    # if filename.endswith('.txt'):
    f = open(filename)
    file = f.read()
    txt = file.lower()
    for element in work_list:
        if element in file:
            print(f'"{element}" found in file {filename}')

#Sample output:

"at least" found in file data_files/sample.txt
"from time to time" found in file data_files/sample.txt
"greater than" found in file data_files/sample.txt
"lower than" found in file data_files/sample.txt
"up to" found in file data_files/sample.txt
"approximate" found in file data_files/sample.txt


text:
Q: boost::locale::date_time: How to get data from date_time object in Boost C++? I'm trying to handle dates and times in my code, and have been pointed in the direction of the boost library - specifically, boost::locale::date_time (in part because this lets me avoid Daylight Saving Time weirdness that was making my previous implementation difficult).
However, I'm getting inconsistent results.  When I store a date in the date_time object and later try to get data from it, it is incorrect.  Here's an example:
#include <boost\\asio\\error.hpp>
#include <boost\\locale.hpp>
using namespace std;

int main()
{
    // Necessary to avoid bad_cast exception - system default should be fine
    boost::locale::generator gen;
    std::locale::global(gen(""));

    // Create date_time of 12/19/2016
    boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(12) + boost::locale::period::day(19);

    unsigned int month = dt.get(boost::locale::period::month());
    unsigned int day = dt.get(boost::locale::period::day());
    unsigned int year = dt.get(boost::locale::period::year());

    cout << month << "/" << day << "/" << year << endl;

    // Expected output:  12/19/2016
    // Actual output:    0/19/2017
}

What am I doing wrong?  I just want to extract the saved days, months, years, hours, etc.
Thank you.
EDIT:  It's possible I'm initially setting the date_time in an incorrect manner.  Is there a better way to explicitly set a date time (for instance, to 12-19-2016), assuming I have all the relevant data in integer (not string) format?

A: 2016-04-05 + 12 months = 2017-04-05. This makes sense, since 12 months is a whole year.
Try adding 11 months instead, then increment to adjust from a 0-based month to a 1-based month.
boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(11) + boost::locale::period::day(19);

uint month = dt.get(boost::locale::period::month()) + 1;
uint day = dt.get(boost::locale::period::day());
uint year = dt.get(boost::locale::period::year());

cout << month << "/" << day << "/" << year << endl;


text:
Q: Prove that one can choose evenly many objects from a collection of objects in $2^{n-1}$ ways. Here is the solution -
Let us prove that the number of subsets of the given set of objects with evenly many elements is the same as the number of subsets with oddly many objects. We begin by choosing one of the objects-say, $A$, which will play a special part further in the solution. Now, we will split all the subsets in pairs in such a way that each pair consists of two subsets, one of which always has evenly many elements and another which contains oddly many elements. To do this, we consider one arbitrary subset of the given set of objects and, if it contains $A$ as its element, we remove $A$ from it; if it does not, we add $A$ to it. The resulting subset will be in the same pair with the original one, and the number of elements in these two subsets have different parity. It is easy to see that if the subset $S$ generates the subset $S'$ ,then this construction applied to $S'$ gives us $S$. Therefore, we have the required splitting, and the proof is complete.
Can you re-engineer the same proof so that it's more understandable? Or can you explain the same proof in a simpler way?

A: Consider $S = {1,2,3}$
All subsets $= \{\}, \{1\}, \{2\}, \{3\}, \{1,2\}, \{2,3\}, \{3,1\}, \{1,2,3\}$
Let $3$ be the special number.
Take the first subset. And we by adding $3$, we get {} and {3}
And for second subset, we get $\{1,3\}$ and $\{1\}$
This construction shows that we have now pairs of subsets, where the pairs are of opposite parity.
Therefore we are done.


text:
Q: how can i solve this problem of dart null safety this the screenshot of the error that i found

A: The compiler can't see what type data is, so it considers it as type Object. Object doesn't have a [] operator. Assuming that data is actually a Map you can try to replace
var data = doc.data();

with
Map? data = doc.data() as Map?;

Although there might be a nicer way to write this, but that's hard to know without seeing more of your code. Usually you can indicate the type already somewhere above it by using <Map> at the right place


text:
Q: How can I generate cluster graphs from java output? I am looking for something similar to GraphViz, but that would allow me to generate the graphs without having to install the program on the computer. As I understand, I would have to make external calls to the program after generating a DOT file in order to make this work, but I would like to package my program into an executable jar file that runs as a Stand alone app. Is there something that would allow me to do this with JAVA?
If there are any good tutorials out there please link them here.


text:
Q: prepareForSegue method in iOS7 I used the storyboard for the project.The problem is it cannot push to the Function1DetailViewController.Moreover, since the tableview do not have the cell inside,I don't know how to draw the segue to link between the two view controllers. Also, I don't know how to write the prepareForSegue method.
Should I also need to make some changes in didSelectRowAtIndexPath method?
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *tempSqlStatement = @"";
    NSString *tempString = @"%";
    databaseName = @"TCMdb8.sql";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    if (buttonNum == 0) {
        Function1DetailViewController *function1DetailViewController = [[Function1DetailViewController alloc] initWithKey:[listOfItems objectAtIndex:indexPath.row] type:@"1"];
        [self.navigationController pushViewController:function1DetailViewController animated:YES];
    } else if (buttonNum != 0){
        if (buttonNum == 1) {
            tempSqlStatement = [NSString stringWithFormat:@"select name from Medicine where stroke ='%@' ORDER BY length(name) ASC", [listOfItems objectAtIndex:indexPath.row]];
        }
        function1SQLStatement = [tempSqlStatement UTF8String];
        [self checkAndCreateDatabase];
        [self readFromDatabase];
        [tableList reloadData];
        buttonNum = 0;
    }
}

A: You can draw a segue between two view controllers in storyboard.  Select the whole view controller (best to click where the status bar would be), ctrl-drag to the other.  Give that new segue an identifier.
When you want to trigger it in the view controller:
[self performSegueWithIdentifier:@"TheIdentifierYouPutInIB"];

You can replace the navigation logic in your didSelectRowAtIndexPath method with the above.  See here for prepare for segue example.

A: Here are different ways to create a segues:
1 - From Cell To detail Controller:

2 - Using Connection Inspector

3 - From View Controller to View Controller

*

*#1 and #3 you will need to hold control before
dragging.

*#2 & #3 :
You will need to give an identifier to your segue, unlike #1 You have to performe the segue using code:

add identifier:

Perform the segue:
[self performSegueWithIdentifier:@"Function1Segue" sender:sender];

Now here is the thing, this will just perform the segue, if you ever needed to pass some data to that view controller. Then you have to implement the following segue deleguate:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"Function1Segue"])
    {
       NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        // Get reference to Function1DetailViewController
       Function1DetailViewController *functionVC =
                (Function1DetailViewController *)segue.destinationViewController;
       functionVC.item = [listOfItems objectAtIndex:indexPath.row] type:@"1"];
    }
}

functionVC.item because you would have a property called item that you want to set in Function1DetailViewController.

A: select the view controller icon (yellow below source view controller) and drag it to destination view controller. You'll be able to call it by program.


text:
Q: JOptionPane cursor I have some problem with the cursor when using JOprionPane. I set a cursor to the pharent frame, then show a dialog using this:
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String) JOptionPane.showInputDialog(MagicCollectorClient.getMainFrame(),"Complete the sentence:\n\"Green eggs and...\"",
            "Customized Dialog",JOptionPane.PLAIN_MESSAGE,null,possibilities,"ham");

It show the dialog, but change the cursor to the default system cursor until I close  the dialog. is there any way to fix this?

A: How about an SSCCE? Yes it's possible, you have to "unbundle" the JOptionPane from the static method helper as you wish to do something special with it. This unfortunately means you have a little more work to do, but nothing too scary.
public static void main(String[] args) {
    JFrame parent = new JFrame();
    parent.setSize(400, 400);
    parent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    parent.setVisible(true);

    Object[] possibilities = { "ham", "spam", "yam" };

    // raw pane
    JOptionPane optionPane = new JOptionPane(
            "Complete the sentence:\n\"Green eggs and...\"",
            JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null,
            possibilities, possibilities[0]);

    // create a dialog for it with the title
    JDialog dialog = optionPane.createDialog("Customized Dialog");

    // special code - in this case make the cursors match
    dialog.setCursor(parent.getCursor());

    // show it
    dialog.setVisible(true);

    // blocking call, gets the selection
    String s = (String) optionPane.getValue();

    System.out.println("Selected " + s);
}


text:
Q: Arithmetic operations in the head of a clause I am a writing Prolog predicate that would compare some point (myPosition(2,2)) in Cartesian coordinate system with some other point in the neighbourhood. As a result, it should show the direction (north, east, south, west) that we should choose to get from myPosition(2,2) to that point. Here is the code of my .pl file:
myPosition(2,2).

turn_to_east(X+1,Y) :-
    myPosition(X,Y),
    write('East.').

turn_to_west(X-1,Y) :-
    myPosition(X,Y),
    write('West.').

turn_to_north(X,Y+1) :-
    myPosition(X,Y),
    write('North.').

turn_to_south(X,Y-1) :-
    myPosition(X,Y),
    write('South.').

turn_to_the_point(X,Y) :- turn_to_east(X,Y).
turn_to_the_point(X,Y) :- turn_to_west(X,Y).
turn_to_the_point(X,Y) :- turn_to_north(X,Y).
turn_to_the_point(X,Y) :- turn_to_south(X,Y).

Then, when I upload the file to SWI-Prolog and write:
turn_to_the_point(1,2).

I get just:
false.

Why can't I get the answer 'West.' or any other?

A: The reason is that by default Prolog does not interpret +, - and other arithmetic operators. 1+1 is simply 1+1 (this is syntactical sugar for +(1,1)), not 2. This could be useful if you for instance would like to define your own expression evaluator, and you see + as the boolean sum, or something completely different.
There is however one way to collapse such expression such that it derives 2 out of 1+1 using the (is)/2 predicate. For instance:
turn_to_east(NX,Y) :-
    myPosition(X,Y),
    NX is X+1,
    write('East.').

Given you query turn_to_east/2 with turn_to_east(1,2), NX = 1. Now you fetch the myPosition/2 data: X = 2 and Y = 2. Prolog does an equivalence check in the meantime and sees that the Y-coordinate of turn_to_east/2 is the same as the one of myPosition. Next it collapses 2+1 to 3 and sees that this is not equivalent to NX = 1 so this predicate fails. But if you had queried turn_to_east(3,1) it would have succeeded and thus write East..
If you modify your entire theory with the above discussed concept, like:
myPosition(2,2).

turn_to_east(NX,Y) :-
    myPosition(X,Y),
    NX is X+1,
    write('East.').

turn_to_west(NX,Y) :-
    myPosition(X,Y),
    NX is X-1,
    write('West.').

turn_to_north(X,NY) :-
    myPosition(X,Y),
    NY is Y+1,
    write('North.').

turn_to_south(X,NY) :-
    myPosition(X,Y),
    NY is Y-1,
    write('South.').

turn_to_the_point(X,Y) :- turn_to_east(X,Y).
turn_to_the_point(X,Y) :- turn_to_west(X,Y).
turn_to_the_point(X,Y) :- turn_to_north(X,Y).
turn_to_the_point(X,Y) :- turn_to_south(X,Y).

It answers the query correctly:
?- turn_to_the_point(1,2).
West.
true ;
false.

A note in general is that predicates better not have side-effects like write/1 stuff: this is not only for Prolog, almost all programming languages advice to split a program into calculation and interaction. Perhaps a better way to solve this, is to see the direction as an parameter:
myPosition(2,2).

turn_to_point(NX,Y,east) :-
    myPosition(X,Y),
    NX is X+1.
turn_to_point(NX,Y,west) :-
    myPosition(X,Y),
    NX is X-1.

turn_to_point(X,NY,north) :-
    myPosition(X,Y),
    NY is Y+1.

turn_to_point(X,NY,south) :-
    myPosition(X,Y),
    NY is Y-1.

turn_to_the_point(X,Y) :-
    turn_to_point(X,Y,D),
    write(D).

In that case the turn_to_the_point/2 predicate is clearly an interaction predicate whereas its turn_to_the_point/3 variant does computations.


text:
Q: If $ABC$ is invertible, then show matrices $A$, $B$, and $C$ are all invertible. In Linear Algebra, I am working with inverting matrices and doing proofs. The exact question is:
Show that if $ABC$ is invertible, then $A, B, C$ are all invertible.
Each matrix is a $n\times n$ matrix, but I do not understand how to show that each individual matrix is invertible.

A: Hints:
$M$ is invertible iff $\det(M)\ne0$.
$\det(ABC)=\det(A)\det(B)\det(C).$

A: You only really need to show that, if $AB$ is invertible, then $A$ and $B$ are invertible. If you then have $ABC = (AB)C$ is invertible, then $AB$ and $C$ are invertible (by the simple result), and hence $A, B, C$ are all invertible (by the simple result again).
Another thing to think about is that this is a property that is going to rely on finite-dimensionality in some way. The result is not true for infinite matrices (or, more generally, operators on infinite-dimensional spaces). So, expect finite dimensions to come in some way. There's a few ways to attack this problem, but all of them will make use of the finite-dimensionality of the problem.
Here's one way. Recall that, in finite dimensions, if $MN = I$, where $M$ and $N$ are square matrices, then $NM = I$ too, i.e. $M = N^{-1}$. Then, if $D = (AB)^{-1}$, then
$$I = (AB)D = A(BD).$$
Therefore, $A$ is invertible, and $BD = A^{-1}$. Similarly,
$$I = D(AB) = (DA)B,$$
so $B$ is invertible with inverse $DA$.

A: It is enough, by induction, to show that if $AB$ is an invertible matrix, then both $A$ and $B$ are invertible. By definition, we have a matrix $C$ such that $(AB)C=I$ (where $I$ is the identity matrix.) Now, obviously, by the associative property, we see that $A(BC)=I,$ so $BC$ is an inverse of $A.$ In other words, $A$ is invertible.
The same argument applies for $B,$ since $C(AB)=I,$ so $CA$ is an inverse of $B.$
(Note: this argument applies for any ring.)

A: If exists $X$ such that $(ABC)X=\mathbb1$ then $X$ has inverse too, and $BCX$ is the inverse of $A$. Then $BC=A^{-1}X^{-1}$. But also $(XAB)C=\mathbb1$, hence $C$ is invertible. So $B=(CXA)^{-1}$ then $B(CXA)=\mathbb1$, that is $B$ is also invertible.


text:
Q: non-static method count(int) cannot be referenced from a static context this is N queens problem that i try to solve ,but i have this problem of non-static method .. how can i solve it .....
*> at the count(int) method .. i don't understand how to solve this problem

error: non-static method count() cannot be referenced from a static context

import java.util.*;

 public class NQueens {
static int n;
int[][] board = new int[n][n];
public static void main(String[] args) {

    //int result;
    int col = 0;
    Scanner input=new Scanner(System.in);
    n=input.nextInt();
    if(n < 4)
        System.out.println("the result is 0");
    else
        count(0);

}

int cnt=0;
void  count(int col){
    if(col == n){
        cnt++;
        System.out.println("the result is " + cnt);
    }

    else{
        for(int row=0 ; row<n ; row++){
            if(placeQueen(row, col))
                count(col+1);
            else
                removeQueen(row , col);
        }
    }

}

boolean placeQueen(int row , int col){
    boolean x =false;
    if(validPlace(row , col)){
        setQueen(row , col);
        x = true;
    }
    return x;
}
boolean validPlace(int row ,int col){
    boolean x = false;
    if(board[row][col] != -1)
        x=true;
    return x;
}
void setQueen(int row , int col){
    board[row][col] = 1;
    killCell(row , col);
}
void killCell(int row , int col){
    for(int i=col+1 ; i<n ; i++)
        board[row][i] = -1;
    for(int k=col+1 ; k<n ; k++){
        for(int j=0 ; j<n ; j++)
            if(Math.abs(row-j) == Math.abs(col-k))
                board[j][k] = -1;
    }
}
void removeQueen(int row , int col ){
    board[row][col] = 0;
    refreshCell(row , col);
}
void refreshCell(int row , int col){
    for(int i =col+1 ; i<n ; i++)
        board[row][i]=0;
    for(int k=col+1 ; k<n ; k++){
        for(int j=0 ; j<n ; j++)
            if(Math.abs(row-j) == Math.abs(col-k))
                board[j][k]=0;
    }
}

}

A: Your main method is a static method and has no instance of your class until it creates one. You cannot call the count(int) method unless you have an instance of the class.  Try this instead:
public static void main(String[] args) {

    //int result;
    int col = 0;
    Scanner input=new Scanner(System.in);
    n=input.nextInt();
    if(n < 4)
        System.out.println("the result is 0");
    else {
        NQueens nq = new NQueens();
        nq.count(n);
    }

}

Another problem is that your count(int) method tries to refer to the 'n' variable.  It cannot because it's only existing in the static main method.  You have to pass 'n' to the count method so it can see it. If you want to initialize the class with a starting value, perhaps you need a constructor that takes that value instead, like this:
public void NQueens(int starting_n) {
    start = starting_n;
}

Then in main you'd use NQueens nq = new NQueens(n); to create your object.  You'd also have to define int start = 0; in your class so it has a place to store the value being passed in.


text:
Q: TypeScript defining key and value for Object probably with discrimination union I want to define what kind of value is permitted inside an object, based on a defined interface/type:
type StorageValuesSyncOptions = {
  toDoOrNotToDo: boolean,
  piecesOfEight: number,
  poem: string,
};

type SyncOptions<Options extends StorageValuesSyncOptions = StorageValuesSyncOptions> = {
  [key in keyof Options]: SyncOption<Options, Options[key]>;
};

type SyncOption<K, V> = {
  id: keyof K,
  value: V,
};

As long as I use SyncOptions I have a guarantee that 'SyncOption' is on the format specified in StorageValuesSyncOptions. However I want to flesh out the generics of SyncOption so that it will be locked in that way. I think I need to use a discriminated union, and a default value would be nice so I didn't need to specify the generics.
As an example this works as expected:
const options: SyncOptions = {
  toDoOrNotToDo: {
    id: 'toDoOrNotToDo',
    value: true, //3 will result in an error
  },
  piecesOfEight: {
    id: 'piecesOfEight',
    value: 7, //"string" will result in an error
  },
  poem: {
    id: 'poem',
    value: "You and me", // true will not work
  },
};

I would like this to result in an error:
  const poem: SyncOption = {
    id: 'poem',
    value: true //"but a string" should be valid
  },


text:
Q: Detecting when shared element transition has finished I need to know when does a shared transition finishes between activities.
I have ActivityA and ActivityB and I have tried setLayoutAnimationListener, setEnterSharedElementCallback, setExitSharedElementCallback, onEnterAnimationComplete and every answer in How to know when Shared Element Transition ends in the ActivityB
In any case, I have my shared element transition working, but the callbacks are called when the animation is started and not when it has finished.