text:
Q: R - ggplot2 - geom_area - Remove break in color fill under a geom_line For the data:
   year     N cumulative time.period
1  2000   100        100        blue
2  2001   100        200        blue
3  2002   100        300        blue
4  2003   100        400        blue
5  2004   100        500        blue
6  2005   100        600         red
7  2006   100        700         red
8  2007   100        800         red
9  2008   100        900         red
10 2009   100       1000         red

I want to first plot the line for "cumulative" and then color it using the "time.period" variable.  After that I want to fill in the area below the line using the same "time.period" variable.  Here's my code for generating that plot:
library(dplyr)
library(ggplot2)

year<-2000:2009
N <- rep(100, 10)

DF<-as.data.frame(cbind(year, N))

DF <- DF %>%
 mutate(cumulative = cumsum(N)) %>%
 mutate(time.period = ifelse(year<2005, "blue", "red"))

 ggplot(DF, aes(x=year, y=cumulative)) +
  geom_line(color=DF$time.period) +
  ylab("Cumulative count") +
  geom_area(aes(fill=DF$time.period)) +
  scale_fill_manual(values=c("blue", "red"))

This generates the following plot:

I then get a gap in the fill for year 2004.  How can I adjust my code so that there are no breaks in the coloring for geom_area fill?

A: Since you are working with count data, I think it is reasonable to visualize your data using a bar chart.  The figure will need to be cleaned up a bit, but this eliminates the broken part of the visualization.
DF <- structure(list(year = 2000:2009, N = c(100L, 100L, 100L, 100L,
100L, 100L, 100L, 100L, 100L, 100L), cumulative = c(100L, 200L,
300L, 400L, 500L, 600L, 700L, 800L, 900L, 1000L), time.period =
structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
.Label = c("blue", "red"), class = "factor")),
.Names = c("year", "N", "cumulative",
"time.period"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10"))

ggplot(DF, aes(year, cumulative, fill = time.period)) +
geom_bar(stat="identity", position = "identity")


text:
Q: Is there a version of Windows OS that will allow a bootable disc beyond 2 TB capacity? I have a shiny new 5TB WD Black and was hoping to use it as the OS System disc and for a fair number of audio production programs, Workstations, samplers, synthesizers and such. Moving from a 2TB. The new drive loses nearly 3 TB as "unallocated space" if run direct from the Win7 program disc. I reset the drive, initialized it in GPT, got back all 5 TB but can't put the OS there. Do any newer versions allow this or do I go backwards to a 4 year old 2 TB that's in the habit of crashing to bluescreen at least daily and use the new one for all programs but windows? (I'm backing the old drive up using Acronis in total as I type, (tired of rebooting ). Win 10 upgrades are free right now...will this change allow me to increase the storage on my system while using a new drive for the system? Old format has 2TB OS + programs, 3TB full of samples, 2 x 3TB as RAID backup system, too many usb drives to list when I need to empty stuff out......Thank in advance!

A: Quite simply your motherboard is too old. Buy (or use) a smaller drive as your boot disk and use the new one for bulk storage.
From Table 3: Windows support for combinations of boot firmware and partitioning schemes for the boot volume at Windows support for hard disks that are larger than 2 TB Microsoft does not support BIOS + GPT as a boot volume, nor does it support UEFI + MBR.  You either use BIOS + MBR (limited to <2TB boot disk) or you make sure your firmware is UEFI based and use GPT with full large disk support.
System        BIOS + MBR   UEFI + GPT                  BIOS + GPT                   UEFI + MBR
Windows 7     Supported    Supported; (64-bit only)   Boot volume not supported     Boot volume not supported
Windows Vist  Supported    Supported; (64-bit only)   Boot volume not supported     Boot volume not supported
Windows XP    Supported    Not supported              Boot volume not supported     Boot volume not supported

I fought this a short while ago and found out that while Windows itself supports GPT disks, it does not support booting from a GPT disk on a BIOS based system. If you want to use your disk to boot from then you need a UEFI based motherboard.
Linux seems to be able to work around this, but Windows doesn't seem to care to.
The only reliable way around this restriction is to use a <2 TB disk as your boot/system disk, Windows is perfectly happy using a GPT disk as a bulk data disk without BIOS involvement.  I ended up buying a 240 GB SSD then installing and booting from that.
PC World has a nice article describing the problem: Everything You Need to Know About 3TB Hard Drives
Essentially though, the MBR partition scheme cannot support disks greater than 1.7 TB, and BIOS does not support booting from anything other than an MBR disk. There are workarounds but they're all horrific kludges and will block you from installing Windows.
I actually managed to make one of the kludges work, but it only worked until Win10 threshold 2 was released. The th2 installer basically ran the full operating system install from scratch and it was at this point I was unable to upgrade because the installer didn't "see" the disk as valid in able to update itself.

A: You haven't said how old your motherboard is, or what features it supports. Mokubai may be correct, but if your computer was introduced in mid-2011 or later, it may already use UEFI firmware, which supports booting from a GPT disk. Even a few older motherboards use EFI. You'll need to re-install in EFI mode, though; most EFIs include a Compatibility Support Module (CSM), which enables them to boot in BIOS/CSM/legacy mode. It sounds like you're using that now (or have an older BIOS-only motherboard).
If your motherboard is an older BIOS model, you have a few options, most of which you won't like:

*

*Use only 2TiB of your disk's space.

*Return the disk and get a smaller ~2TB disk to replace it.

*Split the disk such that one to three partitions fall entirely under the 2TiB mark, and one final partition extends from just under the 2TiB mark up to just under 4TiB. This will enable you to use most of the disk, but it's awkward and at least a little risky. Although Windows 7 works with such disks, some utilities may fail -- possibly disatrously. Personally, I wouldn't go with this option; I mention it only for completeness.

*Use a second, smaller disk, in conjunction with your 5TB disk. You can boot from the smaller disk and use the 5TB disk as a GPT data (non-boot) disk. If you have the funds, a small SSD can make a good boot disk, since it will be a fast place for the OS itself to reside. If not, you can dig up an old ~60GB disk that should be plenty big enough to hold Windows.

*Use Clover or DUET to put what is essentially an EFI-as-a-bootloader on your disk. You should then be able to install Windows in EFI mode and use the whole disk. This solution is a good way to "have it all," but it requires comfort with unusual low-level tools to set up and it doesn't work on all systems. In particular, AMD CPUs work poorly, although Intel CPUs work better. Clover is designed as a Hackintosh boot loader, and so requires access to OS X to begin to use it. (You should be able to put Clover on a USB flash drive to get started, then transfer it to your hard disk.) DUET may be better if you have no access to OS X, but Clover has an active community supporting it, so I'd use it if at all possible. Neither option is good for a non-geek; you must have pretty high "geek creds" to use either tool.

You should NOT continue to use a failing disk. Such disks may be sort-of kind-of usable for a while, but sooner or later they're likely to fail catastrophically and with *no warning."
Overall, the two-disk solution is probably the best one, provided you have space in your computer for two disks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot use Firebase Client SDK `firebase.auth()` under Node.js I'm not able to use firebase.auth() in Client SDK under Node.js.
I'm using Node.js 9.11.2 and Firebase 4.13.1.
I looked at the documentation, and it specifically has a Client SDK section for Node.js with auth namespace. So I'm very confused that firebase.auth is not defined.
Have I done anything wrong?
$ node
> const firebase = require('firebase/app')
undefined
> firebase
{ __esModule: true,
  initializeApp: [Function: initializeApp],
  app: { [Function: app] App: [Function: FirebaseAppImpl] },
  apps: [Getter],
  Promise: [Function: Promise],
  SDK_VERSION: '4.13.0',
  INTERNAL:
   { registerService: [Function: registerService],
     createFirebaseNamespace: [Function: createFirebaseNamespace],
     extendNamespace: [Function: extendNamespace],
     createSubscribe: [Function: createSubscribe],
     ErrorFactory: [Function: ErrorFactory],
     removeApp: [Function: removeApp],
     factories: {},
     useAsService: [Function: useAsService],
     Promise: [Function: Promise],
     deepExtend: [Function: deepExtend] },
  default: [Circular] }
> require('firebase/auth')
{}
> firebase
{ __esModule: true,
  initializeApp: [Function: initializeApp],
  app: { [Function: app] App: [Function: FirebaseAppImpl] },
  apps: [Getter],
  Promise: [Function: Promise],
  SDK_VERSION: '4.13.0',
  INTERNAL:
   { registerService: [Function: registerService],
     createFirebaseNamespace: [Function: createFirebaseNamespace],
     extendNamespace: [Function: extendNamespace],
     createSubscribe: [Function: createSubscribe],
     ErrorFactory: [Function: ErrorFactory],
     removeApp: [Function: removeApp],
     factories: {},
     useAsService: [Function: useAsService],
     Promise: [Function: Promise],
     deepExtend: [Function: deepExtend] },
  default: [Circular] }
> .exit

P.S. require('firebase') shows similar result.
Update: I'm able to get this to work with 4.11.0 and 4.12.1, looking through the release notes now. But any help is hugely appreciated.
Update: Both 4.13.x and 5.x.x series don't work.


text:
Q: watson's two sample test with ties - does it exist on R? I would like to compare two samples with the watson's two sample test in R (circular data). As I have a lot of ties in my samples, I followed the example given in the book from Zar (Biostatistical analysis) for the watson's two sample test with ties (I did it by hand). I was curious to see if it would give me the same result with the code developped in R (watson.two.test). I saw some differences so I guess the test available in R is not adapted when there are a lot of ties. May I ask you if it exists on R a code for this test with ties?
Thanks a lot for your answer.

A: I am not sure if it could help someone but in any case I think I found a way to solve my problem. I just read a paper from Jammalamadaka et al. 2021 (https://link.springer.com/article/10.1007/s13571-020-00244-9) where they describe circular tests for low sample size using spacing frequencies instead of ranking. This solve as well the problems with the ties. I advise to read if you are working in these type of data. The Rcode is taken from here: https://github.com/SMAC-Group/TwoCircles#readme
Hope it will help someone else!


text:
Q: Determing / Naming `Iterable`, `Sequence` and "infinite" `Iterable` in Python I am aware that there are very good reasons not to force __len__ to be part of the iterators' API (e.g. Understanding len function with iterators) and I do understand that the difference between an Iterable and a Sequence is mostly with the implementation of __len__ (e.g. What exactly does "iterable" mean in Python?).
However, I was wandering if there is a standard way of determining or at least naming "(in)finite" iterators, so that the need for avoiding infinite iterators is at least well-documented.
This would be useful if, for example, the code needs to iterate through all the elements of the Iterable and waiting for the system to run out of memory is not an acceptable behavior for the software.


text:
Q: Why won't this code work to generate a tilemap? I am currently trying to create a tilemap for my game with some mario sprites. For some reason, no images are loading and I've tried everything I can think of.
I have tried the following code to generate my map with a 2d array:
JS:
var canvas = document.getElementById("GameCanvas")
var ctx = canvas.getContext("2d")

var testMap = [
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1]
];

        var testBlock = new Image();
        testBlock.src = "./img/52571.png"

var posX = 0;
var posY = 0;

function drawMap () {
    for (var i = 0; i < testMap.length; i++) {
    for (var j = 0; j < testMap[i].length; j++) {
        if (testMap[i][j] == 1) {
            ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
        }
        posX += 16;
    }
    posX = 0;
    posY += 16;
    };
}

HTML:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Game</title>
    </head>
<body>
    <canvas id = "GameCanvas" width = "800" height = "480"></canvas>
    <script src ='game_main.js'></script>
</body>
</html>

Here is the tileset.
Can anyone provide some insight on why this is not working?

A: Make sure your image is loaded before you draw with it.
You can do that by calling drawMap in testBlock.onload.
Here's a working demo (just click Run code snippet):

var testMap = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];

var testBlock = new Image();
testBlock.onload = drawMap;
testBlock.src = "https://i.stack.imgur.com/R6JFX.png"

function drawMap() {

  var canvas = document.getElementById("GameCanvas")
  var ctx = canvas.getContext("2d")

  var posX = 0;
  var posY = 0;

  for (var i = 0; i < testMap.length; i++) {
    for (var j = 0; j < testMap[i].length; j++) {
      if (testMap[i][j] == 1) {
        ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
      }
      posX += 16;
    }
    posX = 0;
    posY += 16;
  };
}
<body>

  <canvas id="GameCanvas" width="160" height="96" style="border:1px solid #000000;" />

</body>

A: In your code you defined drawMap function but it is not called. Call the drawMap function on onload of image.

const canvas = document.getElementById("GameCanvas");
const ctx = canvas.getContext("2d");

var testMap = [
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1]
];

