text:
Q: How can I keep multiple copies of a very large dataset in memory? TLDR for people in the future: I inherited a program and need to adapt it to handle data several magnitudes larger than it currently is. I need help figuring out a way to manage multiple copies of a 30GB array.
I inherited some research code pretty recently (written in c) which was initially written to be run on a small set of data comparatively ~5 GB. The code requires that I am able to access four copies of the array at once (one char array and three double arrays). The author at the time thus did not need to worry about memory usage and as such has multiple instances where there are 2-4 extra arrays concurrently in memory.
Also, this is biological data (genome) and the arrays are not sparse.
The issue is now I have to adapt the code to where a single array of doubles is 30GB.
I am not sure if I need all of the values to be accessible at once, but I know that it is very often the case that the code loops through all of the values.
Things I've Tried
Emulating constant time access with files
I split up each of the arrays into sets of 10k characters or doubles and wrote them all into files. I then changed all of the access to functions of my own and had it read from the file or overwrite that line in the file. Although this worked. The issue was that it was terribly slow (most likely due to all of the file openings and closing + speed of writing to disk) which is something that is a problem with the program already and I don't want to make it worse.
Writing arrays to the disk when not needed
I noticed that multiple times there would be periods of time that the program would not need an array and I decided to write that to disk and then read from it when needed. The issue that I am facing is that it still takes a really long time (10 minutes+?) to write the entire array to disk, only opening the file and closing it once (unlike the above method).
Using more memory
As this is for research I do have access to a computing cluster with 150GB of RAM. I submitted this program as a job but unfortunately, even then the process got killed from taking up too much memory. I suspected originally that this was just a memory leak but upon further inspection, it really appears that there are >5 double arrays being created when the program was running. Just as a side note personal machine has 40 (a weird number I know) GB of memory.
Stupid last-ditch attempts
I disabled the kernel from overpromising memory because I noticed that it was crashing not when allocating many of the arrays but instead when it actually started accessing them. However, I don't think this ended up doing anything because it still overpromises.
One night I got quite frustrated that it was being killed all the time and decided to run the program with a niceness of -10000 which resulted in my computer crashing as it killed other processes to make up for more memory.
I also played around with using mmap() but am not sure if this is something that I should pursue.
Why do you need so much memory? Is this an XY problem?
Although I really can't be sure if it is an XY problem, I feel pretty confident that I need to have at least three arrays concurrently (although I don't jump around too much in the arrays).
Does anyone have any expertise on how to fix this issue? Thank you for your help in advance. And finally, I am using Linux.

A: This sounds like a good use case for mmap.
The mmap function can be used to take an open file and map it to a region of memory.  Reads and writes to the file via the returned pointer are handled internally, although you can periodically flush to disk manually.  This will allow you to manipulate a data structure larger than the physical memory of the system.
This also has the advantage that you don't need to worry about moving data back and forth from disk manually.  The kernel will take care of it for you.
So for each of these large arrays, you can create a memory mapping backed by a file on disk.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

#define DATA_LEN 30000000000LL

int main()
{
    int array1_fd = open("/tmp/array1", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (array1_fd < 0) {
        perror("open failed");
        exit(1);
    }

    // make sure file is big enough
    if (lseek(array1_fd, DATA_LEN, SEEK_SET) == -1) {
        perror("seek to len failed");
        exit(1);
    }
    if (write(array1_fd, "x", 1) == -1) {
        perror("write at end failed");
        exit(1);
    }
    if (lseek(array1_fd, 0, SEEK_SET) == -1) {
        perror("seek to 0 failed");
        exit(1);
    }

    char *array1 = mmap(NULL, DATA_LEN, PROT_READ | PROT_WRITE, MAP_SHARED, array1_fd, 0);
    if (array1 == MAP_FAILED) {
        perror("mmap failed");
        exit(1);
    }

    // Use array1

    munmap(array1, DATA_LEN);
    close(array1_fd);
    return 0;
}

The important part of the mmap call is the MAP_SHARED flag.  This means that updates to the mapped memory region are carried through to the underlying file descriptor.


text:
Q: Can an F-test for Full vs. Reduced Model Always Be Trusted? I am trying to compare two models:
Costs = Income + Education1 + ... + Education10 and Costs = Income
From the ANOVA table using anova() in conjunction with the corresponding lm() objects, I get that the p-value is < 2.2e-16. However, I was wondering if there was any way that the numerous factor levels in Education could throw off the p-value? I was thinking that it may be deflated due to multiple comparisons because of the numerous parameters but I wasn't sure. Also, is this test influenced by multicollinearity between Income and Education?
Thanks

A: As to the first question, I agree with Dave that the F test does not perform multiple comparisons, but just one. You would possibly run into a multiple comparison issue if you did separate t tests on each education level to find out which has a nonzero effect.
With the F test, you "only" have the alternative hypothesis that there is at least one level that has a nonzero effect, but if you reject, the "price" you pay for using the F test is that you do not know which level is "responsible" for the rejection.
As to the second question, somewhat to my surprise (but see the comments below), this little simulation does not find any sensitivity of the F test to what is near perfect multicollinearity when we test for the relevance of all correlated predictors (see below for an edit).
library(lmtest)
library(mvtnorm)

n <- 30
reps <- 5000
k <- 2
critical.value <- qf(p = .95, df1 = k, df2 = n-k)

covariance <- 0.999
Fstat <- rep(NA,reps)

for (i in 1:reps){
  y <- rnorm(n)
  X <- rmvnorm(n, sigma = matrix(c(1,covariance,covariance,1), ncol=2))
  reg <- lm(y~X)
  Fstat[i] <- waldtest(reg, test="F")$F[2]
}

mean(Fstat>critical.value)

hist(Fstat, breaks = 100, col="lightblue", freq = F, xlim=c(0,5))
x <- seq(0, 6, by=.01)
lines(x, df(x, df1 = k, df2 = n-k), lwd=2, col="purple")

The rejection rate (mean(Fstat>critical.value)) is, even for relatively small $n=30$ and very strong covariance of the regressors (0.999), still very close to the nominal 0.05, and the histogram and theoretical null density agree very well:

EDIT: Here is a modification of the code that, in response to Dave's comment , tests only one of the two correlated predictors (so that the F statistic is then nothing but a squared t-statistic), and the result still appears to go throgh:
library(lmtest)
library(mvtnorm)

n <- 30
reps <- 5000
k <- 2
critical.value <- qf(p = .95, df1 = k-1, df2 = n-k)

covariance <- 0.999
Fstat <- rep(NA,reps)

for (i in 1:reps){
  y <- rnorm(n)
  X <- rmvnorm(n, sigma = matrix(c(1,covariance,covariance,1), ncol=2))
  X1 <- X[,1]
  X2 <- X[,2]
  reg <- lm(y~X1+X2)

  regX1 <- lm(y~X1)
  Fstat[i] <- waldtest(reg, regX1, test="F")$F[2]
}

mean(Fstat>critical.value)

hist(Fstat, breaks = 200, col="lightblue", freq = F, xlim=c(0,5))
x <- seq(0, 6, by=.01)
lines(x, df(x, df1 = k-1, df2 = n-k), lwd=2, col="purple")

redpajama_set_name: RedPajamaStackExchange


text:
Q: error code -1407 Mac OS X 10.6.7 Out of the blue, I can't send any files to the trash bin. "The operation can't be completed because an unexpected error occurred (error code -1407)
Any ideas for me?

A: Finder's trash can is an amalgam of several different directories:

*

*~/.Trash/

*/.Trashes/<uid>/ on each volume (including the startup volume)
e.g. /Volumes/Big Media Volume/.Trashes/501/
Most trash operations will move the trashed item to the directory under your home directory. If you trash something on an separate volume, however, Finder will move the item into the volume's /.Trashes/<uid>/ directory instead (because moving a file to a location on the same volume is very fast, but copying a file from some other volume to your home directory's trash directory could be quite slow).
Try checking your main trash directory (in a Terminal window):
ls -ld ~/.Trash

If the result does not look like start with drwx------ and show your user's "short name" twice (the second is actually a group name), then your personal trash directory has probably been fouled. You can move it aside then logout and login again:
cd ~ && mv .Trash .Trash.old
# now logout and re-login

This should create a new ~/.Trash directory for you. You may want to investigate the contents of the .Trash.old file/directory to try to determine its origin.
If the problem is with a per-volume trash directory, you should be able to use the same idea: move it aside, eject it, then remount it (disconnect and reconnect an external disk, reopen a disk image, use Disk Utility to remount an internal volume):
cd '/Volume/whereever' && mv .Trashes .Trashes.old
# then eject and remount

You may need … && sudo mv … if the volume has "Owners Enabled".

A: You might want to try repairing file permissions with Disk Utility.

A: If you don't want to reboot or reformat, just open a Terminal and delete files or folder with rm. Worked for me to delete an app from a USB key.


text:
Q: I want to get every resources wise billing for my Azure portal I want to get every resources wise billing for my Azure portal account, after having a discussion with their support team they tell me to download that xls or invoice pdf, but it's not contain resource name and proper value for that.

A: Take a look at Azure Cost Management (Cloudyn)
https://azure.microsoft.com/en-us/services/cost-management/
Cloudyn is a free-to-use service for Azure subscriptions, which help you to track costs of individual services and workloads. It also enables you to create custom dashboards and reports based on which services you want to track.
You can start using Cloudyn by logging in to Azure portal, and choosing "Cost Management + Billing" from the left hand blade, and clicking Cost Management.


text:
Q: DB:SQLSTATE[42000]: Syntax error or access violation: 1064 Error  $sql = "INSERT INTO `call-request`(`mob`, `dat`, `nam`) VAULES( `hello`, `hi`, `he`)";

    $result = $db->exec($sql);
    $insertId = $db->lastInsertId();

is getting this error
 DB:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VAULES( 'hello', 'hi', 'he')' at line 1

I have not using any keywords please help

A: $sql = "INSERT INTO `call-request`(`mob`, `dat`, `nam`) VAULES( `hello`, `hi`, `he`)";

VAULES

It should be VALUES
and the query should be look like below -
$sql = "INSERT INTO `call-request`(`mob`, `dat`, `nam`) VALUES( 'hello', 'hi', 'he')";
$result = $db->query($sql);

