text:
Q: Return result from a parallelized for loop I want to simulate data and at the same time perform analysis on those data 10000 times. Therefore I used a "for" loop in R to repeat the work 10000 times. Now I want to parallelize this tasks. For which I followed the following codes:
library(parallel)
library(doSNOW)
cl <- makeSOCKcluster(3)
registerDoSNOW(cl)

progress <- function(n) cat(sprintf("task %d is complete\n", n)) # to check the progress of the work

setno<- data.frame(sample_no=c(1:10000))
no_of_samples<- unique(setno$sample_no)

simulated_data_list <- vector("list",length(no_of_samples))
analysis_result <-  numeric(length(simulated_data_list ))

foreach(i=1:10000,progress)%dopar%{
 tryCatch({
 simulated_data_list[[i]]<-  rnorm(100)# suppose we are simulating data
 analysis_result[[i]] <-  1-pnorm(simulated_data_list[[i]][1])
 },error=function(e){cat("ERROR:",conditionMessage(e),"\n")})
}

But each time I do this, I find that the program is not simulating data (there is no problem in the program code as it runs normally without parallelization). I can't understand where is the problem in the above code. Can you suggest any better way to do this work?

A: You have to return result from a foreach loop. For example:
library(parallel)
library(doSNOW)
cl <- makeSOCKcluster(3)
registerDoSNOW(cl)

result <- foreach(i = 1:5) %dopar% {
    sim <- rnorm(2)
    list(sim , 1 - pnorm(sim[1]))
}
simulated_data_list <- lapply(result, "[[", 1)
analysis_result <- lapply(result, "[[", 2)

For example using simple for we can append to list, but foreach doesn't work like that:
dummyList <- list()
dummyList2 <- list()
foreach(i = 1:5) %dopar% {
    dummyList[[i]] <- rnorm(2)
}
for(i in 1:5) {
    dummyList2[[i]] <- rnorm(2)
}
lapply(list(dummyList, dummyList2), length)

[[1]]
[1] 0
[[2]]
[1] 5


text:
Q: How do I backup a failing disk? I'm trying to recover some information on a failing disk. At this point, it won't let me log in(asks for a manual fsck run which gets stuck during runtime). I'm guessing I can access some of the files using a recovery disk. How do I proceed from there on?

A: You shoudl try to clone the disk using ddrescue as described here
Once it's done, remove the original disk and run TestDisk, Advanced, Boot, RebuildBS, List.
If you can see your files, choose Write, confirm, Quit and restart your computer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOError with Python xlrd (Python Excel) and Amazon S3 I'm doing a simple Python (Django) app that reads an Excel file and prints part of it on screen. When I ran it locally with the excel file stored in my local PC it works well.
Here's the code:
from xlrd import open_workbook
def hello(request):
        wb = open_workbook('test.xlsx')
        sh = wb.sheet_by_index(0)
        a = sh.cell_value(rowx=0, colx=0)
        return HttpResponse(a)

Nevertheless, when I try to read the file from S3 using this:
wb = open_workbook('http://s3.amazonaws.com/mybucketsample/test.xlsx')

I receive the following error:
IOError at /

[Errno 22] invalid mode ('r') or filename: 'http://s3.amazonaws.com/mybucketsample/test.xlsx'

What am I doing wrong?
Thanks so much,
Ed

A: Perhaps this works:
import urllib2

url = 'http://s3.amazonaws.com/mybucketsample/test.xlsx'
filecontent = urllib2.urlopen(url).read()

wb = open_workbook(file_contents=filecontent)


text:
Q: Grafana Pod is in Init Error state after adding an existing PVC Installing grafana using helm charts, the deployment goes well and the grafana ui is up, needed to add an existence persistence volume, ran the below cmd:
helm install grafana grafana/grafana -n prometheus --set persistence.enabled=true --set persistence.existingClaim=grafana-pvc

The init container crashes, with the below logs:
kubectl logs grafana-847b88556f-gjr8b -n prometheus -c init-chown-data
chown: /var/lib/grafana: Operation not permitted
chown: /var/lib/grafana: Operation not permitted

On checking the deployment yaml found this section:
initContainers:
      - command:
        - chown
        - -R
        - 472:472
        - /var/lib/grafana
        image: busybox:1.31.1
        imagePullPolicy: IfNotPresent
        name: init-chown-data
        resources: {}
        securityContext:
          runAsNonRoot: false
          runAsUser: 0
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /var/lib/grafana
          name: storage
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext:
        fsGroup: 472
        runAsGroup: 472
        runAsUser: 472
      serviceAccount: grafana
      serviceAccountName: grafana

Why is the operation failing though its running with runAsUser: 0 ? and the pvc is having access:ReadWriteMany, any workaround ? Or am I missing something
Thanks !!

A: NFS turns on root_squash mode by default which functionally disables uid 0 on clients as a superuser (maps those requests to some other UID/GID, usually 65534). You can disable this in your mount options, or use something other than NFS. I would recommend the latter, NFS is bad.

A: Actually, sometimes you might want to avoid changing your storage provider settings or it is impossible at all.
In my case, the error described in the question occured while deploying kube-prometheus-stack helm chart. I wasn't able to access storage provider settings, so I read through chart's example values, where I noticed following section:
initChownData:
  ## If false, data ownership will not be reset at startup
  ## This allows the prometheus-server to be run with an arbitrary user
  ##
  enabled: true

I changed enabled to false and after helm upgrade ... pod initialized successfully and with storage working as expected. This appears to be somewhat safer solution than changing storage provider's security policy and certainly requires less effort.


text:
Q: What is this dot appearing in the middle of proofs? In G.H. Hardy's 6th edition of Introduction to the Theory of Numbers, this dot appears in some proofs. For example, on page 2,
$$b\mid a \;.\; c\mid b \implies c\mid a$$
What is the dot on the left hand side of the arrow?

A: In the section REMARKS ON NOTATION right at the beginning of the book we find:

and
  \begin{align*}
b\,|\,a \,.\,c\,|\,b\ \rightarrow\ c\,|\,a\qquad (p.1)
\end{align*}
  means 'if $b$ divides $a$ and $c$ divides $b$ then $c$ divides $a$'.


text:
Q: MongoEngine distinct() filtering and EmbeddedDocument Recently, maybe after a software upgrade, I've encountered a problem: distinct() filtering now returns a dictionary collection rather then a EmbeddedDocument collection. Mean while direct traverse of objects works as expected.
Here is the piece of code, maybe not stripped down but rather simple. This is a simple product catalog with features for functionality like filtering by features and so on:
from mongoengine import *

class FeatureInfo(Document):
    title = StringField()

class ProductFeature(EmbeddedDocument):
    featureInfo = ReferenceField(FeatureInfo)
    value = StringField()

    def eq(a, b):
        return a.featureInfo.title == b.featureInfo.title and a.value == b.value

class Product(Document):
    title = StringField()
    features = ListField(EmbeddedDocumentField(ProductFeature))

def populate():
    producer_feature_info = FeatureInfo("Producer")
    producer_feature_info.save()

    screen_size_feature_info = FeatureInfo("Screen size")
    screen_size_feature_info.save()

    iphone_producer_feature = ProductFeature(featureInfo=producer_feature_info, value="Apple")
    iphone_screen_size_feature = ProductFeature(featureInfo=screen_size_feature_info, value="4 inch")

    iphone = Product(title="iPhone 5S")
    iphone.features.append(iphone_producer_feature)
    iphone.features.append(iphone_screen_size_feature)
    iphone.save()

    galaxy_producer_feature = ProductFeature(featureInfo=producer_feature_info, value="Samsung")
    galaxy_screen_size_feature = ProductFeature(featureInfo=screen_size_feature_info, value="5 inch")

    galaxy = Product(title="Galaxy S4")
    galaxy.features.append(galaxy_producer_feature)
    galaxy.features.append(galaxy_screen_size_feature)
    galaxy.save()

    galaxy_producer_feature = ProductFeature(featureInfo=producer_feature_info, value="Samsung")
    galaxy_screen_size_feature = ProductFeature(featureInfo=screen_size_feature_info, value="4 inch")

    galaxy = Product(title="Galaxy S2")
    galaxy.features.append(galaxy_producer_feature)
    galaxy.features.append(galaxy_screen_size_feature)
    galaxy.save()

if __name__ == "__main__":
    connect('test')
    populate()

    products = Product.objects()

    print "\n".join(map(lambda p: p.title + " [" + ", ".join(map(lambda f: f.featureInfo.title + " = " + f.value, p.features)) + "]", products))

    print "\nProduct features"

    features = []

    for product in products:
        print product.title
        for feature in product.features:
            if feature not in features:
                features.append(feature)
            print feature.__class__.__name__

    print "\nUnique features"

    for feature in features:
        print feature.featureInfo.title + " = " + feature.value + " (" + feature.__class__.__name__ + ")"

    print "\nDistinct features"

    features = products.distinct("features")

    for feature in features:
        print feature.__class__.__name__

Here is the output:
python test.py
iPhone 5S [Producer = Apple, Screen size = 4 inch]
Galaxy S4 [Producer = Samsung, Screen size = 5 inch]
Galaxy S2 [Producer = Samsung, Screen size = 4 inch]

Product features
iPhone 5S
ProductFeature
ProductFeature
Galaxy S4
ProductFeature
ProductFeature
Galaxy S2
ProductFeature
ProductFeature

Unique features
Producer = Apple (ProductFeature)
Screen size = 4 inch (ProductFeature)
Producer = Samsung (ProductFeature)
Screen size = 5 inch (ProductFeature)

Distinct features
BaseDict
BaseDict
BaseDict
BaseDict

I found such a question on StackOverflow but there was issue with MongoEngine 0.8.3 and ok in 0.8.4. I've followed it and upgraded but with no effect.


text:
Q: Intel Xeon Phi Coprocessor 7120P And HP Proliant? Does anyone know where I could check the HP Proliant DL 380 Gen 6 and 380p Gen8 compatibility with Intel Xeon Phi Coprocessors? At first sight it seems they fit the PCI Riser. Would services like nginx, mysql and clickhouse benefit from Intel Xeon Phi Coprocessor? I run latest Ubuntu.
Thanks!

A: Intel Xeon Phi Coprocessors actually are single-board-computer, so I think they are compatible with anything providing PCI-E and adequate power/cooling. They run an embedded Linux distro, SSHable from the host.
That said, they will not do anything for apache/nginx/etc. They are almost "pure computing" device, providing dual massive FMAC/vector pipelines only useful for HPC. Their general-purpose cores are Atom-based, with performance much lower than traditional CPUs. Moreover they are EOL and unsupported by now.
So don't bother with them.