const testBlock = new Image();
testBlock.src = "https://mdn.mozillademos.org/files/5397/rhino.jpg"
testBlock.onload = drawMap;

let posX = 0;
let posY = 0;

function drawMap () {
    for (let i = 0; i < testMap.length; i++) {
    for (let j = 0; j < testMap[i].length; j++) {
        if (testMap[i][j] == 1) {
            ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
        }
        posX += 16;
    }
    posX = 0;
    posY += 16;
    };
}
<canvas id = "GameCanvas" width = "800" height = "480"></canvas>


text:
Q: Accessing multiple YAML files So, I have been fiddling around with this for the past 5 hours and I can't seem to figure out why I can't access my second yaml file. I've been searching google for answers, and still haven't found anything even remotely similar to what I am looking for. Now, before you ask if I have registered it onto the onEnable event, I have. The config.yml file works perfectly fine, and as I need it to. However, when I create a second yaml file, "blocks.yml", I can't access the functions, for example:
I need to get data into the blocks.yml file, but using plugin.data.getBlocks().contains(...) the .contains() part shows an error, and it when I delete the .contains() part, my only options after the plugin.data.getBlocks() part are the try and lambda events. I am honestly extremely confused with this. I've even tried it without the .data part of the plugin.data.getBlocks() line, and it just doesn't show getBlocks() altogether. Here is my config manager file;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ConfigManager {

    private main plugin;
    private FileConfiguration config;
    private File configFile;

    private FileConfiguration blocks;
    private File blocksFile;

    public ConfigManager(main plugin) {
        this.plugin = plugin;
    }

    public void reloadConfig() {
        if (configFile == null) {
            configFile = new File(plugin.getDataFolder(), "config.yml");
        }
        config = YamlConfiguration.loadConfiguration(configFile);
        InputStream defaultStream = plugin.getResource("config.yml");
        if (defaultStream != null) {
            YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defaultStream));
            config.setDefaults(defaultConfig);
        }
    }

    public void getConfig() {
        if (config == null) {
            reloadConfig();
        }
    }
    public void saveConfig() {
        if(config == null || configFile == null) {
            return;
        }
        try {
            config.save(configFile);
        } catch (IOException e) {
            plugin.getServer().getConsoleSender().sendMessage(ChatColor.RED + "Could not save config to " + this.configFile, e.toString());
        }
    }
    public void saveDefaultConfig() {
        if(configFile == null) {
            configFile = new File(plugin.getDataFolder(), "config.yml");
        }
        if(!configFile.exists()) {
            plugin.saveResource("plugin.yml", false);
        }
    }

    public void reloadBlocks() {
        if (blocksFile == null) {
            blocksFile = new File(plugin.getDataFolder(), "blocks.yml");
        }
        blocks = YamlConfiguration.loadConfiguration(blocksFile);
        InputStream defaultBlocksStream = plugin.getResource("blocks.yml");
        if (defaultBlocksStream != null) {
            YamlConfiguration defaultBlocks = YamlConfiguration.loadConfiguration(new InputStreamReader(defaultBlocksStream));
            blocks.setDefaults(defaultBlocks);
        }
    }

    public void getBlocks() {
        if (blocks == null) {
            reloadBlocks();
        }
    }
    public void saveBlocks() {
        if(blocks == null || blocksFile == null) {
            return;
        }
        try {
            blocks.save(blocksFile);
        } catch (IOException e) {
            plugin.getServer().getConsoleSender().sendMessage(ChatColor.RED + "Could not save blocks to " + this.blocksFile, e.toString());
        }
    }
    public void saveDefaultBlocks() {
        if(blocksFile == null) {
            blocksFile = new File(plugin.getDataFolder(), "blocks.yml");
        }
        if(!blocksFile.exists()) {
            plugin.saveResource("blocks.yml", false);
        }
    }
}

A: There is multiple things to say.
Your method getBlocks() return "void", so nothing. You should do something like this :
public FileConfiguration getBlocks() {
    if (blocks == null) {
        reloadBlocks();
    }
    return blocks;
}

Also, the JavaPlugin's class already implement saveConfig() & saveDefaultConfig() method. You don't have to copy them yourself. Do like that :
plugin.saveDefaultConfig(); // copy if not found
plugin.getConfig().set("a", "b");
plugin.saveConfig(); // save config

A: To be frunk, the description of the problem doesn't help so much to help you.
Looking to your design pattern I found a difference between the methods saveDefaultConfig and saveDefaultBlocks.
Looking to this methods I could suggest your last command plugin.saveResource("blocks.yml", false); to be changed to plugin.saveResource("plugin.yml", false);.
Additionally, method contains is not inside the code snippet you added in the question. Try to search inside the files of your project the word contains, because probably the error is related to this command. Probably you use this command on an object that doesn't contain such a method.
Update
Change the method getBlocks to,
public YamlConfiguration getBlocks() {
    if (blocks == null) {
        reloadBlocks();
    }
    return blocks;
}


text:
Q: How to remove duplicates data from array Im implementing followes and following feature in my app . Im storing a data on firestore after fetching data from Firestone and passing into the function array data gets multiplied.
FirebaseReference(.Users).getDocuments{(snapshot, error) in
    if error != nil {
        print("Document Error: ", error!)
    } else {
        if let doc = snapshot, doc.isEmpty == false {
            print("User Document is present.")
            let desc = doc.documents
            for item in desc
            {

                let user = item.data()
                let name = user["name"] as! String
                let uid = user["userID"] as! String
                let img = user["imgUrl"] as? String

                FirebaseReference(.Users).document(FUser.currentUser()?.userID ?? "").collection("Following").getDocuments{(snapshot1,error) in
                    if error != nil {
                        print("Document Error: ", error!)
                    } else {
                        if let doc1 = snapshot1, doc1.isEmpty == false {
                            let data = doc1.documents

                            var followingid = ""
                            for newitem in data
                            {

                                let value = newitem.data()
                                followingid = value["followedToUserId"] as? String ?? ""
                                self.getPostData(name: name, uid: uid, img: img ?? "",followingId: followingid )
                            }

                        }
                        else
                        {
                            self.getPostData(name: name, uid: uid, img: img ?? "",followingId:"NA")
                        }
                    }
                }
            }
        }
        else
        {
            print("User Document is not present.")
        }
    }
}

IF Im passing data in this function self.getPostData() inside for loop my data gets multiplied.Please anyone can help me out from this.
Thank You

A: use set
let a = ["hai","hai","hello"]
let unique = Array(Set(a))
print(unique)

output should -> ["hai", "hello"]

NB: result won't be in order, if you want remove a duplicate model , model just needs to confirm the class Hashable and the process and result would be same

struct User: Hashable{
var name: String
var age: Int
}

let a = [User(name: "a",age:15), User(name: "a",age:15),User(name: "b",age:30)]
let unique = Array(Set(a))
print(unique)

result -> [main.User(name: "a", age: 15), main.User(name: "b", age: 30)]


text:
Q: How to copy a single cell from a filtered column I'm trying to copy a single cell from a filtered column, the cells all have the same value (date of the document) right now the macro just copies the cell D2 specifically. I want it to copy the date corresponding to the filtered list. is there any syntax that can specify the first visible cell?
Sub Macro12()
'
' Macro12 Macro
'

'
Sheets("INBD").Select
Range("D2").Select
Selection.Copy
Sheets("Sheet1").Select
Range("J1:K2").Select
ActiveSheet.Paste
End Sub

A: This should do the trick for you assuming that you have a header row in D1. It will select the first visible row after D1 and copy it into J1:K2
Sub test()

    Sheets("INBD").Range("D2", Cells(Rows.count, "D").End(xlUp)).SpecialCells(xlCellTypeVisible).Cells(1, 1).copy _
        Destination:=Sheets(1).Range("J1:K2")

End Sub


text:
Q: R Sum 11th to N record of a column into the 11th record The Problem: I have the following issue. In R I create summary statistics for a variable and order them from highest to lowest value. The number of records (rows) can range from 20 to 100 depending on the variable. In order to create the desired output, I have to take the first 10 rows from the R output then for rows 11 to N I have to sum it up in Excel and add the resulting record as the 11th variable to my list. This is very inefficient as I have to keep going between Excel and R and would prefer to do it in R itself.
R Code
one = aggregate(rail11$Tons,rail11['STCC4'],sum)
answer = data.frame(Commodity=one$STCC4, PATons=one$x)
answer1 <- answer[order(-answer$PATons), ] # Sort it from Highest to lowest
# answer2 <- answer1[1:10,] # This line takes only the top 10 records
write.table(answer1, "testdata.csv",sep=",", row.names=FALSE)