for value you have to use single quote or double quote not `

A: Use ' to quote string literals and typo in VALUES:
$sql = "INSERT INTO `call-request`(`mob`, `dat`, `nam`) VALUES( 'hello', 'hi', 'h')";


text:
Q: ArcGIS mean aspect of polygons from SRTM I have a shapefile with >1200 polygons and wish to extract mean aspect (0-360) for all of them from an SRTM DEM (raster). Both are WGS84 GCS. I have found Python code to do this (here: https://geonet.esri.com/thread/47864), however get errors when trying to run.
Is there another way of doing this?
I have read other posts but have not fully understood what to do - I'm inexperienced in ArcGIS.
====================================================
SCRIPT:
CalcZonalMeanAspect.py
DESCRIPTION:
This script calculates the mean aspect azimuth (like 52 degrees) and the mean aspect
class (like 045 NE) for each zone (polygon) in a shapefile, or MDB or GDB feature class.
Mean aspect value fields are appended to the input's attribute table.
USER INPUTS:
> A polygon shapefile, or MDB or GDB feature class, containing the zones of interest
> A field name representing each polygon's unique ID
> An elevation raster
====================================================
Import modules and Spatial Analyst.
import arcpy, math, os
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
arcpy.AddMessage(" ")
arcpy.AddMessage(" ")
arcpy.AddMessage("Calc Zonal Mean Aspect was developed by Carl Beyerhelm, Coconino National Forest.")
arcpy.AddMessage(" ")

try:
# Accept user input.
inZone      = arcpy.GetParameterAsText(0) ## The "zone" polygon shapefile or feature class
zoneField   = arcpy.GetParameterAsText(1) ## The zone ID field
inElevation = arcpy.GetParameterAsText(2) ## The elevation raster

# Set the workspace to inZone's parent folder.
currentDir = inZone
scratchFolder = ""
while scratchFolder == "":
    currentDir = os.path.dirname(currentDir)
    if os.path.isdir(currentDir): ## If currentDir is a folder
        if currentDir[-4:] == '.gdb': ## If currentDir is a file geodatabase
            currentDir = os.path.dirname(currentDir) ## Retreat one more directory level
        scratchFolder = currentDir
arcpy.env.workspace = scratchFolder ## Set the workspace to inZone's parent folder

# Set environment variables.
arcpy.env.mask = inZone
arcpy.env.extent = inZone
arcpy.env.snapRaster = inElevation
arcpy.env.overwriteOutput = True

# Generate a temporary aspect grid named asp from inElevation.
arcpy.AddMessage(" ")
arcpy.AddMessage("Generating an aspect grid...")
asp = arcpy.sa.Aspect(inElevation)
# asp.save("xxasp")
# del asp

# Set asp cells having a value of -1 (flat) to NULL.
arcpy.AddMessage(" ")
arcpy.AddMessage("Setting cell values with a FLAT aspect to NO DATA...")
aspNull = arcpy.sa.SetNull(asp, asp, "VALUE = -1")
# aspNull.save("xxaspnull")
# del aspNull
del asp

# Generate the cosine of aspect expressed in radians.
arcpy.AddMessage(" ")
arcpy.AddMessage("Getting the cosine of each cell's aspect expressed in radians...")
aspCos = arcpy.sa.Cos(aspNull * math.pi / 180.0)
# aspCos.save("xxaspcos")
# del aspCos

# Generate the sine of aspect expressed in radians.
arcpy.AddMessage(" ")
arcpy.AddMessage("Getting the sine of each cell's aspect expressed in radians...")
aspSin = arcpy.sa.Sin(aspNull * math.pi / 180.0)
# aspSin.save("xxaspsin")
# del aspSin
del aspNull

# Calculate the zonal sums of aspect cosine and aspect sine.
arcpy.AddMessage(" ")
arcpy.AddMessage("Calculating the zonal sums of aspect cosine and aspect sine...")
arcpy.sa.ZonalStatisticsAsTable(inZone, zoneField, aspCos, "xxSumCos.dbf", "DATA", "MEAN")
arcpy.sa.ZonalStatisticsAsTable(inZone, zoneField, aspSin, "xxSumSin.dbf", "DATA", "MEAN")
del aspCos
del aspSin

# Add fields to inZone's attribute table.
arcpy.AddMessage(" ")
arcpy.AddMessage("Adding fields Aspect_Azm and Aspect_Cls to " + os.path.basename(inZone) + "...")
arcpy.AddField_management(inZone, "MeanCos", "DOUBLE")
arcpy.AddField_management(inZone, "MeanSin", "DOUBLE")
arcpy.AddField_management(inZone, "Aspect_Azm", "DOUBLE")
arcpy.AddField_management(inZone, "Aspect_Cls", "TEXT", "", "", 6)

# Populate fields MeanCos and MeanSin with mean values from xxSumCos.dbf and xxSumSin.dbf.
arcpy.MakeTableView_management(inZone, "zoneView")
arcpy.MakeTableView_management("xxSumCos.dbf", "cosView")
arcpy.MakeTableView_management("xxSumSin.dbf", "sinView")
arcpy.AddJoin_management("zoneView", zoneField, "cosView", zoneField) ## Populate MeanCos values
arcpy.CalculateField_management("zoneView", "MeanCos", "[xxSumCos.Mean]")
arcpy.RemoveJoin_management("zoneView", "xxSumCos")
arcpy.AddJoin_management("zoneView", zoneField, "sinView", zoneField) ## Populate MeanSin values
arcpy.CalculateField_management("zoneView", "MeanSin", "[xxSumSin.Mean]")
arcpy.RemoveJoin_management("zoneView", "xxSumSin")

# Calculate the mean aspect azimuth for each zone.
arcpy.AddMessage(" ")
arcpy.AddMessage("Calculating the mean aspect azimuth for each zone in " + os.path.basename(inZone) + "...")
expression = "math.fmod(360 + (math.atan2(!MeanSin!, !MeanCos!)) * (180 / math.pi), 360)" ## This is the fundamental calculation
arcpy.CalculateField_management("zoneView", "Aspect_Azm", expression, "PYTHON")

# Calculate the mean aspect class for each zone.
arcpy.AddMessage(" ")
arcpy.AddMessage("Calculating the mean aspect class for each zone in " + os.path.basename(inZone) + "...")
arcpy.CalculateField_management("zoneView", "Aspect_Cls", '"' + '000' + ' NO' + '"') ## Calc everything to "000 NO" as a default
clsList = ["045 NE", "090 EA", "135 SE", "180 SO", "225 SW", "270 WE", "315 NW"] ## A list of aspect classes
low = 22.5
high = 67.5
fc = inZone
field = "Aspect_Azm"
delimField = arcpy.AddFieldDelimiters(fc, field) ## Construct a properly delimited field name
for cls in clsList:
    expression = delimField + ' >= ' + str(low) + ' and ' + delimField + ' < ' + str(high) ## Select zones with an aspect azimuth between the
    arcpy.SelectLayerByAttribute_management("zoneView", "NEW_SELECTION", expression)       ## low and high bounds of the current aspect class
    arcpy.CalculateField_management("zoneView", "Aspect_Cls", '"' + cls + '"', "PYTHON")
    low = low + 45
    high = high + 45

arcpy.AddMessage(" ")
arcpy.AddWarning("OK, done!  Mean aspect azimuth and mean aspect class have been appended to:")
arcpy.AddWarning("    > " + inZone)
arcpy.AddMessage(" ")

except:
arcpy.AddError(" ")
arcpy.AddError("Something is cooked...")
arcpy.AddError(arcpy.GetMessages(2))
arcpy.AddError(" ")

finally:
# Clean up.
killFiles = ["xxSumCos.dbf", "xxSumSin.dbf"] ## Delete remnant .dbf files
for file in killFiles:
    if arcpy.Exists(file):
        arcpy.Delete_management(file)
killFields = ["MeanCos", "MeanSin"] ## Delete remnant fields
fieldList = arcpy.ListFields(inZone)
for field in fieldList:
    if field.name in killFields:
        arcpy.DeleteField_management(inZone, field.name)
killRasters = ["asp", "aspNull", "aspCos", "aspSin"] ## Dismiss remnant temporary rasters
for raster in killRasters:
    if arcpy.Exists(raster):
        del raster
arcpy.CheckInExtension("Spatial") ## Return SA license
arcpy.RefreshCatalog(scratchFolder) ## Refresh ArcCatalog view

A: A suitable answer may be present in Is there a zonal statistics tool to calculate median and mode raster values for each polygon?
It mentions median and mode in heading but the answers include mean calculation.


text:
Q: cost-sensitive multi-label classification using mlr package Is there a way to perform a cost-sensitive multi-label classification with example-dependent costs using the mlr package?
(not class-dependent costs! see: mlr tutorial)
It seems to me the according Task() should somehow be a combination of makeMultilabelTask() and makeCostSensTask()
I think it would be sufficient to pass a label-specific weight vector from the cost matrix to each of the (e.g. Binary Relevance) classifiers, right?
Is there already an elegant way to do this with mlr?


text:
Q: Use non-generic method of Hashset through reflection I want to be able to call the Hashset.ExceptWith() method using reflection but I can't make it happen.
I can't create a generic method. It seems it isn't a generic method.
I also can't seem to call the method itself using invoke.
Does anyone know how to do this?
var newSet = pi.GetValue(newItem);
var existingSet = pi.GetValue(existingItem);
MethodInfo methodExcept = typeof(HashSet<>).GetMethod("ExceptWith");

//The next line throws: Void ExceptWith(System.Collections.Generic.IEnumerable`1[T]) is not a GenericMethodDefinition.
//MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.'
MethodInfo genericExcept = methodExcept.MakeGenericMethod(pi.GetType().GetGenericTypeDefinition().UnderlyingSystemType);

//The next line throws 'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'
methodIntersect.Invoke(existingSet, new[] { newSet });
//The next line is not possible since instantiation of the variable doesn't work
genericIntersect.Invoke(existingSet, new[] { newSet });

A: Ok, so this seems to work. Apparently you have to get the GenericArguments from the Type first.
var newSet = pi.GetValue(newItem);
var existingSet = pi.GetValue(existingItem);

var itemsType = existingSet.GetType().GetGenericArguments()[0];

MethodInfo methodExcept = typeof(HashSet<>).MakeGenericType(itemsType).GetMethod("ExceptWith");

methodExcept.Invoke(newSet, new[] { existingSet });


text:
Q: Successfully Installed Ruby 1.9.2 with RVM but now it reverted back to 1.8.7 Note: Im on OSX 10.6.6
I successfully installed 1.9.2 using RVM. After doing so I ran rvm --default use 1.9.2, which also appeared to work fine. Ran Ruby -v command and sure enough 1.9.2 appeared.
Now, I closed my terminal session and opened a new one, ran ruby -v and it reverted back to 1.8.7
I removed rvm, repeated the install and the same thing happens.
Any ideas?
Thanks

A: You need to add the following to your ~/.bash_profile file to ensure that RVM is loaded properly in a terminal session:
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"


text: Q: Splunk Alerts to slack not working I have currently set some basic alerts on Splunk my requirement is that, whenever these alerts get raised, I should receive them on Slack. I have an incoming webhook set up for my slack channel and an ordinary POST message from my server (where Splunk is running) successfully reaches my slack channel. However, when the Splunk alert is generated it does not get sent to my Slack Channel even though I have already set it up to send it to the required webhook. Any insights on where I might be going wrong?


text:
Q: At what levels do the various types of armour start to appear in Skyrim? I was wondering at what levels do the various types of armour start to appear?
For instance right at the beginning hide/studded is the more prevalent armor type (from memory) However I'm now level 18 and starting to see bits of Elven armour creep in to bandit chief loot, etc.

A: Copied from another post:

The full Heavy Armor progression is (with very rough levels):

*

*Iron (lv 1)

*Steel (lv 6)

*Dwarven (lv 12)

*Steel Plate (lv 18)

*Orcish (lv 25)

