unexpected token in JSON at position 0 Api Rest file uploading

Question: I'm trying to make an API using express in nodejs.
This api should get a request with a photo and post that photo to firebase storage.
The main problem is that when the server recieves a petition with a File object it throws this error
SyntaxError: Unexpected token � in JSON at position 0
at JSON.parse ()
at createStrictSyntaxError (C:\Users\yupoj\Desktop\api\node_modules\body-parser\lib\types\json.js:158:10)
at parse (C:\Users\yupoj\Desktop\api\node_modules\body-parser\lib\types\json.js:83:15)
at C:\Users\yupoj\Desktop\api\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\yupoj\Desktop\api\node_modules\raw-body\index.js:224:16)
at done (C:\Users\yupoj\Desktop\api\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\yupoj\Desktop\api\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
This is the code for the server:
const express = require("express");
const morgan  = require("morgan")
const cors    = require('cors')

const app = express();

// Settings

app.set('port', process.env.PORT || 8000)
app.set('json spaces', 4)

// middleware

app.use(morgan("dev"))
app.use(express.json({limit: "1000mb"}))
app.use(express.urlencoded({extended: true}))
app.use(cors({origin: "http://localhost:3000"}))

// routes

app.use(require("./routes/index"))

app.listen(app.get('port'), () => {
    console.log("Server using port " + app.get('port'));
});

Routes
const { Router } = require('express')

const router  = Router()

router.post('/postImage', async (req, res) => {
    try {
        console.log("HELLO") // Code never reach here

        // TODO

        return res.status(200).json({messae: "DONE"})
    }
    catch(error) {
        console.log(error)
        return res.status(500).json({error})
    }
})

module.exports = router

Client side
const postImage = async (image) => {
    console.log(image)

    const response = await fetch("http://localhost:8000/postImage", {
        headers: {
            'Content-Type': 'application/json',
            'Accept':       'application/json',
        },
        method: "POST",
        body: image
    })

    console.log(await response.json())
}

Comment: @JorgeSánchez — That isn't what you claim here: 'Content-Type': 'application/json',
Comment: See https://stackoverflow.com/questions/68710311/empty-body-api-rest-express-node-js#comment121436390_68710311
Comment: What is `image`? The argument you pass to `postImage`. Is it really JSON?
Comment: image is a File type object
Comment: is it a valid JSON?
Comment: Then what should I put instead of it?
Answer: So on the client side, you have console.log(image) - assuming this doesn't print a nice JSON format, as this is an image so it'll more than likely print garbage.
You need to create a new object (example below) that will contain the image data. Then use this newly created object as the body of your post.
var json_data = {
   "image": image
}
const response = await fetch("http://localhost:8000/postImage", {
        headers: {
            'Content-Type': 'application/json',
            'Accept':       'application/json',
        },
        method: "POST",
        body: json_data
    })


BigQuery dataset level access control via IAM

Question: Issue: In GCP IAM I have >30 users assigned the pre-defined roles BigQuery Data Viewer and BigQuery Data Editor, and now when I create a new dataset, it's automatically accessible to these 30+ users because of "policy inheritance".
Question: As BQ project admin, I want a newly created dataset only accessible to certain users (a small subset of the 30+ users). What's the best approach to do this? Thanks!
Answer: You cannot override the permissions granted at higher leves. So, if you want to restrict access at dataset level, the best approach would be to:
1) Remove the current permissions BigQuery Data Viewerand BigQuery Data Editor from project level.
2) Grant the permissions again, but only at dataset level
This also complies with the recommended best practice of least privilege. Also, if possible, use groups to grant the permissions, as it will be easier to manage.
In addition to this, you could use another project to create the dataset and allow access to the desired subset of users; however, I wouldn't recommend this approach as it only makes more difficult to handle the data and the users with access to them.


Slow waiting bug? (Xbox 360)

Question: When I press A to wait it takes 30 seconds to actually start waiting. Is there any way to fix this?
Comment: The "A" key isn't default to waiting.  It's default to strafe left.  Did you double bound the key manually?
Answer: Are you sure you're pressing A? It isn't the default key for waiting as Nelson said. You need to press it once.

Slow waiting bug? (Xbox 360)


Connect excel to azure datalake gen 2 with OAuth

Question: When I am looking at microsoft documentation of excels connections possibilities and it says that my Microsoft 365 Apps for enterprise can connect to Azure Blob Storage and Azure Data Lake Storage
I want to connect to my Datalake Gen 2 in excel, I'll go to the Data tab Get Data > From Azure > From Azure Blob Storage

Here is the question: How do I connect to my Gen 2 datalake with Azure AD / OAuth / username (email@example.com) and password? Storage Account Key Access is disabled on this datalake. That includes Shared key and shared access signature (SAS)
Answer: I can see only a UI connector for ADLS Gen1

Alternately for ADLS Gen2....
Here is something I tried, you can use user delegation SAS Key, which is secured with Azure AD credentials.

Generate a user delegation SAS url for that blob you want to access.

Select Web Source to get Data,

If prompted, select Anonymous
Comment: Shared access signature (SAS) is not an option as authorization with Shared Key is disabled for datalake gen 2 as mentioned above
Comment: yes, and that is why I have mentioned to use User Delegation key Option. There are two types of authorization, account access key for Shared Key authorization and  user delegation SAS is authorized with Azure AD even when AllowSharedKeyAccess property is set to false. Please try as shown in snip once
Answer: First I want to thank KarthikBhyresh-MT for his input that inspired me to find the right solution.
The Solution
First I found the url to the desired file inside the datalake inside azure portal

I copied the changed the url and changed the word blob to dfs
In excel (office 365) I Get Data > From Web, and put in the altered url. From there I get this image, where I can log into the datalake with OAuth credentials

Then I could load the simple.csv file into excel, work on it and see the transactions in the datalake logs.


install dependencies from CRAN for a package installed from source

Question: I want to give a beta version of my package to a coworker for testing purposes.
I build the package and put the .zip file on the Network Folder.
The Problem is, how to tell R that it should install the package from the ZipFile but its dependencies from CRAN?
install.packages("path\\to\\zipfile.zip", source = TRUE, repos = NULL)

Because repos =  null disables the dependency resultion. If under stand the documentation correctly:

dependencies
logical indicating whether to also install uninstalled packages which these packages depend on/link to/import/suggest (and so on recursively). Not used if repos = NULL. Can also be a character vector, a subset of c("Depends", "Imports", "LinkingTo", "Suggests", "Enhances").

I would like to give the coworker a short snippet of code to install for himself without him having to interact further with the installation.
Comment: `install.packages()`?
Answer: As the Imports or dependencies might change in later development, i would prefer not to hardcode them.
I found devtools::install() which satisfies this requirement. Although it needs devtools.


Momentary switch - press once needs to give 5 seconds of power

Question: Electronics is not my forte, so bear with me on the nomenclature.
Backstory
We have an old house and my wife bought me some old butler bells to get going as our door bell.

I found a motor which turns a handle to throw the bell left and right and when it's on, it needs to be on for a few seconds for the momentum to build up and ring properly.
Now, I can have a door bell button and if I hold it on for 4-5 seconds, the bell rings nicely. However, I have this old door bell puller.  I have a momentary switch installed at the back of it so, at rest, the switch is pressed and no power flows (momentary off??).  When you pull the handle, the switch is open and power flows while you pull it. This works, but I've found most people when they pull it, they just let it go.  So I want to do something that allows power to flow for a minimum of 5 seconds, whether I pull it once and let it go or for longer. Obviously if I pull and hold for 10 seconds, it should ring for 10 seconds.
Question
What can I add to a momentary off switch, to allow it to run for a minimum of 5 seconds on one press/release?
Thank you.
Update from the comments.  This is all about 12v from a normal doorbell transformer.
Comment: People will be better able to help you if you provide details such as the voltage and current requirements of your bell. But, yes, there are circuits that will accomplish what you want.
Comment: attach a set of gears, or a pulley, to the motor ... the gears (pulley) drive a wheel at a rate of 5 seconds per revolution ... the wheel has a notch (low spot) ... low spot allows a switch to open ... pressing the doorbell button starts the motor ... the wheel operated switch keeps the motor going for 5 seconds ... the switch would be a microswitch with a roller ... https://www.surpluscenter.com/productImages/image.axd/i.11-3506/w.1000/h.1000/Roller+Microswitch_L.jpg
Comment: Cheap and available solution to what jsotola has suggested - a windscreen wiper motor with return to home power off.  Power it on and it has a cam that keeps power on until the motor returns to horm position. Take power from the motor lead. Motor action a bonus that can be used or ignored.
Comment: Someone queried this being here rather than on DIY. This is (or can be if desired) an electrical design question so is OK enough here.
Comment: Try pneumatic time delay lighting switch.
Comment: What are the voltage and current requirements of the thing you are switching on and off?
Comment: Motor voltage and current? Mains or low voltage. AC or DC. ???
Comment: Sorry, i should have mentioned this this is all over a 12v doorbell circuit which is stepped down from the mains
Comment: I have an old house too, and at the risk of evading the question I have to ask ... if you've gone to all this trouble to create this beautiful ode to the past, why not solve it properly, which is to say, mechanically?  Cables, pulleys, levers.  If you want to be showy you use all brass fittings and leave them exposed.
Answer: There are 2 approaches possible here:

You grab a bunch of capacitors, resistors and transistors and start messing around to make a timer circuit. This is the most fun (according to the users of this board) and the most educational, but it is also the most likely to fail. This solution is also super cheap, if you don't value your time much.

You grab an off the shelf component that has solved this issue thousands of times in the field. I personally like the Omron H3DK series timer relays. They are robust and intuitive to use.
Comment: Questions about timing circuits with such long delays, when asked on the EE site, especially if they involve a 555, always end with at least one comment to the tune of "just use an MCU".
Comment: Use a time delay relay for simple reliable behavior from off-the-shelf components - or have an electronics project. Perfect answer.
Answer: I would purchase a cycle timer, with the button pushed the relay pulls in for a time period you select sometimes with switches , or dials . I have some that work on ac-dc120 -240v  others that work on 12-36v ac or dc, both have isolated relay contacts so you could operate a high voltage device with a standard low voltage, (doorbell signal circuit)  these are made by  Omron (h3CR-A8) Allen Bradley, automation direct (ms4sm-ap-arc).
Of the brands I have handy those are 100-240v,  24v ac-dc MS4SM-CE-ADC.  This with the appropriate socket can be easily wired and you can dial the ringer for whatever length you want if you want 5 seconds for a bump of the switch set it for seconds and turn the dial to 5.
I use these for all kinds of things. If the 100-240v model is used it needs to be in an enclosed project box. If the 24v one is used I do like to have them in a box but the rules are quite lax in that case.
Answer: I'd use a modern time delay relay for your "one shot"
While it's possible to fabricobble a one-shot function out of components rather readily in this day and age, if you want a known-reliable result, though, you're best off with a premade, multifunction time delay relay.  I would use the Macromatic TE-8816U here; it's inexpensive (~$40 as of the time of this writing), can be mounted in a variety of enclosures as it uses standard DIN rail mounting, and is fully UL 508 listed for being field-applied-and-wired.  One note is that you'll have to run a 3-wire control cable from the switch to the relay with this part, as it uses a dry-contact trigger in one-shot mode.