I have uploaded the actual output and desired output to google drive so that you can test the code.
Output from R code: Actual actual from R code:  Testdata.csv
Desired Output from R: Desired output from R: sumrow.csv
Thanks in Advance for your help.
Krishnan

A: Are you dealing with just one column at a time? It seems not. Try
answer2[11,] <- apply(answer1[11:dim(answer1)[1], ], 2, sum)

Also
answer2[11,] <- colSums(answer1[11:dim(answer1)[1], ])

should work.


text:
Q: What does a semicolon outside of curly braces do? This has had me tearing my hair out for an hour:
div {
  key: value;
  ...
};

img {
  key: value;
  ...
}

(Note the semicolon after the curly brace).  None of the styling for imgs was showing up ... finally I noticed the semicolon and removed it -- voila!  it all works as expected.
The question:  what does a ; outside of curly braces mean?

A:
what does a ; outside of curly braces mean?

Invalid syntax.
That's why the parser stopped there and didn't pick up any of the style rules below (e.g. img). Validate it yourself.

A: It means it is invalid CSS, the CSS validator would tell you that.

A: I don't think it is valid CSS, so behaviour in different browsers may vary.
If you use a CSS validator it should show up these sort of issues for you.

A: The CSS parser probably encountered an error, and just refused to parse the rest of the file, but allow to use what it successfully parsed.


text:
Q: $a+c$ is a root of $p(x)$ iff $a$ is a root of $p(x+c)$; $ca$ is a root of $p(x)$ iff $a$ is a root of $p(cx)$.
$a+c$ is a root of $p(x)$ iff $a$ is a root of $p(x+c)$; $ca$ is a root of $p(x)$ iff $a$ is a root of $p(cx)$.

I know that $c$ is a zero of $p$ if and only if $(x − c)$ is a factor of $p(x)$. If $(x − c)$ is a factor of $p(x)$, this means $p(x) = (x − c) q(x)$ where $p(c)=0$. So $p(x+c)=(x-(x+c))q(x)=q(x)\cdot c$. Where $a$ needs to be a root of $q(x)$ I am assuming? Am I on the right track?

A: Asserting that $a+c$ is a root of $p(x)$ means that $p(a+c)=0$. And asserting that $a$ is a root of $p(x+c)$ also means that $p(a+c)=0$. So, the assertions are equivalente.
Can you do the same thing to prove the other equivalence?


text:
Q: javascript with multiple slides within the same div container I have created multiple html slideshows with jquery under different categories. For example, Under 'POOLS' category I have a slideshow for POOLS with 3 images. Under 'DRIVEWAYS'category I have made a slideshow or 3 images of Driveways.
I have it set up where there is a container at the top (for slideshows) and I have also different thumbnails of each category below the container. I want to be able to link each thumbnail to each slideshow. I need these slideshows to appear in the top container everytime I click on a thumbnail the slideshow will appear in the container (with its own controls).
Can someone tell me an easier/quicker way to call these slideshows. I'm just learning Javascript and I'd like to know if there is an option or a way to call these html slideshows in the top container. I have searched for days and I'm not sure if I am searching the right key words. This could be something simple but it's driving me crazy trying to figure it out.
Any help is greatly appreciated!!!!

A: HTML

jQuery
$(document).ready(function () {
    $("#EX2-Poolspic").hover(
    function () {
    $("#myframe").attr("src", "http://s101.photobucket.com/user/ladybytesjdb/slideshow/ACsite");
    });
});

CSS
#EX2contentwrapper {
    width: 2000px;
    height: auto;
    margin: 0 auto;
}
#sliderContainer{
    background-color: #989898;
    width: 1000px;
    height: 400px;
    float: left;
}
#EX2thumbnailpicsbox {
    width: 1066px;
    height: 539px;
    display: block;
    float: left;
    z-index: 99;
}

#thumbs {
    width: 1066px;
    height: auto;
    display: block;
    float: left;
}
#EX2-Poolspic {
    width: 274px;
    height: 229px;
    float: left;
    position: relative;
    z-index: 99;
}

#EX2-Patiospic {
    width: 261px;
    height: 229px;
    float: left;
    position: relative;
}

#EX2-Stairspic {
    width: 260px;
    height: 229px;
    float: left;
    position: relative;
}

#EX2-Walkwayspic {
    width: 271px;
    height: 229px;
    float: left;
    position: relative;
}

#EX2-Pooltxt {
    width: 274px;
    height: 31px;
    float: left;
    position: relative;
}

.EX2-Patiostxt {
    width: 261px;
    height: 31px;
    float: left;
    position: relative;
}

.EX2-Stairstxt {
    width: 260px;
    height: 31px;
    float: left;
    position: relative;
}
.EX2-Walkwaystxt {
    width: 271px;
    height: 31px;
    float: left;
    position: relative;
}

Fiddle Demo


text:
Q: How do I stop Matlab from displaying matrix content on importdata() I'm running a series of scripts that all import data from different matrix files. It seems that displaying the content of the matrix is taking a lot of time. Normally I would do "more on" and just cancel the display after the first page, but I am doing things automatically here, from the command-line version.
Is there a way to stop Matlab from displaying the content of variables when it loads them? Say, a non-verbose/daemon mode? I couldn't find a way to do it when I searched, but I'm sure there must be one.
Thanks in advance!

A: Found it! The answer is to add a semicolon (;) at the end of the line, for example:
m=importdata('matrix.txt');

This will prevent it from printing the contents of m.


text:
Q: find average of json field in postgres rails id  name    overview                created_at
1   john    { 'keywords' => '10' }  2017-02-11 04:55:23 UTC
2   robert  { 'keywords' => '20' }  2017-02-12 04:55:23 UTC
3   litty   { 'keywords' => '10' }  2017-02-13 04:55:23 UTC
4   john    { 'keywords' => '20' }  2017-02-14 04:55:23 UTC
5   john    { 'keywords' => '30' }  2017-02-15 04:55:23 UTC
6   litty   { 'keywords' => '20' }  2017-02-16 04:55:23 UTC
7   robert  { 'keywords' => '40' }  2017-02-17 04:55:23 UTC
8   litty   { 'keywords' => '50' }  2017-02-18 04:55:23 UTC

find records by unique name and having max(created_at).
the output should be like following
id  name    overview                created_at
5   john    { 'keywords' => '30' }  2017-02-15 04:55:23 UTC
7   robert  { 'keywords' => '40' }  2017-02-17 04:55:23 UTC
8   litty   { 'keywords' => '50' }  2017-02-18 04:55:23 UTC

Then need to find average of the JSON field value overview->keywords
The final result based on the given example should be 40


text:
Q: Is there anything to do in the onDestroyView() after a fragment is replaced? I have a fragment which contains a ViewPager that displays images onto the screen. When the user transitions to another screen through a button press and the current fragment is replaced with different fragment, do I have to do anything in the onDestroyView() method in order to release the ViewPager and the ImageViews contained in the previous fragment?
I'm just concerned that even though I do not see that fragment anymore, the ViewPager and ImageViews are still consuming memory.

A: Yes, your views are not garbage collected if you have instance variables referencing them. So if you are concerned about memory usage you should set them to null in onDestroyView.


text:
Q: Save Data Offline Then Automatically Upload It To Firestore Upon Connection - Swift Xcode I'm creating an app that allows the user to create a project, take photos and create labels in that project (using structs), then create a PDF later on. I've got to figure out how to save this data without connection, then backup it up to the server later. I want the app to be able to work both online and offline - whether the user has cell service or not. I've seen many apps where when you load them up, if you have no signal, you can select "Run Offline" or "Continue Offline."
How should I save the data locally until the user comes back into cellular signal and the data can be backed up to Firebase Firestore and Storage? I was considering using UserDefaults to save the data in a cache essentially, then whenever the phone is back within signal, the app automatically runs through this cache and backs everything up to the server. Is this the correct way to accomplish what I'm needing done? Is there a better way?
In the end, the data MUST be able to be saved whether connected to the internet or not - online or offline. I just need to figure out the best way to save the data until it can be uploaded to the server when back online. I want the data the user is creating to be safe in case something happened to the phone or to the app (maybe their phone shut off or there was a random app crash). By the way, the app is project based... so there's multiple files (projects) in other words. They may need to set up multiple files (projects) while offline and access one of them later on while still offline. It needs to put all of these offline projects in a container to be automatically backed up to the server upon returning to signal. These files (projects), with all the data in them, MUST be safe at all times until backed up - even if the user closes the app.
Please leave a detailed answer. I'm a beginner, as you can tell, and need specifics. If you reference a certain way of doing something, kindly leave a link to a tutorial or significant documentation, or explain it thoroughly.
Thanks!
Christian


text:
Q: One producer, multiple consumers. How to use condition variables with unbounded buffer? Despite the number of similar questions on Stackoverflow, I can't come up with a solution for the following Producer-Consumer problem:
My program has three threads:

*

*One writer thread that reads from a file, saves data into a sensor_data_t struct, and writes it into a dynamic pointer-based buffer using sbuffer_insert(buffer, &sensor_data). Once this thread finishes reading it sends an end-of-stream data struct represented by data->id == 0.

*Two reader threads that remove data from the buffer head (FIFO-style), and store it into a temporary data struct using sbuffer_remove(buffer, &data) and then print it to the cmd line for testing purposes.
I think I have to avoid at the least:

*

*My reader threads to try to consume/remove from the buffer while it is empty.

*My reader threads to consume/remove from the buffer at the same time.

On the other hand, I don't think my writer thread in sbuffer_insert() needs to worry if the readers are changing the head because it only appends to the tail. Is this reasoning correct or am I missing something?
Here's what I've done so far:
My main function:
sbuffer_t *buffer;

void *writer(void *fp);
void *reader(void *fp);

int main()
{
    // Initialize the buffer
    sbuffer_init(&buffer);

    // Open sensor_data file
    FILE *sensor_data_fp;
    sensor_data_fp = fopen("sensor_data", "rb");

    // Start thread for reading sensor_data file adding elements to the sbuffer
    pthread_t writer_thread;
    pthread_create(&writer_thread, NULL, &writer, sensor_data_fp);

    // Open sensor_data_out file
    FILE *sensor_data_out_fp;
    sensor_data_out_fp = fopen("sensor_data_out", "w");

    // Start thread 1 and 2 for writing sensor_data_out file
    pthread_t reader_thread1;
    pthread_t reader_thread2;
    pthread_create(&reader_thread1, NULL, &reader, sensor_data_out_fp);
    pthread_create(&reader_thread2, NULL, &reader, sensor_data_out_fp);

    // Wait for threads to finish and join them

    pthread_join(reader_thread1, NULL);
    pthread_join(reader_thread2, NULL);
    pthread_join(writer_thread, NULL);

    // Close sensor_data file
    fclose(sensor_data_fp);
    // Close sensor_data_out file
    fclose(sensor_data_out_fp);

    // free buffer
    sbuffer_free(&buffer);

    return 0;
}