*Ebony (lv 32)

*Dragonplate (lv 40)

*Daedric (lv 48)

  The full Light Armor progression is (with very rough levels):

*

*Hide (lv 1)

*Leather (lv 6)

*Elven (lv 12)

*Scaled (lv 27)

*Glass (lv 36)

*Dragonscale (lv 48)

  Clothing doesn't progress, rather the enchantments get more powerful as your level increases.

Source: this answer by Cloudancer

A: They can appear at random times. Daedric won't be until the 40s but you will see the crafting materials for it really early on.

A: It's not so much related to your level as to your skill level in smithing. I am, for example, about level 16 but have a reasonably high smithing skill (just over 60) and can smith Orcen armour and weapons

A: you do not need the smithing perks or levels for the items to appear.  you can craft the items early on if you get a high enough smithing level.  and dragon armors are the last ones daedric are a bit weaker. i was seeing daedric items at like 48.  i got an ebony sword off a dragur deathlord at level 22.  sometime you get random shit at random levels


text:
Q: How do I preserve installations when exiting colab? When I use a notebook in Colab, it might take some time to install all dependencies that it might require.
Is it the nature of a Colab notebook that it will cease to exist when exited, like a sandbox? Or is there a way to preserve the installations?
An example:
coquiAI installs so many dependencies that it might take 10 minutes.
I wonder if I really have to do that each time I start the notebook.


text:
Q: Issue in finding rmse in PCA Reconstruction in python I am trying to find the root mean squared error between an original sample from Xdata and a reconstructed sample recon for different numbers of components. However when I use the code below:
components = [2,6,10,20]
for n in components:
    pca = PCA(n_components=n)
    recon = pca.inverse_transform(pca.fit_transform(Xdata[0].reshape(1, -1)))
    rmse = math.sqrt(mean_squared_error(Xdata[0].reshape(1, -1), recon))
    print("RMSE: {} with {} components".format(rmse, n))

I always get an RMSE of 0.0 for each component?
For reference, this is what Xdata[0] holds:
array([-8.47058824e-06, -6.12352941e-05, -3.18529412e-04, -1.09905882e-03, -2.64370588e-03, -4.39111765e-03, -8.70000000e-03, -2.35560000e-02, -6.03388235e-02, -1.52837471e-01, -3.48945353e-01, -4.86196588e-01, -5.51568706e-01, -5.38629706e-01, -5.34948000e-01, -5.70773824e-01, -5.45583000e-01, -4.30446353e-01, -2.76558000e-01, -1.10208882e-01, -4.35031765e-02, -2.09613529e-02, -1.25080588e-02, -9.00317647e-03, -5.04900000e-03, -2.75576471e-03, -1.03394118e-03, -1.78058824e-04, -7.53529412e-05, -2.54647059e-04])

A: PCA is a type dimension reduction and I quote wiki:

It is commonly used for dimensionality reduction by projecting each
data point onto only the first few principal components to obtain
lower-dimensional data while preserving as much of the data's
variation as possible.

To me, your data X[0] and only 1 dimension.. How much more can you reduce it?
If it is a case of testing the rmse for the first entry, you still need to fit the pca on the full data (to capture the variance), and only subset the rmse on 1 data point (though it might be meaningless, because for n=1 it is not rmse but square of residuals)
You can see below:
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error

iris = datasets.load_iris()
Xdata = iris.data

components = [2,3]
for n in components:
    pca = PCA(n_components=n)
    recon = pca.inverse_transform(pca.fit_transform(Xdata))
    rmse = mean_squared_error(Xdata[0], recon[0],squared=False)
    print("RMSE: {} with {} components".format(rmse, n))

The output:
RMSE: 0.014003180182090432 with 2 components
RMSE: 0.0011312185356586826 with 3 components


text:
Q: Real matrices with $n$ real positive eigenvalues, $A^2=B^2$. Prove that $A=B$ Let $A$ and $B$ be real $n\times n $ matrices such that both of their characteristic polynomials split into linear factors over $\mathbb{R}$ and each eigenvalue is positive . If $A^2=B^2$, then prove that $A=B$.

A: Look up Theorem 1.29 on principal square roots in Nicholas Higham's book
Functions of Matrices, SIAM 2008. This theorem says that a square matrix without an eigenvalue $\leq 0$ has exactly one square root such that all its eigenvalue belong to the right half plane.

A: Hint: If $A$ is a matrix with positive eigenvalues in Jordan form, note that $A$ and $A^2$ will have the same block structure.


text:
Q: How to create a monomial plot in R? I want to create a function, that result will be a plot of moniomals ( degree less than "n").
I wrote the simple code.
Monomial=function(m){
  x=1:100
  y=1:100
  for(i in m) x2=x^m
  plot(y,x2,type="l",col="red",xlab="Arguments",ylab="Values",
       main=expression("Monomials"))

But for example: Monomial(3) I getting plot x^3. I need yet x^1 and x^2. How to name each line?

A: Here is what you need:
Monomial <- function(m){
  x <- 1:100
  cols <- palette(rainbow(m))

  plot(x,x,type="l",col = cols[1],xlab="Arguments",ylab="Values",
       main=expression("Monomials"))

  for (d in 2:m){
      lines(x, x^d, type="l", col=cols[d])
  }

  legend(90, 60, legend=c(as.character(paste0("x",1:m))),
         col=cols, lty=1, cex=0.6)
}

You need to generate colors. This is what the cols variable achieves. lines adds a new curve to existing axes. Finally, ledend adds a legend to the plot.


text:
Q: Why is home being required in my url? I have a route defined
routes.MapRoute(
    name: "NoRightsRoute",
    url: "norights",
    defaults: new { controller = "Home", action = "NoRights" }
);

and in a check on if the user has rights I redirect them to this route if they don't
Response.RedirectToRoute("NoRightsRoute");

the url that it redirects to is
https://localhost/norights

Home is removed which I would expect since that is assumed by MVC but I get an error
"The resource could not be found"

if I change the url to
https://localhost/Home/norights

the page loads correctly.  Why is "Home" being required in my url?  Is there some way to have "Home" included in the url so that the redirect works or get the page to load as it should when assumed?

A: You may try to remove the default, and hard code Home in url.
routes.MapRoute(
    name: "NoRightsRoute",
    url: "Home/norights",
);

But check that other links /redirections are not impacted !


text:
Q: TypeError: 'Label' object not callable I am creating a simple python GUI, which uses labels to bind a gif image to a function. However, it returns the error TypeError: 'Label' object not callable
The code is as follows:
from tkinter import *

tk = Tk()
mode = 'draw'
filename = PhotoImage(file = 'bin\\Images\\pencil.gif')
draw = Label(tk, image=filename, width=53, height=47)
draw.place(x = 60, y = 620)
draw.img = filename
draw.bind('<Double-Button-1>', draw)
filename = PhotoImage(file = 'bin\\Images\\select.gif')
select = Label(tk, image=filename, width=53, height=46)
select.place(x = 160, y = 620)
select.img = filename
select.bind('<Double-Button-1>', select)
filename = PhotoImage(file = 'bin\\Images\\select_all.gif')
select_all = Label(tk, image=filename, width=53, height=48)
select_all.place(x = 260, y = 620)
select_all.img = filename
select_all.bind('<Double-Button-1>', select_all)
filename = PhotoImage(file = 'bin\\Images\\delete.gif')
delete = Label(tk, image=filename, width=50, height=45)
delete.place(x = 360, y = 620)
delete.img = filename
delete.bind('<Double-Button-1>', delete)
filename = PhotoImage(file = 'bin\\Images\\instrument_choose.gif')
inst = Label(tk, image=filename, width=355, height=51)
inst.place(x = 700, y = 620)
inst.img = filename
inst.bind('<Double-Button-1>', draw)

There is no line number shown in the traceback reading as a line from my file. The functions don't have any parameters, and what they do is continue to the next line so far.


text:
Q: (Android) Change language doesn't work properly I'm choosing the language of my app in the MainActivity.java and sometimes it doesn't work properly.
This is my code on the onCreatemethod:
if(!SaveSharedPreference.getUserId(MainActivity.this).equals("")) {
    if (SaveSharedPreference.getWhoLoggedIn(MainActivity.this).equals("Main_User")) {
        FetchUserLanguage fetchUserLanguage = new FetchUserLanguage();
        fetchUserLanguage.execute();
    }
} else {
    sDefSystemDefaultLanguage = Resources.getSystem().getConfiguration().locale;
    Configuration configuration = new Configuration();
    configuration.locale = sDefSystemDefaultLanguage;
    getBaseContext().getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics());
}

In the FetchUserLanguage I'm getting the language for each user from my database (it is returning the value correctly).
The method where I set the Locale is the next:
@Override
protected void onPostExecute(String result) {
    switch (result) {
        case "English":
            locale = new Locale("en");
            configuration = new Configuration();
            configuration.locale = locale;
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
        case "Deutsch":
            locale = new Locale("de");
            configuration = new Configuration();
            configuration.locale = locale;
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
        default:
            locale = Resources.getSystem().getConfiguration().locale;
            configuration = new Configuration();
            configuration.locale = locale;
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
    }
}

When I run the app from the Android Studio it works perfect and all the app is set in the selected language, but then, if I close and open it again, the first screen is being shown in English, (the other are in German). The language of the device is English so do the default language of the Android project.
Maybe I'm missing something.
Thank you very much.

A: Finally I´ve found the solution.
The problem was that I was doing the translation process in an asynchronous thread, so the app was still running and some of the layouts weren't changed to the new language before the screen changed.
The solution is to create the Intent at the end of the onPostExecute() method:
@Override
protected void onPostExecute(String result) {
    switch (result) {
        case "English":
            locale = new Locale("en");
            Locale.setDefault(locale);
            configuration = new Configuration();
            configuration.locale = locale;
            SaveSharedPreference.setUserLanguage(MainActivity.this, locale.getLanguage());
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
        case "Deutsch":
            locale = new Locale("de");
            Locale.setDefault(locale);
            configuration = new Configuration();
            configuration.locale = locale;
            SaveSharedPreference.setUserLanguage(MainActivity.this, locale.getLanguage());
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
        default:
            locale = Resources.getSystem().getConfiguration().locale;
            Locale.setDefault(locale);
            SaveSharedPreference.setUserLanguage(MainActivity.this, locale.getLanguage());
            configuration = new Configuration();
            configuration.locale = locale;
            getBaseContext().getResources().updateConfiguration(configuration,
                    getBaseContext().getResources().getDisplayMetrics());
            break;
    }
    Intent intent = new Intent(MainActivity.this, MainMenuActivity.class);
    if(SaveSharedPreference.getUserType(MainActivity.this).equals("Full")) {
        intent.putExtra("Type", "Full");
    }
    startActivity(intent);
    finish();
}


text:
Q: Coloring only specific pixels I have a matrix representing an image of brain with each (i,j) position having a value between 0 and 1. I am applying a color map, so that those pixels with value 1 are red and 0 are yellow, those in between get intermediary values. Now, what i want is that those pixels having values above 0.8 get color according to colormap and rest become trasparent(that is they dont get any color), so that i can overlay this image with the another image of brain and identify high activity region. How do i do this ?
i have images like this