A: You want to search Intel Ark for your specific model, and see what the install process and explicit requirements look like.
For example, the most recent (2017) models have a software distribution that supports Ubuntu 17.10, Centos/RHEL 7.x and SLES 12.x - but they also require BIOS "large BAR" support, which older servers may not have:

Enable Large Base Address Registers (BAR) Support in the Platform BIOS
In order for Intel(R) Xeon Phi(TM) coprocessors to function properly in a
platform, BIOS and OS support for large (8GB+) Memory Mapped I/O Base Address
Registers (MMIO BAR's) above the 4GB address limit must be enabled.
By default, most platform BIOS implementations have this set to disabled,
therefore it must be enabled manually in the platform BIOS setup.

This blog explains in detail what to look for in the BIOS. Decoding of 64b PCI resource addresses comes under many names, in my system it is listed as "Above 4G decoding" in the PCI configuration menu.


text: Q: Is it possible to create custom groups in the creative inventory? I'm experimenting with Minecraft Bedrock addons. Currently I'm working with adding custom blocks. In the documentation, they show you can add your block to groups in the creative inventory. Is there any way to make a new group (to group all of my custom blocks)?


text:
Q: Is there an IDE for python that creates the same kind of reflective environment that Smalltalk provides? As anyone who has used Smalltalk knows, one of the main benefits (other than a late-bound language that discourages many poor practices), is that the system is totally transparent and reflective, which makes understanding APIs and existing code easy, and locating functionality pretty easy.
Is there anything that creates a similar environment for Python?
A few examples of features of a smalltalk development environment, not natively found in python are:

*

*search class/method/etc names,

*examine inheritance hierarchies

*functionality to show the full interface of a given class/object, and where the properties therein originate

*an integrated graphical debugger which allows one to examine the full state of everything in the system, and see every instance of a given type, as well as all threads.

Note that I use windows, so anything that works well on windows would be particularly useful.

A: Having worked with Smalltalk myself for two years, I can tell you I haven't seen any Python IDE available that will give you the level of expressiveness you are looking for in Smalltalk IDEs such as VisualWorks or Squeak.
The key thing about most Smalltalk IDEs is that code + development tools are stored in the same place. So rather than coding in a text editor, then compiling/interpreting it on a VM, It's all done on the same binary. This has obvious benefits as you could connect to a Smalltalk image in a production environment and start coding/debugging on the image itself rather than having to change then publish a new copy as everything is already there.  The main drawback I found with this approach is the amount of memory it consumes. You can obviously strip the image down to remedy this, but that takes time.
I will say that it's not impossible to have a Python IDE that does this, but there simply isn't one available as far as I've seen. Despite the dynamic nature of both languages, the approach to development between both languages different given that Python is file based and Smalltalk is image based.

A: ipython adds lots of syntactic sugar over the default Python REPL. In particualr, you get tab-completion, a nice "?" shortcut for the help() function and everything is nicely colorized and easier to read.
Not quite a Smalltalk environment but I find it very helpful.

A: I sometimes find myself using PythonWin's IDE just for the gui available during debugging (run using 'Step-through in the debugger' then show the Stack View).  I've never touched smalltalk, though, so I might be way off base...

A: You can't really expect a Smalltalk-like Python IDE. In Smalltalk, the IDE is an integral part of the runtime (or "image").

A: There is one fundamental difference between the Smalltalk world and Python world. In Smalltalk, one works with an image, whereas in Python there is a distinct static and dynamic view of the program/project.
The usual way of bridging this difference on the Python side consists of improving the static analysis tooling, and in making interacting with a running program easier by being able to run small chunks of a program often, and examining the running program in a debugger, or tool such as Jupyter Notebook.
Let me talk about PyCharm (https://www.jetbrains.com/pycharm/) as my IDE of choice.
Static
PyCharm has decent static analysis capabilities, and one may put in static type hints to assist it https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html

*

*search class/method/etc names --- https://www.jetbrains.com/help/pycharm/navigating-to-class-file-or-symbol-by-name.html

*examine inheritance hierarchies --- there are the gutter icons, and also https://www.jetbrains.com/help/pycharm/viewing-class-hierarchy-as-a-class-diagram.html
Dynamic
The road to being able to run small chunks of your program often are unit tests, naturally. If you have these, you should always be able to find/write a test which will recreate the program state you are interested in inspecting.

*

*functionality to show the full interface of a given class/object, and where the properties therein originate --- get a breakpoint with an instance in scope, and inspect it by evaluating instence. calling help(instance). https://stackoverflow.com/questions/34439/finding-what-methods-a-python-object-has. There is open feature request https://youtrack.jetbrains.com/issue/PY-27760.

*an integrated graphical debugger which

*

*allows one to examine the full state of everything in the system -- you can evaluate arbitrary expressions https://www.jetbrains.com/help/pycharm/evaluating-expressions.html

*and see every instance of a given type --- you can, but there is no "heap explorer" GUI for it https://stackoverflow.com/questions/4458701/how-to-get-the-list-of-all-initialized-objects-and-function-definitions-alive-in

*

*I never wanted to do this myself. I presume this is because I do not have a long running image and recreate the process on every execution. If I had long running application server, I might want this. This sounds to me as admin/ops feature, more than dev feature.

*as well as all threads --- no problem, and there is even https://www.jetbrains.com/help/pycharm/thread-concurrency-visualization.html
In Python, we rarely (never?) think in terms of "full state of everything in the system". That is probably a Smalltalkism.
Combination of the two
There is a PyCharm feature which enriches the static view of the program by information collected at runtime during debugging sessions https://blog.jetbrains.com/pycharm/2013/02/dynamic-runtime-type-inference-in-pycharm-2-7/


text:
Q: Raphael Javascript I am new to Raphael and am trying to do something very simple, but failing miserably.  Does anyone know how to create a Raphael canvas and set the background color (ex: green)?  This is what I have so far, but when I open it in a browser it displays nothing....
<html>
<head><title></title>
<script src="raphael-min.js"></script>
</head>

<body>

<script type="text/javascript">
//all your javascript goes here

var paper = Raphael(15,40,320,300);

</script>

</body>
</html>

When I put this code inside the js script it displays a circle correctly...
var circle = paper.circle(50,10,10);
circle.attr("fill","#0f0");

But again, my issue is trying to set the background color.  Any help would be appreciated.
Thanks

A: RaphaelJS doesn't provide a default background styling, since its event system relies on being object-driven.  However, you can designate a particular DIV and style it accordingly:
<div
    id="my_paper_div"
    style="background-color:limegreen;width:400px;height:400px"
></div>

Make sure you don't call either the DIV or variable paper.  Give them different names, otherwise you'll run into some IE incompatibility.
Redeclare your paper javascript like so:
// declare outside the startup scope, so you can do fancy things later
var my_paper;

// raphaeljs' version of onload
Raphael( function() {
    my_paper = Raphael("my_paper_div", 400, 400);
});

Since RaphaelJS rendering doesn't interfere with the background, you can technically mix and match HTML and SVG/VML.  For example, see this jsfiddle: http://jsfiddle.net/NQtU5/

A: You could also draw a rectangle the size of the canvas:
var paper = Raphael("my_paper_div", 600, 400),
    placemat = paper.rect(0,0,paper.width,paper.height).attr({"fill" : "#99FF99" });

I usually start this way with Raphael projects because I find it useful to have an object in the background to which to attach events, like a click event that closes all open tooltips.
See example.


text:
Q: Parse Twitter Login - Choose Which Twitter Account I have an iOS app that lets users login with their twitter account. It uses the Parse API to do this. Following is the code that handles the login:
- (IBAction)twitterAuthButtonPressed:(id)sender {
    [PFTwitterUtils logInWithBlock:^(PFUser *appUser, NSError *error) {
        if (!appUser) return;
        //todo: display loading indicator
        [[CPUserCacheProvider _] loginWithSuccess:^{
            [self showHideAuthButtons];
            [self updateNameAndAvatar];
        } andFailure:^{
            UIAlertView *failWhale = [[UIAlertView alloc] initWithTitle:@"Twitter Login Failed!" message:@"There was a problem with logging in with Twitter." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [failWhale show];
        }];

        NSLog(@"CPSettingsViewController.twitterAuthButtonPressed: Twitter User Logged in %@", appUser.username);
        [[NSNotificationCenter defaultCenter] postNotificationName:userAuthChangedNotification object:nil];
    }];

}

I have a personal Twitter account and one I use for testing. The first time I logged in, I logged in with my personal account. I would like to log in with my test account. But every time I login, the app automatically logs me in with my personal account. I have even deleted the corresponding PFUser (trough Parse's dashboard) and the app still automatically logs me in with my personal account.
How I can make the app make me ask for my Twitter credentials again? I wonder if there is something I can do in iOS settings to make the app forget my personal Twitter account.

A: Try using [PFUser logout] this is the way to log a user out. The user is cached locally when you call to login and so you'll need to destroy that by logging out.


text:
Q: GroupBy DayOfMonth in mongodb but project Complete Date I have a Collection containing a date field. I want to group it by dayOfMonth but at the time of projection I want to project the complete Date and associated count.
I have a raw Collection in mongodb containing a Timestamp (Date field)
This is my Aggregation query:
db.raw.aggregate(
{
    "$match" : { "Timestamp":{$gte:new Date("2012-05-30T00:00:00.000Z"),$lt:new Date("2014-05-31T00:00:00.000Z")}}
},
{
    $group:
    {
        _id: { ApplicationId: "$ApplicationId", date: {$dayOfMonth: '$Timestamp'}   },
        count: { $sum: 1 }
    }
}
)

In the above query I'm grouping with dayOfMonth but how can I project complete the Date with count?

A: Your "Timestamp" values are clearly actual points in time so there really isn't a "complete date" to return. You could just generally "do the math" based on the date range you are applying and the "day of month" values returned as you process the results returned.
But alternately you could just "apply the math" to the date values in order by rounding the "timestamp" values out to the day. The returned values are no longer date objects, but they are the millisecond since epoch values, so it is relatively easy to "seed" those to date functions:
db.raw.aggregate([
    { "$match" : {
        "Timestamp":{
            "$gte": new Date("2012-05-30"),
            "$lt": new Date("2014-05-31")
        }
    }},
    { "$group": {
        "_id": {
            "$subtract": [
                { "$subtract": [ "$Timestamp", new Date("1970-01-01") ] },
                { "$mod": [
                    { "$subtract": [ "$Timestamp", new Date("1970-01-01") ] },
                    1000 * 60 * 60 * 24
                ])
            ]
        },
        "count": { "$sum": 1 }
    }}
])

So when you subtract one date object from another the difference is milliseconds is returned as a number. So this just normalizes to epoch seconds by subtracting the epoch date. The rest is basic date math to round the result to the current day.
Alternately again you could just use other date aggregation operators and concatenate to a string, but there would be usually a bit more work involved unless those values were for direct use:
db.raw.aggregate([
    { "$match" : {
        "Timestamp":{
            "$gte": new Date("2012-05-30"),
            "$lt": new Date("2014-05-31")
        }
    }},
    { "$group": {
        "_id": {
            "$concat": [
                 { "$substr": [{ "$year": "$Timestamp" },0,4] },
                 "-",
                 { "$substr": [{ "$month": "$Timestamp" },0,2] },
                 "-",
                 { "$substr": [{ "$dayOfMonth": "$Timestamp" },0,2] }
            ]
        },
        "count": { "$sum": 1 }
    }}
])

A: Neil Lunn has provides a great answer.
Theirs one more approach that u can use :
db.raw.aggregate([
    {
        "$match" :
            {
                "Timestamp":{"$gte": new Date("2012-05-30"), "$lt": new Date("2014-07-31")}
            }
    },
    {
        "$group" :
            {
                "_id":{"$dayOfMonth": "$Timestamp"},
                "Date":{"$first":"$Timestamp"},
                "count": { "$sum": 1 }
            }
    }
])

It will return you date.
Hope so this helps you.


text:
Q: Does it make sense to study plots of residuals with respect to the dependent variable? I would like to know whether it makes sense to study the plots of residuals with respect to the dependent variable when I've got a univariate regression. If it makes sense, what does a strong, linear, growing correlation between residuals (on the y-axis) and the estimated values of the dependent variable (on the x-axis) mean?

A: Assuming the estimated model is correctly specified...
Let's denote $P_X=X(X'X)^{-1}X'$, the matrix $P_X$ is a projection matrix, so $P_X^2=P_X$ and $P_X'=P_X$.
$Cov(\hat{Y},\hat{e})=Cov(P_XY,(I-P_X)Y)=P_XCov(Y,Y)(I-P_X)'=\sigma^2P_X(I-P_X)=0$.
So the scatter-plot of residuals against predicted dependent variable should show no correlation.
But!
$Cov(Y,\hat{e})=Cov(Y,(I-P_X)Y)=Cov(Y,Y)(I-P_X)'=\sigma^2(I-P_X)$.
The matrix $\sigma^2(I-P_X)$ is a projection matrix, its eigenvalues are 0 or +1, it's positive semidefinite. So it should have non-negative values on the diagonal. So the scatter-plot of residuals against original dependent variable should show positive correlation.
As far as i know Gretl produces by default the graph of residuals against original dependent variable (not the predicted one!).

A: Is it possible you are confusing fitted/predicted values with the actual values?
As @gung and @biostat have said, you hope there is no relationship between fitted values and residuals.  On the other hand, finding a linear relationship between the actual values of the dependent/outcome variable and the residuals is to be expected and is not particularly informative.
Added to clarify the previous sentence:
Not just any linear relationship between residuals and actual values of the out come is to be expected... For low measured values of Y, the predicted values of Y from a useful model will tend to be higher than the actual measured values, and vice versa.

A: The answers offered are giving me some ideas about what's going on here. I do believe there may have been some mistakes made by accident.  See if the following story makes sense: To start, I think there is probably a strong relationship between X & Y in the data (here's some code and a plot):
set.seed(5)
wage <- rlnorm(1000, meanlog=2.3, sdlog=.5)
something_else <- .7*wage + rnorm(1000, mean=0, sd=1)
plot(wage, something_else, pch=3, col="red", main="Plot X vs. Y")

But by mistake Y was predicted just from the mean.  Compounding this, the residuals from the mean only model are plotted against X, even though what was intended was to plot against the fitted values (code & plot):
meanModel <- lm(something_else~1)
windows()
plot(wage, meanModel$residuals, pch=3, col="red",
    main="Plot of residuals from Mean only Model against X")
abline(h=0, lty="dotted")

We can fix this by fitting the appropriate model and plotting the residuals from that (code & plot):
appropriateModel <- lm(something_else~wage)
windows()
plot(appropriateModel$fitted.values, appropriateModel$residuals, pch=3, col="red",
main="Plot of residuals from the appropriate\nmodel against fitted values")
lines(lowess(appropriateModel$residuals~appropriateModel$fitted.values))

This seems like just the kinds of goof-ups I made when I was starting.

A: Suppose that you have the regression $y_i = \beta_0 + \beta_1 x_i + \epsilon_i$, where $\beta_1 \approx 0$. Then, $y_i - \beta_0 \approx \epsilon_i$. The higher the $y$ value, the bigger the residual. On the contrary, a plot of the residuals against $x$ should show no systematic relationship. Also, the predicted value $\hat{y}_i$ should be approximately $\hat{\beta}_0$---the same for every observation. If all the predicted values are roughly the same, they should be uncorrelated with the errors.
What the plot is telling me is that $x$ and $y$ are essentially unrelated (of course, there are better ways to show this). Let us know if your coefficient $\hat{\beta}_1$ is not close to 0.
As better diagnostics, use a plot of the residuals against the predicted wage or against the $x$ value. You should not observe a distinguishable pattern in these plots.
If you want a little R demonstration, here you go:
y      <- rnorm(100, 0, 5)
x      <- rnorm(100, 0, 2)
res    <- lm(y ~ x)$residuals
fitted <- lm(y ~ x)$fitted.values
plot(y, res)
plot(x, res)
plot(fitted, res)

A: This graph indicates that the model you fitted is not good.  As @gung said in the first comments on the main question that there should be no relationship between predicated response and residual.
" an analyst should expect a regression model to err in predicting a response in a random fashion; the model should predict values higher than actual and lower than actual with equal probability. See this"
I would recommend first plot response vs independent variable to see the relationship between them. It might be reasonable to add polynomial terms in the model.

A: Isn't this what happens if there is no relationship between the X & Y variable?  From looking at this graph, it appears you are essentially predicting Y with it's mean.

A: I think OP plotted residuals vs. the original response variable (not the fitted response variable from the model). I see plots like this all the time, with nearly the same exact pattern. Make sure you plot residuals vs. fitted values, as I'm not sure what meaningful inference you could gather from residuals vs. original Y. But I could certainly be wrong.


text:
Q: Best way for implement multiple TableviewCells Which is the best way to implement multiple UITableViewCell
I have tableview which do have three section one for notification holds switch in UITableViewCell, another edit profile shows the username and disclosure & third one static information.
So create three UITableViewCell, three section holds items ["notification","editProfile","userInfo"]
Each section holds multiple Items [["enable"],["changeItem","changeName"],["mobile","name","age"]]
In CellForRowAt index the old process use if/else condition to display the team differently which works fine.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "firstTableCell") as! FirstTableCell
        // Set up cell.label
        return cell
    } else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "secondTableCell") as! SecondTableCell
        // Set up cell.button
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "thirdTableCell") as! ThirdTableCell
        // Set up cell.textField
        return cell
    }
}