My reader and writer threads:
typedef uint16_t sensor_id_t;
typedef double sensor_value_t;
typedef time_t sensor_ts_t;         // UTC timestamp as returned by time() - notice that the size of time_t is different on 32/64 bit machine

typedef struct {
    sensor_id_t id;
    sensor_value_t value;
    sensor_ts_t ts;
} sensor_data_t;

void *writer(void *fp)
{
    // cast fp to FILE
    FILE *sensor_data_fp = (FILE *)fp;

    // make char buffers of size sensor_id_t, sensor_value_t and sensor_ts_t
    char sensor_id_buffer[sizeof(sensor_id_t)];
    char sensor_value_buffer[sizeof(sensor_value_t)];
    char sensor_ts_buffer[sizeof(sensor_ts_t)];

    // parse sensor_data file into sensor_id_buffer, sensor_value_buffer and sensor_ts_buffer
    while(fread(sensor_id_buffer, sizeof(sensor_id_t), 1, sensor_data_fp) == 1 &&
    fread(sensor_value_buffer, sizeof(sensor_value_t), 1, sensor_data_fp) == 1 &&
    fread(sensor_ts_buffer, sizeof(sensor_ts_t), 1, sensor_data_fp)) {
        // create sensor_data_t
        sensor_data_t sensor_data;
        // copy sensor_id_buffer to sensor_data.id
        memcpy(&sensor_data.id, sensor_id_buffer, sizeof(sensor_id_t));
        // copy sensor_value_buffer to sensor_data.value
        memcpy(&sensor_data.value, sensor_value_buffer, sizeof(sensor_value_t));
        // copy sensor_ts_buffer to sensor_data.ts
        memcpy(&sensor_data.ts, sensor_ts_buffer, sizeof(sensor_ts_t));

        // print sensor_data for testing
        // printf("sensor_data.id: %d, sensor_data.value: %f, sensor_data.ts: %ld\n", sensor_data.id, sensor_data.value, sensor_data.ts);

        // insert sensor_data into buffer
        sbuffer_insert(buffer, &sensor_data);
    }
    // Add dummy data to buffer to signal end of file
    sensor_data_t sensor_data;
    sensor_data.id = 0;
    sensor_data.value = 0;
    sensor_data.ts = 0;
    sbuffer_insert(buffer, &sensor_data);

    return NULL;
}

void *reader(void *fp)
{
    // cast fp to FILE
    //FILE *sensor_data_out_fp = (FILE *)fp;

    // Init data as sensor_data_t
    sensor_data_t data;
    do{
        // read data from buffer
        if (sbuffer_remove(buffer, &data) == 0) { // SBUFFER_SUCCESS 0
            // write data to sensor_data_out file
            // fwrite(&data, sizeof(sensor_data_t), 1, sensor_data_out_fp);
            // print data for testing
            printf("data.id: %d, data.value: %f, data.ts: %ld \n", data.id, data.value, data.ts);
        }
    }
    while(data.id != 0);

    // free allocated memory
    // free(fp);

    return NULL;
}

Global variables and buffer initialization:
typedef struct sbuffer_node {
    struct sbuffer_node *next;
    sensor_data_t data;
} sbuffer_node_t;

struct sbuffer {
    sbuffer_node_t *head;
    sbuffer_node_t *tail;
};

pthread_mutex_t mutex;
pthread_cond_t empty, removing;
int count = 0; // reader count

int sbuffer_init(sbuffer_t **buffer) {
    *buffer = malloc(sizeof(sbuffer_t));
    if (*buffer == NULL) return SBUFFER_FAILURE;
    (*buffer)->head = NULL;
    (*buffer)->tail = NULL;

    // Initialize mutex and condition variables
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&empty, NULL);
    pthread_cond_init(&removing, NULL);

    return SBUFFER_SUCCESS;
}

sbuffer_remove (Consumer)
int sbuffer_remove(sbuffer_t *buffer, sensor_data_t *data) {
    sbuffer_node_t *dummy;
    if (buffer == NULL) return SBUFFER_FAILURE;

    // while the count is 0, wait
    pthread_mutex_lock(&mutex);
    while (count > 0) {
        pthread_cond_wait(&removing, &mutex);
    }
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    while (buffer->head == NULL){

        pthread_cond_wait(&empty, &mutex); // Wait until buffer is not empty

        if (data->id == 0){ // end-of-stream
            pthread_mutex_unlock(&mutex);
            return SBUFFER_NO_DATA;
        }
    }

    count++;

    *data = buffer->head->data;
    dummy = buffer->head;
    if (buffer->head == buffer->tail) // buffer has only one node
    {
        buffer->head = buffer->tail = NULL;
    } else  // buffer has many nodes empty
    {
        buffer->head = buffer->head->next;
    }
    free(dummy);

    count--;

    pthread_cond_signal(&removing); // Signal that data is removed
    pthread_mutex_unlock(&mutex);

    return SBUFFER_SUCCESS;
}

sbuffer_insert (Producer)
int sbuffer_insert(sbuffer_t *buffer, sensor_data_t *data) {
    sbuffer_node_t *dummy;
    if (buffer == NULL) return SBUFFER_FAILURE;
    dummy = malloc(sizeof(sbuffer_node_t));
    if (dummy == NULL) return SBUFFER_FAILURE;
    dummy->data = *data;
    dummy->next = NULL;

    if (buffer->tail == NULL) // buffer empty (buffer->head should also be NULL
    {
        pthread_mutex_lock(&mutex);
        buffer->head = buffer->tail = dummy;
        pthread_cond_signal(&empty); // Signal that buffer is not empty
        pthread_mutex_unlock(&mutex);

    } else // buffer not empty
    {
        buffer->tail->next = dummy;
        buffer->tail = buffer->tail->next;
    }
    return SBUFFER_SUCCESS;
}

Currently, the code has very unstable behavior. Sometimes it runs and prints everything, sometimes it doesn't print anything and gets stuck in a loop, sometimes it prints everything but the last value comes after the end-of-stream code and it doesn't terminate.
I would really appreciate a solution that explains what I'm doing wrong or a comment that redirects me to a duplicate of my question.

A: Not a complete answer here, but I see this in your sbuffer_remove function:
    // while the count is 0, wait
    pthread_mutex_lock(&mutex);
    while (count > 0) {
        pthread_cond_wait(&removing, &mutex);
    }
    pthread_mutex_unlock(&mutex);

That looks suspicious to me. What is the purpose of waiting for the count to become zero? Your code waits for the count to become zero, but then it does nothing else before it unlocks the mutex.
I don't know what count represents, but if the other reader thread is concurrently manipulating it, then there is no guarantee that it will still be zero once you've unlocked the mutex.
But, maybe that hasn't caused a problem for you because...

...This also looks suspicious:
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);

Why do you unlock the mutex and immediately lock it again? Are you thinking that will afford the other consumer a chance to lock it? Technically speaking, it does that, but in practical terms, the chance it offers is known as, "a snowball's chance in Hell." If thread A is waiting for a mutex that is locked by thread B, and thread B unlocks and then immediately tries to re-lock, then in most languages/libraries/operating systems, thread B will almost always succeed while thread A goes back to try again.
Mutexes work best when they are rarely contested. If you have a program in which threads spend any significant amount of time waiting for mutexes, then you probably are not getting much benefit from using multiple threads.

A:
I think I have to avoid at the least:

*

*My reader threads to try to consume/remove from the buffer while it is empty.

*My reader threads to consume/remove from the buffer at the same time.

Yes, you must avoid those. And more.

On the other hand, I don't think my writer thread in sbuffer_insert()
needs to worry if the readers are changing the head because it only
appends to the tail. Is this reasoning correct or am I missing
something?

You are missing at least that

*

*when the buffer contains fewer than two nodes, there is no distinction between the head node and the tail node.  This manifests at the code level at least in the fact that your sbuffer_insert() and sbuffer_remove() functions both access both buffer->head and buffer->tail.  From the perspective of synchronization requirements, it is this lower-level view that matters.

*Insertion and removal modifies the node objects themselves, not just the overall buffer object.

*Synchronization is not just, nor even primarily, about avoiding threads directly interfering with each other.  It is even more about the consistency of different threads' views of memory.  You need appropriate synchronization to ensure that one thread's writes to memory are (ever) observed by other threads, and to establish ordering relationships among operations on memory by different threads.

Currently, the code has very unstable behavior. Sometimes it runs and
prints everything, sometimes it doesn't print anything and gets stuck
in a loop, sometimes it prints everything but the last value comes
after the end-of-stream code and it doesn't terminate.

This is unsurprising, because your program contains data races, and its behavior is therefore undefined.
Do ensure that neither the reader nor the writer accesses any member of the buffer object without holding the mutex locked.  As the code is presently structured, that will synchronize access not only to the buffer structure itself, but also to the data in the nodes, which presently are involved in their own data races.

Now note that here ...

    while (buffer->head == NULL){

        pthread_cond_wait(&empty, &mutex); // Wait until buffer is not empty

        if (data->id == 0){ // end-of-stream
            pthread_mutex_unlock(&mutex);
            return SBUFFER_NO_DATA;
        }
    }

... you are testing for an end-of-data marker before actually reading an item from the buffer.  It looks like that's useless in practice.  In prarticular, it does not prevent the end-of-stream item from being removed from the buffer, so only one reader will see it.  The other(s) will then end up waiting indefinitely for data that will never arrive.

Next, consider this code executed by the readers:

    // while the count is 0, wait
    pthread_mutex_lock(&mutex);
    while (count > 0) {
        pthread_cond_wait(&removing, &mutex);
    }
    pthread_mutex_unlock(&mutex);