I want only  the bright yellow part, so that i can overlay it with other image and get something like this.

(source: psychcentral.com)
Edit:
I followed the  method suggested by Jigg, but recently observed that the final image was rotated and inverted , any idea why ?

A: Here is another option, create a 3-layers array replicating your grayscale brain image (imagesc will scale each layer similarly resulting in equal r, g, and b values -> levels of gray).
GrayBckgnd = repmat(brain, [1, 1, 3]);
data = …

Then overlay it with the activity data:
imagesc(GrayBcknd);
hold on;
DataImg = imagesc(data);
set(DataImg, 'AlphaData', im2double(data>0.8));
colormap jet; % or any other colormap.

A: You can do this by plotting a surf(-ace) and passing in alpha values as follows.
brain = ... % background brain image
data = ...  % the data you are trying to overlay
imshow(brain);
hold on;
surf(zeros(size(data)), data, 'AlphaData', data > 0.8);
colormap(...); % whatever colormap you like

Have a look at the surface properties documentation for more options you can pass to surf.


text:
Q: Values inside a custom field to determine which category posts to display I am facing a little problem whilst trying to display posts, from certain categories, on the front end. I've created a custom field whose key is 'related_categories' and I've different categories with slugs such as 'army', 'navy', 'airforce' etc.
When creating a new custom post, I enter the slugs of different categories inside the 'related_categories' custom field, for e.g. 'navy', 'airforce', and this is the code which I've inside my template file to echo the custom field values inside the 'tax_query' array.
<?php global $post;

$related = array ( get_post_meta($post->ID, 'related_categories', true) );

$the_query = new WP_Query( array( 'post_type' => 'medals', 'posts_per_page' => 3, 'tax_query' => array( array( 'taxonomy' => 'medal-categories', 'field' => 'slug', 'terms' => $related, ), ), ) );

while ( $the_query->have_posts() ) : $the_query->the_post();

//loop starts after this

Now the problem which I am facing is that if I enter only one slug inside the 'related_categories' custom field, for e.g. 'navy', then the posts from the 'navy' category successfully show up but if I enter more than one slug inside the 'related_categories' custom field, for e.g. 'navy', 'army', then the posts do not show up.
I tried searching for a solution on the internet but couldn't find any therefore any help would be appreciated. Thank you.

A: Please use this plug-in. I hope all of you problems will solve in this : https://wordpress.org/plugins/advanced-custom-fields/
In this u can easily assign which fields need to show in which category and pages.

A: Found a solution at last! Instead of using:
$related = array ( get_post_meta($post->ID, 'related_categories', true) );

I was advised to use:
$related = explode(',', trim( get_post_meta($post->ID, 'related_categories', true) ) );

along with adding the category slugs inside the custom field in the following format:
navy, army, air-force..

This is how the final code looks like:
<?php global $post;

$related = explode(',', trim( get_post_meta($post->ID, 'related_categories', true) ) );

$the_query = new WP_Query( array( 'post_type' => 'medals', 'posts_per_page' => 3, 'tax_query' => array( array( 'taxonomy' => 'medal-categories', 'field' => 'slug', 'terms' => $related, ), ), ) );

while ( $the_query->have_posts() ) : $the_query->the_post();

//loop starts after this


text:
Q: Call EventTrigger RoutedEvent in Class MainWindow.xaml.cs I have an EventTrigger called when a TextBlock is loaded:
<TextBlock Name="Hit" Text="Hit!">
 <TextBlock.Triggers>
  <EventTrigger RoutedEvent="TextBlock.Loaded">
   <BeginStoryboard>
    <Storyboard>
       <DoubleAnimation
       Storyboard.TargetProperty="Opacity"
       From="0" To="1" Duration="0:0:1"/>
    </Storyboard>
   </BeginStoryboard>
  </EventTrigger>
 </TextBlock.Triggers>
</TextBlock>

But I want to create my own launcher and call this EventTrigger directly in my C# class.
Can someone help me?

A: My understanding is that you need to call the story board  when text box loads.
Below code worked for me.
Xaml:
<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

            <Storyboard x:Key="animation">
                <DoubleAnimation
       Storyboard.TargetProperty="Opacity"
       From="0" To="1" Duration="0:0:1"/>
            </Storyboard>

    </Window.Resources>

    <Window.DataContext>
        <vm:ViewModel></vm:ViewModel>
    </Window.DataContext>
    <Grid x:Name="grid">
        <StackPanel>
        <TextBlock Name="Hit" Width="200" Height="100" Text="Hit!">
        </TextBlock>
        </StackPanel>
    </Grid>
</Window>

Code:
public MainWindow()
        {
            this.InitializeComponent();
            Hit.Loaded += Hit_Loaded;

        }

        private void Hit_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("animation") as Storyboard;
            Storyboard.SetTarget(sb, this.Hit);
            sb.Begin();
        }


text:
Q: Evalutaing a sum of a cool sequence So I was messing around, and just thought of a random sequence: $$a_1=3,a_2=5,a_n=a_{n-1}a_{n-2}$$ I wanted to then find the sum of the first $n$ terms of this, and started as so: $$\sum_{k=1}^n a_n = 3+5+3\dot{}5+3\dot{}5^2+3^2\dot{}5^3+... = 8+\sum_{k=2}^{n-1}3^{F(k-1)}\dot{}5^{F(k)}$$where F(k) is the kth Fibbonacci Number. And from here I felt I had reached a dead end. By messing around with the Fibbonacci sequence, I found $$F(n)=F(m)F(n-m-1)+F(m-1)F(n-m) \forall m\in[0,n]$$
When substituting this into my new sum, It makes it intensely complicated regardless of the $m$ chosen. I'm not sure where to go from here, or if I've gone anywhere at all. Better approaches, anything I'm not seeing?


text:
Q: SDL_main linking issue with VS2010 I've written some basic setup code for an OpenGL application:
#include <Windows.h>
#include <gl/gl.h>
#include <SDL.h>

int main()
{
    SDL_Init( SDL_INIT_VIDEO );

    SDL_Surface* surface = SDL_SetVideoMode( 800, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_OPENGL );
    glViewport( 0, 0, 800, 600 );

    SDL_Event windowEvent;
    while ( true )
    {
        if ( SDL_PollEvent( &windowEvent ) )
        {
            if ( windowEvent.type == SDL_QUIT ) break;
        }

        glClearColor( 1.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT );

        SDL_GL_SwapBuffers();
    }

    SDL_Quit();
    return 0;
}

Unfortunately this fails to link with the following error:
1>SDLmain.lib(SDL_win32_main.obj) : error LNK2001: unresolved external symbol _SDL_main

Linker settings:
http://puu.sh/kVae

A: Use main's full signature:
int main(int argc, char *argv[])

or
int main(int argc, char **argv)

or try implementing _SDL_Main instead of main.


text:
Q: What type of temperature sensor is this? I have a bunch of these temperature sensors that I want to use for a project, but I can't find any information about the specifications of it.  There are no markings on it to aid in identification.
I have hooked it to a multimeter, and it appear to be a simple varying resistance.  At body temperature it reads about 6.5kΩ, and at room temperature about 11kΩ.  Is it simply a variable resistance?