I would like to know the best procedure for implenting in this case.


text:
Q: Cocoa NSView blurred background I know it's possible to create transparent windows in Cocoa, although is it possible to blur whatever is behind it? I know there's been similar questions, but they deal more blurring what is within the actual NSView, not what is behind it. Is this even possible, and If so what method would I need to look into?

Possible                      Impossible?

A: In order to answer you, yes its Possible.
If you want that effect, check out this GitHub Project I created. I subclassed NSWindow in order to disable opacity and then I added a Background Filter:Gaussian Blur to the NSView using the View Effects Inspector located at the Xcode Utilities Side Bar (you can change the radius value for more or less blur effect).
If you want the new Yosemite View effect, check out the new class they released NSVisualEffectView, just subclass the NSView you want to use this effect.
Hope you find my answer useful.
Best regards,

A: My contribution as I wanted to set the radius and the color.
Doing it in a custom view to blur what is behind. HTH
view.wantsLayer = true
view.layerUsesCoreImageFilters = true
view.layer?.backgroundColor = NSColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5).CGColor

let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter?.setDefaults()
blurFilter?.setValue(2.5, forKey: kCIInputRadiusKey)
view.layer?.backgroundFilters?.append(blurFilter!)

A: As of 2021, instead of applying a CIFilters and increasing your APP size by at least 60MB for the blur effect you just use NSVisualEffectView in exchange for your NSView. Choose the reference to blur onto and set the material you think it posses for, so an appropriate color or window background is chosen the blurring will be based on.
NSVisualEffectView *viewWithFX = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0, frameRect.size.width, 100)];
viewWithFX.autoresizingMask = NSViewWidthSizable | NSViewMinXMargin | NSViewMaxXMargin;
viewWithFX.translatesAutoresizingMaskIntoConstraints = YES;
viewWithFX.material = NSVisualEffectMaterialSidebar; // or NSVisualEffectMaterialMenu, or ..
viewWithFX.blendingMode = NSVisualEffectBlendingModeBehindWindow; //NSVisualEffectBlendingModeWithinWindow
[viewWithFX addSubview:<#subviews-will-not-have-fx-applied#>];

[self.view addSubview:viewWithFx];

This has the advantage that you don't need layers and it's faster than CIFilters.
PS: this will increase your App size by around 8..12MB.


text:
Q: Datamapper ORM save data in join table I am currently working an application with Code Igniter and Datamapper ORM and I am trying to save data in the database. I have two tables which have a many to many relationship between eachother. For example: ShoeDesigns and ShoePieces. I would also like to save some data in the join table between ShoeDesigns and ShoePieces i.e. ShoeDesigns_ShoePieces. I have tried to look around for examples but no luck.
I was just wondering if it is possible to actually do it and if I can do it in one save call or would I have to do it in multiple save calls?
Thanks guys.

A: If you added data to ShoeDesigns_ShoePieces other than that pertaining to the relationship between ShoeDesigns and ShoePieces, you would be violating the ORM concept. ShoeDesigns_ShoePieces would no longer only model a relationship, but it would be a hybrid between entity and relationship.
You need to do this if you have some attributes that attach to the relationship between ShoeDesigns and ShoePieces; and this means that the "relationship" is actually an entity.
Let us call it ShoeAssemblyPlan. Then you have:

*

*a many-to-many relationship between ShoeDesigns and ShoeAssemblyPlan

*a many-to-many relationship between ShoeAssemblyPlan and ShoePieces
(The relationships could also be many-to-one).
Your old relationship between Designs and Pieces is now realized through an Assembly Plan, to whom you can attach the attributes you desire.
For example you could have a "Glue Stacked Design to Four-Piece Set" assembly plan and a "Stitch Formal Design to Four-Piece Set" assembly plan; and you might have a different Cost and LeadTime associated to each plan.


text:
Q: Locate files which ONLY contain printable characters in bash script I'm trying to write a bash script that looks at a directory full of files and categorises them as either plaintext or binary.  A file is plaintext if it ONLY contains plaintext characters, otherwise it is binary.  So far I have tried the following permutations of grep:
#!/bin/bash
FILES=`ls`
for i in $FILES
do
    ########GREP SYNTAX###########
    if grep -qv -e[:cntrl:] $i
    ########/GREP SYNTAX##########
    then
        mv $i $i-plaintext.txt
    else
        mv $i $i-binary.txt
    fi
done

In the grep syntax line, I have also tried the same without the -v flag and swapping the branches of the if statements, as well as both combinations of the same with [:alnum:] and [:print:].   All six of these variations produce some files labelled binary wich consist solely of plantext and some files labelled plaintext which contain at least one non-printable character.
I need to find a way to identify files that only contain printable characters i.e. A-Z, a-z, 0-9, punctuation, spaces and new lines.  All files containing any character that is not in this set shoudl be classified as binary.
I've been bashing my head against a wall trying to sort this for half a day.
Help!
Thanks in advance,
Rik

A: First you can/should do
for f in *

instead of putting the output of ls in a variable. The chief reason for doing this is to be able to handle filenames that include spaces.
Second, you need to enclose the character class in a set of brackets or it's going to look at those characters as literals. And I would enclose them in a set of single quotes to protect against the shell interpreting them. Don't use -v and negate the print class and see if that works for you.
if grep -aq -e '[^[:print:]]' "$f"

And as shown in that line, always quote variables when they contain filenames.
mv "$f" "$f-plaintext.txt"

To keep grep from complaining about binary files, use -a.
The variable i is often used for an integer or an index. Use f or file.
Finally:
#!/bin/bash
for f in *
do
    if grep -aq -e '[^[:print:]]' "$f"
    then
        mv "$f" "$f-binary.txt"
    else
        mv "$f" "$f-plaintext.txt"
    fi
done

A: You can use the -I option of grep which will treat binary files as files without a match and just use a regex that will always match (like the empty string):
if grep -qI -e '' $i


text:
Q: Pushing ABPersonViewController to ABPeoplePickerNavigationController on iOS8 Presenting the people picker
ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
peoplePicker.allowsActions = YES;
peoplePicker.allowsEditing = NO;
peoplePicker.peoplePickerDelegate = self;
[self presentViewController:peoplePicker animated:YES completion:nil];

Implementing the ABPeoplePickerNavigationControllerDelegate in iOS 7
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
  ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
  personViewController.displayedPerson = person;
  [peoplePicker pushViewController:personViewController animated:YES];
  return NO;
}