Note well that the reader unlocks the mutex while count is 0, so there is an opportunity for another reader to reach the while loop and pass through.  I'm not sure that two threads both getting past that point at the same time produces a problem in practice, but the point seems to be to avoid that, so do it right: move the count++ from later in the function to right after the while loop, prior to unlocking the mutex.
Alternatively, once you've done that, it should be clear(er) that you've effectively hand-rolled a binary semaphore.  You could simplify your code by switching to an actual POSIX semaphore for this purpose.  Or if you want to continue with a mutex + CV for this, then consider using a different mutex, as the data to be protected for this purpose are disjoint from the buffer and its contents.  That would get rid of the weirdness of re-locking the mutex immediately after unlocking it.
Or on the third hand, consider whether you need to do any of that at all.  How is the (separate) mutex protection of the rest of the body of sbuffer_remove() not sufficient by itself?  I propose to you that it is sufficient.  After all, you're presently using your hand-rolled semaphore exactly as (another) mutex.

The bones of this code seem reasonably good, so I don't think repairs will be too hard.
First, add the needed mutex protection in sbuffer_insert().  Or really, just expand the scope of the critical section that's already there:
int sbuffer_insert(sbuffer_t *buffer, sensor_data_t *data) {
    sbuffer_node_t *dummy;
    if (buffer == NULL) return SBUFFER_FAILURE;
    dummy = malloc(sizeof(sbuffer_node_t));
    if (dummy == NULL) return SBUFFER_FAILURE;
    dummy->data = *data;
    dummy->next = NULL;

    pthread_mutex_lock(&mutex);
    if (buffer->tail == NULL) // buffer empty (buffer->head should also be NULL
    {
        assert(buffer->head == NULL);
        buffer->head = buffer->tail = dummy;
        pthread_cond_signal(&empty); // Signal that buffer is not empty

    } else // buffer not empty
    {
        buffer->tail->next = dummy;
        buffer->tail = buffer->tail->next;
    }
    pthread_mutex_unlock(&mutex);

    return SBUFFER_SUCCESS;
}

Second, simplify and fix sbuffer_remove():
int sbuffer_remove(sbuffer_t *buffer, sensor_data_t *data) {
    if (buffer == NULL) {
        return SBUFFER_FAILURE;
    }

    pthread_mutex_lock(&mutex);

    // Wait until the buffer is nonempty
    while (buffer->head == NULL) {
        pthread_cond_wait(&empty, &mutex);
    }

    // Copy the first item from the buffer
    *data = buffer->head->data;

    if (data->id == 0) {
        // end-of-stream: leave the item in the buffer for other readers to see
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&empty); // other threads can consume this item
        return SBUFFER_NO_DATA;
    } // else remove the item

    sbuffer_node_t *dummy = buffer->head;

    buffer->head = buffer->head->next;
    if (buffer->head == NULL) {
        // buffer is now empty
        buffer->tail = NULL;
    }

    pthread_mutex_unlock(&mutex);

    free(dummy);

    return SBUFFER_SUCCESS;
}


text:
Q: Push/Set Data to Firebase From JSON File Using Javascript and Nodejs I want to upload data to Firebase's Real-time Database. This information is relative to user's ID. I have downloaded this relevant user information in a JSON file. I can read this information to the Node.js command prompt easily using JavaScript.
I know how to push and set data using JavaScript as well.
My issue seems to be including both this read from a file operation and this write to firebase operation in the same JavaScript code.
To test this I wrote a really basic JavaScript program that uses a call back function so I can make sure that it finishes reading from the file before anything starts writing but even writing the commented out codes makes the whole JavaScript program not work. (I know that I do not need BOTH the first 2 lines, but I was trying different things and I wanted to show them both)
function GetAllData(callback) {

//var userData = require('./save_file.json');
// var fs = require('fs')
//   var obj = JSON.parse(fs.readFileSync('save_file.json').toString())
    var a=2;

if (typeof callback === 'function') {
    callback();
}
}

function PushData() {
var config = {
    apiKey: ,
    authDomain: ,
    databaseURL: ,
    projectId: ,
    storageBucket: ,
    messagingSenderId:
  };
// Initialize your Firebase app
firebase.initializeApp(config);

// Reference to your entire Firebase database
var myFirebase = firebase.database().ref();
var recommendations = myFirebase.child("recommendations");

setTimeout(pushStuff(), 500);

function pushStuff(){

    recommendations.set({
        "title": "nn"
    });
}
};
 //}

 GetAllData(PushData);

If I remove the commented out code in the  first section, "nn" is written just fine.
At this point I just want to be able to READ and WRITE in the same code :(

A: As you mention in your question, read and write calls to the Firebase database are asynchronous.
They return promises, as you can see here or here, from the Firebase documentation.
You therefore have to chain these promises like for example, in the case of a read followed by a write:
return firebase.database().ref('/users/' + userId).once('value')
.then(snapshot => {
    var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
    return firebase.database().ref(....).set({ username: username });
})
.then(() => {
    console.log('Operation succeeded');
})
.catch(error => {
    console.log('Operation failed');
});

Also, have a look a this SO post Reading a nodejs promise with firebase


text:
Q: Unable to display data with __str__ This code is part of a larger program .. I am trying to generate a summary that displays the data taken from a user
class Mbilling:
   def __init__(self, income, debit = 0, rent = 745):
       self.income = income
       self.debit   = debit
       self.rent    = rent

class Display(Mbilling):

   def listMbilling(self):
       self.m = f"""
            ------------------------------------
            --> Income = {self.income}
            --> Debit  = {self.debit}
            --> Rent   = {self.rent}
            ------------------------------------
                 """

    def __str__(self):
        return self.m

and i am getting this error:
Traceback (most recent call last):
  File "G:\Engineering\#ZicX\#Programming in Python\Basic Python\Tutorials\test.py", line 25, in <module>
    receipt = Display()
TypeError: __init__() missing 1 required positional argument: 'income'

When i try these  command:
d1 = Mbilling(5000, 0, 750)
receipt = Display()
print(receipt)

Need help to understand what's wrong ,, thanks !

A: I feel that the issue here is a matter of class inheritance. I am by no means a super() expert but here's what I can contribute:
Here is one example:
class MethodOne:

def __init__(self):

    self.param_one = "Car"
    self.param_two = 200

class MethodTwo(MethodOne):

    def __init__(self):
        super().__init__()

    def __str__(self):
        self.string_one = f"I have a {self.param_one}."
        self.string_two = f"{self.param_two} minus 100 equals {self.param_two - 100}!"

        return self.string_one + "\n" + self.string_two

And here is another example that more closely relates to what you are looking to achieve.
class Mbilling:

    def __init__(self, income = 0, debit = 0, rent = 745):
        self.income = income
        self.debit = debit
        self.rent = rent

        print("Hi there. I am the parent")

class Display(Mbilling):

    def __init__(self, income, debit, rent):
        print("Hi, I am the child")

        super().__init__()

    def listMbilling(self):
        self.m = f"""
            ------------------------------------
            --> Income = {self.income}
            --> Debit  = {self.debit}
            --> Rent   = {self.rent}
            ------------------------------------
                 """

    def __str__(self):
        self.listMbilling()
        return self.m

d1 = Display(23, 40, 745)
print(d1)

Also, this link is super ;) useful https://www.educative.io/edpresso/what-is-super-in-python


text:
Q: ¿Por qué desaparecen las cards del DOM cuando el usuario continúa introduciendo letras en el input de este buscador en Javascript? En este simulador de compras de productos alimenticios, existe un problema y es que cuando el usuario utiliza el buscador y va introduciendo letras en él, a medida que esto sucede van desapareciendo las cards generadas en el DOM. He probado varias cosas y quizás el problema esté en la función filtrar en alguna de las dos líneas donde implemento el toLowerCase, pero no logro como hallar la causa y su solución

    // Declaro las variables
    let container = document.getElementById('c9__container');
    let buscador = document.getElementById('c9__input');
    let btn = document.getElementById('c9__btn');
    let pedido = document.getElementById('pedido')

    // STOCK
    const stocks = [{
        id: 1,
        nombre: "Papas",
        precio: 240,
        tipo: "papas",
        img: './assets/papas.jpg'
    },
    {
        id: 2,
        nombre: "Hamburguesa",
        precio: 440,
        tipo: "hamburguesas",
        img: './assets/burger.jpg'
    },
    {
        id: 3,
        nombre: "MediaLuna y Cafe",
        precio: 150,
        tipo: "medialunas",
        img: './assets/medialunasycafe.jpg'
    },
    {
        id: 4,
        nombre: "Empanadas",
        precio: 720,
        tipo: "empanadas",
        img: './assets/empanadas.jpg'
    },
    ];

    const carrito = []

    "use strict"
    let botones = document.getElementsByClassName('btn-compra');

    for (const boton of botones) {
        boton.addEventListener('click', comprarProducto)
    }

    // Creación de cards
    function crearCards(array) {

        array.forEach(elemento => {
            let tarjeta = document.createElement('div');
            tarjeta.classList.add('c9__card');
            tarjeta.innerHTML = `

${elemento.nombre}

$${elemento.precio}

                                    Sumar al carrito
                                `

            container.appendChild(tarjeta);
        })
    }
    crearCards(stocks)

    // Filtrado de los productos
    function filtrar() {
        container.innerHTML = '';
        let texto = buscador.value.toLowerCase();

        for (const stock of stocks) {
            let nombre = stock.nombre.toLowerCase();
            if (nombre.indexOf(texto) !== -1) {
                container.innerHTML += `

${stock.nombre}

$${stock.precio}

                                            Sumar al carrito

`
            }
        }
        if (container.innerHTML === '') {
            container.innerHTML += `<div class="c9__card"><p>Producto no encontrado</p></div>`
        }
    }

    buscador.addEventListener('keyup', filtrar)

    //
    function comprarProducto(e) {
        e.preventDefault();
        let encontrado = stocks.find(x => x.id == e.target.id)
        carrito.push(encontrado)
        sumarCarrito(carrito)
    }

    // Contador de productos en el carrito
    function sumarCarrito(carrito) {
        let contador = document.getElementById('contador');
        contador.innerText = carrito.length
    }

    // Aparecen los iconos
    let marca = document.querySelector('.c9__container')
    marca.onclick = () => {
        let iconos = document.getElementById('iconos')
        iconos.classList.add('mostrar')
    }

    // Desaparición de los iconos y vaciar carrito
    let borrar = document.getElementById('tacho');

    borrar.addEventListener('click', function () {
        iconos.classList.remove('mostrar')
        while (carrito.length > 0) {
            carrito.pop();
        }
        total = 0
    })

    // Suma de todo el carrito
    let comprar = document.getElementById('comprar')
    let total = 0;
    comprar.addEventListener('click', function comprar() {
        for (let i = 0; i < carrito.length; i++) {
            total = total + carrito[i].precio;
        }
    })

    // Popup Enviar compra
    comprar.addEventListener('click', function togglePopup() {
        document.getElementById("popup-1").classList.toggle("active");
        document.body.style.overflow = "hidden";
    })

    comprar.addEventListener('click', function mostrarPedido() {
        for (const producto of carrito) {
            let lista = document.createElement('li');
            lista.innerHTML += `1x ..... <strong>${producto.nombre}</strong> $${producto.precio}`
            document.getElementById('listaCarrito').appendChild(lista)
        }
    })