A: What you have is a Kapton-laminated/Kapton-encapsulated thermistor. From the description, it is a NTC (negative temperature coefficent) device.
(Kapton is the material the amber film is composed of. It's a high-temperature polymer)
The actual packaging is fairly unusual. The only place I have ever seen thermistors like that is in computer sensing hardware. I also did not have much luck finding places where you can purchase similar devices.

For what it's worth, this is actually not a thin film device. It's a standard thermistor, packaged in a film enclosure. Thin film, in an electronics context, typically means that the resistive/active element is composed of a thin film, generally deposited on a substrate, typically with a vacuum deposition process.
In this case, you have a standard chip-type thermistor, which is laminated into a polymer film.

As an aside, if the part has no marking on it, you will likely never find a datasheet for your particular part. However, from the values you specify, it sounds like a bog-standard 10K thermistor (e.g. 10K @ 25°C, which is a common way to specify them), so it should be easy to use even in lieu of having a real datasheet.


text:
Q: Sublime text com exit code 1. Como resolver Estou com este ERRO ao tentar compilar qualquer código em C no meu PC:
[Decode error - output not utf-8]
[Finished in 0.2s with exit code 1]

Eu instalei o MinGW e os módulos gcc(C++ e C), mas mesmo assim dá-me este erro, apesar de a única coisa que os códigos fazem é mostrar-me números. Alguém me pode ajudar?

A: Tente o seguinte salvar seu arquivo C com a codificação certa, o sublime assume que a codificação dos arquivos na saída é UTF-8.
File->Save with encoding->UTF-8
É possivel editar o arquivo .sublime-build para aceitar outras codificações.
Veja:

*

*https://gist.github.com/clijiac/2814161

*Erro "Decode error - output not utf-8" no Sublime Text

*https://stackoverflow.com/questions/21068832/sass-on-sublime-text-3-decode-error-output-not-utf-8

*https://stackoverflow.com/questions/22598005/sublime-text-3-python-3-and-utf-8-dont-like-each-other

*https://www.sublimetext.com/forum/viewtopic.php?f=3&t=7809
Outra possibilidade é que está faltando adicionar o diretório do compilador no PATH do windows.
Painel de Controle > Sistema e Segurança > Sistema > Configurações avançadas do sistema
Clique em Variáveis de Ambiente para ter a opção de incluir o caminho à variável PATH do usuário ou do sistema.


text:
Q: Bulk Insert Type Mismatch T-SQL Am using this BULK INSERT command to insert a csv file in SQL Server 2012 Express.
BULK INSERT dbo.TS_FX
   FROM 'c:\fxRates.csv'
   WITH
   (
      FIELDTERMINATOR =',',
      ROWTERMINATOR =',\n'
   );

The First Row on the fxRatesCSV file looks like this:
101,20130430,20130531,1.5307

The error I get is:

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (FX_RATE).

My table (dbo.TS_FX) has 4 columns in it defined as follows
CURRENCY_ID (Numeric(3,0), null)
BEGIN_DATE (date, null)
END_DATE (date, null)
FX_RATE (float, null)

Clearly the error is the way I have defined the FX_RATE column, I have tried various other types (Decimal, Numeric) but I still get the same error
Any help is much appreciated.
Thanks

A: Remove the comma from ROWTERMINATOR
Your BULK INSERT statement should look like this:
BULK INSERT dbo.TS_FX
FROM 'c:\fxRates.csv'
WITH (
     FIELDTERMINATOR =','
    ,ROWTERMINATOR ='\n'
);


text:
Q: bootstrap slider after convert to wordpress .. image and slider size I am converting bootstrap slider into wordpress .
the original html work look fin
http://t4uacademy.com/univ/
site
http://www.univchiropractic.com/
but its actually because images a perfectly cut and sized .
to 1920 by 500
I already used add_image_size( 'slider', 1920, 500 );
in WordPress I have the following problems
1- images are not all 1920 by 500 some are like 1920 by 1080 so that create a gap so after change the size.
2- some images like square 2000*4000 this result a bigger gap
3- small images and not resized to be bigger even I used add_image_size( 'slider', 1920, 500 ); its only resize to smaller .
4- I try to add CSS to stretch the images but first 2 points looks really bad . thats why I deleted it

A: did you try adding "true" add_image_size( 'slider', 1920, 500 , true  );
this will hard cut the image .


text:
Q: Probability of uniform distribution If I have an array of $n$ numbers in the range [0,1) and have the following events for $y$:
for $i=1$ to $n$ :
  generate a new number $y$ in [0,1) uniformly and independent of previous
if $y\ge0.5$ then
  toss a fair coin
if the coin turns up "HEADS" then
  $y=y-0.5$
I need to find out what is the probability that y is in the range [0,1/n)
My solution:
$1/2+1/2\cdot1/2=3/4$ - the first 1/2 is the probability when y is not greater than 0.5. The second $1/2\cdot1/2$ is the probability when $y>0.5$ AND because of the fair coin - we have 1/2 change of being HEADS.
Is it the correct way ? Do I need to add n into the equation? Please correct me if I am wrong. Thanks!

A: Assume $n$ is fixed beforehand. Then for each $y$ probability that it will be in range [$0,1/n$) is $$\frac{3}{4}*(\frac{1/n}{1/2})=\frac{3}{4}*\frac{2}{n}=\frac{3}{2n}$$
because with probability $\frac{3}{4}$ $y$ is a random number from [$0,1/2$) and there with probability $\frac{1/n}{1/2}$ it belongs to the range [$0,1/n$).
Hereby:
1. Probability that all $y \in$ [$0,1/n$) is equal to $$(\frac{3}{2n})^n$$
2. Probability that exists $y \in$ [$0,1/n$) is equal to:$$1-(1-\frac{3}{2n})^n$$ which is $1-$ probability that all $y \in$ [$1/n,1$)


text:
Q: Include cant find directory PHP i make MVC application (Without frameworks).
I try to include models from folder 'models' in controller, in folder controller.
include("/models/tasks_model.php");

But i get error:
Warning: include(): Failed opening '/models/tasks_model.php' for inclusion (include_path='.') in ...controller\create_task_controller.php on line 3

And
Warning: include(/models/tasks_model.php): failed to open stream: No such file or directory in ...\controller\create_task_controller.php on line 3

A: You need to fix your PHP paths
include("../models/tasks_model.php");

When you use this code:
include("/models/tasks_model.php");

It looks from the start of your disk because it an absolute path.
../ Goes back one folder from where your file is.


text:
Q: C program - Structure variable data packing and alignment What will be the output of the program on a 32-bit machine (using GCC)? Explain.
#include<stdio.h>

int main() {

     struct node {
         int data;
         struct node *link;
     };

     struct node *p, *q;
     p = (struct node *) malloc(sizeof(struct node));
     q = (struct node *) malloc(sizeof(struct node));
     printf("%d, %d\n", sizeof(p), sizeof(q));
     return 0;
}

The output shows

4, 4.

Is the above program related to structure member alignment padding and data packing?

A: No, you are just printing the size of the pointers. It's not related to the internal member layout of structures.

A: On a 32-bit system the stored addresses are always 32 bits big. If you're printing the size of a pointer you're basically just printing the size of the address it points to (32 Bit -> 4 Byte).
If you want to know the size of the struct do something like this:
struct node p;
struct node q = {4, &p};

printf("%zu, %zu\n", sizeof(p), sizeof(q));

A: *

*Point 1 Use %zu format specifier to print the output of sizeof of type size_t .

*Point 2 Note the type of p, it is struct node *, same as q.
So, essentially, sizeof(p) and sizeof(q) are exactly same as sizeof(struct node *), which, on your platform are 32 bit wide. As you're not considering a variable here, so the alignment and padding for the structure and members are neither relevant nor involved in this case.
That said, please see why not to cast the return value of malloc() and family in C.

A:
No, it is not related to the structure member alignment padding and data packing.

Since it is a 32-bit machine the size of any pointer will be 4 bytes. Since p and q are of type struct node * i.e. pointer to struct node the result prints size of pointers p and q.


text:
Q: Creating a new array with all the elements of subarray I want to create an output array which takes all the parameters from its subarray and create a resulting array.
Hard to explain in words, so am explaining with an example below.
var myArr=[
                {
                    "Id":1,
                    "Name":'Ken',
                    "Age" : '30',
                    "Hobbies" : [{'HobbyId':1,'HobbyName':'Swimming'},{'HobbyId':2,'HobbyName':'Reading'}],
                    "Skills" : [{'SkillId':1,'SkillName':'PHP'},{'SkillId':2,'SkillName':'MySQL'}],
                    "Language" : [{'LangId':2,'LangName':'English'},{'LangId':3,'LangName':'Chinese'}]
                },
                {
                    "Id":2,
                    "Name":'Mike',
                    "Age" : '20',
                    "Hobbies" : [],
                    "Skills" : [],
                    "Language" : []
                },
                {
                    "Id":3,
                    "Name":'Charlie',
                    "Age" : '25',
                    "Hobbies" : [{'HobbyId':5,'HobbyName':'Dance'},{'HobbyId':6,'HobbyName':'Sing'},{'HobbyId':7,'HobbyName':'Writing'}],
                    "Skills" : [],
                    "Language" : [{'Id':7,'Name':'English'}]
                }
            ]

In the above example there are 3 subarrays named Hobbies, Skills and Languages.
    I'll have some more subarrays apart from these three.
    I actually want to remove the subarray logic and make it a flat array.
So, when creating this flat array I want to consider all the parameters from subarray even if the subarray is empty.
    So my first item of resulting array will have the first item of all subarrays and so on.
    Even if the subarray is an empty array I need to consider there keys and input the value as null.
And so my resulting array will be as below :
var resultArray = [
                 {
                    "Id":1,
                    "Name":'Ken',
                    "Age" : '30',
                    "HobbyId" : 1,
                    "HobbyName" : 'Swimming',
                    "SkillId" : 1,
                    "SkillName":'PHP',
                    "LangId" : 2,
                    "LangName" : 'English'
                 },
                 {
                    "Id":1,
                    "Name":'Ken',
                    "Age" : '30',
                    "HobbyId" : 2,
                    "HobbyName" : 'Reading',
                    "SkillId" : 2,
                    "SkillName":'MySQL',
                    "LangId" : 3,
                    "LangName" : 'Chinese'
                 },
                 {
                    "Id":2,
                    "Name":'Mike',
                    "Age" : '20',
                    "HobbyId" : '',
                    "HobbyName" : '' ,
                    "SkillId" : '',
                    "SkillName":'',
                    "LangId" : '',
                    "LangName" : ''
                 },
                 {
                    "Id":3,
                    "Name":'Charlie',
                    "Age" : '25',
                    "HobbyId" : 5,
                    "HobbyName" : 'Dance',
                    "SkillId" : '',
                    "SkillName":'',
                    "LangId" : 7,
                    "LangName" : 'English'
                 },
                 {
                    "Id":3,
                    "Name":'Charlie',
                    "Age" : '25',
                    "HobbyId" : 6,
                    "HobbyName" : 'Sing',
                    "SkillId" : '',
                    "SkillName":'',
                    "LangId" : '',
                    "LangName" : ''
                 },
                 {
                    "Id":3,
                    "Name":'Charlie',
                    "Age" : '25',
                    "HobbyId" : 7,
                    "HobbyName" : 'Writing',
                    "SkillId" : '',
                    "SkillName":'',
                    "LangId" : '',
                    "LangName" : ''
                 }
             ]

A: This seems to produce what you wanted:
let results = [];
for(let {Id, Name, Age, Hobbies, Skills, Language} of myArr) {
    let numRows = Math.max(1, Hobbies.length, Skills.length, Language.length);
    for (let i=0; i<numRows; i++) {
        let {HobbyId, HobbyName} = Hobbies[i] || {};
        let {SkillId, SkillName} = Skills[i] || {};
        let {LangId, LangName} = Language[i] || {};
        results.push({
            Id, Name, Age,
            HobbyId, HobbyName,
            SkillId, SkillName,
            LangId, LangName,
        });
    }
}
console.table(results);

The non-trivial bits are:

*

*I use quite a bit of ES6 syntax. You might want to read a bit more about object destructuring, shorthand object literals and for..of.

*I calculate the number of rows needed before starting iteration so that I don't have to check every time whether I should go to the next person or not.

*I do Hobbies[i] || {} in order to make sure that I always have an object to desctructure with let {HobbyId, HobbyName}. I do it this way because it's simpler than checking for null each time.


text:
Q: Roots of $x^3+5x-18=0$ using Cardano's method Given that $x^3+5x-18=0$. We have to solve it using Cardano's method.
Using trial $x=2$ will be a root. Dividing the equation by $x-2$ we shall get the other quadratic equation and solving that one, we shall obtain all the roots.
But when I am trying to solve the equation using Cardan\rq s method, the calculation is becoming very difficult. I don\rq t know why. Please help.
Here is how did I proceed.
Let $x=u+v$. Then $x^3=u^3+v^3+3uvx$ i.e.  $x^3-3uvx-(u^3+v^3)=0$. So $-3uv=5$ and $u^3+v^3=18$. Clearly $u^3, v^3$ are the roots of
\begin{align}
&t^2-(u^3+v^3)t+(uv)^3=0\\
\Rightarrow &t^2-18t-\frac{125}{27}=0\\
\Rightarrow &27t^2-(27\times 18)t-125=0
\end{align}
and from here when we are getting the roots of $t$, they are very complicated. Hence I do not know how to simplify them so that $x=2$ finally be achieved along with the other two roots.
Please help me

A: Cardono's formula says that one root is$$\sqrt[3]{9+\sqrt{81+\frac{125}{27}}}+\sqrt[3]{9-\sqrt{81+\frac{125}{27}}}=\sqrt[3]{9+\frac{34}3\sqrt{\frac23}}+\sqrt[3]{9-\frac{34}3\sqrt{\frac23}}.$$But$$\sqrt[3]{9+\frac{34}3\sqrt{\frac23}}=1+2\sqrt{\frac23}\text{ and }\sqrt[3]{9-\frac{34}3\sqrt{\frac23}}=1-2\sqrt{\frac23}.$$Adding these two numbers, you'll get $2$.

A: Solving $$27t^2-27\cdot18t-125=0$$
we get $(u^3,v^3)\approx(18.25,-0.25)$
So, one of real values of $x$ will be $$\sqrt[3]{18.25}+\sqrt[3]{-0.25}\approx2$$

A: By your work we obtain:
$$x=\sqrt[3]{9+\sqrt{81+\frac{125}{27}}}+\sqrt[3]{9-\sqrt{81+\frac{125}{27}}}=$$
$$=
\sqrt[3]{9+\frac{34}{3}\sqrt{\frac{2}{3}}}+\sqrt[3]{9+\frac{34}{3}\sqrt{\frac{2}{3}}}=\frac{1}{3}\left(\sqrt[3]{243+102\sqrt6}+\sqrt[3]{243-102\sqrt6}\right)=$$
$$=\frac{1}{3}\left(\sqrt[3]{(3+2\sqrt6)^3}+\sqrt[3]{(3-2\sqrt6)^3}\right)=\frac{1}{3}(3+2\sqrt6+3-2\sqrt6)=2.$$


text:
Q: Display an array in a dropdown I want to display a php array in a js dropdown. My problem is in this picture :

I don't get each element of my array but an array of "object" and I don't understand why.
So, I make the array from a sql request, and I get all the data.
            $conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
            $dbconn = pg_connect($conn_string);

            $sql = "SELECT ".$colonne." FROM public.".$tablevar."";
            $res = pg_query($sql) or die("Pb avec la requete: $sql");

            //print_r($sql);
            $data = pg_fetch_all($res);

And I'm tryning to display this array in a dropdown like that :
type:'dropdown',
source:<?php echo json_encode($arrayData);?>

So I don't understand why I don't get the data in the dropdown. Can someone help me please ?

A: You have to access the value inside the object. Try to do a:
echo "<pre>";
print_r($arrayData);
echo "</pre>";

And try to see what's inside to get what you want.


text:
Q: How to download pdf file from data loaded from ajax or fetch calling express route that call our Api via axios? I try to download a pdf file generated by our API.
THE FLOW:
Clicking a "Dowload" button trigger a function that fetch an express route.
The route call our API via axios.
The API generate a pdf and return a raw data pdf file (string).
The route get the response of axios.
To send this response back to the fetch, I put the response in an object {pdf: response} and sent it back with res.json({pdf: response}).
In the fetch.then(), I need to transform the response into blob and use URL.createObjectURL on it to create an invisvible donwload link to trigger click on it and start download.
THE PROBLEM:
The response sent by res.json({pdf: response}) cannot be transformed into blob because it's not the pdf data, it's an json containing the pdf data.
Action triggered by the button click:
var url = "/routePath";

fetch(url)
    .then(response => response.blob())
    .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
        a.href = url;
        // the filename you want
        a.download = couponName + '.pdf';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    })
    .catch((error) => console.error(error));