So far so good. The person view controller is presented as expected. iOS7 method returns a value - one could return NO in order to make sure the people picker remains open. In iOS8 the above delegate method was deprecated and new method must be implemented:
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
  ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
  personViewController.displayedPerson = person;
  [peoplePicker pushViewController:personViewController animated:YES];
}

The person view controller is pushed to the people picker but after a fraction of a second the people picker is dismissed (together with the person view controller).
Is there a way to prevent the people picker from dismissing on iOS8? Any other suggestions?

A: -(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
    [self dismissViewControllerAnimated:NO completion:^{
      ABPersonViewController *personController = [[ABPersonViewController alloc] init];

      [personController setDisplayedPerson:person];
      [personController setPersonViewDelegate:self];
      [personController setAllowsEditing:NO];
      personController.displayedProperties = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty], nil];

      [self.navigationController pushViewController:personController animated:YES];
    }];
}

A: How about using presentViewController instead pushViewController ... in Xcode 6 it says that pushViewController is deprecated and I see you're trying to implement it in iOS8 so give it a try ...
Something like this line:
[peoplePicker presentViewController: personViewController animated: YES completion: nil];

A: In iOS8, you will need to add code as below when you initialise the ABPeoplePickerNavigationController, otherwise the peoplePickerNavigationController will dismiss right away after you select a contact.
if(IOS8_OR_LATER){
    peoplePicker.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false]; }


text:
Q: How can this English sentence be translated into a logical expression? ( Translating " unless")
You cannot ride the roller coaster if you are under 4 feet tall unless you are older than 16 years old.

Let:

*

*$P$ stands for "you can ride the roller coaster"

*$Q$ stands for "you are under 4 feet tall"

*$R$ stands for "you are older than 16 years old"
Is this logical expression correctly translated?
$$P \rightarrow (Q \wedge R)$$