Fast Food Store

                <input class="c9__input" id="c9__input" type="text" placeholder="Busque el producto que desea">

                    0

Su pedido:


text:
Q: CSS nest-list - how to subsection Im creating a list like this one
i want to list rottweiler and doberman like 1.1 and 1.2, but i have no idea how to do it. I copied that css list template and made some modifications.
Here is the code:

#lista2 {
    counter-reset: li;
    list-style: none;
    *list-style: decimal;
    font: 15px 'trebuchet MS', 'lucida sans';
    padding: 0;
    margin-bottom: 4em;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}

#lista2 ol {
    margin: 0 0 0 2em;
     counter-reset: section;
   list-style-type: none;
}

#lista2 li{
    position: relative;
    display: block;
    padding: .4em .4em .4em 2em;
    *padding: .4em;
    margin: .5em 0;
    background: #ddd;
    color: #444;
    text-decoration: none;
    border-radius: .3em;
    transition: all .3s ease-out;

}

#lista2 li:hover{
    background: #eee;
}

#lista2 li:hover:before{
    transform: rotate(360deg);
}

#lista2 li:before{
    content: counter(li);
    counter-increment: li;
    position: absolute;
    left: -1.3em;
    top: 50%;
    margin-top: -1.3em;
    background: #87ceeb;
    height: 2em;
    width: 2em;
    line-height: 2em;
    border: .3em solid #fff;
    text-align: center;
    font-weight: bold;
    border-radius: 2em;
    transition: all .3s ease-out;
}

#lista2 ol ol li:before{
 counter-increment: li;
  content: counters(li,".") " ";
}
#lista2 ol {
    counter-reset: li;
    list-style: none;
}

Animals

Dogs

Rottweiler

Doberman

Cats

Cacatoos

I hope someone could help me. Thanks!

A: Plunkr Link - https://plnkr.co/edit/dtn5xgoOOoSmVc4B3LrH?p=preview
HTML:
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

Dogs

Rottweiler

Doberman

Cats

Cacatoos

CSS:
OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }


text:
Q: How to get lexer to output EOF in Scala TokenParser? If I define a Lexical to feed a TokenParser, I'm having trouble getting the TokenParser to actually output an EOF token. In particular, some of the methods in Parser[T] (acceptIf, acceptMatch, and phrase) directly check whether the Reader is atEnd, so there's no chance for an EOF token to get added to the token stream before an error is returned.
Since the Tokens trait actually defines an EOF token, I'm sure there must be some simple way to output it, but at this point all I can think to do is to create my own Reader that doesn't return true for atEnd until after at least one EOF has been output or adding a '\032' character to the input so that the Reader doesn't realize it's at the end until after it has emitted that character.
Please tell me I'm missing an easier way...

A: You don't need to do this at all. Use
new YourLexical.Scanner("foo")

to create a Reader[YourLexical.Token], which will respond to #atEnd automatically.
Then you can hand this Reader to a TokenParser implementing your syntax directly as input:
class YourTokenParser ... {
    ...
    def program: Parser[...] = ...

    def parse(s: String) =
        phrase(program)(new YourLexical.Scanner(s))
}


text:
Q: how to add new button to open module url on product view page using custom module I want to add new button (Own Measurement) using custom module on product view page along with Add to cart button. on click new button it will redirect module's index.phtml.
my module config.xml file is:-
<?xml version="1.0"?>
<config>
  <modules>
    <SilkSoftware_Measurement>
      <version>0.1.0</version>
    </SilkSoftware_Measurement>
  </modules>
  <frontend>
    <routers>
      <measurement>
        <use>standard</use>
          <args>
            <module>SilkSoftware_Measurement</module>
            <frontName>measurement</frontName>
          </args>
      </measurement>
    </routers>
        <layout>
          <updates>
            <measurement>
              <file>measurement.xml</file>
            </measurement>
          </updates>
        </layout>
  </frontend>
  <global>
    <helpers>
      <measurement>
        <class>SilkSoftware_Measurement_Helper</class>
      </measurement>
    </helpers>
    <blocks>
      <measurement>
        <class>SilkSoftware_Measurement_Block</class>
      </measurement>
    </blocks>
  </global>
  <admin>
    <routers>
      <measurement>
        <use>admin</use>
        <args>
          <module>SilkSoftware_Measurement</module>
          <frontName>admin_measurement</frontName>
        </args>
      </measurement>
    </routers>
  </admin>
  <adminhtml>
    <menu>
      <measurement module="measurement">
        <title>Measurement</title>
        <sort_order>100</sort_order>
        <children>
          <measurementbackend module="measurement">
            <title>own measurement</title>
            <sort_order>0</sort_order>
            <action>admin_measurement/adminhtml_measurementbackend</action>
          </measurementbackend>
        </children>
      </measurement>
    </menu>
    <acl>
      <resources>
        <all>
          <title>Allow Everything</title>
        </all>
        <admin>
          <children>
            <measurement translate="title" module="measurement">
              <title>Measurement</title>
              <sort_order>1000</sort_order>
              <children>
          <measurementbackend translate="title">
            <title>own measurement</title>
          </measurementbackend>
              </children>
            </measurement>
          </children>
        </admin>
      </resources>
    </acl>
    <layout>
      <updates>
        <measurement>
          <file>measurement.xml</file>
        </measurement>
      </updates>
    </layout>
  </adminhtml>
</config>

I create this module with the help of Silksoftware and it show module frontend properly. i want whenever i install module then this button (Own Measurement) add automatically on product view page and on click button it  will redirect to module index.phtml file.


text:
Q: PHP fwrite() , could not fill txt after code execute my file look like this:
1.info
2.
3.info
4.
5.info
....

I tried with different mode in fopen but still the same.
<?php

$file = 'data.txt';
$lines = file($file);

$newArr = array();
$f = fopen($file,'r+');
foreach($lines as $value){
    $newArr[] = $value;
}
    unset($newArr[$_GET['id']-1]);

foreach($newArr as $vv){
    fwrite($f, $vv.PHP_EOL);
}

fclose($f);

?>

A: It appears that this is the same and should work:
$file  = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);

unset($lines[$_GET['id']-1]);

file_put_contents($file, $lines);

For whatever reason using fwrite():
$file  = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);

unset($lines[$_GET['id']-1]);

$f = fopen($file, 'w');
fwrite($f, implode($lines));

/*
foreach($lines as $vv) {
    fwrite($f, $vv);
}
*/


text:
Q: How do I hide the Menu Bar after uninstalling Epson Easy Photo Print on Windows 7? Epson Easy Photo Print is bloatware that installs this annoying toolbar into Windows 7's Explorer. It's hideous. Not only that, it forces the Menu Bar to display at all times. After uninstalling it, the Menu Bar cannot be disabled. I have tried checking and unchecking Organize / Layout / Menu bar and Organize / Folder and search options / View / Advanecd settings: / Always show menus. Neither of them disable the menu bar. The only option I have when right-clicking the menu bar is a horizontal rule followed by Lock all toolbars.

A: *

*Run Regedt32 (registry editor).

*Locate the toolbar location in your
registry.  Click the + next to HKEY_LOCAL_MACHINE to expand it, expand SOFTWARE below that,
etc. until you get down to
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Toolbar."
You will see a list of GUIDs (codes). Locate
{9421DD08-935F-4701-A9CA-22DF90AC4EA6} in the right pane .

*If you want to delete the toolbar, delete the GUID key.  But if you
just want to disable it, you can rename it to
XXX{9421DD08-935F-4701-A9CA-22DF90AC4EA6} , when you want to renable
it, just rename it back to the original GUID.

A: Old question but I found a more user friendly way was just to open up Internet Explorer and disable Easy Photo Print. Next time you open up an explorer window, the toolbar is gone!
Really bad show by Epson not cleaning this up. I uninstalled everything when I was cleaning a laptop and it still remained.

A: @Coops already answered this old question, but just to complete: In Windows 10, it is possible to disable the toolbar even Internet Explorer is not enabled (on new installations it is by default). Just go to Control Panel - Internet Settings - Programs - Manage Extensions.


text:
Q: Independence of random vectors - proof I have a problem to solve but my intuitive solution seems far too easy

Given three random Vectors X, Y, Z.
If we know that X, Y are independent, and Z and (X´, Y´)´ are independent, I have to show that  X, Y, and Z are independent.

My idea:
$$P(X<x, Y<y, Z<z)=P(X<x)*P(Y<y,Z<z)=P(X<x)*P(Y<y)*P(Z<z)$$
which would show independence. But I am not sure if this would prove it. It feels like I am missing a point here.

A: You have considered random variables, not random vectors. Your first step is not correct. The correct argument (in the case of random variables) is $$P(X<x,Y<y,Z<z)=P(X<x,Y<y)P(Z<z)$$ $$=P(X<x)P(Y<y)P(Z<z)$$ where the first equality holds because $Z$ is in dependent of $(X,Y)$ and the second equality is because $X$ and $Y$ are independent.


text:
Q: Getting error [Error: Data intent is null] while requesting auth token from azure active directory in react natve I am trying to authenticate through Azure Active Directory on a react native app using react-native-app-auth package which is the also the official package for this task. I have made the app registration, successfully made it to return me the "auth code" instead of "auth token", also I was able to make the mobile app redirected to the required screen. But right after returning me the "auth code" it says

[Error: Data intent is null]

The code I am using is below
import { authorize } from "react-native-app-auth";
import pkceChallenge from 'react-native-pkce-challenge';

const config = {
    clientSecret: "MY_SECRET_VALUE_FROM_AAD",
    issuer: 'https://login.microsoftonline.com/MY_TENANT_VALUE_FROM_AAD',
    clientId: 'MY_CLIENT_ID_AT_AAD',
    redirectUrl: 'com.sham://com.sham/android/callback',
    scopes: [
        'openid',
        'profile',
        'email',
    ],
    additionalParameters: {prompt: 'select_account'},
    serviceConfiguration: {
        authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
        tokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    },
};

try {
    const result = await authorize(config);
} catch (err){
    console.log(err)
}

// ALSO THROUGH
const challenge = pkceChallenge();
try {
    const result = await authorize({...config, code_challenge: challenge.codeChallenge, code_challenge_method: "S256"});
} catch (err){
    console.log(err)
}