Why .profile (and not .bashrc) appends ~/bin to path?

Question: Since .bashrc is more "generic" (in the sense that .profile sources it), why "include ~/bin to path" procedure is not inside .bashrc? Why the user would not want it in a non-login shell? (Especially nowadays, where non-login shells are more common*.)
I know I can manually do such change, but I want to know if there is a reason.
*can't prove it, but I think that is the case.
Answer: ~/.bashrc and /etc/bash.bashrc are run every time an interactive bash shell is started.
In contrast, ~/.profile and /etc/profile are run every time any login shell is started. So it does not have to be a bash shell, but it does have to be a login shell (and many bash shell instances are not login shells).

A bash shell is a shell where the shell program that provides it is bash, rather than some other program, such as dash.
A login shell is a shell that is started automatically as a consequence of logging in, to provide the user interface (graphical or command-line) for the login. When a login shell is exited, the login terminates.

Therefore, putting a commend that appends entries to PATH in a bashrc file would:

Do nothing when the shell is not bash, which is often the case. For example, PATH would be unmodified when you're in a graphical login session. Remember, PATH is not just used by command-line programs.
Append it over and over again in the presence of nested bash shells. So, if you start a shell within a shell--which is very common, for a variety of reasons--then you'll have multiple ~/bin entries stacked onto your PATH. This makes the PATH environment variable difficult to read, and sometimes also decreases performance.

These would be undesirable. Thus it would be wrong to put this in a bashrc file; it really belongs in ~/.profile. ~/.profile is the right place for:
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

Non-login shells have login shells (or something that behaves like a login shell) as their parent, and inherit most of their environment variables, including PATH, from this login shell. So putting path-modifying commands in ~/.profile requires that you log out and back in for them to be effective, but it affects the environment of non-login shells too (as well as the environment for programs that are not shells, since every program gets its own set of environment variables--called its "environment"--inherited from its parent process).
Comment: I understand. But this decision still doesn't make sense for me. If a open a terminal right now it loads only .bashrc, then I wont able to see my private bin.
Comment: @borges If the default configuration doesn't work well for you, you should feel free to change it. (It's your computer, after all. Or at least your account.) But this sounds like a one-time thing. That is, is sounds like your private `bin` directory didn't exist when you logged on, and that you have created it during this login session. If you log out and back in, it will be in your `PATH`. Since creating your private `bin` directory is something that only needs to be done once, this is a one-time inconvenience.
Answer: It's because traditionally environment variables go only in /etc/profile or .profile. The bashrc file is for things like aliases, prompt settings, shell options and so forth (i.e. things that relate directly to the shell).


Validate user input in using Global variables

Question: I would like a user to input numbers from 1 to 4 and check they are in this range. I have modified some code which I found on Stack Overflow . Is this a good way to validate? Could I have accessed  the variables guessX and guessY without declaring them as global variables?
I get the error:

SyntaxWarning: name 'guessY' is assigned to before global declaration

My code:
def validNum(guessX,guessY):
    if guessX < 1 or guessY < 1 or guessX > 4 or guessY > 4:
        print ("Guess is not in range and should be between \
               1 and 4. Try again.")
        return 0

    else:
        return 1

def getInput():
    while 1:
        guessX = int(input("Enter your guess for the X coordinate: "))
        guessY = int(input("Enter your guess for the Y coordinate: "))

        if validNum(guessX, guessY):
            break
    print ("good: %s is a valid coordinate for X." % guessX)
    print ("good: %s is a valid coordinate for Y." % guessY)
    # Is it a bad idea to declare guessX and GuessY as global?
    global guessX
    global guessY

Answer: That is not technically an error.  Instead, it is a warning from Python that your code may be incorrect.
Specifically, it is complaining that you used the names guessX and guessY before you declared them as being global with global.  Code that does this is not regarding the global status of the names as it should and is usually invalid or logically flawed.
To fix the problem, simply move your global declarations to the top of the function:
def getInput():
    global guessX
    global guessY
    ...

Or, more simply:
def getInput():
    global guessX, guessY
    ...

In fact, global declarations should always be at the top of functions so that they are easily visible.
Note however that it is a best practice to avoid global variables in Python.  Most of the time, the presence of global x in a program means that the design needs reworking.
Comment: @StiofanONia - It actually looks like you do not need the `global` declarations at all since you are passing the `guessX` and `guessY` values to `validNum` (as you should).  Instead of altering globals, you should stick with passing values to functions and then (re)assigning names to their return values.
Comment: Thank you. Super swift reply!  Works fine and Python not complaining anymore. Not so sure on how to rework. Maybe I need to look at more examples on validating inputs
Comment: @StiofanONia - avoiding globals is nothing to do with validating inputs. it has everything to do with good designs. The classic way to avoid globals is to use classes.
Comment: I guess that I need to look at some tutorials using classes. Hadn't quite got that far yet. Thanks for the tip
Comment: Thanks I did as you had suggested re assigning names to the return values and was able to avoid using global variables.
Comment: Happy to have helped!  Please do not forget to accept my answer though by clicking the check.  Doing so lets people know that this problem is solved.


Using CSS Clip-Path to Create a Skewed Background on Menu Item?

Question: Hi and thank you in advance for your help. I've been messing with this for days but can't figure it out. I'm trying to get a skewed box/parallelogram colored background behind the active/hover menu items and can't get it to size properly.
My code is:
#header .main-menu > li.menu-item.active {background-color: #fdb819; clip-path: polygon(66% 20%, 100% 20%, 33% 80%, 0 80%);}
How it currently looks;

The above image is what I'm getting. The yellow background is way too narrow and doesn't "fill" the space behind the text. Can anyone please help me fix this?
I've tried so many different things that I can't even remember now. I want it to look similar to this example when finished:
What I want it to look like:
Answer: I would not be inclined to rely on a clip-path for this particular purpose. I would go with background gradients. There are several kinds to choose from for this, you could do it with 2 or 3 gradients, I chose to do it with 2 linear-gradients that start transparent at an angle and then use the yellow in question. And they need to be sized to be half of the element's width. In that way it will work if the size of the element is longer or shorter. It could also be done with a combination of conic-gradients too.

section#header {
  background: #fff;
}

ul.main-menu {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 2ch;
}

ul.main-menu a {
  display: block;
  text-decoration: none;
  padding: 2ch 4ch;
  color: #fff;
  font-family: sans-serif;
  color: #777;
}

#header .main-menu>li.menu-item.active a, #header .main-menu>li.menu-item.active a:hover {
  color: #fff;
  background-repeat: no-repeat;
  background-size: 50% 100%;
  background-position: 0 0, top 0 right 0;
  background-image: linear-gradient( 115deg, transparent 25px, #fdb819 0), linear-gradient( -65deg, transparent 25px, #fdb819 0);
}

#header .main-menu>li.menu-item a:hover {
  background-repeat: no-repeat;
  background-size: 50% 100%;
  background-position: 0 0, top 0 right 0;
  background-image: linear-gradient( 115deg, transparent 25px, #ccc 0), linear-gradient( -65deg, transparent 25px, #ccc 0);
}

SHOP ALL PARTS

DRIVER INFO

LIVE


Computing $\iint_{\Omega} (x+y^2) \ dx \ dy$ where $\Omega$ is a parallelogram

Question:
Compute $$\iint_{\Omega} (x+y^2) \ dx \ dy$$ where $\Omega$ is a parallelogram bounded by $x+y=0$, $x+y=1$, $2x-y=0$ and $2x-y=3.$

Graphing this in Desmos produces the following plot