A: The suggestion of $P\to (Q \wedge R)$ would say that in order to ride the roller coaster you must be at least $4$ feet tall and you must me at least $16$ years old.  But I would say the meaning of the given sentence is that you need to satisfy one of the age and height conditions, not both.
I think the sentence means: In order to ride the roller coaster, you must be at least $4$ feet tall, or you must be over $16$ years old.
Symbolically (using your $P, Q, R$), this would be $P\to (Q\vee R)$. In contrapositive form (which would tell you what keeps you from riding the roller coaster: $(\neg P\wedge \neg Q)\to \neg R$.  (If you are under 4 feet tall and younger than $16$, then you can't ride the roller coaster).

A: (1) 'Unless' statements:
There are some known strategies to transform 'unless' clauses into conditional statements. The most common one seems to be directly translate them using 'if not':

*

*I'm not coming to the party unless Sylvia comes.

*I wouldn't eat that food unless I was really hungry.
The examples above can be respectively translated as follows:

*

*If Sylvia is not coming to the party, neither am I.

*If am not really hungry I wouldn't eat that food.
Alternatively, we can use their (reverse) contrapositive forms:

*

*I am coming to the party if Sylvia is.

*I would eat that food If was really hungry.
(2) Your Answer:
Consider the English sentence

You cannot ride the roller coaster if you are under 4 feet tall unless you are older than 16 years old.

Following the above reasoning we have:

If you are not older than 16 years, then you cannot ride the roller coaster if you are under 4 feet tall.

which is the same as:

If you are not older than 16 years, then if you are under 4 feet tall you cannot ride the roller coaster.

Now let:

*

*$P$ stand for 'you can ride the roller coaster'

*$Q$ stand for 'you are under 4 feet tall'

*$R$ stand for 'you are older than 16 years old'

The answer you are looking for is
$$ \neg R \to (Q \to \neg P).$$

A: Solution: let suppose
q= You can ride the roller coaster;
p= you are older than 16 years old;
r= you are under 4 feet tall;
There is two states of "q if p" and "q if r";
Because
•   q unless p :: (the statement is as )
You can ride the roller coaster unless you are not older than 16 years old;
•   q, if r :: (the statement is as)
You can ride the roller coaster unless you are under 4 feet tall;
•   These two statements have same conclusion that is "you can ride a roller coaster" and the hypothesis are two.
So these two conclusions may be simplify in one statement as:
"You can ride the roller coaster, if you are under 4 feet tall and you are not older than 16 years old"
Then in this statement there is the (q, if p) form of implication and p which is the hypothesis has the operator "and" .So, the expression is
Hypothesis -> conclusion as:
                (r ^ ~p) -> ~q
Where ~p means: you are not older than 16 years old" and
~q means: You cannot ride the roller coaster.

A: No, because $P\implies Q\land R$ actually means that You must be under 4 feet tall and older than 16 to ride the roller coaster which is not true. You can be under 4 feet tall and more than 16 years old and still ride the roller coaster. The sentence of the question is equivalent to:

If you are more than 16 years old or more than 4 feet tall or both, you can ride the roller coaster.

which is $$(\lnot Q\lor R)\implies P$$so, the if-else-then statements always work.
Another way to tackle these sort of problem is the truth table:
$$
\begin{matrix}
Q&R&P
\\0&0&1
\\0&1&1
\\1&0&0
\\1&1&1
\end{matrix}
$$


text:
Q: How can I get an updated $Revision$ in my code I have a project into which I'd like to embed the revision number automagically.
In this case, it's a multi-file perl script. In the main file, I have a line that looks like this:
my $revision = '$Revision: 24 $';
When I make a release, I checkout the project to my release dir.
The revision number does change whenever I check-in a change to THAT FILE. The $Revision$ attribute is updated on check-in, but not check-out.
The thing is, the main file doesn't change that often, so even though the other files in the project are now at 27, the main still has 24.
Is there a way that I can get the main file to reflect the latest rev number? The one that svn prints out at the end of the checkout, ie "Checked out revision 27."

A: It is similar to CVS, you can use $Revision$ you just have to set the keyword property for that file for SVN to know it is supposed to do a keyword replace.
From the manual:
"With no svn:keywords property set on that file, Subversion will do nothing special. Now,
let's enable substitution of the LastChangedDate keyword.
$ svn propset svn:keywords "Date Author" weather.txt
property 'svn:keywords' set on 'weather.txt'
$
"
http://svnbook.red-bean.com/en/1.5/svn-book.pdf

A: if (! -e '.version')
{
    open VERSION, '>.version';
    print VERSION `svnversion -n | cut -f1 -d:`;
    close VERSION;
}

my $revision = '$Revision: ' . `cat .version` . ' $';

(Note: a puppy will die if you use this code as-is)


text:
Q: Как реализовать выстрел из гарпуна(хука)? Я хочу реализовать выстрел из гарпуна(хука), как в игре Dota 2.
Чтобы когда Pudge бросал крюк:
1. За крюком следовала линия (тросс)
2. При возвращении хука - тросс сокращался и потом вовсе исчезал.
Вот видео - https://youtu.be/xlcw7VGaqiY
1 пункт примерно понимаю как реализовать, а вот со вторым возникают большие трудности.
Есть какие-нибудь идеи как можно такое реализовать? Желательно бы со ссылочками

A: Есть такая штука как Joint.
Всегда актуальная документация по джоинтам есть в документации к юнити: https://docs.unity3d.com/Manual/Joints.html .
Если это 2д проэкт, то там есть отдельно 2dJoint-ы: https://docs.unity3d.com/Manual/Joints2D.html
Через него, например, реализуется таскание при помощи веревок/цепей/проводов. У документации юнити видеотуториал по использованию джоинтов.
А вот здесь можно найти неофициальный туториал, только для создания физики таскания на веревке при помощи джоинтов.
Формально, твоя задача сделать несколько секций цилиндров соединенных между собой при помощи джоинтов и у тебя будет веревка/цепь/провод. Чем больше количество секций - тем реалистичнее выйдет.
Думаю, что если заскейлить размер веревки по нужной оси(Relative только!) то получится именно тот эфект, который нужно и на основе физики будет притягиватся персонаж.
Думаю что это решение подойдет если нужна физическая составляющая.

Так же есть решение через https://github.com/NoxWings/Cable-Component
Здесь физика веревки не будет учитыватся. Немного более широкое описание: Unity Cable-Component

В даном случае т.к. веревка нефизическая, нужно будет при прикреплении к персонажу/предмету подсовывать его... Можно попробовать двигать через MoveToward(), но я не уверен на сколько это красивое решение...

UPD:
Есть еще третий вариант. Думаю, по быстродействию он будет самым оптимальным:
Нарисовать между центрами двух обьектов сплайн, а потом вдоль сплайна рисовать звенья веревки/цепи. Как это сделать можно почитать, например, вот здесь: https://catlikecoding.com/unity/tutorials/curves-and-splines/
Сплайн должен быть двухточечным. Т.е. указыватся начало и конец -- без промежуточных точек. Обновлять позиции точек будет достаточно просто...
Думаю, на том видео которое было примером был взят именно этот путь реализации.

A: К сожалению Joint'ы мне не помогли, но помог Line Renderer. Я просто нацепил на каждый объект хука line renderer и в качестве стартовой позиции линии я указывал игрока, а в качестве конечной - transform.position самого хука.


text:
Q: How to refresh the window with Tkinter I am trying to create a window filled with random integers between 0 and 9. After a certain amount of time, the window should refresh and display new randomly selected integers. My code does the first step just fine but fails at the second part. I have looked up functions like after() but it still doesn't work. The code looks like this:
from tkinter import *
from random import *

root= Tk()
col=170
row=45
num=[[randint(0,9) for i in range(col)] for j in range(row)]

for k in range(row):
        theLabel= Label(root,text=' '.join(str(e) for e in num[k]))
        theLabel.pack()

def ch():
    num1=[[randint(0,9) for i in range(col)] for j in range(row)]
    for k in range(row):
        theLabel= Label(root,text=' '.join(str(e) for e in num1[k]))
        theLabel.pack()

root.after(5000,ch())
root.mainloop()

What should I do? I would appreciate any kind of help.

A: root.after(5000,ch())

This calls ch immediately and registers whatever the return value is to execute five seconds later. Instead, try:
root.after(5000,ch)

Edit: another problem you have is that ch adds new labels to the window, but the old ones still remain. Since you have 45 rows to start with, the new ones appear below that and will probably be off-screen, so you don't notice that they've appeared.
If you want the new numbers to replace the old, don't create a new label - just reconfigure the existing ones to have new text.
from tkinter import *
from random import *

root= Tk()
col=10
row=10
num=[[randint(0,9) for i in range(col)] for j in range(row)]

labels = []
for k in range(row):
    theLabel= Label(root,text=' '.join(str(e) for e in num[k]))
    theLabel.pack()
    labels.append(theLabel)

def ch():
    for label in labels:
        row = [randint(0,9) for i in range(col)]
        label.config(text = ' '.join(str(e) for e in row))

root.after(5000,ch)
root.mainloop()

A: Btw, this is the final working form:
from tkinter import *
from random import *

root=Tk()
col=200
row=57
num=[randint(0,9) for i in range(col*row)]
st=""

for k in range(0,col*row,col):
    st=st + ('  '.join(str(e) for e in num[k:k+col])) + '\n'

theLabel= Label(root,text=st)
theLabel.pack()

def ch():
    st1=""
    num1=[randint(0,9) for i in range(col*row)]
    for k in range(0,col*row,col):
        st1=st1 + ('  '.join(str(e) for e in num1[k:k+col])) + '\n'
    theLabel.config(text=st1)
    theLabel.pack()
    root.after(1000,ch)

root.after(1000,ch)
root.mainloop()

I also added a recursion so that it goes on non-stop.


text:
Q: I am not able to switch Scene in Unity with Easy Movie Texture Plugin I am trying to on gaze function from Google VR, and switch scene that will then play movie clip using Easy movie Texture
On iOS the app just bombs out with thread issue
I Have the project I can share
I thought it was zombies but nope.
have removed the shader from the object as well


text:
Q: change .joinedAt format in discord.js I'm making a user info command, and i want it to say when a user joined, it kinda works but i want to change the time format, this is the code that gets the join data:
message.member.joinedAt

i tried using .format('YYYY-MM-DD') right after joinedAt but nothing, this is what it looks like right now (it has italian text for some reason, probably because my discord account is registered in Italy)

A: You can use a package called moment.
Example:
const moment = require('moment');
moment.utc(<Message>.member.joinedAt).format('YYYY-MM-DD');

Full example:
const Discord = require('discord.js'); // Define Discord
const client = new Discord.Client(); // Define client
const moment = require('moment'); // Define moment
let prefix = 'your-prefix'; // Define your bots prefix

client.on('message', function(message) { // Message event listener
    if (message.content.startsWith(`${prefix}info`)) { // If the message starts with the command
        message.channel.send(`<@!${message.author.id}>, you joined this server on ${moment.utc(message.member.joinedAt).format('YYYY-MM-DD')}`);
    }
});


text:
Q: Why do I get a type mismatch when attempting to return a value for a checked generic parameter? In the following code "Happy Halloween!", 42, etc. are flagged as "Type mismatch." (Required: T, Found: String (or Int)) but shouldn't the compiler be able to infer that the return value is of the correct type from the type check?
interface Type<T>
class StringType() : Type<String>
class IntType1() : Type<Int>
class IntType2(val a: Int, val b: Int) : Type<Int>

fun <T> something(type: Type<T>): T = when (type) {
    is StringType -> "Happy Halloween!"
    is IntType1 -> 42
    is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
    else -> throw IllegalArgumentException()
}

A: You could write this:
interface Type<T>
class StringType() : Type<String>
class IntType1() : Type<Int>
class IntType2(val a: Int, val b: Int) : Type<Int>

inline fun <reified T> something(type: Type<T>): T {
    val result = when(type) {
        is StringType -> "Happy Halloween"
        is IntType1 -> 42
        is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
        else -> throw IllegalArgumentException()
    }
    return if (result is T) result else throw Exception()
}

Running the following:
fun main(args: Array<String>) {
    println(something(StringType()))
    println(something(IntType1()))
    println(something(IntType2(2, 3)))
}

Will give you this output:
Happy Halloween
42
19

Learn more about inline functions and reified parameters here: Reified type parameters.

A: When the compiler applies type erasure the return type is going to be defined. So, let's say, you use a String... your method is going to be like:
fun something(type: Type<String>): String = when (type) {
    is StringType -> "Happy Halloween!"
    is IntType1 -> 42 //Wrong: you must return String!
    is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
    else -> throw IllegalArgumentException()
}

This thing is: you must know your return type at compile time. If you dont know this, you have to tell that to the compiler:
fun <T> something(type: Type<T>): Any = when (type) {
    is StringType -> "blabla"
    is IntType1 -> 42
    is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
    else -> throw IllegalArgumentException()
}

Sorry this code it's not what you are hopping, you are going to make a cast after the method is returned...
But you can this:
fun <T> something(type: Type<T>): T = when (type) {
        is StringType -> type.b
        //is IntType1 -> 42 remove this!
        is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
        else -> throw IllegalArgumentException()
    }

assuming the type.a and type.b are parametized as T. Then your code will work just fine.

A: If I simplify your example a little:
interface Type<T>

fun <T> something(type: Type<T>): T = when (type) {
    is Type<String> -> "Happy Halloween!"
    else -> throw IllegalArgumentException()
}

the compiler now complains that he: cannot check for instance of erased type
So the problem is that because of type erasure there is no difference between Type<String> and Type<Int> at run time, so the compiler wont allow that.
You can try to use something like Gson's TypeToken<T> or Jackson's TypeReference<T>
The docs refer to this blog post explaining the idea: http://gafter.blogspot.ca/2006/12/super-type-tokens.html

A: The is operator, much like Java's instanceof operator, is performed at runtime.
So, at compile time, the compiler does not know the actual type, hence you get a compilation error.
Here is another simple example:
fun <T>f(t: T): T
{
    if (t is Int) return 3 // compilation error
    else return t
}


text:
Q: Rise and fall times typical values for a switching signal in 90 nm technology I have fabricated  NMOS and PMOS devices on simulation using Silvaco software, the fabricated device (CMOS) is shown below.

 Now, I want to find the dynamic power dissipation of the CMOS inverter by applying a pulse to the input and I'm getting right behavior as you can see in the figure below
I used the following command in my code:
vin 1 0 0. PULSE 0 1.2 0 1ps 1ps 500ps 10
The input signal is vin, a pulse signal goes from 0 to 3V, the rise and fall times are 1ps and the pulse width is 500ps. I used 0.1pf as the load capacitor. The supply voltage VDD is is 1.2V.
However my advisor asked me to change the rise and fall times to the typical corresponding values in 90 nm technology. Unfortunately, I could not find a clear answer to my question, and I found some researchers are using values according to their applications. Could you please provide me with a good trusted reference?


text:
Q: Leaving "Else" comments Let's say I have a not-so-intuitive if statement in my code, but only if you're new to the codebase:
def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
        self._set_markets(markets)

For those of you wondering:
The existing system I'm interacting with (a database) expects a list of integers from the front end interface. This code does it from the backend, so a list of ints was chosen since it best represents what a user might feed in otherwise.
The markets stuff is handed down from another class, so even though it appears like it's taking place over 5 lines, it's more like ~50 lines.
My question is, would you consider this more readable? Why or why not?
def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
      # else:
          # markets are set to "all"
        self._set_markets(markets)

EDIT:
This code looks worse than it is because I left off a detail: if None is fed in for markets (the default parameter), then it will not modify the markets settings the database.
Here's what I have now:
    if markets is not None:
        if isinstance(markets, list):
            markets = ','.join(map(str, markets))
        else:
            markets = 'all'
        self._set_new_header_markets(markets)

A: To me, the fact that you've formatted the else: to look like regular code is misleading; something more commenty seems like it'd be appropriate.
Right now it looks like the else is commented out because there is no code for that block yet, and the inner comment is a placeholder for code to come, which is not the case (?). I'd inline both comments, bump up the indentation on the hash and maybe remove the else's formatting:
if markets:
    if type(markets) == list:
        markets = ','.join(map(str, markets))
    # else: markets are set to "all"
    self._set_markets(markets)

A: Firstly, putting code in comments makes me assume it's dead code. It'll just be really confusing if you do that.
Secondly, the fact that you need a comment is because your code is unreadable. Try for making the code readable before adding a comment.
If you accept 'all' or a list, you should really do it like this:
if markets == 'all':
   self._set_markets('all')
else:
   self._set_markets(','.join(map(str, markers))

Then its abundantly clear what is going on and you avoid type checking, and you don't accept invalid data so long as it isn't a list.


text:
Q: Copy-webpack-plugin [INFO] error  cannot locate '\**\*' in '\**\*' - Windows [closed I have been dealing with this for several days, when I want to generate the war of a project in Windows I find this error when executing mvn clean package Error de copy-webpack-plugin [INFO] no se puede localizar '' en ''. I paste that path that the terminal gives me in the explorer and it exists.
I have tried several things but they did not work, I know that it is a problem with the paths in Windows because it is looking for a list of directories that is not working because it does not find anything and it cannot generate the copy of the files, in Linux it works and compile normally. Has anyone had the same problem and can help me with this? I am attaching some images for reference, thank you very much.
Error Terminal
Path of the webpack.config.js file]


text:
Q: Haar Cascade XML I am interested in what everything in the xml file below means:
<stages>
<trees>
<feature>
<rects>
<_>
<tilted>
<threshold>
<left_val>
<right_val>

and what the five integers in between rects mean.
        <feature>
          <rects>
            <_>
              14 18 1 2 -1.</_>
            <_>
              14 19 1 1 2.</_></rects>
          <tilted>0</tilted></feature>
        <threshold>-4.3883759644813836e-005</threshold>
        <left_val>0.3130159080028534</left_val>

A: OK, you are making this a bit harder than it has to be, but I'll try. I guess, you are asking about object detectors in OpnenCV. These are cascades of boosted classifiers which originate from Viola&Jones face detector which classify each image region/patch into object/background classes and are called scanning window object detectors.

*

*<stages> is a series of more and more complex classifiers which try identify if an image patch contains a face (with higher and higher confidence).

*<trees> should be even simpler classifiers which the stages are composed of.

*<feature> is a simple hand-coded feature which extracts single value from an image.

*<rects> are rectangular regions a feature is composed of.

*<tilted> could be a binary value - if the feature is 45° rotated.

*<threshod> is a threhold of the value of the feature.

*<left_val> is a vote about the probability that the classified region contains face if the value of the feature is below the <threshold>.

*<right_val> is a vote about the probability that the classified region contains face if the value of the feature is above the <threshold>.

PS: I could be wrong, I did my Ph.D. on this type of classifiers, I did not write OpenCV.


text:
Q: What is the physical meaning of the characteristic impedance of a transmission line? If it was per unit length, I'd understand, but apparently it is a constant of the whole line.
Consider if I change the length of the transmission line, the impedance of the whole thing should increase since more power is dissipated, but the characteristic impedance doesn't change. So, what exactly is the characteristic impedance?

A: At a risk of collecting few negative points, I will try to answer this question as follows:
The "characteristic impedance" has no direct physical meaning. It is just a constant in amplitude coefficients in the solution to the "Telegrapher's Equation", which describes propagation of a sinusoidal electromagnetic wave(s) along a special geometry of uniform conductors called "transmission line". The equation is a derivative from more general Maxwell Equations.
The actual amplitudes of propagating EM waves are determined by "boundary conditions" to the line, by impedance of driver, and impedance of receiver (terminations).
Formally, the ratio of V(t)/I(t) defines the "characteristic impedance" of an ideal (lossless) transmission line, which appears to be a real (non-imaginary) number, just like an ordinary passive resistor. One might think that this resistor must dissipate Joule heat.
In other words, Z=V(t)/I(t); I(t) = V(t)/Z; P = V*I = (V^2)/Z. V is a real function of t, Z is real, so P must be non-zero, and must dissipate into heat.
But in this case the wave should quickly disappear. However, it is known that the ideal transmission line doesn't dissipate anything, and waves can propagate forever to infinity. Therefore, we have an obvious paradox: we have seemingly a real "impedance", but it doesn't dissipate any energy.
The resolution of this paradox is this: formally and accurately, the Joule dissipation occurs only when a current FLOWS ACROSS A RESISTOR. The trick is that in the case of transmission line no current is flowing across the "characteristic impedance". If one to examine the excellent animation in the referenced Wikipedia page, one can see that the current oscillates ALONG the conductors of transmission line, not across the empty space between conductors. The actual impedance across the conductor gap is infinitely large, and no dissipation occurs. The electrons are moving back and forth along the wires that are assumed to be perfect conductors, so no energy is dissipated there as well.
In different words, formally one can take any V(t) from a circuit, and divide it by I(t) from any node. The result will be a number in units of resistance, but it may mean nothing. In case of "characteristic impedance" the V/I ratio is just that, a characteristic of transmission line geometry/permeability, and does not represent the current across the transmission line.
The characteristic impedance however can serve an important mission: if the termination is purely active (real restive) and equal to the characteristic impedance, the resulting wave solution does not have the reflected wave, which is very useful in design of high-speed electronics (and in power lines as well).

A: You seem to confuse two concepts:

*

*Attenuation is the amount of something (in this case electrical energy) that is absorbed by a medium. Attenuation is linear with the distance.

*Reflection is something (in this case again electrical energy) that is emitted by the source, but not absorbed (accepted, trasmitted, ...) by the medium. Instead it is reflected back.
Reflection is caused by a mismatch between the source (driver) impedance and the destination(medium) impedance. When both are the same no reflection occurs, and all energy is 'acceppted' by the medium.
The characteristic impedance is the impedance of an infinitely long transmission line. When you drive such a transmission line, you likely want to match the impedance of your driver to taht of the transmission line, to avoid reflection (which is, at best, a waste of energy).
In practice, a transmission line doesn't need to be infinitely long to have almost the same characteristic impedance of an infinitely long one, a few wavelengths is often sufficient. Henec it is a very usefull characteristic to know.

A: The characteristic impedance is defined for every point on the line. In a good line, it's constant along the entire length, and much effort is spent by connector manufacturers to maintain  the impedance constant even through the connector. In a bad line, it varies from point to point, and can become very different at connectors.
As a wave propagates along a transmission line, it consists of a voltage wave, which is the voltage of one conductor with respect to the other, and a current wave, which is the out-flowing current in one conductor and the return current in the other.
The characteristic impedance is the ratio of wave voltage to wave current at each point along the line.
Physically, the characteristic impedance depends on the cross-sectional geometry of the line, which controls the shunt capacitance per unit length, and the series inductance per unit length of the line. The impedance is sqrt(L/C) at any point, where L and C are the per unit length values for the capacitance and inductance.
In a coaxial cable with conductor radii R_inner and R_outer, the capacitance, inductance, and so impedance, are all proportional to the log(R_outer/R_inner).
The cross section
Now we see why a line must have a constant impedance to be called good. If the impedance varies along the line, then the ratio of the volts/current of the wave must vary as it travels along the line as well. The only mechanism nature has available for doing this is to reflect some of the energy back to the source when the impedance changes, in the right phase and amplitude to make up the difference between the old and new voltage and current values.
Now we also see why terminating a line in a resistor equal in value to the line characteristic impedance is good. We know the wave coming out of a (for example) 50ohm line has that ratio between voltage and current. If fed into a 50ohm resistor, the conditions match perfectly, and all the energy in the wave is absorbed in the resistor without reflection.
If a line is terminated in an open circuit, then the current cannot flow. Nature sorts that out by reflecting an anti-phase current wave of the same amplitude, which adds up to zero current at the open circuit. Of course that current wave has a voltage wave with it, which doubles the voltage at the open circuit end as it's in phase with the incident voltage wave.

A: The impedance of a transmission line is the square root of the ratio between L and C. Given the line is uniform, L and C increase with line length but their ratio stays the same. That's why the impedance is constant for a uniform line of arbitrary length.

A:
Consider if I change the length of the transmission line, the impedance of the whole thing should increase since more power is dissipated,

Power isn't really fundamentally relevant here, but let's run with it for a moment: More power is dissipated along the length of the line, and less power comes out the other end of the line. But the amount of power put into the line by the source is unchanged.
That's how you should think about the characteristic impedance: it's a property of any end of the line, which is independent of how much length of line is behind that end (or port).
That property is that the end of the line behaves the same in response to an applied voltage, as a resistor of the same value as the characteristic impedance. But that doesn't mean that the line is dissipating the power like a resistor would: it's moving it instead.
Ohms don't mean dissipation, they mean a voltage/current relationship.

A: An intuitive approach but nothing more!:
If you agree that the charactertic imepdance of a transmission line is defined as the ratio of the voltage wave divided by current wave at any POINT, then it is easy to see intuitively why this is constant.
When I say POINT, i an literarly refering to an infestesimally small length of the transmission line.
So as a mental picture you can imagine the transmission line made up of many fictitious resistors of value equal to the characteristic imepdance. So when you refer to the characteristic impedance you are refering to simply ONE of that fictitious resistors value. See the photo below:
Do you now see why the characteristic impedance is independant of the length of the line and independant of the POINT of measurement? (Because changing the length of the line merely changes the number of copies of the fictitious resistors but not their value and hence the characteristic impedance)

A: A cable (or generally transmission line) can be modelled as infinite number of LC stages. So per meter you have inductance or capacitance. But the LC itself is constant.
By the way, if you have infinite transmission line, you can measure characteristic impedance with just ohm meter. It applies certain voltage and current becomes V/Z0, but never changes, as it must charge all infinite LC and will never reach the end of the line.

A:
What is the physical meaning of the characteristic impedance of a
  transmission line?

Thought experiment: -
If you took an infinite length of 50 ohm coax and applied 1 volt dc at one end, what curent flows: -

*

*No current because the voltage hasn't reached the load (which is infinitely far away

*A current of 20 mA

One of the answers is right and one is wrong.
When you make a radio frequency transmitter and a transmit a signal onto an antenna, does power get emitted into space by the antenna or, will that only happen when there is a receiver capable of receiving something?
Hint: free space has an impedance of 377 ohms.

So, what exactly is the characteristic impedance?

For free space it is the square root of the ratio of magnetic permability (\$\mu_0\$) to electric permittivity (\$\varepsilon_0\$) : -

This also forces the ratio of electric field and magnetic field to be 377:1 (\$120\pi\$).
For space, coax or any transmission line, the same principle is involved; henries per metre (\$\mu\$) are divided by farads per metre (\$\varepsilon\$) and square rooted.


text:
Q: 3 digits are truncated from an 18 digit long column when I save my pandas dataframe as a csv file I've created a dataframe from a dictionary populated by a JSON file. The "id" column in my dataframe contains 18 digits integer. When I print ids using python the value is equal to the original value in the JSON file, but when I try to save my dataframe as a csv file the id column is saved in scientific notation and also three digits on the right side of ids are converted to zero.
How can I prevent the id value conversion to scientific notation in the csv file?
For example, I get 1.01045E+17 for id when I view the csv, and when I see the value I get 101044874404577000, while the true value is 101044874404577281
This is my code:
with open(data_path, encoding="utf8") as input_file:
    data = json.load(input_file)
df = pd.DataFrame.from_dict(data)
df.to_csv(output_path)

I have tried to change the format of the column by astype to str, object, and float64 but that didn't help.
I've set float_format argument of to_csv function to save floating numbers with specified number of decimals, too. This didn't work either.

A: The problem is not in convertion to csv, but when you load it into a spreadsheet. Excel is known to have a poor support for csv files, and unfortunately LibreOffice calc does its best to emulate Excel...
It sees a number and wrongly convert it as a double value.
Demo:
In python:
>>> x = 101044874404577281
>>> data = [{"id": x, "str": "foo"}]
>>> fd = io.StringIO()
>>> json.dump(data, fd)
>>> fd.seek(0,0)
0
>>> df = pd.read_json(fd)
>>> print(df)
                   id  str
0  101044874404577281  foo

Ok everything is fine here. Let's go on:
>>> df.to_csv('foo.csv', index=False)

When opened in a dumb text editor, foo.csv if still fine:
id,str
101044874404577281,foo

Let's load that into a spreadsheet:

Shame on calc, it put that into scientific notation! Let's use normal display:

Sigh... it has destroyed the last digits...
TL/DR: It is not a problem in Python nor in pandas nor even with the csv file but only with Excel.


text:
Q: Changing observable stream while keeping subscription In RxJS, I want the subscription to persist on the stream even when the stream is changed. Below I used an interval stream to test the behaviour
//Works because foo$ is unchanged
let foo$ = Rx.Observable.interval(1000);
foo$.subscribe(x => console.log(`foo$: ${x}`));

//Doesn't work because bar$ is changed
let bar$ = Rx.Observable.never();
bar$.subscribe(x => console.log(`bar$: ${x}`))
bar$ = Rx.Observable.interval(1000);

jsbin Live Demo
How do I persist the subscription while changing bar$ stream?
Do I have do dispose the subscription and set another subscription after I change bar$?

A: The general pattern in Rx is to replace state mutation with a stream of values (i.e. an observable). Here, rather than reassigning bar$, bar$ should be modeled as an Observable<Observable<T>> (that is, a stream of streams of values of type T). It can then be "flattened out" into a stream of values (in this case, using switch).
For example:
const bar$ = new Rx.Subject();
bar$.switch().subscribe(x => console.log(`bar$: ${x}`));
bar$.onNext(Rx.Observable.fromArray([1,2,3]));
bar$.onNext(Rx.Observable.interval(1000).take(3));

https://jsbin.com/firoso/edit?js,console,output


text:
Q: destructing a pointer to a dynamic 2d array in C++ Iv'e been trying to solve this allocation/destruction problem for a significant amount of time as part of an assignment I got from school, basically I need to allocate a 2d array pointer of a simple class i designed.
class RobotsWorld{
public:
    RobotsWorld(int width,int hight);
    ~RobotsWorld();
    /**
     * copy,Assign,operator=
     */
    //RobotsWorld(const RobotsWorld &);
    //void Assign(const RobotsWorld &);
    //RobotsWorld& operator=(const RobotsWorld &);

    bool addRobot(Robot & r,Point p);
    bool moveRobot(Robot & r);
    bool removeRobot(Robot & r);
    Point getPosition(Robot r);
    string toString();

    Robot* getRobotInWorld(Robot & r);

    /** validation functions **/
    bool checkOutOfBounds(int,int);
    bool isEmptySlot(int x,int y);
    bool ableToMove(Robot &);

private:
    Robot*** robots;
    Point point;
    int width,height;
};

this is not the full source file of the functions but these functions causes the crash\memory loss. (and yes it has to be defined as a triple pointer - ***robots)
RobotsWorld::RobotsWorld(int width,int height)
:width(width),height(height)
{
    robots = new Robot**;
    *robots = new Robot*[height];

    for(int i = 0 ; i < height ; i++){
        robots[i] = new Robot*[width];
        for(int j = 0 ; j < width ; j++)
            robots[i][j] = NULL;
    }

}

RobotsWorld::~RobotsWorld(){

    for(int i = 0 ; i < height ; i++){
        delete [] robots[i];
        robots[i] = NULL;
    }
    delete [] *robots;
    delete **robots;
}

the robot class and the main got no allocation whats so ever.
ive been trying to search for a solution but even describing this situation proved it self difficult.

A: You need two nested loops to delete a 2D array of pointers - to delete individual robots, and to delete rows of robots:
RobotsWorld::~RobotsWorld(){
    for(int i = 0 ; i < height ; i++) {
        for(int j = 0 ; j < width ; j++) {
            delete robots[i][j]; // Delete each individual robot
        }
        delete[] robots[i]; // Delete the row of robots
    }
    // Finally delete the 2D array itself
    delete[] robots;
}

Although it is normally a good idea to set a pointer to NULL after deletion, doing so in the destructor is a waste of CPU cycles; I recommend skipping is.
This is a lot of work (as I'm sure you can see). Using the standard C++ library can help you avoid all this work by using a suitable container - say,
vector<vector<unique_ptr<Robot> > > robots;

Now the tasks related to managing the memory for your robots will be taken care automatically.

A: the last line:
delete **robots;

is most likely your problem. It should be:
delete robots;

A: robots = new Robot**;
*robots = new Robot*[height];

is incorrect, you want
robots = new Robot**[height];

A: I cannot imagine why it would ever be necessary to have a T*** and Im certainly not able to maintain resources for something like this without helper classes! If I can't use std::vector<T> to help with the maintenance I wiould implement a similar class (well, it is easy for me: I have implemented my own version of the C++ standard library anyway...).
I haven't looked for all problems but the immediate oroblem is that you new robots** and treat the result as having more than element in robots[i].

A: I copy my comment in this answer:
You can also use:
template <int WIDTH, int HEIGHT>
class RobotsWorld
{
  public:
     /*... functions ...*/

  private:
     Robot robots[WIDTH][HEIGHT];
     /*... other private data ...*/
 };

And you do not have to care about new/delete stuff ;-)
However you have to implement some operators to allow:
RobotsWorld<3,4> rw34;
RobotsWorld<5,6> rw56 = rw34;
if (rw56 == rw34) /*...*/;

If you do not need to allow operations as the lines above, then template is an elegant solution.

A: You want to store a 2 dimension array of pointers to Robot. Here's a possible initialization routine:
RobotsWorld::RobotsWorld(int width,int height)
:width(width),height(height)
{
  robots = new (Robot**)[height];

  for(int i = 0 ; i < height ; i++){
      (*robots)[i] = new (Robot*)[width];
      for(int j = 0 ; j < width ; j++)
          robots[i][j] = NULL;
  }
}

The destructor should implement the dual operation.


text:
Q: Add timeout error when comment fails to be submitted via the app Sometimes, comment posting is stuck: (e.g. when internet connection lags, internal API issues)

In such cases, it just keeps loading... and loading... and loading, and never stops, forcing me to close the entire app.
Can you please add a timeout error e.g. after 10-20 seconds without response from the server?


text:
Q: How to use Two Toggle buttons on same page having same function with different css? I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.
However when I use
onclick="themeToggle()" id="theme-switcher"

for both of the buttons, only one of them works.
This is my Toggle Buttons Test Page.
This is the js which is being used :
 var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

This is the code for Two Toggle buttons

    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

<input type="checkbox" onclick="themeToggle()" id="theme-switcher">

Kindly help me in solving the issue with the code as well.
Thanks for the help.

A: Because you are using ID in <input type="checkbox" onclick="themeToggle()" id="theme-switcher">, which you repeat in other checkbox. so only first ID in the DOM will be taken.
Change your <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
To
<input type="checkbox" onclick="themeToggle()" class="theme-switcher">
And update the below code
Note: dont repeat ID
var tSwitcher = document.getElementsByClassName('theme-switcher');
let element = document.body;

let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
        for(let i = 0; i<tSwitcher.length; i++){
                tSwitcher[i].checked = true;
    }

}

if(onpageLoad) element.classList.add(onpageLoad);

So update your themeToggle() to
  function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      element.classList.add('dark-mode');
    } else {
      localStorage.setItem('theme', '');
      element.classList.remove('dark-mode');
    }
  }