I have also tried to install the demo app at https://github.com/microsoftgraph/msgraph-training-react-native but that app never gets installed maybe due to old dependencies. Please point out if someone knows what mistake I might be commiting.


text:
Q: Revel with mgo.v2 - How to return all data from a collection as json? I'm trying to build an API endpoint using Revel for Go.
My models/models.go looks like this -
type Category struct {
Name string        `bson:"name"`
Slug  string        `bson:"slug"`}

func GetCategories(s *mgo.Session) *Category {
var results []Category
Collection(s).Find(nil).All(&results)
return results}

My controllers/book.go looks like this -
type Category struct {
*revel.Controller
revelbasic.MongoController}

func (c Category) Categories() revel.Result {
b := models.GetCategories(c.MongoSession)

return c.RenderJson(b)}

I've configured my conf/routes like this -
GET /categories Book.Categories

When I run the code, I get this error -
cannot use results (type []Category) as type *Category in return argument
I understand that I'm doing something wrong with the database query.
Please help!

A: The error in your code is because of type mismatch between function GetCategories's return value declaration and what you are actually returning. To fix, change the return type to return a slice of results:
func GetCategories(s *mgo.Session) []Category {
    var results []Category
    Collection(s).Find(nil).All(&results)
    return results
}


text:
Q: How to apply a parametrised SQLITE query to each row of a table returned by another query (in the context of interpolation)? Input
My input consists of x_0_y_0 and x_1.
x_0_y_0 (table dates) contains the dates and values of the form:
timestamp   value
2000-01-01  1
2000-01-03  3
2000-01-05  5

x_1 (query dates_to_interpolate) contains the dates of the form:
timestamp
2000-01-01
2000-01-02
2000-01-03
2000-01-04
2000-01-05

Output
My desired output x_1_y1 (query interpolation_results) would be of the form:
timestamp    value
2000-01-01   1
2000-01-02   2
2000-01-03   3
2000-01-04   4
2000-01-05   5

Method (Attempt)
Using info in this thread and some native sqlite syntax I managed to get a query which gives an interpolated value (say 4) for a single selected date, say '2000-01-04'.
SELECT CASE WHEN next.timestamp IS NULL  THEN prev.value
            WHEN prev.timestamp IS NULL  THEN next.value
            WHEN next.timestamp = prev.timestamp  THEN prev.value
              ELSE ( ( julianday(date('2000-01-04')) - julianday(prev.timestamp) ) * next.value
                +    ( julianday(next.timestamp) - julianday(date('2000-01-04')) ) * prev.value
                   ) / (julianday(next.timestamp) - julianday(prev.timestamp))
       END AS interpolated_value
FROM
(SELECT dates.timestamp, dates.value FROM dates WHERE dates.timestamp <= date('2000-01-04') ORDER BY dates.timestamp DESC LIMIT 1) AS prev
CROSS JOIN
(SELECT dates.timestamp, dates.value FROM dates WHERE dates.timestamp >= date('2000-01-04') ORDER BY dates.timestamp ASC LIMIT 1) AS next

Now I would like to parametrise this using @interpolation_date rather than '2000-01-04' so I have a function of the form interpolated_value(). It seems this could work if I was to call this programatically (say from Python or MATLAB). The problem is that I would like to apply interpolated_value() to dates_to_interpolate using sqlite syntax only (in a single query). I found out that sqlite does not support parameters in views, it does not support custom functions. I did see attempts at implementing loops (which I think I might need here); loops seems to involve recursive triggers or WITH syntax which I am not quite familiar with.

A: You want something like this:
SELECT timestamp,
       (...) AS value
FROM x1;

This can simply be done by making the other query a correlated subquery, i.e., just replace '2000-01-04' with x1.timestamp wherever it occurs:
SELECT timestamp,
       (SELECT CASE WHEN next.timestamp IS NULL  THEN prev.value
                    WHEN prev.timestamp IS NULL  THEN next.value
                    WHEN next.timestamp = prev.timestamp  THEN prev.value
                      ELSE ( ( julianday(x1.timestamp) - julianday(prev.timestamp) ) * next.value
                        +    ( julianday(next.timestamp) - julianday(x1.timestamp) ) * prev.value
                           ) / (julianday(next.timestamp) - julianday(prev.timestamp))
               END AS interpolated_value
        FROM
        (SELECT dates.timestamp, dates.value FROM dates WHERE dates.timestamp <= x1.timestamp ORDER BY dates.timestamp DESC LIMIT 1) AS prev
        CROSS JOIN
        (SELECT dates.timestamp, dates.value FROM dates WHERE dates.timestamp >= x1.timestamp ORDER BY dates.timestamp ASC LIMIT 1) AS next
       ) AS value
FROM x1;


text:
Q: How to display a picture on JFrame? I'm doing this exercise where I'm supposed to write a program that simulates a race between two cars.
I've created a JFrame and added two rectangles that are supposed to be the tracks.
But I can't insert the cars. I have googled and tried some solutions but it just doesn not work out.
Here is my code.
public class Race extends JComponent {
private ImageIcon image;
public void paint(Graphics g) {
    g.setColor(Color.GRAY);
    g.fill3DRect(30, 150, 530, 55,true);
    g.setColor(Color.GRAY);
    g.fill3DRect(30, 250, 530, 55, true);
    g.setColor(Color.BLACK);
    g.fill3DRect(90, 130, 12, 189, true);
}
public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setPreferredSize(new Dimension(600, 400));
    window.getContentPane().setBackground(Color.GREEN);
    window.setResizable(false);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new Race());
    window.pack();
    window.setVisible(true);
}
}

Where and how can I add two pictures?
Thanks

A: This is how you would add a image into your JFrame
frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));


text:
Q: Hash key multiplying by 9 and modulus I have this peculiar piece of code that is bothering me,
   // exbPtr points to 128-bit unsigned integer
   // lgID is a "short" with 0xFFFF being the max value

   int hash = (*exbPtr + (int)lgID * 9) & tlpLengthMask;

Initially this "hash table", which is really an array is initialized to 256 elements, and tlpLengthMask is set to 255.
Then there is this mysterious code .. with a comment right above it saying "if we reached here .. there has been a collision". And then it starts looping back again, so looks like this is a hash collision, and re-hashing?
   hash = (hash + (int)lgID * 2 + 1) & tlpLengthMask;

In addition, there is a ton of debug code that says that the length of this array should be a power of 2 because we're using mask as a modulus.
Can someone explain what the authors intent was? What is the reasoning behind this?
EDIT -- what I'm trying to discern is why he multiplied by 9, and then why multiply by 2 to re-hash.

A: There are three possibilities:
1) The original author just constructed the hashing functions more or less randomly, saw that they worked well enough, and left it at that.
2) The original author had test data that well represented the actual data and saw that these functions worked extremely well for his exact application.
3) This code is performing very poorly and his hash table is not operating efficiently at all.
The only real requirement is that the output look evenly distributed over the hash table for whatever input he actually encounters and always produce the same output for the same input. While these kinds of functions generally perform poorly, they may be good enough for this specific application.
By the way, this type of open hashing doesn't work in the face of deletions. For example, say you add one record to the table. Then you go to add a second, but it collides with the first, so you skip forward to add the second. Everything's fine now -- you can find both the first record (directly) and the second record (by skipping over the first when you find it at the second record's hash location).
But if you delete the first record, how do you find the second? When you look at the second record's hash location, you find nothing. Do you try skipping? If so, how many times?
There are workarounds to these problems, but they tend to be very easy to do incorrectly.


text:
Q: Perl parsing ps fwaux output I am trying to figure out children processes of a given parent from ps fwaux (there may very well be a better way to do this). Basically, I have daemons running that may or may not have a child process running at any given time. In another script I want to check if there are any child processes, and if so do something. If not, error out.
ps fwaux|grep will show me the tree, but I'm not exactly sure what to do with it. Any suggestions would be great.

A: You could parse the results of a call to Proc::ProcessTable:
use Proc::ProcessTable;

my $processes = Proc::ProcessTable->new(enable_ttys => 0);
my @children = grep { $_->cmndline =~ /some_pattern_matching_your_children/ }  @{$processes->table};

# or:
my @children = grep { $_->ppid == $parent_pid } @{$processes->table};

But stepping back to the larger problem of tracking children: instead of grepping the process table, the children should track themselves using pid files.  File::Pid can help you with that.

A: As an update, this is what I ending up doing (in bash ...)
while :
do
        # find parent ids
        PIDS="`ps -eao bsdtime,pid,command | egrep -v egrep | egrep 'processname' | awk '{print $2}'`"
        count=0
        # loop through ppids and look for children
        for j in ${PIDS}
        do
                #echo "Parent process = $j"
                CPID="`ps -ef | awk '$3 == J {print $2}' J=$j`"
                for i in ${CPID}
                do
                        #echo "Child process = $i"
                        let count++
                done
        done

Then if count > 0, there are child processes.


text:
Q: The text on the right side cannot be shown in tkinter treeview     self.fm10 = tk.Frame(self.fm5)
    self.fm10.grid(row=3,rowspan=3,columnspan=3,padx=5,pady=5)

    self.treeview_box2 = Treeview(self.fm10,columns=('Assignment'))
    self.style2 = Style()
    self.style2.configure('Treeview',rowheight=70)

    self.treeview_box2.heading('#0',text='Date')
    self.treeview_box2.heading('Assignment',text='Assignment')

    self.treeview_box2.column('#0',width=60,stretch=False)
    self.treeview_box2.column('Assignment',width=175,stretch=False)

    self.treeview_box2.pack(expand=True,pady=5)

    my_cursor.execute('SELECT * FROM schedule')
    self.schd = my_cursor.fetchall()
    print(self.schd) ##A138MS Excel Test
    self.count2 = 1
    for s in self.schd:
        self.treeview_box2.insert('',tk.END,text=s[0],values=(s[1]))
        self.count2 += 1

In this code, I am trying to show the value s[1] on the treeview_box2 second column. The program is run successfully and stored into the database table. However the right side of value s[1] cannot be shown and only the left part is shown on the treeview_box2 table. May I ask is there any problems causing the value can be printed out but only the right part cannot be shown on the table?


text:
Q: How to generate an array of the alphabet? In Ruby I can do ('a'..'z').to_a to get ['a', 'b', 'c', 'd', ... 'z'].
Does JavaScript provide a similar construct?

A: A short ES6 version:

const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);

A: in case if you need a hard-coded array of the alphabet, but with a less typing. an alternative solution of what mentioned above.
var arr = "abcdefghijklmnopqrstuvwxyz".split("");