Express route handling on server side:
router.get('/routePath', async function(req, res, next) {

    const pdf = await Api.send(req, 'entity', 'action', {data}, {});
    res.json({pdf: pdf});
});

Call via Axios:
const config = require(`../config/config.${process.env.NODE_ENV}.json`);
const axios = require('axios');

module.exports = {
    send: async function(req, entity, action, data, pathValues){
        let response = false;

        try {
            // Prepare headers
            let headers = {'Content-Type': 'application/json'};

            // Request
            let axiosConfig = {
                method: 'get',
                headers,
                url: path,
                data: data,
                validateStatus: false
            };
            axiosConfig.params = data;

            response = await axios(axiosConfig);

            if (response.data == '') response.data = {};
            response = response.data;
            response.callSuccess = true;
        } catch(error) {
            console.error(error);
            if (error.response){

                response = error.response.data;
                response.callSuccess = false;
                console.error(response);
            }
            else {
                console.error(error);
            }

        }

        return response;
    }

}

A: Client side:
I switched Fetch for Ajax to get more compatility (ie).
I also transform with base64ToArrayBuffer, the recieved pdf data to be able to transform it into blob.
[...]
var url = "/routePath";

    $.ajax({ url: url })
    .done(function(pdf) {
        const arraybuffer = base64ToArrayBuffer(pdf);
        const blob = new Blob([arraybuffer], {type: 'application/pdf'});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = 'GoCoupons.' + couponName + '.pdf';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    })
    .fail(function(error) {
        console.error(error);
    })

    [...]

function base64ToArrayBuffer(data) {
    var binaryString = window.atob(data);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

Server side:
Instead of returning a json, I send the pdf response from our API.
router.get('/routePath', async function(req, res, next) {
    const pdf = await Api.send(req, 'entity', 'action', {data}, {});
    res.send(pdf);
});

The Axios call is still the same
const config = require(`../config/config.${process.env.NODE_ENV}.json`);
const axios = require('axios');

module.exports = {
    send: async function(req, entity, action, data, pathValues){
        let response = false;

        try {
            // Prepare headers
            let headers = {'Content-Type': 'application/json'};

            // Request
            let axiosConfig = {
                method: 'get',
                headers,
                url: path,
                data: data,
                validateStatus: false
            };
            axiosConfig.params = data;

            response = await axios(axiosConfig);

            if (response.data == '') response.data = {};
            response = response.data;
            response.callSuccess = true;
        } catch(error) {
            console.error(error);
            if (error.response){

                response = error.response.data;
                response.callSuccess = false;
                console.error(response);
            }
            else {
                console.error(error);
            }

        }

        return response;
    }

}


text:
Q: Ruby: Net::HTTP.start issue I've got this code (roughly):
parsed_url = URI.parse(url_string)
puts "before Net::HTTP.start block"
response = Net::HTTP.start(parsed_url.host, parsed_url.port) { |http|
  puts "inside Net::HTTP.start block"
  http.read_timeout = 10
  http.get(parsed_url.path)
}

When I execute the code against a url that timesout in the browser, it never gets into the block. Any other situation it works perfectly. Is there some behavior on the start method that I don't see? I was assuming that the connection wouldn't be opened at all until the http.get(parsed_url.path) statement so I'm confused why this code more doesn't execute...
thanks in advance...

A: Net:HTTP.start calls do_start which then calls connect (both of them are private methods):
http://apidock.com/ruby/Net/HTTP/connect
The first 3 lines are
D "opening connection to #{conn_address()}..."
s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
D "opened"

and while I can't seem to find docs for the timeout method, this could be your culprit.

A: The documentation for the Net::HTTP class reads

Opens TCP connection and HTTP session.

So when you call Net::HTTP.start, the connection is made and if you cannot access the given URL, then a Timeout::Error is thrown inside the start method and the code inside your block is indeed never executed.


text:
Q: update word1 to be the last word generated (In Python)
Using a bigram dictionary built from Green Eggs and Ham.
I would like to ask the user for a word(word1) which is in a bigram dictionary/list. In the first loop the users input(Word1) will print out a random value from it's list in the dictionary (word2), for every loop after that will update so word2 become the last word we generated.
In short, Ask user for starting word then print it a newly generated pair of words 5 times.
Here's an example of what the output should do:
input: do
do not
not like
like green
green eggs
eggs and

Here is my code so far.
import random
bigrams = {'Do': ['you'], 'you': ['like', 'like', 'like', 'like'], 'like': ['green',
'them,', 'green', 'them', 'them', 'them', 'green', 'them,', 'them', 'them', 'them', 'them',
'them', 'them', 'green', 'them,'], 'green': ['eggs', 'eggs', 'eggs', 'eggs'], 'eggs':
['and', 'and', 'and', 'and'], 'and': ['ham?', 'ham.', 'ham.', 'ham.'], 'ham?': ['I'], 'I':
['do', 'am.', 'do', 'would', 'would', 'do', 'do', 'am.', 'do', 'do', 'do', 'do', 'do', 'do',
'am.'], 'do': ['not', 'not', 'not', 'not', 'not', 'not', 'not', 'not', 'not', 'not'], 'not':
['like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like',
'like'], 'them,': ['Sam', 'Sam', 'Sam'], 'Sam': ['I', 'I', 'I'], 'am.': ['I', 'Would'],
'ham.': ['Would', 'I', 'I'], 'Would': ['you', 'you', 'you'], 'them': ['here', 'here',
'anywhere.', 'in', 'with', 'in', 'with', 'here', 'anywhere.'], 'here': ['or', 'or', 'or'],
'or': ['there?', 'there.', 'there.'], 'there?': ['I'], 'would': ['not', 'not'], 'there.':
['I', 'I'], 'anywhere.': ['I', 'I'], 'in': ['a', 'a'], 'a': ['house?', 'mouse?', 'house.',
'mouse.'], 'house?': ['Would'], 'with': ['a', 'a'], 'mouse?': ['I'], 'house.': ['I'],
'mouse.': ['I']}

word = input('Word: ')
for i in range(5):
  word = random.choice(bigrams[word])
  print(word, random.choice(bigrams[word]))

and this is the current output.
Word: do
not like
like them
them here
here or
or there.

A: It's because you're resetting the value of word. Try:
for i in range(5):
  next_word = random.choice(bigrams[word])
  print(word, next_word)
  word = next_word


text:
Q: Could not load file or assembly 'Oracle.DataAccess' (x64) I am trying to create a WCF service to host in IIS.
My production and development servers are 64 bit.
The WCF service needs to be able to connect to a several different Oracle databases based on the client request.
I am using Entity Framework 5 with ODAC, and with the DbContext Initialiser, I have the option of providing a database connection to use.
private void ExampleSelect(string dataSource, string user, string password)
{
    var connection =
        string.Format("DATA SOURCE={0};PASSWORD={1};USER ID={2}",
                          dataSource, password, user);

    using (var context = new OracleDbContext(new OracleConnection(connection)))
    {
        // do stuff here
    }
}

The problem I have lies with new OracleConnection(connection).  To use this line, I need to reference the x64 version of Oracle.DataAccess.dll
When I come to publish, I get the warning:

and the error:

The platform target for my project is currently 'Any CPU'. If I change this to target x64, I get the same error, but this time it refers to my project and not Oracle.DataAccess

Any of the above builds successfully on my development machine, I only get the errors when I come to publish.
What am I doing wrong here?
These solutions appear to be related, but they all refer to 32 bit Oracle Dlls:
Could not load file or assembly Oracle.DataAccess
Could not load file or assembly 'Oracle.DataAccess' 64 bit ODP.NET
Could not load file or assembly 'Oracle.DataAccess error
To rule it out, I have also tried installing both the 64bit and 32bit Oracle Clients on the development server, but I still don't get as far as even publishing so I'm not sure that the server is the cause of the problem.
The Enable 32 bit Application property on the Application pool in IIS does not make any difference, but I tried it anyway.

A: To eliminate your problem you must meet the following conditions. Since you want everything run in x64:
1.Make sure that you have installed 64-bit Oracle client software
2.Make sure that you using 64-bit Oracle.DataAccess.dll (use corflags to verify)
3.Make sure you build your application with x64 configuration
4.Disable Enable 32 bit Application on IIS pool
This is a common mistake by many people. They install 32-bit client and try to run x64 Oracle.DataAccess


text:
Q: BB10 simulator : "This file could not be found" Im studying with BB10 simulator. Today I follow an example here :
http://developer.blackberry.com/html5/documentation/package_and_launch_your_app_bb10.html
The problem is when I package and build in Ripple Emulator, the app in BB10 simulator cant run :

Can someone tell me why and how to fix this problem? Tks so much :)

A: The problem is so simple, it must be index.html instead of index.htm


text:
Q: How to auto increment serial number in database whenever a new row is added? I have a table which consist of many columns and one of them is serial number. My requirement is whenever user enters the data in form and data gets added to the database but i don't want the user to enter the serial number every time. How to increment serial number in database itself?