I was instructed to use change of variables here, but I'm not familiar with that at all. How can I compute this kind of integral? Any tips would be much appreciated.
Comment: I recommend the change of variables $u = x+y$ and $v=2x-y$. You say you don't know about change of variables - do you mean you don't know anything, or just how to apply it in this case? You may find [this resource](https://tutorial.math.lamar.edu/Classes/CalcIII/ChangeOfVariables.aspx) helpful.
Comment: Thank you for the link. I haven't had any introductory to this so this is helpful.
Answer: In single variable calculus, you used a change of variables called $u$-substitution to make some integrands nicer. In multivariable calculus, you can use a change of variables for that purpose, or for making the region over which you are integrating nicer. Here, the region is not a Type 1 or Type 2 or polar region. But we can change variables to $u$ and $v$ in a clever way to make the region much nicer:$$u=x+y,\quad v=2x-y$$
With this change of variables, the region we integrate over is simply a rectangle: $0\leq u\leq 1, \ 0\leq v\leq 3$.
We have to solve these equations for $x$ and $y$ in terms of $u$ and $v$ so that we can substitute in the integrand as well as find the Jacobian of this change of variables. Here, if we add the equations, notice that $y$ is eliminated, so $x=\frac{1}{3}(u+v)$. Alternatively, if we take twice the first equation and subtract the second equation, $x$ is eliminated, so $y=\frac{1}{3}(2u-v)$.
The Jacobian $\frac{\partial (x,y)}{\partial (u,v)}$ of a change of variables is the determinant of the 2x2 matrix $\begin{pmatrix} \frac{\partial{x}}{\partial{u}}&\frac{\partial{x}}{\partial{v}}\\\frac{\partial{y}}{\partial{u}}&\frac{\partial{y}}{\partial{v}}\end{pmatrix}$.
Finally, the change of variables theorem says that $$\iint_\Omega f(x,y)dA = \int_0^3\int_0^1 f\left(\frac{1}{3}u+\frac{1}{3}v,\frac{2}{3}u-\frac{1}{3}v\right)\cdot \frac{\partial (x,y)}{\partial (u,v)}dudv.$$
Can you finish the calculation?
Answer: If you do $x+y=X$ and $2x-y=Y$, then $x=\frac{X+Y}3$ and $y=\frac{2X-Y}3$. Besides, if you define$$g(X,Y)=\left(\frac{X+Y}3,\frac{2X-Y}3\right),$$then $\Omega=g\bigl([0,1]\times[0,3]\bigr)$ and the absolute value of the Jacobian of $g$ is $\frac13$. So,\begin{align}\iint_\Omega x^2+y\,\mathrm dx\,\mathrm dy&=\iint_{g([0,1]\times[0,3])}x^2+y\,\mathrm dx\,\mathrm dy\\&=\iint_{[0,1]\times[0,3]}\frac13\left(\left(\frac{X+Y}3\right)^2+\frac{2X-Y}3\right)\,\mathrm dX\,\mathrm dY\\&=\frac13\int_0^1\int_0^3\left(\frac{X+Y}3\right)^2+\frac{2X-Y}3\,\mathrm dY\,\mathrm dX.\end{align}Can you take it from here?


C array traversal cause loop on c90 standard (but not on c99)

Question: #include <stdio.h>

int main(void){
    double arr[] = { 1.1, 2.2, 3.3, 4.4 };
    int i;

    for (i=0; i<=4; i++) {
        printf("%d\n", i);
        arr[i] = 0;
    }

    return 0;
}

Compiling with gcc(c90) gives an infinite loop(1,2,3,4,1,2,3,4...) while compiling with gcc(c99) produces only (0, 1, 2, 3, 4). What can be attributed to the difference?
Comment: the array is size 4 and you are setting 5 values `for (i=0; i<=4; i++)` so your are setting something out of bounds which is causing this unexpected thing
Comment: @sri.vatsa This is not related to version of compiler. When you set something out of bound whatever happens next is quite undefined. If you dont see anything unexpected you were just lucky.
Comment: With what flags did you compile it? This shouldn't give a infinite loop.
Comment: @AyonNahiyan yea i understood that but why does that cause an infinite loop in an older version of a compiler?
Comment: Thanks! I was just wondering if there is any way to anticipate the output and  it that depends on the version of compiler. Thanks Anyways :)
Comment: undefined behavior means nothing can be guaranteed. Each compiler version, compiler options can produce vastly different results
Comment: @sri.vatsa I posted the exact reason it is looping infinitely. When you have problems like this, looking at the assembly is often the way to find out why something weird is happening.
Comment: In C, the standard idiom for iterating over an array with N elements in it is `for (int i = 0; i < N; i++) { …array[i]… }`.  While `<=` is not always wrong, it often is wrong.
Comment: The older version of the compiler apparently didn't place `i` in a register, so the out-of-bounds access to `arr[4]` was resetting `i` to 0, effectively restarting the loop. Newer version of the compiler register-allocated `i` even without explicit optimization flags, making the loop variable unharmed by the out-of-bounds write. As others explained, accessing an array out of its bounds is undefined behavior, and there is no guarantee that the newer compiler would keep producing working code if anything were changed.
Answer: You are writing to an element outside the array (namely when i is 4).
This leads to undefined behavior hence anything could happen.
Answer: Arr is declared with 4 values, but you are accessing 5 of it (i=0; i<=4). Accessing an array out-of-bounds results in undefined behavior.
What exactly happens if you do that depends on implementation details of the compiler, linker, and OS - if the compiler has put i there, you are overwriting i with 0; if it has put your stack frame there, you will end up with a crash, etc.
Answer: In loop you are assigning arr[4] = 0, but array has only 4 elements (arr[0..3]), so you are assigning value to memory outside of array. In this place compiler has placed int i, because it is declared just after array.
Answer: If you look at the assembly, you'll see that the variable i is stored at the end of the array, right after arr[3]. On my computer, it is not aligned in a way that it is exactly at arr[4] but I'm guessing on yours, the variable i is located exactly at arr[4] and thus you are overwriting it to 0 by going out of bounds in your for loop with the <= instead of <. This means in the last iteration of your for loop, you are setting i to 0 which keeps the loop going infinitely.
000000000040052d :
  40052d:   55                      push   %rbp
  40052e:   48 89 e5                mov    %rsp,%rbp
  400531:   48 83 ec 30             sub    $0x30,%rsp
  400535:   48 b8 9a 99 99 99 99    movabs $0x3ff199999999999a,%rax
  40053c:   99 f1 3f
  40053f:   48 89 45 e0             mov    %rax,-0x20(%rbp)               # move 1.1 into arr[0] at memory address rbp - 0x20
  400543:   48 b8 9a 99 99 99 99    movabs $0x400199999999999a,%rax
  40054a:   99 01 40
  40054d:   48 89 45 e8             mov    %rax,-0x18(%rbp)               # move 2.2 into arr[1] at memory address rbp - 0x18
  400551:   48 b8 66 66 66 66 66    movabs $0x400a666666666666,%rax
  400558:   66 0a 40
  40055b:   48 89 45 f0             mov    %rax,-0x10(%rbp)               # move 3.3 into arr[2] at memory address rbp - 0x10
  40055f:   48 b8 9a 99 99 99 99    movabs $0x401199999999999a,%rax
  400566:   99 11 40
  400569:   48 89 45 f8             mov    %rax,-0x8(%rbp)                # move 4.4 into arr[3] at memory address rbp - 0x8
  40056d:   c7 45 dc 00 00 00 00    movl   $0x0,-0x24(%rbp)               # declaring i at memory address rbp-0x24 (notice this is at location arr[4] (kind of))
  400574:   eb 28                   jmp    40059e
  400576:   8b 45 dc                mov    -0x24(%rbp),%eax
  400579:   89 c6                   mov    %eax,%esi
  ...

Answer: You are trying to access arr[4] since i value goes till 4 because of i<=4. But you have only arr[0],arr[1],arr[2],arr[3] in the array. You have change the condition in the for loop to i<4.
#include <stdio.h>
int main(void){
    double arr[] = { 1.1, 2.2, 3.3, 4.4 };
    int i;

    for (i=0; i<4; i++) {     // Since you have only 4 values in the array
        printf("%d\n", i);
        arr[i] = 0;
    }

    return 0;
}

Comment: I haven't downvoted but I'd guess probably a lack of explanation
Comment: @gowrath, I have added some explanation, Thans for the suggestion.


cannot log on to Ubuntu 14.04

Question: I have just finished loading on Ubuntu 14.03 now after putting in my password the screen goes blank then goes back to the password logon page
Comment: Is this a fresh install?
Answer: Do Ctrl + Alt + F1 to go to prompt.Login with your username and password.Then do
sudo chmod -R ug+rwx /home/[username]
Then do  Ctrl + Alt + F7 to login
Comment: I tried your suggestion but it didn't work  its still taking me back to the logon screen

cannot log on to Ubuntu 14.04


AND Gate in Logical Circuit