A: First of all, you cannot have two or more elements with the same id.
To detect what button is being clicked you can pass the event to the function as argument like this.
onclick="themeToggle(event)" class="switcher" id="theme-switcher-2"

Once you have the event you can get the object that has fired it (In your case the button) like this.
    function themeToggle(event){
          var tSwitcher = event.target;
          if(tSwitcher.checked){
              localStorage.setItem('theme', 'dark-mode');
                element.classList.add('dark-mode');
            } else {
              localStorage.setItem('theme', '');
                element.classList.remove('dark-mode');
            }
    }

EDIT
To set the default behaviour properly you have to add class="switcher" to each button and do this.
var tSwitchers = document.querySelectorAll('.switcher'));
let onpageLoad = localStorage.getItem("theme") || "";
tSwitchers.forEach((element) => {
    if(onpageLoad != null && onpageLoad  == 'dark-mode'){
       element.checked = true;
    }
});

A: If you are using getElementById it will return the first occurrence of that id from dom, and as you are having same id on both button it is updating the first button every time.
Instead, you can except event object, in click function, and assign event.target to get the button element.

A: You can't use the same ID for two or more HTML elements. Also, once you want to use this functionality in multiple elements, I strongly recommend you to not use onclick inline. Instead, you can get all switchers from your page and add a listener to them:
Get all switchers in your page
const switchers = document.querySelectorAll('.switcher');