A: From the description of your project I can recommend you to do a while loop to run the program. Create a variable for the serial number with an initial value and set it to be incremented every time it passes through the loop(when the user inputs the information). You can increment the serialNumber variable doing: serialNumber++. This will bring it up by one every time it goes through the loop.
This can work in case you are using JAVA.

A: Why don't you use as Identity for that serial number column with auto increment property. That will auto increment every time a row is added to that table
http://www.w3schools.com/sql/sql_autoincrement.asp
https://msdn.microsoft.com/en-us/library/ms186775.aspx


text:
Q: Parse text and store it to render in canvas (like in console) with javascript I have some code like this:
// highlight text
vi.prototype.parse = function (text) {
    // some code
    this.data = data;
};
// place it on canvas
vi.prototype.render = function () {
    /* loop */
        this.ctx.clearRect(/* ... */);
        this.ctx.fillStyle = this.data[i].bg;
        this.ctx.fillRect(/* ... */);
        this.ctx.fillText(data[i].text, /* ... */);
        // ....
    /* end loop */
};

I parse and render text every time when text changed.
Everything is complicated by the fact that the line can not get into the canvas.
1 Some line
2 Some long line line line line line line line li
 ne line line
3 Some line

What is the best way to parse and store text with background and foreground colors?
I need to print text with syntax highlighting.
I have a function that parses the text and returns it in some form, for example
text = "var x;";
highlightedText = vi.parse (text);
console.log (highlightedText);
>> [[  {text: "var", fg: "#dd5", bg: "#000"},
       {text: " ", fg: "#FFF", bg: "#000"},
       {text: "x", fg: "#5dd", bg: "#000"},
       {text: ";", fg: "#FFF", bg: "#000"}]];
// Displays the text in canvas
vi.render (highlightedText);

I think it's not a good way to store text data

A: This is not tested code, but here are my ideas:
Keep your style definitions in your main class (vi?)
Create textSegment objects that have everything needed to draw the text:

*

*The text.

*The style of the text.

*The width of the text.

Keep all your textSegments in an array in your main class.
    this.textSegments.push({
        text  : text,
        textWidth : ctx.measureText(newText).width,
        style : style
    });

Here is code (untested/incomplete!):
function vi(context,lineheight){

    this.ctx=context;
    this.lineHeight=lineheight;
    this.textSegments=[];
    this.x=0;
    this.y=0;

    // keep the style definitions once and reference them in your text segments
    this.styles=[];
    this.styles["normal"]=   { font:"12px Arial", bg:"#000", fg:"#fff" };
    this.styles["operator"]= { font:"12px Arial", bg:"#000", fg:"#5dd" };
    this.styles["keywordS"]= { font:"12px Arial", bg:"#000", fg:"#d55" };

}
//
// usage: myVi.addTextSegment("Hello","normal");
//
vi.prototype.addTextSegment(text,style){

    // measure the text once while you're adding it
    this.ctx.font=newStyle.font;

    // create a textSegment object
    // that has everything needed to draw the text
    this.textSegments.push({
        text  : text,
        textWidth : ctx.measureText(newText).width,
        style : style
    });
}
// draw the textSegment
vi.prototype.drawTextSegment(textSegment){
    var style=this.styles[textSegment.style];
    this.ctx.save();
    this.ctx.font=textSegment.style.font;
    this.ctx.fillStyle=textSegment.style.bg;
    this.ctx.rect(this.x,this.y,textSegment.textWidth,this.lineHeight);
    this.drawText(textSegment.text,this.x,this.y);
    this.ctx.restore();
    this.x+=textSegment.textWidth;
}


text:
Q: foreign key in google app's datastore A quick question, Does google app's datastore support foreign key mapping, if yes, can anyone enlightened me XD, or share some link.

A: You can use ReferenceProperty to refer to other items of different Kind, or SelfReferenceProperty to refer to other items of the same Kind.

A: All entities have a key, which you can reference and store in an entity's property. Note that holding a key to an entity doesn't imply that the entity pointed to actually exists - i.e. there is no relational integrity. Similarly, removing an entity that exists doesn't have any effect on the key.
A similar SQL construct would be a table with a column that holds a value that is a primary key elsewhere, but without a foreign key relationship and therefore no relational integrity.
There is a concept of a dependent child with cascading delete. This is a JDO construct and not natively supported by the datastore itself - the delete is managed by the higher-level JDO framework.
You can also use embedded classes. An embedded object is essentially contained by the holding object store as a normal property. If you delete the holding class, you delete the embedded object.
http://code.google.com/appengine/docs/python/datastore/keyclass.html
http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent_Children_and_Cascading_Deletes
http://code.google.com/appengine/docs/java/datastore/dataclasses.html#Embedded_Classes


text:
Q: Stopping a for loop in a while loop I have a for loop in a while loop running on a condition. The button changes the condition variable but the for loop does not stop.
self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
self.cancel_button.grid(row=0)

def cancel(self):
    self.break_main = 1

self.break_main = 0
while self.break_main == 0:
    for x in list:
        #do stuff

A: See if this works:
self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
self.cancel_button.grid(row=0)

def cancel(self):
    self.break_main = 1

self.break_main = 0
while True:
    if self.break_main:
        break
    #do stuff

A: Have you tried doing it like this? I cant test it as tkinter is always hit and miss with my computer, sometimes it works, sometimes it doesnt.
def cancel(self):
    self.break_main = 1

while True:
    self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
    self.cancel_button.grid(row=0)
    if self.break_main:
       break

A: This is like staring at the entrails of a goat to glean some meaning... but here is an example that does what you want. You have not posted the other 90% of the code so its hard to guess where you went wrong. I posted this partially just to show that working examples can be written and they make the job of answering questions easier.
try:
    import tkinter
except ImportError:
    import Tkinter as tkinter # python 2

import threading
import time

class Foo(tkinter.Frame):

    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        cancel_button = tkinter.Button(self, text="Stop While", command=self.cancel)
        cancel_button.place(x=50, y=50)
        self.pack(fill=tkinter.BOTH, expand=1)
        self._thread = threading.Thread(target=self.while_thread)
        self._thread.isDaemon()
        self._thread.start()

    def cancel(self):
        self.break_main = 1

    def while_thread(self):
        print("Thread start")
        self.break_main = 0
        while self.break_main == 0:
            time.sleep(.1)
        print("Thread done")

if __name__ == "__main__":
    root = tkinter.Tk()
    root.geometry("250x150+300+300")
    app = Foo(root)
    root.mainloop()
    print("Main Done")


text:
Q: In Safari/Chrome, how can I trigger a function A on both ready() and focus() and a function B on blur()? I have a counter that counts down when windows is on focus and stops counting when window is on blur.
My code works perfectly with Firefox and IE because with FF or IE, focus() event is triggered upon load of the document.
But in Safari/Chrome it's not.
Does anyone know how I can trigger the countDown() function upon loading with Safari/Chrome?
Thanks a lot
my code has this structure:
$(document).ready(function(){
         $(window).focus(function(){
              countDown();
          });

       $(window).blur(function(){
              stopCount();
          });

});

A: How about you call countDown from ready aswell? You might have to check if the window still has focus first though. And you should make sure countDown wasn't called already - or make countDown "resistant" against additional calls.
Or another way, that should make the code a bit cleaner is to simply call $(document).focus() from $(document).ready.
More context:
$(document).ready(function(){
    $(window).focus(function(){
        countDown();
    }).blur(function(){
        stopCount();
    }).focus();
});

A: Could you try something like:
if ( $.browser.webkit ) {
   countDown();
}

I think this will check if it's a webkit browser and then fire the countDown() event


text:
Q: Immediately dereferencing unique_ptr I'm not very familiar with modern C++ and would like to better understand the following fragment:
State & m_rootstate;
//...
auto currstate = std::make_unique<State> (m_rootstate);
do_something (*currstate);
// currstate is not used anywhere else

I see a unique_ptr is created from a reference to a State. This should use the copy ctor of State to create a new instance of State, and a pointer to this new instance gets wrapped in currstate.
currstate is then immediately dereferenced as an argument to a function. currstate is not used after that, but it does not go out of scope until after the call finished so it and its linked State do not get destructed prematurely.
For the call, the value inside the unique_ptr is used. Depending on whether do_something takes a State or State&, it will be copied again or not.
Is this right? If so, is it correct that the purpose of the unique_ptr is only to create a copy of m_rootstate without having to worry about memory management?

A: State & m_rootstate;

This makes no sense on it's own - im guessing you left vital stuff out. A reference has to be initialized.
//...
auto currstate = std::make_unique<State> (m_rootstate);

This constructs a new State and wraps it in a unique_ptr (in this case through a copy constructor, so you are right, its a copy)
do_something (*currstate);
// currstate is not used anywhere else

Depending on whether do_something takes a State or State&, it will be copied again or not. True.
If so, is it correct that the purpose of the unique_ptr is only to create a copy of m_rootstate without having to worry about memory management?
In this case, it seems unnecessary to create the unique_ptr in the first place.
You might as well just a create a direct stack copy like this:
State currstate(m_rootstate);

A:
Is this right?

Your description is accurate, yes.
If you mean to ask whether the program is well defined: Disregarding the uninitialized reference at the beginning, there is no code shown that would be either ill-formed or would have undefined behaviour. That said, you didn't show a complete program, so we cannot know whether the complete program is correct.

If so, is it correct that the purpose of the unique_ptr is only to create a copy of m_rootstate without having to worry about memory management?

Correct. Taking care of memory management of dynamic allocation is indeed the purpose of the unique pointer class. (Or more generally, taking care of releasing a resource).
Note that the shown excerpt doesn't reveal why or whether dynamic allocation is needed at all. It also doesn't reveal why or whether a copy is needed. Maybe those things are needed. However, those things should be avoided whenever they aren't needed.


text:
Q: Dom Parser Java - > 2 same name tag in different header with different Attributes. How? Im having a little problem with parsing the xml file using dom parser. Basically i want the xml listed below to be parsed by dom. The problem is that it gives me an error and to avoid it i want to read it properly. First of all i want it to read first, variables that are only in 1st header then after it read variables that are  only in 2nd header. I dont want to read it by item number cause not all 2nd header variables are same name as in 1st header so it will probably cause more problems. The whole xml is really big and i need to operate on about 50-60 variables in each header.
So somebody can give me any sample code or link how to read it using the header for it ??
<Analyzer version="2.0">
    <event1>
       <xxxx lll="FALSE" mmm="FALSE" ggg="FALSE" ccc="FALSE"/>
       <cccc lll="FALSE" mmm="FALSE" ggg="FALSE" ccc="FALSE"/>
    </event1>
    <event2>
       <xxxx drdr="2.500000000000000000000000e+00" zzzz="FALSE" />
       <notcccc drdr="1.556000000000000000000000e+00" zzzz="FALSE" />
    </event2>
</Analyzer>

Part of code of my program, i just didnt included the closing at the end.
File inputFile = new File("xxxx.xml");
             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
             Document doc = dBuilder.parse(inputFile);
             doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("Analyzer");
             int k =0;
             Node nNode = nList.item(k);
             Element eElement = (Element) nNode;