Question: folks... I'll do my best to explain what the method does as it gets a lot of members from other classes but its logic should be straightforward.
So, in AND Gate of a logical circuit, if any input signal is 0 then the output is also 0; if all of the input signals are 1 then the output is also 1; but if we have signals 0 and X(unknown signal), then the ouput is 0; when 1 and X then the output should be X.
I have a bug in the code of method because when, let's say 0X signals are fed in the gate, I'm getting X instead of 0. Could smb please help me? Note:Signal.HI is 1, Signal.LO is 0, Signal.X is X. Please let me know if any more information is needed.
public boolean propagate()
    {
        Signal inputSignal;
        Signal outputFinalSignal;
        Signal temp = getOutput().getSignal();

        List<Wire> inputs = getInputs();

        for(int i = 0; i < inputs.size(); i++)
        {
            inputSignal = inputs.get(i).getSignal();
            if(inputSignal == Signal.LO)
            {
                getOutput().setSignal(Signal.LO);
                break;
            }

            else if(inputSignal == Signal.X)
            {
                getOutput().setSignal(Signal.X);
                break;
            }

            else
            {
                getOutput().setSignal(inputSignal);
            }

        }
        ........................//Unnecessary for this problem code

Answer: your logic should be like this:
Signal result = Signal.HI; // default value is 1
for(int i = 0; i < inputs.size(); i++) {
    inputSignal = inputs.get(i).getSignal();
    if(inputSignal == Signal.LO) {
        // input is 0 - final result is 0 always, break immediately
        result = inputSignal;
        break;
    }
    else if(inputSignal == Signal.X) {
        // input is X, but we could have 0 later, so we store X and continue without break
        result = inputSignal;
    }
    else  {
        // signal is 1, just skip as we could meet 0 or X later or already met X
    }
}
getOutput().setSignal(result);

Comment: Cool! @Lashane Thank you! I got it from your snippet!
Answer: Just continue the iteration after encountering X, and initialize to HI:
public boolean propagate()
{
    Signal inputSignal;
    Signal outputFinalSignal = Signal.HI;
    Signal temp = getOutput().getSignal();

    List<Wire> inputs = getInputs();

    for(int i = 0; i < inputs.size(); i++)
    {
        inputSignal = inputs.get(i).getSignal();
        if(inputSignal == Signal.LO)
        {
            getOutput().setSignal(Signal.LO);
            break;
        }

        else if(inputSignal == Signal.X)
        {
            getOutput().setSignal(Signal.X);
        }

    }

Comment: what if all inputs are HI?
Comment: Then the result will be HI, because of the initialization.
Comment: if you looking at `outputFinalSignal ` and assume that it is used later, then this code will always return HI
Comment: You're correct, missed that. Bad naming. Your solution is complete.

AND Gate in Logical Circuit


Create a histogram of specific columns and rows from a `data.frame` in R

Question: ## my data frame
crime = read.csv("url")

## specific columns that need to be represented
property_crime = crime$Burglary + crime$Theft + crime$`Motor Vehical Theft`

## the rows that I am looking for have the name "harris" within the column named "county_name"

## my attempt
with(crime, hist(harris))

## Error in hist(harris) : object 'harris' not found

Not sure why I am getting object 'harris' not found as that is the name under the county_name column. I'm new to R, could someone walk me through the process of displaying a histogram only including the values of specific columns and specific rows?
Comment: Please share your data with `dput()`
Comment: Do you want the unorganized output that is pasted into the console after using dput()?
Comment: @LoganWhitehair Yes, please paste the results of `dput(crime)`
Comment: I am unable to edit my question w/ the contents of dput(crime) as it exceeds the 30000 character limit
Comment: @LoganWhitehair How about `dput(crime[1:50, ])` ?? Do you have any instance of `county_name == "harris"` in the first 50 rows? Also, did my answer get you closer to what you need?
Comment: Sorry guys I'm not sure that I understand R's syntax well enough to ask a good question, I will see my professor in a few hours and will  either check back in if I can articulate a better question or post a solution if I arrive at one, thanks for your help anyway!
Answer:
the rows that I am looking for have the name "harris" within the column named "county_name"

You have to tell R the same logic that you are telling us.
There are several ways of making this in R but I am going to put here the base R way.
We can access the desired rows of object crime column county_name by indexing like data.frame[rows, columns]. So, in your case, crime[harris_rows, "county_name"] should work. To get harris_rows, we can make a boolean index like so crime$county_name == harris. If we put all of this together and call hist():
hist(crime[crime$county_name == "harris", "county_name"])

You don't provide a reproducible example, but you can check a similar logic with the mtcars dataset. Here, I am making the histogram of the cars with mpg > 15
hist(mtcars[mtcars$mpg >15, "mpg"])
# this is another option that produces the same result
# hist(mtcars$mpg[mtcars$mpg >15])

Comment: Would it be best practice to add - crime[harris_rows, "county_name"] to a variable and add the columns that I want to include into another variable. Then call hist() with the variables defined earlier, as parameters?
Comment: I wouldn't worry too much about best practices at this level of your R journey, but you can certainly create a variable and then pass it as index.
Comment: Thanks for your help, you helped me improve my logical understanding of my problem, however, I don't believe that I understand R's syntax enough to ask anymore good questions to arrive at an answer. I will update if I either find a solution or can think of a better question.


Scrapy: How to send null value in FormRequest.from_response{}'s formdata attibute?

Question: I am trying to send form data using FormRequest.From_reponse() method. But the problem is there are some dummy values and some blank value in the form data.
So, for null values I am sending '' or None and 'space' but nothing seem to work,
 form_dta = {
                    'term_in': '202130',
                    'sel_subj': 'dummy',
                    'sel_subj': 'CS',
                    'SEL_CRSE': '100',
                    'SEL_TITLE': '',
                    'BEGIN_HH': '0',
                    'BEGIN_MI': '0',
                    'BEGIN_AP': 'a',
                    'SEL_DAY': 'dummy',
                    'SEL_PTRM': 'dummy',
                    'END_HH': '0',
                    'END_MI': '0',
                    'END_AP': 'a',
                    'SEL_CAMP': 'dummy',
                    'SEL_SCHD': 'dummy',
                    'SEL_SESS': 'dummy',
                    'SEL_INSTR': 'dummy',
                    'SEL_INSTR': '%',
                    'SEL_ATTR': 'dummy',
                    'SEL_ATTR': '%',
                    'SEL_LEVL': 'dummy',
                    'SEL_LEVL': '%',
                    'SEL_INSM': 'dummy',
                    'sel_dunt_code': '',
                    'sel_dunt_unit': '',
                    'call_value_in': '',
                    'rsts': 'dummy',
                    'crn': 'dummy',
                    'path': '1',
                    'SUB_BTN': 'View+Sections'
        }
        yield scrapy.FormRequest.from_response(
            response,
            formcss='div.pagebodydiv form',
            formdata=form_dta,
            callback=self.course_scrap)

Sending '' for as suggesting null value to form request does not work.
Form actually only contains 1 select tag on frontend where I have to select course name(name=sel_subj). all other form data is hidden.
Answer: I meet the same problem.
At first, I tried '' like you, and failed. Then I use None, but python tell me that to_bytes must receive a str or bytes.
After checking the source code, I found that by default FormRequest will encode the formdata with to_bytes() function and then set the headers "Content-Type" to "application/x-www-form-urlencoded".
What you are looking for is JsonRequest which use json.dumps as its encode function. None in python will convert into null in javascript as you wish.
from scrapy.http.request.json_request import JsonRequest

Be careful, JsonRequest needs parameter data instead of formdata.
English is not my native language, sorry if there is any mistakes.


Passing an array with spaces to a Bash function to act as its list of arguments

Question: I am trying to use getopts to make my script be able to take command line arguments, like -s "gil.sh 123. Because it does not support command line arguments with long names, I have a function that takes the arguments, and changes every appearance of the long version (in this case --script) to the short version (-s) and only then getopts gets called.
The problem is that if it contains spaces (in this case "gil.sh 123") then I cannot get the second function to take this as an array with 2 members, in this case i get the array (-s gil.sh 123) instead of (-s "gil.sh 123") which is what I sent the function.
Here is my code:
#!/bin/bash
#change long format arguments (-- and then a long name) to short format (- and then a single letter) and puts result in $parsed_args
function parse_args()
{
    m_parsed_args=("$@")
    #changes long format arguments (--looong) to short format (-l) by doing this:
    #res=${res/--looong/-l}
    for ((i = 0; i < $#; i++)); do
        m_parsed_args[i]=${m_parsed_args[i]/--script/-s}
    done
}

#extracts arguments into the script's variables
function handle_args()
{
    echo "in handle_args()"
    echo $1
    echo $2
    echo $3
    while getopts ":hno:dt:r:RT:c:s:" opt; do
        case $opt in
            s)
                #user script to run at the end
                m_user_script=$OPTARG
                ;;
            \?)
                print_error "Invalid option: -$OPTARG"
                print_error "For a list of options run the script with -h"
                exit 1
                ;;
            :)
                print_error "Option -$OPTARG requires an argument."
                exit 1
                ;;
        esac
    done
}

parse_args "$@"
handle_args ${m_parsed_args[@]}

(This code is obviously shorter than the original which has many more substitutions and types of arguments, i only left one)
I call the script like this: ./tmp.sh -s "gil.sh 123" and I can see that after parse_args the variable m_parsed_args is an array with 2 members, but when I send it to handle_args the array has 3 members, so I cannot give the variable m_user_script the correct value that i want it to get ("gil.sh 123")
Answer: Why do not you use double quotes for the m_parsed_args array?
handle_args "${m_parsed_args[@]}"

Comment: I was absolutely certain that I've already tried that. Guess not!
Can you actually explain the difference between the two though?
Comment: @gil_bz: When in double quotes with @, bash properly quotes each element in the array. See "Arrays" in `man bash`.


Regex to extract

Question: I want my string to always start with one of the letters A, B, C or D  followed by \n\n and then ending with [,.!?]\n\n. For example ".\n\n" or "?\n\n" or "!\n\n".
Comment: You've included the regex-group tag, do you want to include some part of the match in a group?
Comment: `^[A-D]\n{2}.*?[,.!?]\n{2}`
Comment: 'A\n\nI should have known you\'d be here,\n\nSam.\n\n'
This is my String and I want to Extract everthing from A till .\n\n
Answer: Quite similar to what you already had:
[ABCD]\n\n[,.!?]\n\n

Try it out here: https://regex101.com/r/QGoXHX/1
Comment: I want to cover everything in between. All the letters numbers and characters. It should only stop at [. ! ?]\n\n and then next sentence should again begin with [ABCD]\n\n

Regex to extract


What's the meaing of: incremental, preDexLibraries, jumboMode, inside dexOptions?

Question: inside build.gradle we can add that params
android {
    dexOptions {
        incremental
        preDexLibraries
        jumboMode
        javaMaxHeapSize
    }
}

but documentation is too low
http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.DexOptions.html#com.android.build.gradle.internal.dsl.DexOptions

boolean incremental
Whether to enable the incremental mode for dx. This has many limitations and may not work. Use carefully.
boolean jumboMode
Enable jumbo mode in dx (--force-jumbo).
boolean preDexLibraries
Whether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.

1) which limitations are in incremental?
2) what is jumbo mode?
3) what is pre-dex libraries?
Comment: Possible duplicate of [how can I use Android dexOptions?](http://stackoverflow.com/questions/28927255/how-can-i-use-android-dexoptions)
Answer: first of all lets see whats dex file. in pure java when you compile the java code,it will be compiled into a .class file while in android your java code will be compiled into .dex file. (both are bytecodes but different)
incremental: it means Gradle will use previous dex file and appends the new changes to them (not building them again every time).
the answer of your first Q: e.g. one of the limitation were you couldnt use it along with multidex* (though this limitation was solved - for sdk versions 21+ incremental builds are possible for multidex apks by rebuilding only the affected dex files)
-note: you dont need to worry about this limitations anymore because incremental option is true by default since Gradle version 2.1.0
multidex: this option means compiling java code into multiple dex file you dont need this unless your code methods outnumbers the max limitation on a single dex file (64k methods)
jumboMode (the answer of your second Q): there is also a limitation for strings count in the dex file enabling this option will extend the strings count in dex file (this option is true since Gradle 2.1.0 so you dont have to worry about it either)
preDexLibraries (the answer of your third Q): it builds dex file out of libraries so it can be used in incremental builds (not building dex files every time for libraries). so using this item when clean build makes everything a little slower.
Comment: to sum up: with Gradle 2.1.0 or higher do not need to set any of these parameters to speed up build
Comment: Not true about multidex and predexLibraries. These two are not true by defualt. Every feature that wants to be added as default to gradle firstly is added as incubating feature (means you can use them but they are not stable and may have problem). But after some versions it gets out of incubating state and it gets default.
Comment: multidex is not in question because the meaning is clear


In Python 3, best Pythonic way to set base class method to run once only

Question: I'm currently trying to log the full class name and method that is currently running.
In the following rough code, I have a class attribute in Base that tracks whether or not the logging handler has been added. Without it, I get one message for each time the Base class is inherited, which makes perfect sense. e.g. without it I get this output:
1688489421.224986 DEBUG Base.TestClassA.testmethod1 |debug message from test class A|
1688489421.225088  INFO Base.TestClassB.testmethod2 |info message from test class B|
1688489421.225088  INFO Base.TestClassB.testmethod2 |info message from test class B|
1688489421.225162 ERROR Base.TestClassC.another_method |error message from test class C|
1688489421.225162 ERROR Base.TestClassC.another_method |error message from test class C|
1688489421.225162 ERROR Base.TestClassC.another_method |error message from test class C|

A test at the end of the __init__ method then only calls self.__logger.addHandler(console_handler) once. With the check, the correct output is seen:
1688490430.369992 DEBUG Base.TestClassA.testmethod1 |debug message from test class A|
1688490430.370093  INFO Base.TestClassB.testmethod2 |info message from test class B|
1688490430.370155 ERROR Base.TestClassC.another_method |error message from test class C|

But is that the right way to do it? It feels a little fragile, but I'm still very much a beginner so I don't have the experience to really tell.
What's the correct Pythonic way to only call self.__logger.addHandler(console_handler) once?
#!/usr/bin/env python3

import logging

# Cargo culted from https://stackoverflow.com/a/50731615/2988388
class MetaBase(type):
    def __init__(cls, *args):
        super().__init__(*args)

        # Explicit name mangling
        logger_attribute_name = "_" + cls.__name__ + "__logger"

        # Logger name derived accounting for inheritance for the bonus marks
        logger_name = ".".join([c.__name__ for c in cls.mro()[-2::-1]])

        setattr(cls, logger_attribute_name, logging.getLogger(logger_name))

class Base(metaclass=MetaBase):
    log_handler_added = False

    def __init__(self):
        log_formatter = logging.Formatter(
            "{created:<f} {levelname:>5s} {name}.{funcName:>8s} |{message}|",
            style="{",
        )
        loglevel = "DEBUG"

        # turn the "info", "debug" etc env var value into a number
        # that sets the logging level of detail
        numeric_level = getattr(logging, loglevel.upper(), None)
        if not isinstance(numeric_level, int):
            raise ValueError("Invalid log level: %s" % loglevel)

        # Just log to stdout/stderr
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(log_formatter)
        self.__logger.setLevel(numeric_level)

        # use the class attribute to only add the handler once,
        # otherwise you get a log message for each time Base
        # has been inherited
        # https://stackoverflow.com/q/36320514/2988388
        if not Base.log_handler_added:
            self.__logger.addHandler(console_handler)
            Base.log_handler_added = True

class TestClassA(Base):
    def testmethod1(self):
        self.__logger.debug("debug message from test class A")

class TestClassB(Base):
    def testmethod2(self):
        self.__logger.info("info message from test class B")

class TestClassC(Base):
    def another_method(self):
        self.__logger.error("error message from test class C")

a = TestClassA()
a.testmethod1()

b = TestClassB()
b.testmethod2()

p = TestClassC()
p.another_method()

And as a bonus question, is it possible to use this metaclass+inheritance to log messages in __main__?
Answer: This seems over-complex. I would use a simple mixin and a formatter set on the root logger of the application. It can be the responsibility of main to initialize the root logger.
Mixin:
class LoggingMixin:
    @classmethod
    @property
    def log(cls):
        return logging.getLogger(cls.__name__)

Classes:
class TestClassA(LoggingMixin):
    def testmethod1(self):
        self.log.debug("debug message from test class A")

class TestClassB(LoggingMixin):
    def testmethod2(self):
        self.log.info("info message from test class B")

class TestClassC(LoggingMixin):
    def another_method(self):
        self.log.error("error message from test class C")

Setup:
if __name__ == "__main__":
    logging.basicConfig(
        format="{created:<f} {levelname:>5s} {name}.{funcName:>8s} |{message}|",
        level=logging.DEBUG,
        style="{",
    )

    a = TestClassA()
    a.testmethod1()

    b = TestClassB()
    b.testmethod2()

    p = TestClassC()
    p.another_method()

Output:
1688494741.449282 DEBUG TestClassA.testmethod1 |debug message from test class A|
1688494741.449282  INFO TestClassB.testmethod2 |info message from test class B|
1688494741.450281 ERROR TestClassC.another_method |error message from test class C|

Comment: Astonishing! That's so much simpler than the other solutions I've seen. I will give this a try and mark you as the correct answer as soon as I can. Huge thank you, I can see that I have a lot, a whole enormous amount, more to learn about Python.
Comment: @acjca2 Glad to have helped! Doing it this way also has the advantage of sharing a single log format for the entire application. It will even make the formatting consistent from dependencies you pip install if they also output to the logging module.


how to make a hash map (key value pair) from two arrays in perl

Question: I have two arrays of equal length one contains the keys and the other the values.
How do I make them into one hash where I can access it by hash{key} and get the value.
I tried
        my %hash = map { $key[$_], $values[$_] } 0..$#key;

but it kinda saved everything in one long list where every second value is the value as you can see from the debugger.
 DB<104> x %hash
0  'linking_parameter_1'
1  '$$SHIBBOLETH'
2  'service_type'
3  'getFullTxt'
4  'crossref_supported'
5  'Yes'
6  'parser'
7  'Bulk::BULK'
8  'internal_name'
9  'ELSEVIER_SD_EBOOK-COMPLETE_COLLECTION_1995-20065'
10  'object_lookup'
11  'yes'
12  'linking_level'
13  'BOOK'
14  'displayer'
15  'FT::NO_FILL_IN'
16  'parse_param'
17  ''

When I type
x %hash{parser}

it can't evaluate that. maybe I'm just not trying to access it in the right way?
Comment: A hash is just a list. If you want the debugger to show it in key/value form, you need to give it a reference. `x \%hash`.
Comment: %hash{parser} should be $hash{parser}.
Comment: Faster, simpler: `my %hash; @hash{@key} = @values;`
Answer:
Use a hash slice to define it
my %hash;
@hash{@key} = @values;

But the output from the debugger is what you should expect as the hash is expanded into a key/value list before being passed to x. To see the internal structure of composite data you should pass a reference to x
  DB<104> x \%hash
0  HASH(0xe7c88880)
   'linking_parameter_1' => '$$SHIBBOLETH'
   'service_type' => 'getFullTxt'
   'crossref_supported' => 'Yes'
   'parser' => 'Bulk::BULK'
   'internal_name' => 'ELSEVIER_SD_EBOOK-COMPLETE_COLLECTION_1995-20065'
   'object_lookup' => 'yes'
   'linking_level' => 'BOOK'
   'displayer' => 'FT::NO_FILL_IN'
   'parse_param' => ''

Comment: I personally would not be able to write that hash slice line on a MacBook. :(
Answer: The x command in the Perl debugger takes a list of values. Since a hash in list context is simply a list of values, it cannot see that there are key/value pairs. If you want to see the output as pairs, pass it a reference to your hash.
$ perl -d -e 'my %hash = foo => 123; sleep 1;'
Loading DB routines from perl5db.pl version 1.44
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):   my %hash = foo => 123; sleep 1;
  DB<1> s
main::(-e:1):   my %hash = ( foo => 123 ); sleep 1;
  DB<1> x %hash
0  'foo'
1  123
  DB<2> x \%hash
0  HASH(0x122e9c8)
   'foo' => 123
  DB<3>

If you want to access an individual hash element, use the correct sigil. To access a scalar value, the sigil is always a $.
  DB<2> x $hash{foo}
0  'foo'
1  123

However, doing %hash{foo} should work too if you don't have use strict and use warnings. Of course you don't want to do that.
Comment: @Borodin I needed something so I could stop it to output the values. Otherwise it would finish immediately.


Ajax serialize() doesn't include data from dynamically created divs

Question: I have a form and I add divs here dynamically using append(). It is successful in creating the divs, and that divs have input fields inside. But the problem is, after serializing the the data from the form, it doesnt include the data from the dynamically created divs.
This is my createDiv function:
function createDiv() {
    var count = 5;
    for (var i = 0; i < count; i++) {
        $('#userQues').append("

 " +
            " Question A " +
            "<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
            "

");
    }
};

Is there a problem in creating my div? Why does serialize doesnt include the data from my created div?
Thanks in advance!
Here is where is serialize the data. When the form is submitted:
$('#explorer_form').submit(function(e){
  var serializedData = $('#explorer_form').serialize();
  alert(serializedData);

  $.ajax({
    url : url + api,
    type : method,
    data : serializedData,
    success : function(response){
        $('#response').val(JSON.stringify(response));
    }
  });

  e.preventDefault(); //STOP default action
  e.unbind(); //unbind. to stop multiple form submit.
});

And the form:
<form id='explorer_form'>
    <input id='uname' name='uname' type='text'/>

    <button type='submit'>Submit</submit>
</form>

And now, the alerted data is only the data from the input 'uname' only. It doesn't serialize the data from the created div.
Comment: How/when do you call the serialize? Can you reproduce the problem?
Comment: I can not see the point where you do serialize. Also it would be smart to do a fiidle or pen because its more fun to the folks who like to help you :)
Comment: Use hidden field for this  not div
Answer: Make sure your userQues is a form and that you do the serialize AFTER you added the inputs. Your code works, here: http://jsfiddle.net/9v3khbts/
HTML
<form id="userQues">
</form>

<button id="doSer">Serialize</button>

JS
$(document).ready(function(){
  function createDiv() {
    var count = 5;
    for (var i = 0; i < count; i++) {
        $('#userQues').append("

 " +
            " Question A " +
            "<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
            "

");
    }
};

    createDiv();
    $('#doSer').click(function(){
        alert($('#userQues').serialize())
    })

});

Comment: No. I am serializing the "explorer_form" not the "userQues" itself. Because the "userQues" is the div where I append some divs.
Comment: do an e.preventDefault() on your submit button, the data is getting serialized correctly, you just don't see it. Here, I updated the fiddle: http://jsfiddle.net/9v3khbts/1/
Comment: Yes, after testing it in the jsfiddle, it seems to be working. But still I can't find out why in my code, it is not including the data. Maybe I have some errors in my original code.
Answer:

<form id='explorer_form'>
    <input id='uname' name='uname' type='text'/>

    <button type='submit'>Submit</button>
</form>

This works fine for me.
Don't use [] in ID or name.
Output will be -
Answer: You can use .appendTo() https://api.jquery.com/appendTo/ instead of .append()


Bootstrap tooltip disappearing target

Question: I have installed Bootstrap and need some help with the JavaScript/jQuery portion of it.
My HTML looks like this:
?

Some tooltip text!

My JavaScript:

The tooltip works on hover like it should, however, after moving off the element the entire element disappears. Basically you can only hover on it once and then the a tag is set to display:none;. Why is that?
Answer: I figured this out. I see a lot of people face this issue so maybe it will help.
I simply downloaded the latest jquery-1.11.1.min.js and installed that. After doing so, it works fine now.
Answer: This is old but I ran into it today on a site, so I'll answer in case it's helpful to someone else eventually...
If you have prototype.js loaded on the site, then prototype adds a .hide() method to elements:
function hide(element) {
  element = $(element);
  element.style.display = 'none';
  return element;
}

jquery's trigger method mistakes this for an event emitter and calls it to announce that the tooltip has been hidden:
elem[ type ]();

...thereby hiding the element to which the tooltip is attached.
Best fix is to stop using prototype.js which extends the DOM in ways that aren't compatible with modern standards.
Second best fix, if you can't kill prototype.js, is to avoid using bootstrap tooltips. Browser tooltips work just fine.
If you really need both, you can instrument bootstrap's tooltips.js to change the name of the hide event (and the show event while you're there):
diff --git a/bootstrap/js/src/tooltip.js b/bootstrap/js/src/tooltip.js
index ee721a1..eca1726 100644
--- a/bootstrap/js/src/tooltip.js
+++ b/bootstrap/js/src/tooltip.js
@@ -81,6 +81,10 @@ const Tooltip = (() => {

+  // Leading underscore on _hide and _show to rename hide/show events. This
+  // is important because prototype.js supplies Element.hide and
+  // Element.show, so if those names are used here, jquery will discover
+  // and call the prototype-supplied methods when .trigger is called.
   const Event = {
-    HIDE       : `hide${EVENT_KEY}`,
+    HIDE       : `_hide${EVENT_KEY}`,
     HIDDEN     : `hidden${EVENT_KEY}`,
-    SHOW       : `show${EVENT_KEY}`,
+    SHOW       : `_show${EVENT_KEY}`,
     SHOWN      : `shown${EVENT_KEY}`,

or you can monkey-patch it:
!function (Event) {
  Event.HIDE = '_' + Event.HIDE
  Event.SHOW = '_' + Event.SHOW
}(jQuery.fn.tooltip.Constructor.Event)

You'll just have to be aware in your own code that the event name changed, in the unlikely case that you're hooking on it.

Bootstrap tooltip disappearing target


Comments in command-line Zsh

Question: I switched from Bash to Zsh on Ubuntu and I'm quite happy about it. However, there is something I really miss and I did not find how to achieve the same thing.
In Bash, whenever I was typing a long command and noticed I had to run something else before, I just had to comment it out like in the following:
me@home> #mysuperlongcommand with some arguments
me@home> thecommandIhavetorunfirst #and then: up up
me@home> #mysuperlongcommand with some arguments #I just need to uncomment it!

However, this quite recurrent situation is not as easy to address as with zsh, given #mysuperlongcommand will be run as such (and resulting in: zsh: command not found: #mysuperlongcommand.
Comment: It's also dangerous because if you put a `;` character in your comment, it will execute the proceeding commands (I just ran a rm -r operation I wasn't planning on running yet :P ).
Answer: Having just started trying out zsh, I ran into this problem too. You can do setopt interactivecomments (in your .zshrc file to make it permanent) to activate the bash-style comments.
The Z Shell Manual indicates that while this is default behavior for ksh (Korn shell) and sh (Bourne shell), and I am guessing also for bash (Bourne-again shell), it is not default for zsh (Z shell):

In the following list, options set by default in all emulations are marked <D>; those set by default only in csh, ksh, sh, or zsh emulations are marked <C>, <K>, <S>, <Z> as appropriate.

INTERACTIVE_COMMENTS (-k) <K> <S>
Allow comments even in interactive shells.
Comment: Is there a reason that this isn't the default behaviour?
Comment: You can also do `set -k` if it's just a one off. But I'd use the `setopt` line from this answer in my zshrc
Comment: @naught101 lots of the best bits of zsh are default off. don't know why
Comment: @naught101 I like too, tho some tools don't ;)
Comment: @aryndin, good/sane/meaningful defaults is the hallmark of usability. Besides, that argument doesn't fare well if I have to ssh into dozens of computers (where I cannot expect to find my zshrc).
Comment: I did this at some point but the setting doesn't appear to be permanent and goes away later. Maybe if I had it to `.zshrc` it will work
Comment: @naught101 maybe this should encourage people to dig down into mans and settings to make zsh their own tool as opposed to something that __just works__
Comment: @6005 It is not permanent no. When I quite and reopen Terminal, I need to run `setopt` again. Anyone knows how to make it permanent?
Answer: I use
bindkey "^Q" push-input

From the zsh manual:

Push the entire current multiline construct onto the buffer stack and return to the top-level (PS1) prompt.  If the current parser construct is only a single line, this is exactly like push-line.  Next time the editor starts up or is popped with get-line, the construct will be popped off the  top  of the buffer stack and loaded into the editing buffer.

So it looks like this:
> long command
Ctrl+Q => long command disappears to the stack
> forgotten command
long command reappears from stack
> long command

Also, if you set the INTERACTIVE_COMMENTS option (setopt INTERACTIVE_COMMENTS), you will be able to use comments in interactive shells like you are used to.
Comment: @Mihnea if the command disappears it seems that push-input is working. It should appear back when you run the next command or just press enter. Doesn't it do that?
Comment: @barbaz the stack can be manipulated with `read -z` and `print -z`, so with some scripting and temporary files you could. But then a custom zle widget for saving the command line to a temp file might be simpler, and shared history will be simpler still.
Comment: While the currently accepted answer addresses the questioner's *question*, this answer addresses the questioner's *intention*.  I.e. zsh has a better way of achieving the intended result, and this is it.
Comment: This should be the accepted answer. If you use oh-my-zsh you can use Ctrl-Q for this out of the box.
Comment: I like your option, but I can't make it work :( Is there a way I should write the binding in the file, or is it just two characters, ^ and Q? My command is erased, but I don't know how to make it appear again in input.
Comment: Silly me, i was expecting to have to press up-arrow. Thanks, great tip, !
Comment: Is there a way to share the stack with child processes? I often used the comment thingy with bash when I forgot to launch a screen, i.e. i did '#large command; history -a; screen' and the picked it up inside the screen from the history...
Comment: Thanks for the tip! Adding `setopt INTERACTIVE_COMMENTS` to my `~/.zshrc` file worked for me!
Answer: I find myself doing this often as well. What I do is cut the long command, execute the command that needs to go first and then paste the long command back in. This is easy: CTRL+U cuts the current command into a buffer, CTRL+Y pastes it. Works in zsh and bash.
Comment: This shouldn't be the accepted answer. The solution below which says to use "setopt interactivecomments" should be. The reason for this is that if you just cut the current command, then it isn't in your zsh history, and also you then can't easily use cut and paste while typing in your new command without overwriting the command you were trying to save.
Comment: Using comments and the solution in this answers are both workarounds; the push-input method posted by Michał Politowski is more correct.
Comment: well, actually, my way is a workaround while your solution is the best fit ;)
Answer: Add the line setopt INTERACTIVE_COMMENTS to your ~/.zshrc file, save it, and relaunch the shell.
This is to clarify on @Lajnold's answer and @Hamish Downer's comment. It just took me a little bit to figure out how to make this change permanent. You probably want to add that line before exporting variables, so maybe add it toward the top of the file. I already had setopt PROMPT_SUBST in my ~/.zshrc file, so I just added it after that line. This will ensure the settings are loaded every time you launch the zsh terminal.
Comment: Once you've edited `~/.zshrc` you can apply the changes to your current shell without closing or relaunching anything by running this: `source ~/.zshrc`
Comment: `set interactive_comments` also works for command line. I wonder why this doesn't work for comments within a function?
Comment: i didn't even have a .zshrc file in ~ in my refurbished Mac Mini that came with Catalina. Thanks.
Answer: : sh generate_sample.sh arg1

The addition of ":" doesn't execute the command in zsh.
sh generate_sample.sh : arg1

Now the arg1 is commented.
I am on Mac OS Big Sur and used it multiple times.
Edit: ":" procedure works with giving no spaces. ": command" is correct but ":command" isn't
Comment: This seems to work? But I'm having a hard time googling to find more info...
Comment: @DanielWaltrip Check out https://stackoverflow.com/q/3224878/115690 for details in bash, but the same should apply to zsh
Answer: In addition to setopt interactivecomments, suggested by @Lajnold, you might also want to add something like the following to prevent certain comments from being written to history (from https://superuser.com/questions/352788/how-to-prevent-a-command-in-the-zshell-from-being-saved-into-history):
This overrides the ZSH built-in function zshaddhistory():

Will log comments that start in column 1 not followed by one or more spaces (i.e. #somecommand that I want to come back to)
Won't log comments that start in column 1 followed by one or more spaces
Won't log indented comments, padded by spaces from column 1
Won't log commands with a space in column 1 (handy shortcut for running commands that you don't want logged

setopt interactivecomments

function zshaddhistory() {
  emulate -L zsh
  if ! [[ "$1" =~ "(^#\s+|^\s+#|^ )" ]] ; then
      print -sr -- "${1%%$'\n'}"
      fc -p
  else
      return 1
  fi
}

For reference, this is the default zshaddhistory() http://zsh.sourceforge.net/Doc/Release/Functions.html
zshaddhistory() {
  print -sr -- ${1%%$'\n'}
  fc -p .zsh_local_history
}

Comment: Or just add `setopt HIST_IGNORE_SPACE` to your `~/.zshrc` as mentioned in that link.

Comments in command-line Zsh


Simple tag synonym suggestions

Question: Some tag synonym suggestions just don't require that much conversation to settle. That's why I prefer to consolidate simple synonym suggestions as answers to one big meta-question, which I'm starting here. This will also get more attention for all the simple little synonym creation tasks we have by facilitating readers' voting on them all at once. I'm basing this on a model question I've found useful on Cross Validated (CV), and proposing the same policy as I've discussed in a separate meta-question on CV...
Please upvote this question if you think it's a useful repository for simple synonym suggestions, and downvote if you prefer that all synonym suggestions be made as questions unto themselves. If you have specific comments or suggestions for this system, leave them as comments. Please only answer with new tag synonym suggestions, and upvote these if you think they should be made synonymous, or downvote them if you think the tags should not be synonyms. When answering, please indicate which tag should be the master tag and which should be the synonym that redirects to the master. Please also add information about the number of questions using each version of the tag, and briefly discuss any differences in the content of the tag wikis and excerpts.
As an initial recommendation subject to revision following the community's preferences, consider posting any complex synonym suggestions (e.g., involving more than 3 tags, requiring retagging effort, likely to deserve thorough discussion) as their own questions. This page will work best if suggestions here don't require more than a few comments to sort out before decisions are made. To reduce "clutter" and direct attention optimally, also consider flagging new synonym suggestion questions that are very simple as duplicates of this after they've been resolved. If it's not very simple (e.g.), don't call it a duplicate, as opinions will vary on where to draw the line between a simple suggestion for this page and a complex one that deserves its own. Also, feel free to delete your suggestions here after they've been implemented, and to suggest that others do the same, but do not consider deletion mandatory as an initial policy.
Answer: Master: hearing; Synonyms: audition,auditory
Questions tagged: 9, 7, & 1, respectively.
The one question tagged "auditory" is fairly new and could be retagged, which would zombify auditory and burninate it automatically six months later if I'm not mistaken.
hearing and audition have tag wikis; auditory does not.
hearing: For questions regarding the sensation (transduction) and perception of sound information by the brain in humans and animals.
audition: For questions pertaining to the sensation or perception of sound and its localization.
If localization is worth noting, this could be edited into the hearing wiki easily.
Comment: I don't know to which degree this is the scientifically established term, but I feel audition to be the least clear of other possible synonyms, 'auditory' and 'hearing' included.
Comment: I'd agree it's most obscure...Hadn't noticed [tag:hearing]! Will edit :)
Answer: A meta-tag synonym suggestion:
Master: tags; Synonym: tagging
Questions tagged: 42 & 1, respectively.
The one latter question is fairly old, but could be retagged, which would zombify tagging and burninate it automatically six months later if I'm not mistaken.
tags has a tag wiki; tagging does not. Seems an open-and-shut case with nothing to lose!

Simple tag synonym suggestions


Non-toxic materials for edging garden

Question: I'm looking for a edging for my garden which is non-toxic. I've currently got pressure treated lumber (supposedly it is not arsenic laced). I've been stapling chicken wire to the top of the lumber to keep out rabbits (this has been working), so I'd like to continue to use pressure treated lumber, but as I understand it, they no longer sell it without the chemical treatments.
Is this true? Any ideas as the best way to "seal" off my garden area? I've tried plastic edging and found it incredibly frustrating. I guess if there were some trick to installing it, I'd consider it, but I still need to be able to seal the area off.
Answer: I've used cedar for a number of years on garden projects with great luck. You can get the fence pickets relatively inexpensively as well. I use them (cut into 1' lengths) to build my above ground planters, and laid out lengthwise to build a box around the garden for mulch/fence supports.
Comment: Even though I am using my answer, I'll give you the green :)
Answer: @iivel
After reading the following:
http://www.finegardening.com/design/articles/pressure-treated-wood-in-beds.aspx
It doesn't sound very threatening, so I'm just going to go ahead with the configuration I had (which is stapling chicken wire to the wood edging)

Non-toxic materials for edging garden


Inserting primay key values to another table through cursor

Question: I have a cursor inside a procedure which fetch the primary key of the table
passed in the procedure parameter. i need to insert the values of the primary key into a another table
<code>CREATE  PROCEDURE TRY25  @CURRENT_TABLE NVARCHAR(100)

AS

DECLARE @QUERY NVARCHAR(4000)

SET NOCOUNT ON
DECLARE     @COLUMNNAME AS NVARCHAR(MAX)
DECLARE CURP CURSOR FOR
SELECT COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
         ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
            TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND
            KU.TABLE_NAME=@CURRENT_TABLE
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;
OPEN CURP
FETCH NEXT FROM CURP INTO @COLUMNNAME
WHILE @@FETCH_STATUS = 0 BEGIN
print concat(@columnname)
FETCH NEXT FROM CURP INTO @COLUMNNAME
END -- END OF FETCH
CLOSE CURP
DEALLOCATE CURP
</code>
Answer: You need to use dynamic sql to do this. below is the sample code which     you can use -
<code>    CREATE  PROCEDURE TRY25  @CURRENT_TABLE NVARCHAR(100)

    AS

    DECLARE @QUERY NVARCHAR(4000)   , @COLUMNList NVARCHAR(4000)
    SET @COLUMNList = ''

    SET NOCOUNT ON
    DECLARE     @COLUMNNAME AS NVARCHAR(MAX)
    DECLARE CURP CURSOR FOR
    SELECT COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
             ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
                TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND
            KU.TABLE_NAME=@CURRENT_TABLE
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;
OPEN CURP
FETCH NEXT FROM CURP INTO @COLUMNNAME
WHILE @@FETCH_STATUS = 0 BEGIN

SET @COLUMNList = @COLUMNList + @columnname + ','

FETCH NEXT FROM CURP INTO @COLUMNNAME
END -- END OF FETCH
CLOSE CURP
DEALLOCATE CURP

SET @COLUMNList  = SUBSTRING(@COLUMNList , 1 , LEN(@COLUMNList) -1)
SET @QUERY = 'INSERT INTO YOUR_DEST_TABLE SELECT ' + @COLUMNList + ' FROM '     + @CURRENT_TABLE  --CHANGE YOUR TABLE NAME
EXEC (@QUERY)
PRINT @QUERY
</code>


Characters of almost quasisimple groups

Question: A group $ Q $ is called quasisimple if it is a perfect central extension of a simple group.
A group $ A $ is called almost simple if there exists a series of containments $ S \subset A \subset Aut(S) $ where $ S $ is a simple group and $ Aut(S) $ is the automorphism group of $ S $. In other words, a group $ A $ is almost simple if it is the extension of a simple group by some subgroup of the outer automorphism group.
For a quasisimple group $ Q $, all characters of the corresponding simple group $ Q/Z(Q) $ lift to characters of $ Q $. Since the characters of finite simple groups are well known, these are easy to obtain. There are some other characters of $ Q $ which cannot be obtained from the characters of the simple group $ Q/Z(Q) $. Even these are not too hard to find since quasisimple groups are perfect and there are good libraries of characters for (small) perfect groups. For example GAP has the characters tables of all Perfect Groups of size up to two million. https://www.gap-system.org/Datalib/perfect.html
The characters of finite almost simple groups are also not too hard to obtain. They can usually be found in the same references as the characters tables of finite simple groups. In GAP one can just use the command AutomorphismGroup(S) where $ S $ is the simple group in question. For a given almost simple group $ A $ most (but not all) of its characters can be found by just restricting the characters of $ Aut(S) $ to the subgroup $ A $.
For an almost quasisimple group $ G $ I am unsure how to find characters. Some characters can be lifted from the character table of $ Aut(G) $. However I think there are many that cannot.  For example there is a group of size $ 1440 $ which is an extension of $ SL(2,9) $ by an outer automoprhism of order $ 2 $ and it appears to have a degree $ 4 $ character. However I do not know how to compute this character.
Even easier than computing the full character table, I would just be curious how to find all the irrep dimensions for an almost quasisimple group.
TLDR: I'm curious how to find the character tables of almost quasisimple groups. Even figuring out all the irrep dimensions for (small) almost quasisimple groups would be interesting to me. I would be happy with a reference for the character tables, or a way to find them in GAP, or some direct method to find irrep dimensions for almost quasisimple groups, as long is works for a few interesting small groups, say of size less than 10,000.
Edit 1: very interesting point raised in the comments by Derek Holt. In response here is a (perhaps slightly vague but hopefully no longer incorrect) definition: A group $ G $ is called almost quasisimple if it is the extension of a quasisimple group by some subgroup of its outer automorphism group, with the outer automorphisms acting in the natural way.
Comment: The group that you describe as $Q.{\rm Out}(Q)$ does not always exist. For example when $Q = {\rm SL}(2,9) = 2.A_6$, we have ${\rm Out}(Q) = C_2 \times C_2$. But there is no group $Q.{\rm Out}(Q)$. More precisely, there are groups $2.S_6$ and $2.{\rm PGL}(2,9)$, but no group $2.M_{11}$. You can find information on the characters of a lot of almost quasisimple groups in the ATLAS, but it requires some expertise to extract it. Alternatively, they are all in the GAP character table library.
Comment: @DerekHolt Thanks so much! This comment helped me answer https://math.stackexchange.com/a/4698409/758507 Just a heads up I think you made a small typo and meant to say $ 2.M_{10} $
Comment: Yes I meant to write $2.M_{10}$!
Answer: Since you have the [gap] tag: In GAP you could construct the group, calculate the automorphism group, and then its character table. Say, for $SL(2,9)$:
<code>gap> g:=PerfectGroup(720,1);
A6 2^1
gap> IsomorphismGroups(g,SL(2,9))<>fail; # verify its the right one
true
gap> a:=AutomorphismGroup(g);
<group of size 1440 with 4 generators>
gap> p:=Image(IsomorphismPermGroup(a),a); # convert to permutation (since faster)
<permutation group of size 1440 with 4 generators>
gap> c:=CharacterTable(p);
CharacterTable( <permutation group of size 1440 with 4 generators> )
gap> Irr(c);; # completes character calculation
gap> Display(c); # show table
CT1

      2  5  5  4  3  3  1  4  3  4  1  1  3   1
      3  2  .  .  .  .  .  .  .  1  2  1  .   .
      5  1  .  .  .  1  1  .  .  .  .  .  .   1

        1a 2a 4a 4b 2b 5a 4c 8a 2c 3a 6a 8b 10a
     2P 1a 1a 2a 2a 1a 5a 2a 4c 1a 3a 3a 4c  5a
     3P 1a 2a 4a 4b 2b 5a 4c 8a 2c 1a 2c 8b 10a
     5P 1a 2a 4a 4b 2b 1a 4c 8a 2c 3a 6a 8b  2b
     7P 1a 2a 4a 4b 2b 5a 4c 8a 2c 3a 6a 8b 10a

X.1      1  1  1  1  1  1  1  1  1  1  1  1   1
X.2      1  1 -1 -1  1  1  1  1 -1  1 -1 -1   1
X.3      1  1 -1  1 -1  1  1 -1 -1  1 -1  1  -1
X.4      1  1  1 -1 -1  1  1 -1  1  1  1 -1  -1
X.5      9  1 -1 -1  1 -1  1 -1  3  .  .  1   1
X.6      9  1 -1  1 -1 -1  1  1  3  .  . -1  -1
X.7      9  1  1 -1 -1 -1  1  1 -3  .  .  1  -1
X.8      9  1  1  1  1 -1  1 -1 -3  .  . -1   1
X.9     10  2  2  .  .  . -2  .  2  1 -1  .   .
X.10    10  2 -2  .  .  . -2  . -2  1  1  .   .
X.11    16  .  .  . -4  1  .  .  . -2  .  .   1
X.12    16  .  .  .  4  1  .  .  . -2  .  .  -1
X.13    20 -4  .  .  .  .  .  .  .  2  .  .   .
</code>
Comment: Ah I see so I can find character tables for $ 2.S_6 $ using c:=CharacterTable("2.A6.2_1"); and for $ 2.PGL(2,9) $ using c:=CharacterTable("2.A6.2_2"); etc... Thanks!

Characters of almost quasisimple groups


Create Sum of calculated columns in Microsoft Reporting Services like Fibonacci series

Question: Help me, please.
I have a Tablix with column group that shows values for each month.
Like the exemple:
 JUN/2012|JUL/2012
 15,00   |26,00
 15,00   |41,00

I want to sum up the values in the second line, row 2 of second month needs to be value of first month + second month.
Thanks.
Answer: You could create a function in the Report Code to keep a running total value, like below:
Dim runningTotals As System.Collections.Hashtable

Public Function AddRunningTotalValue(ByVal dateStr As Object, ByVal amount As Object)
        If (runningTotals Is Nothing) Then
            runningTotals = New System.Collections.Hashtable
        End If
        If (Not runningTotals.Contains(dateStr)) Then
            runningTotals.Add(dateStr, amount)
       End If
       AddRunningTotalValue = amount
End Function

Public Function GetRunningTotalValue(ByVal dateStr)
    If (Not runningTotals.Contains(dateStr)) Then
        GetRunningTotalValue = 0
    End If
        If (runningTotals.Contains(dateStr)) Then
            For Each dateStrPair As System.Collections.DictionaryEntry In runningTotals
                If dateStrPair.Key.ToString() = dateStr Then
                GetRunningTotalValue = dateStrPair.Value
            End If
        Next
        End If
End Function

Of course you would modify the get function to only return the sum of the month values that you want to add together.


When to replace respirator filters?

Question: I've got a respirator like this one:

I assume with the particulate filters (for dust) you just change them when they get hard to breathe through, but what about the organic vapor or chemical cartridges? How do you know when they need to be replaced?
Comment: I have an organic vapor respirator I use when working with mineral spirits and the like. I use it for comfort and not to save my life, so I judge whether the cartridges are shot based on whether I can smell the chemical I'm working with. I've used the respirator (and its original cartridges) about twice a year for fifteen years and have never smelled anything through it.
Answer: You are correct regarding the dust filters... in fact the "caking" particles can sometimes improve filtration... so the cartridges only need to be replaced when damaged, soiled or when they unacceptably obstruct breathing.
As for chemical filters... this depends a great deal on the chemicals being dealt with, as each will have different properties.
Each cartridge should have a specified service life or change schedule... nonetheless, for vapors and certain organic compounds 3M™ recommends that they be used for only a single shift exposure

Can chemical cartridges be used for more than one shift?
Organic vapors are removed by the process of adsorption.
Weak physical forces hold the organic vapor on the
activated carbon. Since these forces are weak, the process
can be reversed and the organic vapor can be desorbed.
Desorption during storage or nonuse periods can result in
the migration of the chemical through the cartridge.
Migration is mainly a concern only for organic vapor
cartridges. Organic vapors adsorbed on an organic vapor
cartridge can migrate through the carbon bed without
airflow. Desorption of very volatile contaminants can
occur after a short period (hours) without use (e.g.,
overnight). Partial use of the chemical cartridge and
subsequent reuse could potentially expose the user to the
contaminant. This is most significant for the most volatile
and poorly retained organic vapors (e.g., boiling point < 65°C). For organic vapors with a boiling point less than
65°C, it is recommended that the organic vapor cartridge
never be used longer than one shift even if the estimated
service life is greater than 8 hours and the cartridge is
used for only a short time during the shift.
Comment: That's more complex than I thought. Could get kinda expensive replacing them every day. My main concerns are wood finishes and epoxies; are there any general guidelines for those?

When to replace respirator filters?


Almost Sure Convergence/Strong Law for the Coupon Collector's Problem

Question: Consider the usual coupon collector's problem - $n$ coupons with equal probability, and let $T_n$ be the time required to collect all $n$ coupons. It is well known that:
$$
\mathbb{E}[T_n] = nH_n
$$
with $H_n$ denoting the $n$th harmonic number:
$$
H_n = \sum_{k=1}^n \frac{1}{k}
$$
It is easy to show that:
$$
\frac{T_n}{\mathbb{E}[T_n]} \to 1 \text{ in probability}
$$
This follows from applying Chebyshev's inequality and the divergence of the harmonic series:
$$
\mathbb{P}\left(\left|\frac{T_n}{\mathbb{E_n}} -1 \right| > \epsilon\right) \leq \frac{\mathrm{Var}(T_n)}{n^2 (H_n)^2\epsilon^2} = \frac{n\sum_{k=1}^n\frac{n-k}{k^2}}{n^2 (H_n)^2\epsilon^2} \leq \frac{n^2(\pi^2/6)}{n^2(H_n)^2\epsilon^2} = \frac{C}{(H_n)^2}\to 0
$$
Question: Can this convergence in probability be upgraded to almost sure convergence?
To see this, I tried to show that:
$$
\mathbb{P}\left(\left|\frac{T_n}{\mathbb{E}[T_n]} -1 \right| > \epsilon\right)
$$
is summable, which implies almost-sure convergence by Borel Cantelli. However, I am pretty sure this approach is doomed, because the estimate on the RHS will pretty much never be summable, even if one tries something less crude.
If it does not converge almost-surely, is there an elementary way to prove it does not?
Answer: It's a strange question, because there doesn't seem to be anything which indicates the joint distribution of the $T_n$ as $n$ varies, or actually to suggest that they are defined on the same probability space. In the absence of that, it's not clear what meaning to give to almost sure convergence.
If you're asking about whether you'd have almost sure convergence for such a sequence $T_n$ with independent terms, or whether you'd have almost sure convergence for every possible coupling of the distributions of the $T_n$, then (from both Borel-Cantelli Lemmas) either of these properties is in fact equivalent to the summability property you mention, namely that the probabilities $\mathbb{P}\left(\left|\frac{T_n}{\mathbb{E}[T_n]} -1 \right| > \epsilon\right)$ are summable over $n$ for every $\epsilon$.
On the other hand, since you have convergence in distribution, there must indeed exist some coupling of the random variables for which you have the desired almost-sure convergence (this follows from Skorohod's Representation Theorem).


Core Data NSManagedObject Insert and Save Methods

Question: Is there an easier way to do something like the following in Core Data:
Entry *entry = [[Entry alloc] init];
entry.name = @"An Entry";
[entry save];

I realize you don't have to allocate an NSManagedObject, have to insert directly into the context like the following:
Entry *entry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry"
                         inManagedObjectContext:[self managedObjectContext]];

But this is a lot of code. Also I would like to save by just messaging rather than have to save the entire context:
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

Could I put these in an NSManagedObject abstract class and have my managed objects extend that abstract class? Basically, I'm just trying to encapsulate more in my models and write less code in my controllers. Any help appreciated.
Comment: After thinking this over for a few hours, I'm beginning to realize that I may have been looking at this all wrong. Core Data's not an ORM framework at all like a PHP Doctrine. I'm thinking there's no need to serialize per object. At startup, you just fetch all the objects from the store. Then you manipulate and delete the objects as needed in an OBJECT ORIENTED manner. When you're all done, you save the context. That's all. There's no need to be concerned with per object serialization.
Answer: You can define your own subclass of NSManagedObject, and set all of your entities to use it.
The subclass can have whatever initialiser/save patterns you define, so long as it calls the proper parent class's initialiser.
You could have a +entity method, which might link to a statically defined context (this will restrict you to a single managed object context of course, but that's not always bad as long as you can also call the more primitive initialisers when you need a second context).
You might even have a +entityWithName: method.
As for saving the context, once again you can always define a subclass and add a simple -save method which saves the context and throws an exception if the save fails. You may choose to do this with a category extending the NSManagedObject class, instead of a subclass.
Note it is impossible to save just the change you made to that one entry object. You can only save all changes to an entire managed object context. If you need to save a single record, then you need to create a temporary managed object context, make a single change in it, then save the temporary context, and then sync the temporary context change over to all other managed object context's that currently exist in the app (there is an API to do make this complicated process relatively easy).
I don't like the code you posted to save the context, for several reasons:

Don't define a managedObjectContext variable that just points to self.managedObjectContext. In almost all situations that's an extra line of code for no benefit. At best you're making your code hard to read, at worst you might be introducing bugs.
Why are you checking if it is nil? Usually you should design your code so that it cannot ever be nil. Do the nil check in the constructor of your object, and if it's nil that is a critical failure. Your whole app is completely useless for the user, and you should make it clear to the user that they can't use the app by doing something drastic, such as a crash (an error alert first would be nice, but I wouldn't bother. I'd just throw an exception).
Why are you doing a check for hasChanges? I cannot think of many situations where you would need to do this check. Perhaps your app is allowing a user to make many changes, and then saving them several minutes later? This is bad. The context should be changed milliseconds after a group of changes are made, or else you're risking data loss. Your app could crash, the phone could run out of battery, or the user might receive a phone call and your app is consuming enough RAM that the OS will terminate it instantly in order to present the "incoming call" screen. You shouldn't need to check for hasChanges because you always perform a save operation immediately after making some changes.
As I kind of mentioned before, if the save fails you should present an error to the user then throw an exception. Avoid using NSLog() in deployment code, it's really only useful for development and beta builds.
Comment: The save code was boilerplate generated by xcode in the app delegate.
Answer: Check out
NSManagedObject+ActiveRecord.h
Inside Restkit : http://restkit.org/
It is based on :
https://github.com/magicalpanda/MagicalRecord
I am using in RestKit app, but you can adopt it quite easily.
Good luck


Query by Attribute Value - VersionOne REST

Question: Given a Number Attribute with a specific value, I want to find the story with that value.
For example, I have a request with the number R-56614.
What I'm attempting is along the line of this:
rest-1.v1/Data/Story?sel=SuperAndUp&where=Attribute.Number="R-57154"

Any suggestions would be greatly appreciated.
Answer: I figured it out.
rest-1.v1/Data/Request?where=Request.Number="R-57154"

Comment: FYI, you can also do rest-1.v1/Data/Request?where=Number="R-57154" since you have specified the root asset as being a Request.  This obviously cuts down some of the redundancy when you start listing multiple attributes with conditions.


Can't access project absolute url from inside Django Docker instance

Question: I have a project started with Cookiecutter Django and I'm currently adding WeasyPrint to serve some views as PDF files. This is working fine on development. Cookiecutter Django is using Caddy as the HTTP server.
I'm having errors on production due I can't access to files through its absolute URL from inside the Django docker instance.
From inside the Django docker instance, this does not work:
<code>$ curl https://myowndomain.com
curl: (7) Failed to connect to myowndomain.com port 443: Connection timed out
</code>
But this does:
<code>$ curl https://www.google.com
</code>
From outside the Django docker instance both curl commands are working OK.
My Caddyfile:
<code>myowndomain.com {
    proxy / django:5000 {
        header_upstream Host {host}
        header_upstream X-Real-IP {remote}
        header_upstream X-Forwarded-Proto {scheme}
        except /media
        transparent
    }

    log stdout
    errors stdout
    gzip

    header / {
        # Don't show Caddy/Gunicorn as server header.
        -Server

        # Enable HTTP Strict Transport Security (HSTS) to force clients to always connect via HTTPS (do not use if only testing)
        Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

        # Only send Referer header to same origin.
        # Django CSRF protection is incompatible with referrer policy set to none.
        Referrer-Policy "same-origin"

        # Enable cross-site filter (XSS) and tell browser to block detected attacks.
        X-XSS-Protection "1; mode=block"

        # Prevent some browsers from MIME-sniffing a response away from the declared Content-Type
        X-Content-Type-Options "nosniff"
    }
}
</code>
Is there something I need to set? Am I missing something?
Comment: Hi @Tadeo - so the connection would time out in this fashion because the port is likely closed and not receiving a connection - are you using nginx as your proxy server?
Comment: @WindUpLordVexxos Thanks for your comment. I'm using [Caddy server](https://caddyserver.com/), not Nginx
Comment: Hmmmm, I'm not as aux fait with caddy server...it should be a case of port opening tho...
Comment: That was my first thought, but as far as I can curl external https:// URLs from the Django container and as I can curl the https://myowndomain.com from the outside, the problem seems to be related to the DNS resolution inside the docker container.
Thanks for your help!
Comment: Could you add your caddy server config here please...
Comment: @WindUpLordVexxos I've added the Caddyfile content
Comment: @Tadeo Hey, have you found a solution for this, please?
Comment: @MurphyAdam Regarding curling from inside the docker container, currently I'm being able to curl the same domain, receiving empty response content instead of the timeout error. Caddy version upgraded from 0.10.6 to 0.11.5 after I posted this question.
Regarding WeasyPrint error in production, looking at the git log I solved it a few days after I posted this question adding `WEASYPRINT_BASEURL=''` in settings/base.py.
I hope this can help someone.
Answer: probably in development it use http on port 80 and in production it use https on port 443.
In the docker-compose.yml or when you invoke docker do you expose port 443?
Comment: Yes, I have "0.0.0.0:80:80" and "0.0.0.0:443:443" declared under the 'Caddy / ports' section of the docker-compose.yml in production. In fact the site is accesible from outside the Django docker container, and other https URLs are accesible from inside it.