Apply the click event listener on them
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});

Finally, you must add the switcher class to all elements
<input type="checkbox" id="theme-switcher-1" class="switcher">
<input type="checkbox" id="theme-switcher-2" class="switcher">
<input type="checkbox" id="theme-switcher-3" class="switcher">

Using this approach, you can use this method all over your website or application and it's also easier to maintain.
Update: you should adjust the themeToggle() method like so:
function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is on');
  } else {
    localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is off');
  }
}

Example snippet
Obs.: You should adjust it into your code. I had to comment localStorage because it didn't work here.

const switchers = document.querySelectorAll('.switcher');
console.log(switchers);
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    //localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode');
    console.log('Dark mode is ON on ' + tSwitcher.id);
  } else {
    //localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode');
    console.log('Dark mode is OFF on ' + tSwitcher.id);
  }
}
<input type="checkbox" id="theme-switcher-1" class="switcher">

<input type="checkbox" id="theme-switcher-2" class="switcher">

<input type="checkbox" id="theme-switcher-3" class="switcher">


text:
Q: upload multiple images to firebase with react native expo project I have a react native project and I need to upload multiple images to firebase storage. in my code below I can select images from the device, and when I upload to the storage, only the first image gets uploaded. I need a way to be able to upload array of images to firebase storage.
I need to upload these images to storage because I will store the array of images in firestore.
const pickImages = async () => {
setIsLoading(true);
let result = await ImagePicker.launchImageLibraryAsync({
  mediaTypes: ImagePicker.MediaTypeOptions.All,
  // allowsEditing: true,
  allowsMultipleSelection: true,
  selectionLimit: 10,
  aspect: [4, 3],
  quality: 1,
});

if (!result.canceled) {
  setImages(result.uri);
}};