nList = doc.getElementsByTagName("xxxx");
             nNode = nList.item(k);
             eElement = (Element) nNode;
             System.out.println("Event :" + nNode.getNodeName());
             class.lll = Boolean.valueOf(eElement.getAttribute("lll"));

nList = doc.getElementsByTagName("xxxx");
             nNode = nList.item(k);
             eElement = (Element) nNode;
             System.out.println("Event :" + nNode.getNodeName());
             class.xxxx2 = Float.valueOf(eElement.getAttribute("drdr"));

I am getting error listed below
java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseFloat(Unknown Source)
    at java.lang.Float.parseFloat(Unknown Source)
    at java.lang.Float.valueOf(Unknown Source)
    at configure.parseXml(configure.java:209)
    at configure.main(configure.java:28)
java.lang.NullPointerException
    at java.util.Calendar.setTime(Unknown Source)
    at java.text.SimpleDateFormat.format(Unknown Source)
    at java.text.SimpleDateFormat.format(Unknown Source)
    at java.text.DateFormat.format(Unknown Source)
    at configure.saveXml(configure.java:807)
    at configure.main(configure.java:29)


text:
Q: Is it possible to create a button to download all files attached to a record? Currently, we have a page on our community in which people can go in and look at our cases and see and download all of the files attached to the case. That said, we recently got a request to create a button that will allow them to download all of the files attached to the case at once, rather then individually downloading them one at a time. At face value this seems like it should be easy, but the more I think about it the less sure I am of how I would do it. I see there is some ideas on it that imply that it is not possible in the standard salesforce functionality, but am still wondering if it can be done using some of the development tools.
My current thought is to have a button that upon click sends a call through the JS controller to the Server side controller and asks to query for all of the content documents linked to this record. Fairly straightforward. Then I think it should send the list of files back through the JS to the Aura component via a callback. However, once it is there, all I have is the file ID, which I am not confident I can really utilize as I will need to in the component itself and have no idea how I would go about doing so.
In essence, I suppose this breaks into two key questions-

*

*Is it possible to do this at all? Does the salesforce system support this in any way, even if it may not be through the lightning component system I had in mind?

*If so, where and how does this occur? Does the download functionality live in the Javascript controller, or the actual component itself? Where can I find any documentation on the method that is needed, if it exists?
Again, I am not married to the idea that I outlined above, but figured it was useful for context, so if anyone knows a better way to do this outside of that, I am open to any ideas, as long as it ends with the files being downloaded in a single click or two.

A: I don't think it would be possible easily in lightning.
The sessionID in lightning is not API enabled, Thus you cannot access standard rest endpoint to download files. On top of that you cannot make calls to RestEndpont from javascript.

You can't make Salesforce API calls from JavaScript code. For security
  reasons, the Lightning Component framework places restrictions on
  making API calls from JavaScript code. To call third-party APIs from
  your component's JavaScript code, add the API endpoint as a CSP
  Trusted Site.
To call Salesforce APIs, make the API calls from your component's Apex
  controller. Use a named credential to authenticate to Salesforce.

The one way you can do is, call that rest endpoint in APEX to download files using Named Credentials, But heap limit won't allow you to download large files.
So it is not straightforward path :/
I think building a chrome plugin that parses dom and then downloads all file would be easier.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm

A: This may not be an answer, but will provide a context around achieving a "bulk download", which does not seem to be a straight forward solution.
If it was about downloading a single file from a lightning component, you could have done by using a combination of force:navigateToURL and utilizing the download URL which is in form of https://<instance-url>/sfc/servlet.shepherd/document/download/id-of-file.
If the aforementioned URL worked with multiple Ids, then you could have utilized that approach, however that doesn't work. Furthermore, when you look towards downloading files in bulk, you will need to also consider how are you going to download all of those files --

*

*Download independently
OR

*Zip all files and download as a single file.
You may still be in luck if you can Zip the files as one file and utilize the download URL as mentioned above, but this gets complicated when the file sizes are big. You will most likely hit the heap size limits while constructing the zip file in such scenarios.
In summary, this seems to be a good use case but seemingly complex to implement using platform capabilities.

A: There is no way to create server-side ZIP files in Apex. It's just not a feature supported by the platform and they don't provide any way to manipulate binary data at the level required to hand-roll an implementation. Plus you run into the issue of heap limits.
If it is possible for JavaScript to download each of the files into memory via an XMLHttpRequest to their URLs (and I'm not 100% sure that's allowed?), you could use a front-end ZIP library such as JSZip to stitch them all together and then offer the download to the end-user. Otherwise you could make individual calls to an Apex controller to pull down the data from each file (but be stuck by heap limits if any one file is big), and zip them on the front end.


text:
Q: Unable to called the Method of the Class in Dialog Class I have one Modal Class ::
public class A
{
    java.lang.String fieldName;
    java.lang.String fieldType;

    public static class B
    {
        java.lang.String  Min;
        java.lang.String Max;

        public java.lang.String getMin() {
            return Min;
        }
        public void setMin(java.lang.String string) {
            Min = string;
        }
        public java.lang.String getMax() {
            return Max;
        }
        public void setMax(java.lang.String string) {
            Max = string;
        }
    }

    public java.lang.String getFieldName() {
        return fieldName;
    }

    public void setFieldName(java.lang.String string) {
        this.fieldName = string;
    }

    public java.lang.String getFieldType() {
        return fieldType;
    }

    public void setFieldType(java.lang.String string) {
        this.fieldType = string;
    }
}

Now i want to called the Method of this class in another class which extends Dialog
i have tried a lot like
com.test.modal.A.B number=new A.B();

or
context.com.test.modal.A.B number=new A.B();

Here it is my Dialog Class
public class TestDialog extends Dialog implements android.view.View.OnClickListener
{

     //com.test.modal.A.B number=new A.B();
    com.test.modal.A.B number;

    public TestDialog (Context context)
    {
        super(context);
    }

    public TestDialog (Context context)
    {
        super(context);
        this.number=new Number.ValidationNumber();
    }
    String min=number.getMin();
}

I want to called the Method of Modal Class and need to fetch the values from it.
I am not able to get the values once i called the methods....
Any help will be appreciated !!!!
Thanks in Advance ....


text:
Q: R Studio won't insert tabs, instead displays `(No matches)` - How to fix? I'm trying to pad my R Studio code with a bunch of "white space" between said code and comments. See the image below.

Every time I try to add padding by hitting Tab on my keyboard I instead get a (No matches) warning? How do I disable this behavior? Here's a repro:
library(ggplot2)                        # line 1
p1 <- ggplot(mtcars, aes(disp, mpg)) +  # line 2
  geom_point()                          # line 3

ggplot(mtcars, aes(mpg, disp)) +        # line 5
  geom_point()                          # line 6

10 + 10                                 # line 8

A: tabs are usually used to complete the object name or function name. For example if I type library(ggp and press tab, it will complete it as library(ggplot). If you want tab space, go to new line and press tab and that will give you tab formatting.
This should hep you support.rstudio.com

A: I don't think it's possible, but you shouldn't disable it anyway. The tab key is used for code completion, which is far more useful for a programmer than a regular tab. If you hit the tab button a second time it should tab normally.
Whenever I want multiple tabs I just copy and paste, which can be much faster anyway because you can copy and paste multiple tabs at once. Also, you should know that tabs in RStudio are just four spaces, so you can also use the spacebar (plus copy and paste) and every chunk of four spaces will be treated as a tab.
One more thing: Your "comments" are superfluous because the line number is already there on the left. Any good IDE will have line numbers, so adding them isn't necessary. Inline comments should also be used sparingly.

A: You need to untick the following option from the Tools > Show Command Pallet

Autocompletion was the bee's knees in the primordial days of IDEs. It seems we've come full circle. But I sometimes have need for a tab here or there, and not according to Rstudio's stringent tabbing rules. For instance, I hate editing output from dput, so for inline data creation I create a little tab separated data table with read.delim2(textConnection(<tabbed stuff>)))
Anyway, a cheater's trick is to create a tab separately in a lightweight text editor (hi, Notepad), and paste it into your Rstudio R file tab.


text:
Q: Dispatching events between classes I have a custom event class
public class FFTDrawEvent extends Event {

    public static const DRAW_EVENT:String = "drawEvent";

    private var _param:Array = new Array();

    public function FFTDrawEvent(type:String, __param:Array, bubbles:Boolean=true, cancelable:Boolean=false) {
        _param = __param;
        super(type, bubbles, cancelable);
    }

    public function get param():Array {
        return _param;
    }
}

This event is dispatched by a class, that extends EventDispatcher:
public class ToneGenerator extends EventDispatcher {

 public function someFunction():void {

 this.dispatchEvent(new FFTDrawEvent(FFTDrawEvent.DRAW_EVENT,_param));
}

Another class listen to this event. This class is extending SpriteVisualElement.
public class SpectrumVisualizer extends `SpriteVisualElement`:
{
    public function SpectrumVisualizer()
    {
        this.addEventListener(FFTDrawEvent.DRAW_EVENT, draw);
    }

Unfortunately this doesn't work. The event is dispatched (returns with true), but the Event listener is never triggered.
Both class (Dispatcher & Listener) are Child class of a MXML application. Also listen to the event in the parent MXML application doens't work. Listen to the event in the dispatching class itself somehow works.
I have to feeling that the EventDispatcher class is not the right one to dispatch events to a mxml application or respectivly AS classes, which extend/inherent from a MXML component class.
Anybody can help me with that?

A: You should listen for events on the dispatcher. In your case, an instance of ToneGenerator is dispatching the event and SpectrumVisualizer is listening - it wouldn't work.

Listen to the event in the dispatching class itself somehow works.

That's the only way it would work.
When you call
this.addEventListener(FFTDrawEvent.DRAW_EVENT, draw);

you are telling this object to call this.draw method whenever it (the this object) dispatches an event of type FFTDrawEvent.DRAW_EVENT. Change it to
toneGen.addEventListener(FFTDrawEvent.DRAW_EVENT, draw);

Now you are telling toneGen object to call this.draw method whenever it (the toneGen object) dispatches an event of type FFTDrawEvent.DRAW_EVENT.
You can also do the following from the parent mxml.
toneGen.addEventListener(FFTDrawEvent.DRAW_EVENT, specVis.draw);

Call specVis.draw method whenever the toneGen object dispatches an event of type FFTDrawEvent.DRAW_EVENT.

A: Martin,
The problem is that listener listens to itself instead of listening to event dispatcher. Here is the correct code:
public class SpectrumVisualizer extends SpriteVisualElement
{
    public function SpectrumVisualizer()
    {
        toneGenerator = new ToneGenerator();
        toneGenerator.addEventListener(FFTDrawEvent.DRAW_EVENT, draw);
        toneGenerator.someFunction();
    }

    private var toneGenerator:ToneGenerator;

    private function draw(event:FFTDrawEvent):void
    {
        trace("draw");
    }

}

This will help you to understand events.
P.S: If you tried to use bubbling, see the corresponding section in docs. Here it does not work because events "bubble" only in display list while ToneGenerator is not visual object (Sprite, MovieClip, ...).