will output an array like this
/* ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m","n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] */

A: You can easily make a function to do this for you if you'll need it a lot

function genCharArray(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}
console.log(genCharArray('a', 'z')); // ["a", ..., "z"]

A: Magic
[...8337503854730415241050377135811259267835n.toString(36)]

// chrome & firefox
let a1 = [...8337503854730415241050377135811259267835n.toString(36)];

console.log(a1);

// version working on all browsers (without using BigInt)
let a2 = [...[37713647386641440,2196679683172530,53605115].map(x=>x.toString(36)).join``];

console.log(a2);

A: In case anyone came here looking for something they can hard-code, here you go:
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

A: Try
[...Array(26)].map((x,i)=>String.fromCharCode(i + 97))

let alphabet = [...Array(26)].map((x,i)=>String.fromCharCode(i + 97));

console.log(alphabet);

Update
As you noticed in comments this idea was already used in this answer (I missed it) - but this answer is shorter so treat it as size improvement of that older answer

A: new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

Use 97 instead of 65 to get the lowercase letters.

A: To add to @Sherwin Ablaña Dapito solution ( I like to have some hints in answers)

*

*65 is start for upper Alphabet, 26 is number of chars in Alphabet

*fill() method changes all elements in an array to a static value (1), in-place.

*map() is applied to every elem, creates a new array and has a func as arg.

*=> arrow function expression, can be written as function (i){ return i+ 65;}

*_ in map: ignore param (placeholder value, no value here) and use second = index

*String.fromcharcode is self explanatory

new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

A: By using ES6 spread operator you could do something like this:
let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));

A: Generate Character List with one-liner

const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));

console.log("from A to G", charList('A', 'G'));
console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
console.log("reverse order from Z to P", charList('Z', 'P', -1));
console.log("from 0 to 5", charList('0', '5', 1));
console.log("from 9 to 5", charList('9', '5', -1));
console.log("from 0 to 8 with step 2", charList('0', '8', 2));
console.log("from α to ω", charList('α', 'ω'));
console.log("Hindi characters from क to ह", charList('क', 'ह'));
console.log("Russian characters from А to Я", charList('А', 'Я'));

For TypeScript
const charList = (p: string, q: string, d = 1) => {
  const a = p.charCodeAt(0),
    z = q.charCodeAt(0);
  return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
    String.fromCharCode(a + i * d)
  );
};

A: I saw an answer I loved above which was the hardcoded list of the english alphabets but it was in lower case only and I needed upper case too so I decided to modify it in case someone else needs it:
const lowerAlph = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
const upperCaseAlp = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

A: Personally I think the best is:
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

Concise, effective, legible, and simple!
EDIT:
I have decided, that since my answer is receiving a fair amount of attention to add the functionality to choose specific ranges of letters.

function to_a(c1 = 'a', c2 = 'z') {
    a = 'abcdefghijklmnopqrstuvwxyz'.split('');
    return (a.slice(a.indexOf(c1), a.indexOf(c2) + 1));
}

console.log(to_a('b', 'h'));

A: A lot of these answers either use an array of characters or String.fromCharCode, I propose a slightly different method that takes advantage of letters in base36:
[...Array(26)].map((e,i)=>(i+10).toString(36))

The advantage of this one is purely code golf, it uses fewer characters than the others.

A: Here is a quick one-liner
No dependencies!
Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x));

console.log(Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x)));

A: Try this

let name = ''

for(let i=0; i<26; i++){
  name+=(i+10).toString(36)
}

console.log(name.split(''))

A: Using JavaScript's Array.from syntax allows you to create an array and perform a mapping function on each of the array elements. Create a new array of length 26 and on each element set the value equal to the string obtained from the char code of the index of the current element plus the ascii magic number.
const alphabet = Array.from(Array(26), (e, i) => String.fromCharCode(i + 97));

Again, 97 may be interchanged with 65 for an uppercase alphabet.
The array may also be initialized with values using the object's keys method rather than utilising the index of the map
const alphabet = Array.from(Array(26).keys(), i => String.fromCharCode(i + 97));

A: const ALPHA = Array.from({ length: 26 }, (_, i) => String.fromCharCode('a'.charCodeAt(0) + i)); // ['a', 'b', ...'z']

I believe the above code is more idiomatic. Short enough to be an inline code.
You don't have to remember the charCode of your start letter and configurable to retrieve subsets of the alphabet by simply controlling the length and start letter e.g
Array.from({ length: 3 }, (_, i) => String.fromCharCode('x'.charCodeAt(0) + i)) // ['x', 'y', 'z]

A: Just for fun, then you can define a getter on the Array prototype:
Object.defineProperty(Array.prototype, 'to_a', {
  get: function () {
    const start = this[0].charCodeAt(0);
    const end = this[1].charCodeAt(0);
    return Array.from(Array(end - start + 1).keys()).map(n => String.fromCharCode(start + n));
  }
});

Which makes it possible to do something like:
['a', 'z'].to_a; // [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", ..., "z" ]

A: //using map 1 line code
let alphabet =[...Array(26)].map( (_,i) => String.fromCharCode(65+i) )

// using array for inserting A-Z
let newArray = []
for(var i = 0; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i))
}

// using array for inserting a-z
let newArray = []
for(var i = 0`enter code here`; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i).toLowerCase())
}

//using split
 let a = 'abcdefghijklmnopqrstuvwxyz'.split('');

A: I like to use this:
[...Array(26).keys()].map(n => n + 'a'.codePointAt(0)).map(ch => String.fromCharCode(ch))

A: See result

function getAsciiToString(from, total) {
  let count = 0;
  let asciiLetters = "";

  while (count < total) {
    const asciiDigit = from.charCodeAt(0) + count;
    asciiLetters += String.fromCharCode(asciiDigit);
    count++;
  }

  return asciiLetters;
}

console.log(getAsciiToString("a", 26));
console.log(getAsciiToString("A", 26));
console.log(getAsciiToString("0", 10));

A:

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + (i * step));

let alpha  = range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) => String.fromCharCode(x));
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
console.log(alpha);

A: Here's another way:
const chars = [];
for (let i=65; i<=65+25; i++){
  chars.push(String.fromCharCode(i));
}

console.log(chars, Array.isArray((chars )));

A: This is the most efficient as there are no wasted temporary arrays.

const alphabetLowerCase = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i));

console.log(alphabetLowerCase);

const alphabetUpperCase = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));

console.log(alphabetUpperCase);

A: No Javascript or Jquery doesnot provide anything like that. You have to create your own array.
You may try like this:
var alpha = ["a","b","c",....];

or better try like this:
var index = 97;
$("#parent .number").each(function(i) {
    $(this).html(String.fromCharCode(index++));
});

DEMO


text:
Q: How to connect ESP32 I am getting the following eroor while connecting ESP32
Arduino: 1.8.19 (Windows Store 1.8.57.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"
Multiple libraries were found for "WiFi.h"
In file included from C:\Users\Ayan Atal\Desktop\College\SEM 6\Minor\Ultrasonic\Ultrasonic.ino:3:0:
Used: C:\Users\Ayan Atal\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\libraries\WiFi
C:\Users\Ayan Atal\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:33:22: fatal error: AsyncTCP.h: No such file or directory
Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\libraries\WiFi
compilation terminated.
exit status 1
Error compiling for board ESP32 Dev Module.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

A: There is library name conflicts. I usually solve this by first uninstalling Arduino IDE and then deleting arduino libraries, and then reinstalling everything from scratch. Sometimes using older versions of arduino IDE also had helped.
Thank You,
Have a Great Day,
Naveen.


text:
Q: About CompleteRequest(); I'm using Response.Redirect(url, **false**); in order to prevent an exception. However, I have seen it recommended to use CompleteRequest(); after it, and I don't understand that. Example: here on MSDN  .  As far as I know, CompleteRequest will not terminate the execution (though it will affect rendering) so any code with persisting consequences such as database writes - will have an effect. And therefore stopping the code must be managed by a return etc. And it is not needed for the Redirect to process.
Is my understanding correct? (I'm asking because of the link above and similar ones.)

A: Your understanding is correct. Using CompleteRequest() signals the ASP.NET runtime that no further processing on the request is needed and it bypasses all the events in the HTTP pipeline and directly calls the EndRequest event. However, it won't stop executing the the remaining lines of code. It would just end the request gracefully in order to prevent data loss.


text:
Q: Clearing /boot. Advice which files are safe to purge My boot folder was full. I removed some old kernels. Could you advise which of these can be also purged?
gideon@gideon:~$ uname -r
4.10.0-32-generic
gideon@gideon:~$ ls /boot
abi-4.10.0-27-generic         memtest86+.bin
abi-4.10.0-28-generic         memtest86+.elf
abi-4.10.0-30-generic         memtest86+_multiboot.bin
abi-4.10.0-32-generic         System.map-4.10.0-27-generic
config-4.10.0-27-generic      System.map-4.10.0-28-generic
config-4.10.0-28-generic      System.map-4.10.0-30-generic
config-4.10.0-30-generic      System.map-4.10.0-32-generic
config-4.10.0-32-generic      vmlinuz-4.10.0-27-generic
efi                           vmlinuz-4.10.0-27-generic.efi.signed
grub                          vmlinuz-4.10.0-28-generic
initrd.img-4.10.0-27-generic  vmlinuz-4.10.0-28-generic.efi.signed
initrd.img-4.10.0-28-generic  vmlinuz-4.10.0-30-generic
initrd.img-4.10.0-30-generic  vmlinuz-4.10.0-30-generic.efi.signed
initrd.img-4.10.0-32-generic  vmlinuz-4.10.0-32-generic
initrd.img-4.8.0-36-generic   vmlinuz-4.10.0-32-generic.efi.signed
lost+found


text:
Q: Flashing STM32 Nucleo from Raspberry Pi I'm using an STM32 Nucleo board connected to a Raspberry Pi. To flash the MCU I drop a binary file to a mounted drive. The problem is that it takes a random, and sometimes long time, from the moment I drop the file to the actual moment the MCU is flashed. As a contrast, I have an instantaneous result when flashing from Windows. Is there a way to expedite the process?

A: Linux thinks it's just some external storage, and holds back (caches) writes while it's mounted. You can try to

*

*umount the Nucleo interface after copying, forcing everything to be written back

*issue a sync command after copying

*mount it with -o sync to disable write caching.

The first two methods are preferred over -o sync (as long as they work), because writes are still cached until the system is told to write everything, using up fewer flash write cycles.
If none of the above works reliably, then install openocd or texane st-link on the pi, and use that for flashing.