useEffect(() => {
const uploadImage = async () => {
  const blobImage = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function () {
      reject(new TypeError("network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", images, true);
    xhr.send(null);
  });

  const metadata = {
    contentType: "image/jpeg",
  };

  const storageRef = ref(storage, "Service/" + blobImage.data.name);
  const uploadTask = uploadBytesResumable(storageRef, blobImage, metadata);

  uploadTask.on(
    "state_changed",
    (snapshot) => {
      const progress =
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log("Upload is " + progress + "% done");
      switch (snapshot.state) {
        case "paused":
          console.log("Upload is paused");
          break;
        case "running":
          console.log("Upload is running");
          break;
      }
    },
    (error) => {

      switch (error.code) {
        case "storage/unauthorized":
          break;
        case "storage/canceled":
          break;

        case "storage/unknown":
          // Unknown error occurred, inspect error.serverResponse
          break;
      }
    },
    () => {
      // Upload completed successfully, now we can get the download URL
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log("File available at", downloadURL);
      });
    }
  );
};
if (images != null) {
  uploadImage();
  setImages(null);
}}, [images]);


text:
Q: Can we create custom map application having turn by turn navigation feature like google map app and Apple's native Maps application? I need to create a Map Navigation application with turn by turn navigation features like Apple's map.
I know we can open the Maps application to show address and route between source and destination location which provides direction for routing.
Here is code i have used.
-(void)openMaps
{

 MKPlacemark *place1 = [[MKPlacemark alloc]
initWithCoordinate:CLLocationCoordinate2DMake(38.40904,-121.36562)
   addressDictionary:nil];

MKMapItem *mapItem1 = [[MKMapItem alloc]initWithPlacemark:place1];

MKPlacemark *place2 = [[MKPlacemark alloc]
   initWithCoordinate:CLLocationCoordinate2DMake(38.41406,-121.36305)
   addressDictionary:nil];
MKMapItem *mapItem2 = [[MKMapItem alloc]initWithPlacemark:place2];

NSArray *mapItems = @[mapItem1, mapItem2];

NSDictionary *options = @{
   MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
   MKLaunchOptionsMapTypeKey:[NSNumber numberWithInteger:MKMapTypeSatellite],
   MKLaunchOptionsShowsTrafficKey:@YES
   };

[MKMapItem openMapsWithItems:mapItems launchOptions:options];

}

But it opens Maps application to show turn by turn navigation.
Is it possible to show this feature without opening maps i.e. inside custom application?
Thanks


text:
Q: How to get options in a form with values extracted from SQL database <select class="form-control" name="symbol">
    <option disabled selected value="">Symbol</option>
    <? for each($symbols as $symbols): ?>
    <option value="<?=$symbol?>"><?=$symbol?></option>
    <? endforeach ?>
</select>

$ symbols consists of data submitted by query (SELECT....) of cs50

A: Almost, you were very close. It's: foreach($symbols as $symbol)
Also, it's a good idea to escape untrusted data before displaying it.
For this purpose, I'd suggest htmlentities(...) The exception, of course, is if you were already storing it escaped in the database. I'd advise against this practice, though, as it's easy for the database to wind-up in an inconsistent state, especially over a long period of time, over many revisions.
So, altogether, that would be:
<select class="form-control" name="symbol">
   <option disabled selected value="">Symbol</option>
   <? foreach($symbols as $symbol): ?>
   <option value="<?=htmlentities($symbol)?>"><?=htmlentities($symbol)?></option>
   <? endforeach ?>
</select>


text:
Q: How to do join for my sitaution i have two select statement from two different table and the common join field a datefield
one date field name is JobFinishedDate and it is from MyJobs table and another date field name is createddate and it is from DailyFinishJobsHistory table
here is my two independent sql
sql 1
SELECT  CONVERT(varchar,createddate,101) as [Date],
                                SUM([No of Jobs]) as [No of Jobs],
                                SUM([Turnaround Time]) as [Turnaround Time],
                                SUM([One Day Per]) as [One Day Per],
                                ROUND((SUM([No of Jobs]) * SUM([Turnaround Time])),2) as [TOTAL hours]

from DailyFinishJobsHistory d
WHERE CONVERT(varchar,createddate,112)>='20131015' AND CONVERT(varchar,createddate,112)<='20131021'
group by createddate

sql 2
Select
  convert(varchar,JobFinishedDate,112) as JobFinishedDate
, Count(*) [Number of techs]
From
(
    select
    convert(varchar,JobFinishedDate,112) JobFinishedDate,Specialist
    from MyJobs
    where convert(varchar,JobFinishedDate,112)>='20131015'
    and convert(varchar,JobFinishedDate,112) <='20131021'
    and JobState='FINISHED'
    group by convert(varchar,JobFinishedDate,112) , Specialist
) t1
Group By
  JobFinishedDate

now i have to join. i tried like this way but right syntax is not coming to my mind to join this way.
SELECT  CONVERT(varchar,createddate,101) as [Date],
                                SUM([No of Jobs]) as [No of Jobs],
                                SUM([Turnaround Time]) as [Turnaround Time],
                                SUM([One Day Per]) as [One Day Per],
                                ROUND((SUM([No of Jobs]) * SUM([Turnaround Time])),2) as [TOTAL hours],
(
Select
  convert(varchar,JobFinishedDate,112) as JobFinishedDate
, Count(*) [Number of techs]
From
(
    select
    convert(varchar,JobFinishedDate,112) JobFinishedDate,Specialist
    from bbajobs
    where convert(varchar,JobFinishedDate,112)>='20131015'
    and convert(varchar,JobFinishedDate,112) <='20131021'
    and JobState='FINISHED'
    group by convert(varchar,JobFinishedDate,112) , Specialist
) t1
Group By
  JobFinishedDate
) a
from DailyFinishJobsHistory d
WHERE CONVERT(varchar,createddate,112)>='20131015' AND CONVERT(varchar,createddate,112)<='20131021'
group by createddate

so please help me bit to build the join. thanks
EDIT
i tried this script also but [Number of techs] is getting NULL
    SELECT  CONVERT(varchar,createddate,101) as [Date],
            SUM([No of Jobs]) as [No of Jobs],
            SUM([Turnaround Time]) as [Turnaround Time],
            SUM([One Day Per]) as [One Day Per],
            ROUND((SUM([No of Jobs]) * SUM([Turnaround Time])),2) as [TOTAL hours],
(
        SELECT
        --CONVERT(varchar,JobFinishedDate,112) as JobFinishedDate,
        COUNT(*) [Number of techs]
    From
    (
        SELECT  CONVERT(varchar,JobFinishedDate,112) JobFinishedDate,
                Specialist
        FROM bbajobs
        WHERE d.createddate=JobFinishedDate AND
        JobState = 'FINISHED'
        GROUP BY CONVERT(varchar,JobFinishedDate,112), Specialist
    ) t1
    GROUP BY JobFinishedDate
) [Number of techs]

    FROM DailyFinishJobsHistory d
    WHERE CONVERT(varchar,createddate,112) >= '20131015' AND CONVERT(varchar,createddate,112) <= '20131021'
    GROUP BY createddate

A: Something like this should do the trick:
    SELECT *
FROM
(
    SELECT  CONVERT(varchar,createddate,112) as [Date],
            SUM([No of Jobs]) as [No of Jobs],
            SUM([Turnaround Time]) as [Turnaround Time],
            SUM([One Day Per]) as [One Day Per],
            ROUND((SUM([No of Jobs]) * SUM([Turnaround Time])),2) as [TOTAL hours]
    FROM DailyFinishJobsHistory
    WHERE CONVERT(varchar,createddate,112) >= '20131015'
    AND CONVERT(varchar,createddate,112) <= '20131021'
    GROUP BY createddate
) A
JOIN
(
    SELECT
        JobFinishedDate,
        COUNT(*) [Number of techs]
    From
    (
        SELECT CONVERT(varchar,JobFinishedDate,112) JobFinishedDate
        FROM MyJobs
        WHERE CONVERT(varchar,JobFinishedDate,112) >= '20131015'
        AND CONVERT(varchar,JobFinishedDate,112) <='20131021'
        AND JobState = 'FINISHED'
    ) t1
    GROUP BY JobFinishedDate
) B
ON B.JobFinishedDate = A.[Date]

See joining two select statements for a simpler example.