text:
Q: Apt-get update through Tor I'm trying to update my apt-get list. In my country a lot of sites are blocked or have been blocked from companies.
When I use a proxy for the whole system I get errors,
Tor works perfectly when browsing.
Can I update apt-get through a connection from Tor?
I mean I want to unblock the blocked sites using Tor connection, so I can perform apt-get update without errors.
Edit: I'm using Ubuntu 13.10 and Tor 0.2.21
$ sudo apt-get update
[sudo] password for alexander:
Ign http://extras.ubuntu.com saucy InRelease
Ign http://security.ubuntu.com saucy-security InRelease
Ign http://us.archive.ubuntu.com saucy InRelease
Hit http://extras.ubuntu.com saucy Release.gpg
Get:1 http://dl.google.com stable InRelease [1,540 B]
100% [1 InRelease gpgv 1,540 B] [Waiting for headers] [Waiting for headers]
[WaSplitting up/var/lib/apt/lists/partial/dl.google.com_linux_chrome_deb_dists_stabIgn
http://dl.google.com stable InRelease
E: GPG error: http://dl.google.com stable InRelease: Clearsigned file isn't valid,
got 'NODATA' (does the network require authentication?

A: Install the apt-transport-tor package and then:
Edit /etc/apt/sources.list to add the prefix tor+ to your repositories.
deb     tor+http://deb.debian.org/debian unstable main
deb-src tor+http://deb.debian.org/debian unstable main

This will allow apt to run over tor.
Note: Substitute http://deb.debian.org/debian unstable main with the appropriate sources for your distribution.

A: You can use torsocks, It's shell wrapper to torify applications, to simplify the use of the Tor socks.
torsocks apt-get update

A: You must remove http://dl.google.com from apt source the first way is remove from software center or edit /etc/apt/sources.list with root access,Read it.
and if you use the kubuntu you can use software center and choose source tap click on configure source software and choose other tab remove http://dl.google.com.
and after than :
sudo apt-get clean
sudo apt-get update

A: If you have installed Tor from terminal, you must have torify. If so, simply you can pass the traffic of any script or program from tor.
First become root using sudo su then run this:
torify apt-get update

Then you can update your Google Chrome in the regular way using
apt-get upgrade

I am in Iran so facing with same problem of yours. I just used this method to update my Chrome.


text:
Q: ycbcr to rgb color conversion error on edge cases I have some problems converting a rgb photo to ycbcbr, modifying the y channel and converting back to rgb, generally it works perfect but for some edge cases it returns negative values or values greater than 255 so when i convert it back to uint8 for matplotlib it shows bright spots.
RGB to YCbCr
def rgb2ycbcr(data):
    res = np.empty(data.shape)
    res[...,0] = (data[...,0] * 0.299 + data[...,1] * 0.587 + data[...,2] * 0.114)
    res[...,1] = 128 + (data[...,0] * -0.169 + data[...,1] * -0.331 + data[...,2] * 0.5)
    res[...,2] = 128 + (data[...,0] * 0.5 + data[...,1] * -0.419 + data[...,2] * -0.081)
    return res

and YCbCr to RGB:
def ycbcr2rgb(data):
    res = np.empty(data.shape)
    data[...,1] = data[...,1] - 128
    data[...,2] = data[...,2] - 128
    res[...,0] = data[...,0] * 1 + data[...,2] * 1.4
    res[...,1] = data[...,0] * 1 + data[...,1] * -0.343 + data[...,2] * -0.711
    res[...,2] = data[...,0] * 1 + data[...,1] * 1.765
    return res

The strange thing is that when i dont touch the Y channel the photo converts ok (i know that when i modify the Y channel i keep the values in range)

A: Because of precision issues you are getting negative values and values over 1, so you would have to round/convert to integer:
RGB = np.asarray([[0, 0, 0], [255, 255, 255]])
print(rgb2ycbcr(ycbcr2rgb(RGB)))

[[-0.1423 0.6689 0.1714]
[255.1412 254.3363 254.8299]]

Now a major issue problem is that you are using constants that have too much rounding and do not agree with Recommendation ITU-T T.871, tweaking your code slightly accordingly to the 4 decimals rounded reference:
RGB = np.asarray([[0, 0, 0], [255, 255, 255]])

def rgb2ycbcr(data):
    res = np.empty(data.shape)
    res[..., 0] = (
        data[..., 0] * 0.299 + data[..., 1] * 0.587 + data[..., 2] * 0.114)
    res[..., 1] = 128 + (
        data[..., 0] * -0.1687 + data[..., 1] * -0.3313 + data[..., 2] * 0.5)
    res[..., 2] = 128 + (
        data[..., 0] * 0.5 + data[..., 1] * -0.4187 + data[..., 2] * -0.0813)
    return res

def ycbcr2rgb(data):
    res = np.empty(data.shape)
    data[..., 1] = data[..., 1] - 128
    data[..., 2] = data[..., 2] - 128
    res[..., 0] = data[..., 0] * 1 + data[..., 2] * 1.402
    res[...,
        1] = data[..., 0] * 1 + data[..., 1] * -0.3441 + data[..., 2] * -0.7141
    res[..., 2] = data[..., 0] * 1 + data[..., 1] * 1.772
    return res

print(rgb2ycbcr(ycbcr2rgb(RGB)))

[[-0.0055 -0.0082 -0.0006]
[255.0054 255.0082 255.0006]]

You still have to do conversion to integer but should be in a better place.
I noticed that you are modifying data in place in ycbcr2rgb, you should make a copy of the array when entering the definition or you will have very nasty surprises down the line.
I would suggest implementing the version without rounding from Recommendation ITU-T T.871.
Colour that we maintain has a very solid and complete implementation of Y'CbCr that you can use to verify your computations:
RGB = np.asarray([[0, 0, 0], [255, 255, 255]])

print(colour.YCbCr_to_RGB(
    colour.RGB_to_YCbCr(
        RGB,
        K=colour.YCBCR_WEIGHTS['ITU-R BT.601'],
        in_bits=8,
        in_int=True,
        in_legal=False,
        out_bits=8,
        out_int=True,
        out_legal=True),
    K=colour.YCBCR_WEIGHTS['ITU-R BT.601'],
    in_bits=8,
    in_int=True,
    in_legal=True,
    out_bits=8,
    out_int=True,
    out_legal=False))

[[  0   0   0]
[255 255 255]]

I would also suggest using BT.709 weights instead of those from ITU-T T.871/BT.601, the former are more widespread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve oracle Timestamp column in expected timezone in Java? I have a timestamp column in oracle table. While storing time I store it in UTC in this column. For retrieving this time stamp I am using Spring's JdbcTemplate while returns object of type TimeStamp.
I want to get date time string in "dd-MM-YYYY HH:mm:ss" format in current time zone. In order to achieve that I am trying following code:
new LocalDateTime(<retrieved TimeStamp>, <current user DateTimeZone>).toString("yyyy-MM-dd HH:mm:ss")

Both LocalDateTime and DateTimeZone from Joda library.
How ever this isn't working as per expected. Instead of current user's time zone above code gives me date time string in UTC only.
What am I missing?

A: I think your application is using java.util.Date which has no time zone information, the toString usage applies the JVM's current default time zone when creating a string.
You can adjust the timezone instant by (Using Joda Library)
ZonedDateTime Tokyo = ZonedDateTime.ofInstant (instant,zoneIdTokyo) ;

Or implement zones
DateTimeZone zone = DateTimeZone.forID("Asia/Tokyo");

You are using
LocalDateTime which is immutable class representing a local date and time (no time zone)
EDIT - You can try this
(I haven't tested it)
DateTime udate = new DateTime("2016-05-01T20:10:04", DateTimeZone.UTC);
System.out.println(udate);
DateTime zone = udate.plusMillis(10000)
.withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(zone);

A: Add utc calendar when fetching the timestamp from database, so the jdbc driver can use this calendar timezone instead of default system timezone.
//Assign utc calendar
Calendar utc= Calendar.getInstance();
utc.setTimeZone(TimeZone.getTimeZone("UTC"));
Timestamp timestamp = rs.getTimestamp("timestampcolumn", utc);
//Convert to client date time
DateTime dateTime = new DateTime(timestamp.getTime(), DateTimeZone.forID("Asia/Kolkata"));
//Format
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
//Change to client wall clock time
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime)

Example
String utcTime = "2016-06-17 14:22:02Z";
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");
DateTime dateTime = parser.parseDateTime(utcTime).withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
System.out.println(dateTime);
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime);
System.out.println(formattedlocalDateTime);


text:
Q: Qt4 QSettings read array with multiple values I have an .ini file of this form:
#init file:

[files]
fileAmount=2

file1=string1, string2, 0
file2=string1, string2, 1

//cpp file:
settings=new QSettings(QString(":resources/configuration"), QSettings::IniFormat);

int n=set("files/fileAmount").toInt();

for(int i=1; i<=n; i++){
    QStringList list=settings->value("files/file"+QString::number(i)).toStringList();
    out<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
}

//output:
string1 string2 0
string1 string2 1

Is there any way to set whitespaces as delimiter for QStringList instead of komma?
i.e have this file:
#init file:

[files]
fileAmount=2

file1=string1 string2 0
file2=string1 string2 1

and get the same output?

A: Ini File:
C:\Users\username\AppData\Roaming\MyOrg\MyApp.ini
[files]
file1=string1 string2 0

Sample code for space delimited stringlist in ini file:
#include <QCoreApplication>
#include <QStringList>
#include <QSettings>
#include <QDebug>

void readSettings();
void writeSettings();

QStringList list;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSettings::setDefaultFormat(QSettings::IniFormat);
    qApp->setApplicationName("MyApp");
    qApp->setOrganizationName("MyOrg");

    readSettings();

    qDebug() << list;

    writeSettings();

    return a.exec();
}

void readSettings()
{
    // read a space delimited value from QSettings string
    // into a stringlist
    QSettings s;

    s.beginGroup("files");

    QString temp = s.value("file1","string1 string2 0").toString();
    list << temp.split(" ");

    s.endGroup();
}

void writeSettings()
{
    // write a space delimited value from QStringList
    QSettings s;

    s.beginGroup("files");

    s.setValue("file1",list.join(" "));

    s.endGroup();
}

Output:
("string1", "string2", "0")

Hope that helps.


text:
Q: Is there a way to mark SQL Server objects as deprecated? I'd like to mark some SQL Server tables, columns, stored procedures and functions as deprecated. Something like pragma in Oracle Mark PLSQL procedure/function as deprecated
I can't remove them right away because it would break a lot of things in our legacy system. Because there are a lot of objects with similar or misleading names, it's common for a member of the team to utilize them inadvertedly. If existed something that would indicate visually that an object should not be used anymore, it would be perfect!
I'm looking for something like the IDE intellisense shows deprecation for common programming languages like Java as in this image:

A: You could perhaps use RAISERROR to print a warning message that a procedure is deprecated.
RAISERROR('This procedure is deprecated.', 1, 0);

If you use a low severity for the error then it shouldn't affect code execution, however it would display a message to other developers who are calling the procedure.


text:
Q: KnockoutJS - can't use "Slice" with ko.computed object I'm trying to create pagination using knockoutjs-2.1.0, and I'm getting the following error:

Uncaught TypeError: Object function h(){if(0return i||e(),a.U.La(h),k} has no method 'slice'

I've narrowed the problem down to this:  Apparently knockout doesn't like calling the "slice" method on an object which is created using ko.computed.  My computed type is this:
this.contactsToShow = ko.computed(function() {
// Represents a filtered list of contacts
// i.e., only those matching the "typeToShow" condition
var desiredType = this.typeToShow();
if (desiredType == "all") {
return this.allContacts();
}
return ko.utils.arrayFilter(this.allContacts(), function(aContact) {
return aContact.contactType == desiredType;
});
}, this);

And it throws an error in when I'm setting the "showCurrentPage" property, here:
contactListView.showCurrentPage = ko.dependentObservable(function() {
if (this.currentPage() > this.totalPages()) {
    this.currentPage(this.totalPages() - 1);
}
var startIndex = this.pageSize() * this.currentPage();
return this.contactsToShow.slice(startIndex, startIndex + this.pageSize());
}, contactListView);

However, if I use the original observableArray when setting showCurrentPage (the allContacts array), it works.
You can find the jsfiddle here: http://jsfiddle.net/mzalen/S74rJ/12/
I would really appreciate any advice on this issue, as it's driving me mad.

A: Common error with Knockout: this.contactsToShow becomes a function in your example and you must call it as a function:
return this.contactsToShow().slice(startIndex, startIndex + this.pageSize());


text:
Q: Make phone call from Apple watch app Can we use a button to make a phone call from the apple watch app?
For iPhone app we can use once the button is pressed:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://1111111111"]]);

A: openURL is silently ignored if the device is locked or the app is in the background. Additionally WatchKit doesn't contain an API for initiating a phone call.
Your best bet may be to prompt the user to open the iPhone app, possibly using Handoff, and tap a button to initiate the call from there. Not a great solution, but WatchKit is pretty limited right now.

A: It's now possible from WatchOS2 :
if let telURL = NSURL(string: "tel:5553478") {
    let wkExtension = WKExtension.sharedExtension()
    wkExtension.openSystemURL(telURL)
}

cf1,
cf2.

A: You can't do this on Apple Watch itself. But there alternative ways like:

*

*Tell the user to call the phone in the companion iPhone app

*Use Handoff to jump from Apple Watch app to the companion iPhone app with just a tap on a button (a more user-friendly way)

NOTE: The best way is always waiting for new versions. In WWDC 2015 taking place in San Francisco (June 8-12), they will introduce WatchKit 2 with support for the companion kits on iOS and the native watch apps that run on Apple Watch without having the iPhone nearby.


text:
Q: I need to save the image coordinates in a txt file by clicking on mouse what's up guys. I'm very beginner on programing stuffs. So, I need to create a code that I click on the image and it salve its coordinate. I need to make it in python+opencv. I've already done something, however it does not save its coordinate.
First of all, open an image.
Second, click on the pixel.
Third, save the pixel information (column, line) in txt file.
import matplotlib.pyplot as plt
import numpy as np
import cv2

def callback(event):
    print ('event.x, event.y')

fig, ax = plt.subplots()

fig.canvas.callbacks.connect('button_press_event', callback)
def callback(event):
    print ('event.xdata, event.ydata')

img = cv2.imread('/home/dgt/Pictures/1.jpeg',-1)
plt.imshow(img, cmap='gray', interpolation='bicubic')

plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()

A: With this script you can click on an image, and save the click locations to a spreadsheet:
import cv2, numpy as np

# Path to source video:
output_path = '/home/stephen/Desktop/clicks.csv'

# Mouse callback function
global click_list
positions, click_list = [], []
def callback(event, x, y, flags, param):
    if event == 1: click_list.append((x,y))
cv2.namedWindow('img')
cv2.setMouseCallback('img', callback)

img = cv2.imread('/home/stephen/Desktop/test214.png')

# Mainloop - show the image and collect the data
while True:
    cv2.imshow('img', img)
    # Wait, and allow the user to quit with the 'esc' key
    k = cv2.waitKey(1)
    # If user presses 'esc' break
    if k == 27: break
cv2.destroyAllWindows()

# Write data to a spreadsheet
import csv
with open(output_path, 'w') as csvfile:
    fieldnames = ['x_position', 'y_position']
    writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writer.writeheader()
    for position in click_list:
        x, y = position[0], position[1]
        writer.writerow({'x_position': x, 'y_position': y})


text:
Q: Specify correlation structure for different groups in mixed-effects model (lme4/nlme) I am trying to account for spatial autocorrelation in a linear mixed-effects model in R with measurements repeated in time. BodyMass has been collected once per Year in 150 different Sites over a 4-year period. Temporal autocorrelation should be negligible as body mass measurements are taken from dead animals.
As correlation structures of the form correlation= are not accepted in the lmer() model in lme4, I tried lme() from the older nlme package instead.
My baseline model looks like this:
library(nlme)
M1 <- lme(BodyMass~Year, data=df, random=~1|Site)

Now I want to account for spatial autocorrelation, considering the grouped spatial locations (each combination of coordinates is repeated 4 times due to the 4-year period). This syntax does however not work:
M2 <- lme(BodyMass~Year, data=df, random=~1|Site, correlation=corAR1(form=~x+y|Year))

It gives the following error:
Error in lme.formula(BodyMass ~ 1, data = df, random = ~1 | Site,  :
incompatible formulas for groups in 'random' and 'correlation'

According to Ben Bolker's answer here, the reason for that error is that

lme() insists that the grouping variable for the random effects and for the correlation be the same.

In my model, it would however not make sense to use the same grouping variable, as years are grouping the correlation structure (by the repeated coordinates), while years are inappropriate as a random factor, as they are consisting only of 4 levels (as discussed here).
Using gls() instead, as suggested here, is no real option for me as I need to account for the random factor Site and like to use R-squared, which is only possible in ordinary least squares (OLS) methods.
(1) Do you know any way on how to account for spatial autocorrelation in this case, keeping my random factor as well as the OLS framework to be able to calculate R-squared values?
Thank you very much in advance for your help!
EDIT: AdamO wrote in his answer to the differences between lme4 and nlme (link):

The "big three" correlation structures of: Independent, Exchangeable, and AR-1 correlation structures are easy handled by both packages.

(2) How is it possible to include these "big three" correlation structures in lme4?
I'm thinking that it might be possible to circumvent the grouping variable problem of nlme by using lme4 instead, if it's actually possible to handle spatial autocorrelation in there.
EDIT 2: I found that changing the grouping variable for the correlation structure as follows makes the model work without an error:
M3 <- lme(BodyMass~Year, data=df, random=~1|Site, correlation=corAR1(form=~x+y|Site/Year))

(3) Does this expression for the grouping variable in the correlation structure make sense?
I'm not entirely sure if it does, because in a a random factor, |Site/Year would imply that year is nested within site, but I think year and site would rather be crossed as each site is represented in every year.

A: An alternative very flexible approach is Bayesian. You can implement it in R using JAGS (you will have to go through some steps to download beyond just a package). If you do this, you can specify any correlation structure you want.
To structure it this way, you could either 1) treat your spatially correlated outcomes as part of a multivariate normal model (now y has 2 dimensions, the outcome and the space). or 2) Add another random component for space to the model which has its own correlation structure.
For example, you could modify this code for (2) and build a random intercept and slope model in R. Each person is indexed by i (say a n x 1 vector) and you also provide another nx1 vector of their spatial index (called site_indicator). You also need to provide the total number of sites.
model_RIAS_MVN<-"
model{
#Likelihood
for(i in 1:N_tot) {# all obs
# outcome is normally distributed
bodymass ~ dnorm(mu, sigmainverse)

# outcome model
mu <- b[1] + RI[subj_num[i], 1] + b[2]*Age[i] + RI[subj_num[i], 2]*Age[i] + RandomSpace[site_indicator[i]]
}

# Prior for random intercepts and slopes
# this allows them to be correlated
for (j in 1:N_people) {
RI[j, 1:2] ~ dmnorm(meanU[1:2], G.inv[1:2, 1:2])
}

# CHANGE HERE FOR NEW SITE CORRELATION #
# change number_sites in meanspace and G.invspace to actual number bc it # could throw error
for (j in 1:number_sites) {
RandomSpace[j] ~ dmnorm(meanspace[1:number_sites], G.invspace[1:number_sites, 1:number_sites])
}

for(i in 1:2){
meanU[i] <- 0 # zero mean for random components
}

G.inv[1:2, 1:2] ~ dwish(G0[1:2, 1:2], Gdf)
G[1:2, 1:2] <- inverse(G.inv[1:2, 1:2])

# whatever structure you want for correlation
G.invspace[1:number_sites, 1:number_sites] ~ dwish(G0inv[1:number_sites, 1:number_sites], Gdf_space)
Gspace[1:number_sites, 1:number_sites] <- inverse(G.invspace[1:number_sites, 1:number_sites])

sigmainverse ~ dgamma(1,1)

# informative priors for fixed effects
b[1] ~ dnorm(20, 0.25)
b[2] ~ dnorm(1, 4)

# uncomment for uninformative priors
# b[1] ~ dnorm(0, 0.01)
# b[2] ~ dnorm(0, 0.01)
}

This is just working code and it will need tweaked, but hopefully you get an idea of the flexibility and how you can specify the correlation structure this way.


text:
Q: PHP: Remove certain character from string excluding/ignoring URL I have a string as below
String
 - 17 posts - Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc

Now I want to remove - from string (not from the URL within the string)
I have tried to use str_replace() but than it is removing from URL also and that resulting broken links of course.
Anyone can please help me to remove - from the string but not from the URL

A: Assuming that the string will always be in that format, you can alter your str_replace to be more specific, thus ignoring the - in the URLs:
$newString = str_replace('> - <', '><', $oldString);

Like I said, ensure the format is always the same, i.e > - <

A: You could use DOMDocument, which will parse your HTML. This means that you can use str_replace only on the contents of your elements, rather than risk modifying their attributes as well.
It looks a lot more long-winded but it's also a lot safer and will still continue to work if the format of your HTML changes slightly in the future:
$html = ' - 17 posts - Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc';

$doc = new DOMDocument();
$doc->loadHTML($html);

// DOMDocument creates a valid HTML document, adding a doctype,  and  tags
// The following two lines remove them
// http://stackoverflow.com/a/6953808/2088135
$doc->removeChild($doc->firstChild);
$doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild);

$span = $doc->getElementsByTagName('span')->item(0);
foreach ($span->childNodes as $node) {
    $node->nodeValue = str_replace(' - ', '', $node->nodeValue);
}

echo $doc->saveHTML();

Output:
17 postsLi Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunc

A: Not elegant, but working and universal method:
1) replace all - occurences inside href attribute with some predefined "word" - combination of characters which not include -. This can be done by preg_replace_callback.
2) Do plain string replacement by str_replace:
$result = str_replace('-', '', $source);

3) Do backward replacement of all "word" occurences with - character.

A: $newString = str_replace('> - <', '><', $oldString);


text:
Q: Vectorizing eigen value calculation of 3*3*N matrix in Matlab Currently I am using the following code to obtain eigen values:
A = randi(100,3,3,4000000);
eig_vals = zeros(4000000,1);
for i =1:4000000
    eig_vals(i) = max(eig(A(:,:,i))) ;
end

I need help to vectorize my eigen value calculations without using a for loop.
Thanks,
Prithivi

A: You can  can calculate eigenvalues of a block-diagonal matrix composed of smaller [3 x 3] matrices:
C=mat2cell(A,3,3,ones(1,size(A,3)));
B=blkdiag(sparse(C{1}),C{2:end});    % A sparse block diagonal matrix
eig_vals = max(reshape(eig(B),3,[]),[],1);

But this may not be the most efficient one. So you can process the data part by part to reduce the time for creation of the sparse matrix:
s = 4000;
f = find(kron(speye(s),ones(3)));       % indices for matrix blocks
B = spalloc(s*3,s*3,s*3*3);             % preallocate the sparse matrix composed of 4000 matrices of size [3 x 3]
eig_vals = zeros(4000000,1);
for k = 0: 4000000/s-1
    B(f)= A(:,:,k*s+1:k*s+s);
    eig_vals(k*s+1:k*s+s) = max(reshape(eig(B),3,[]),[],1);
end

Here s=4000 is not the best chunk size. You can tune it for the best performance.


text:
Q: How to cover the entire page width, regardless what the screen size user have with a fixed manu? I have a problem with a menu that is fixed and centered on the page. I want the entire menu (3 background images) to cover the entire page width, regardless what the screen size user have.
Orginal pictures:
(Picture 1: width 1px, height 76px;)
(Picture 2: width 1135px, height 76px;)
(Picture 3: width 1px, height 76px;)
After CSS changes I want those to become:
(Picture 1: width 392,5px, height 76px;)
(Picture 2: width 1135px,  height 76px;)
(Picture 3: width 392,5px, height 76px;)

 Picture 1

 Picture 2 , center of the page , no-repeat

 Picture 3

I want to set the repeat-x on picture 1 and 3, but don't know the width. I can fix it with jQuery but aren't there a way in CSS?

A: Updated for transparent center image See, http://jsfiddle.net/QEPX4/5/show/
HTML

CSS (representative)
.TriHeader {
    position:fixed;
    width:100%;
    height:76px;
}

.TriHeader div {
    height: 76px;
    position: absolute;
}

.TriHeader .left {
    left: 0;
    right: 50%;
    z-index: 0;
}

.TriHeader .left div {
    background: url(repeatingLeftImage.png) top left repeat-x;
    right: 567.5px;
    left: 0;
    top: 0;
}

.TriHeader .center {
    background: url(nonrepeatingCenterImage.png) top left no-repeat;
    width: 1135px;
    left: 50%;
    margin-left: -567.5px; /*ideally, the image would be an even number */
    z-index: 1;
}

.TriHeader .right {
    left: 50%;
    right: 0;
    z-index: 0;
}

.TriHeader .right div {
    background: url(repeatingRightImage.png) top left repeat-x;
    left: 567.5px;
    right: 0;
    top: 0;
}

If you don't care about IE7, then you can eliminate the nested div elements in the left and right sides and replace the css with pseudo element selectors like:
.TriHeader .right:before {
    content: '';
    display: block;
    position: absolute;
    background: url(repeatingRightImage.png) top left repeat-x;
    left: 567.5px;
    right: 0;
    top: 0;
}


text:
Q: Unable to set the custom header view in UITableView I am trying to make the custom header for the UITableView but it is showing the "fatal error: unexpectedly found nil while unwrapping an Optional value". The code is like this:
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    self.headerImage?.frame = CGRect(x: (headerImage?.frame.size.width)! + 20, y: 20, width: 10, height: 10)
    headerLbl?.frame = CGRect(x: (headerImage?.frame.size.width)! + 20, y: 20, width: 10, height: 10)
    arrowImage?.isHidden = true
    arrowImage?.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 20, width: 10, height: 10)
    if selectedIndex == section {
      arrowImage?.image = UIImage(named: "down arrow")
    } else {
      arrowImage?.image = UIImage(named: "side_arrow")
    }
    let headerClick = UIButton(type: .custom)
    headerClick.addTarget(self, action: #selector(self.headerAction), for: .touchUpInside)
    headerClick.frame = CGRect(x: 0, y: 0, width: menuTableView.frame.size.width, height: 40)
    headerClick.tag = section
    headerClick.backgroundColor = UIColor.clear
    headerView.addSubview(headerImage!)
    headerView.addSubview(headerLbl!)
    headerView.addSubview(arrowImage!)
    headerView.addSubview(headerClick)
    return headerView
  }
  func headerAction(_ sender: UIButton) {
    if selectedIndex == sender.tag {
      selectedIndex = -1
    }
    else {
      selectedIndex = Int(sender.tag)
    }
     menuTableView.reloadData()
  }
}

But the error which is getting from this code is as shown in the screenshot below:

Why i am getting the error like this. Any ideas on it?


text:
Q: Xcode 4.4 with admod I would like to add admob at my ios application.
I have follow that tutorial :
https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals?hl=en#ios
But even with sample project or add source code at my ios project with that code, i have one error :
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GADBannerView private]: unrecognized selector sent to instance 0x1727d0'
With that source code :
ViewController.h
#import <UIKit/UIKit.h>
#import "GADBannerView.h"

@interface ViewController : UIViewController{
    GADBannerView *bannerView_;
}

@end

And
ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Create a view of the standard size at the bottom of the screen.
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            self.view.frame.size.height -
                                            GAD_SIZE_320x50.height,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];

    // Specify the ad's "unit identifier." This is your AdMob Publisher ID.
    bannerView_.adUnitID = @"MYID";

    // Let the runtime know which UIViewController to restore after taking
    // the user wherever the ad goes and add it to the view hierarchy.
    bannerView_.rootViewController = self;
    [self.view addSubview:bannerView_];

    // Initiate a generic request to load it with an ad.
    [bannerView_ loadRequest:[GADRequest request]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end

A: I ran into a smilar problem. I fixed it by using the -all_load linker flag.
Here is what you need.
https://developers.google.com/mobile-ads-sdk/docs/#incorporating

A: If you've already add -all_load and it's still not working:

*

*Close XCode make sure you close it properly.

*Reopen XCode.

*Clean the project.

*Build.

Good Luck :)


text:
Q: Convert a list to string in QGIS I have edited a field into the attribute form of a QGIS project as a "Value Relation" to create a checkbox where I can choose few possibilities. I have a tree sickness and the field I am talking about is the LOCATION where the sickness is visible: Roots, leaves, trunk, branches, twigs. The thing is that the output of all of that when I open my attribute table after typing the data it is like this in case the sickness is in all parts of the tree:
{"Roots","Trunk","Braches","Leaves","Twigs"}

Is there anyway where I can transform this into a normal string when it comes to be readable on the attribute table like Roots, Trunk, Branches, Leaves and Twigs (without the and also good solution but for sure without curly braces and quotation marks)?

A: If you try to change/remove curly brackets in-place, you ruin "Value Relation" concept. Therefore, you should add a new field and use an expression like this:
replace(regexp_replace("LOCATION", '\\{|}|"', ''), ',', ', ')

It removes {, }, " and changes,(comma) to ,  (comma+space). It changes, for example, {"Roots","Branches","Twigs"} to Roots, Branches, Twigs.


text:
Q: why does height and top attribute not work when position is relative? This will position the box a little below the top

Hello World

This will position the box near the top and it looks like neither the height nor top property is
working. The height of the box is not 50%, and the box is not 50% below the top.

Hello World

I am pretty much a beginner at this stuff, but it would seem if left and width work with a percentage shouldn't top and height?

A: Your box can't have a height that's a percentage of its parent if its parent doesn't have a fixed height, because then the box wouldn't know how high it needs to be (typically such a parent would be body or some other wrapper element).
As a direct consequence, top with a percentage won't have any effect either.


text:
Q: Scatter plot with two data sets The following code plots two lines. Instead I need dots without lines:
plt.plot(y1, marker='o', color='b')
plt.plot(y2, marker='o', color='r')
plt.show()

What should I change to get proper result?

A: I would do the following:
plt.plot(y1, marker='o', linestyle=None, color='b')
plt.plot(y2, marker='o', linestyle=None, color='r')
plt.show()

EDIT: the linestyle=None raises an Error. You can use linestyle='' or directly:
plt.plot(y1,'bo')
plt.plot(y2,'ro')
plt.show()

should work.

A: You could use plt.scatter to get a scatter plot.
import matplotlib.pylot as plt

plt.scatter(x, y1)
plt.scatter(x, y2)
plt.show()

You would set x to be a list containing the corresponding x axis values for your series. For instance, if your data start from x=0 and go up by one, you could use x = range(len(y1)) as your x axis series.


text:
Q: Forecast interval for ARIMA and ARIMA-GARCH model with $d\geq 1$ I have a question connected with confidence interval calculation.
So, let's have a ARIMA(p, 1, q)-GARCH(P, Q) model with drift: $\phi(L) \omega(t) = \theta_{0} + \theta(L) \varepsilon(t)$, where $\omega(t) = \Delta x(t)$.
In this case (and cases $d \geq 2$) I can get point forecast $\hat{x}_{l}(t)$ as $\hat{x}_{l}(t) = \sum_{k=1}^{l}\hat{\omega}_{k}(t) + \theta_{0}l + x(t)$. But how should I calculate interval forecast in this case? Could anyone give me an answer or get a link on the good manual?


text:
Q: Stopping Invokation of Spring Quartz Job on spring context loading My application has got multiple Jobs which needs to be executed programatically when user wants.
I have implemented all the Jobs using MethodInvokingJobFactoryBean and the issue is whenever my spring context gets loads up all the Jobs gets fired.
How to stop the execution of Job on spring context loading ??
Thanks in advance
Ajay

A: I assume you have problem because your job calls beans which has not been initialized?
Then you will be interested in depends-on attribute on bean element.
You can also set startupDelay property on SchedulerFactoryBean.


text:
Q: Macbook Pro boots successfully when using hard drive in USB enclosure but doesn't boot when connected internally Apologies for the long question. I will keep it as simple as I can.
Last week my Macbook Pro (13-inch, Mid 2010) started to act strange.
It started when I tried to open Skype and received an error complaining that the program could not start because Skype could not read (or lock, unfortunately I can't remember) it's skype.plist file.
I restarted my Macbook hoping that would fix the problem (and I hadn't restarted in a while so I figured it was overdue).
My Macbook restarted and played the startup chime but then hung at the grey startup screen  with the spinning wheel. I thought nothing of it and did a hard shutdown but no matter how many times I did, the Macbook never advanced past the grey startup screen.
I tried to boot using Safe and Verbose mode and got the following error in both cases:
BootCacheControl : Unable to open /var/db/BootCache.playlist: 22 invalid argument

I googled the error and tried various solutions with no luck.
The Macbook would boot to the built-in Mountain Lion recovery partition.
At this point I decided to backup my data so I could mess with the hard drive a bit more without fear of losing any data. I booted in to the recovery partition and cloned my hard drive onto another using a USB enclosure. It seemed to work OK and I verified all of my files were on the backup hard drive by plugging it into another Macbook.
After cloning my hard drive I verified and repaired the disk and disk permissions using the disk utility in the recovery partition but that had no effect.
At this point I decided to reinstall Mountain Lion. I tried numerous times to reinstall it with the hard drive inside the Macbook (both using the recovery partition and a bootable Mountain Lion SD card) but couldn't get it to install. Eventually I got it to install, but only when the hard drive was placed in a USB enclosure. I knew this probably indicated a bigger underlying problem but decided to go ahead anyway.
I installed Mountain Lion successfully but now it will not boot with the hard drive connected inside the Macbook, only when it is used in my USB enclosure. When the hard drive is placed in my USB enclosure it boots to Mountain Lion without any problem.
With the hard drive inside the Macbook:

*

*If the Macbook is booted as standard, it hangs on the grey startup screen with spinning wheel

*If it is booted in verbose mode, it seems to boot successfully (shows no errors when the white text show up) and then hangs on a black screen with a solid white cursor in the top left corner (I can type at this point but it does nothing, it doesn't appear to be a terminal window)

*If it is booted in safe mode, the progress bar appears, progresses to the end and then hangs on the grey startup screen with spinning wheel

I noticed a lot of suggestions on the internet to replace the hard drive cable to the motherboard. I did and it had no effect.
I've tried using another hard drive running a brand new install of Mountain Lion and that behaves exactly the same (boots fine using a USB enclosure but doesn't boot when connected internally).
I've booked an appointment at the Apple store but figured it was worth posting the question anyway, in case anybody has a similar issue in the future (hopefully I'll be able to post the answer, if nobody else does, after a visit to the Genius bar).
Any suggestions?
Thanks for reading.

A: *

*You have eliminated the possibility of a hardware issue on the hard drive by installing a new hard drive and also by installing the operating system on the previous hard drive via USB.

*You have replaced the cable connecting the internal hard drive to the mother board, so it's not a cable problem.

*The only thing left seems to be the hard drive controller on the motherboard. I expect the Genius bar will recommend replacing the motherboard.
For an older model Mac like yours, it might be worth searching for a replacement motherboard and having a local Mac repair shop swapping it in for you. It might cost less.

A: I took my Macbook to the Apple store. After performing some tests the man at the genius bar agreed with me that it would either be the cable or the motherboard. He said he would replace the cable again (just to make sure the one I installed wasn't defective or installed incorrectly) and if that didn't work, replace the motherboard.
I just received a call saying the Macbook was working after installing a new cable. I guess the cable I installed was defective or installed incorrectly.
I hope no-one ever has a similar problem, but if they do, this is what fixed it for me.

A: I literally unscrewed the cable, rubbed off some dirt and grit and dust, replaced it and SOLVED my issue! Thank you to this vlogger for his video! :) try it before you reinstall, format, or buy a new cable! Vid below:
https://www.youtube.com/watch?v=Amg5w0rlwDo

A: This YouTube video was incredibly helpful, and worked for me:
https://www.youtube.com/watch?v=Amg5w0rlwDo
I'd only add that as I chose to upgrade my HDD to SSD at the same time as fixing this problem using James' technique, I had to re-set the PRAM by starting-up while holding the CMD-OPT-P-R keys down.  Before I did that, the MacBook would boot from the drive connected to USB, but not while installed directly onto the HDD SATA cable.  Once the PRAM was re-set, all works properly (and I'm not even sure I need a new cable).


text:
Q: a Sum that no longer evaluates Backslide introduced in 7.0, fixed after 11.0, in or before 12.3.

At http://forums.wolfram.com/mathgroup/archive/2000/Sep/msg00318.html and http://forums.wolfram.com/mathgroup/archive/1999/Jul/msg00375.html we see an apparently successful evaluation of the expression
Sum[Sin[(n + 1)*Pi] - Sin[n*Pi], {n, 1, Infinity}] + Sin[Pi]

Mma 11 (Win 10) does not successfully evaluate this expression.  One supposes that this is a change in some default (Method?).  Can evaluation still be forced somehow?
I am already aware that Limit accepts domain restriction assumption. My question is about Sum.

A: This works:
Sum[Sin[(n + 1)*Pi] - Sin[n*Pi] && n \[Element] Integers, {n, 1, Infinity}]

0

It appears that one has to specify explicitly the domain of the index of summation.

A: Let me give first a short answer. With only one keyword added you achieve the desired result:
Sum[Sin[(n + 1)*Pi] - Sin[n*Pi], {n, 1, Infinity}, Regularization] + Sin[Pi]

Notice also, that this procedure is well defined mathematically. Pushing the limits leads to paradoxes. Consider the following:
b Sum[ b^n, {n, 0,Infinity}] - (Sum[b^n, {n, 0,Infinity}] -1) // Simplify
(*0*)

Thus we can define $x=\sum_0^\infty b^n$ and write the above formula for, say, $b=2$:
b x - (x - 1) == 0 /. b -> 2
(*1 + x == 0*)

or $x=-1$, which is a rather strange result for the sum of all-positive elements....

A: It appears that we can get the desired result by mapping Simplify (suggested by @Alan)
Sum[Sin[(n + 1)*Pi] - Sin[n*Pi], {n, 1, Infinity}]
MapAt[Simplify, %, {1}]
(* 0 *)

A: The OP's code now works in V12 & V13 (tested in 13.0.1):
Sum[Sin[(n + 1)*Pi] - Sin[n*Pi], {n, 1, Infinity}] + Sin[Pi]
(*  0 *)


text:
Q: How to get rid of thin and small areas in a single larger contour? I am trying to come up with a way to get rid of tinier and smaller details from a single larger contour, that I am able to find in an image.
import cv2
import numpy as np

image_vec = cv2.imread('0000000000.eigo.png', cv2.COLOR_BGR2GRAY)
g_blurred = cv2.GaussianBlur(image_vec, (5, 5), 0)

blurred_float = g_blurred.astype(np.float32) / 255.0
edgeDetector = cv2.ximgproc.createStructuredEdgeDetection("model.yml")
edges = edgeDetector.detectEdges(blurred_float) * 255.0
cv2.imwrite('edge-raw.jpg', edges)

def SaltPepperNoise(edgeImg):
    count = 0
    lastMedian = edgeImg
    median = cv2.medianBlur(edgeImg, 3)
    while not np.array_equal(lastMedian, median):
        zeroed = np.invert(np.logical_and(median, edgeImg))
        edgeImg[zeroed] = 0
        count = count + 1
        if count > 70:
            break
        lastMedian = median
        median = cv2.medianBlur(edgeImg, 3)

edges_ = np.asarray(edges, np.uint8)
SaltPepperNoise(edges_)
cv2.imwrite('edge.jpg', edges_)

#canny edge detection
edges_ = cv2.Canny(edges_, 50, 255)
edges_ = cv2.GaussianBlur(edges_, (5, 5), 0)
cv2.imwrite('edgecanny.png', edges_)

def findSignificantContour(edgeImg):
    contours, hierarchy = cv2.findContours(
        edgeImg,
        cv2.RETR_TREE,
        cv2.CHAIN_APPROX_SIMPLE
    )
        # Find level 1 contours
    level1Meta = []
    for contourIndex, tupl in enumerate(hierarchy[0]):
        # Filter the ones without parent
        if tupl[3] == -1:
            tupl = np.insert(tupl.copy(), 0, [contourIndex])
            level1Meta.append(tupl)
    contoursWithArea = []
    for tupl in level1Meta:
        contourIndex = tupl[0]
        contour = contours[contourIndex]
        area = cv2.contourArea(contour)
        contoursWithArea.append([contour, area, contourIndex])
    contoursWithArea.sort(key=lambda meta: meta[1], reverse=True)
    largestContour = contoursWithArea[0][0]
    return largestContour

contour = findSignificantContour(edges_)
contourImg = np.copy(image_vec)
cv2.drawContours(contourImg, [contour], 0, (0, 255, 0), 2, cv2.LINE_AA, maxLevel=1)
cv2.imwrite('contour.jpg', contourImg)

hh, ww = image_vec.shape[:2]

mask = np.zeros((hh,ww), dtype=np.uint8)
cv2.drawContours(mask, [contour], 0, (255,255,255), cv2.FILLED)

# invert mask so shapes are white on black background
mask_inv = 255 - mask

# create new (blue) background
bckgnd = np.full_like(image_vec, (255,0,0))

# apply mask to image
image_masked = cv2.bitwise_and(image_vec, image_vec, mask=mask)

# apply inverse mask to background
bckgnd_masked = cv2.bitwise_and(bckgnd, bckgnd, mask=mask_inv)

# add together
result = cv2.add(image_masked, bckgnd_masked)

cv2.imwrite("imwrite.png", result)

Input Image:

Output Image:

Desired output:

This happens with all images.
I have tried using erosion and dilation, but that works differently with every image.
I was wondering if there is a way I can find two close pixels that are not connected, forming a branch, then connect those two pixels.
I will have a single huge contour in every image I pass, so there is no question of overlapping or smaller but useful contours.

A: I was able to get rid of 'branch like' tiny and unwanted unwanted areas in a following way:(in reference to the code provided in question)
-All stuff before creating 'findSignificantContour()' remains the same
-After creating 'findSignificantContour()':
# Call findSignificantContour()
# Create a binary image with contour filled as white and rest black
# Perform erosion on the binary image (will mostly get rid of tinier areas without messing up the actual target)
# make a call to 'findSignificantContour()' and get final contour
# Done! Mask the contour however you want


text:
Q: Multidimensional Array to table using jQuery I have a multidimensional array generated using PHP as below:
$result = array(
        array(
            'bookID' => '1',
            'bookName' => 'Book1',
            'bookAuthor' => 'Author1',
            'bookISBN' => 'ISBN1',
            'bookStatus' => 'Available'
        ),
        array(
            'bookID' => '2',
            'bookName' => 'Book2',
            'bookAuthor' => 'Author2',
            'bookISBN' => 'ISBN2',
            'bookStatus' => 'On Loan'
        ),
        array(
            'bookID' => '3',
            'bookName' => 'Book3',
            'bookAuthor' => 'Author3',
            'bookISBN' => 'ISBN3',
            'bookStatus' => 'On Loan'
        ),
        array(
            'bookID' => '4',
            'bookName' => 'Book4',
            'bookAuthor' => 'Author4',
            'bookISBN' => 'ISBN4',
            'bookStatus' => 'Available'
        ),
    );
echo json_encode($result);

And I have a HTML file that is using $.getJSON to get that array. What I am now trying to do is create a table using that array, such that it looks something like this:
+---+-------+---------+-------+-----------+
| 1 | Book1 | Author1 | ISBN1 | Available |
+---+-------+---------+-------+-----------+
| 2 | Book2 | Author2 | ISBN2 | On Loan   |
+---+-------+---------+-------+-----------+
| 3 | Book3 | Author3 | ISBN3 | On Loan   |
+---+-------+---------+-------+-----------+
| 4 | Book4 | Author4 | ISBN4 | Available |
+---+-------+---------+-------+-----------+

I have tried using $.each() and foreach() including suggestions from other SO questions but I cannot seem to get it to work at all. Can anyone help?
My jQuery code at the moment:
$(document).ready(function() {
        // var query = $('#query').val();
        $.getJSON('[url of PHP file above]', function(data){
            // Do something to create table
        });
    });

A: First suppose that your array is stored in $books variable.
$books = json_enconde($books);

Then we have received correctly that array.
$.ajax({
 ...
 success: function(data){
    var $table = $('<table />');
    $.each(data, function(i, item){
        var $tr = $('<tr />');
        $tr.appendTo($table);
        $.each(a, function(subitem) {
            $tr.append('<td>'+ subitem + '</td>');
        });
    }
 }
});

Hope it helps!


text:
Q: select rows in a union based on a third table with proc I want to union the same table this way
ID B C D E
1 11 12 13 14
2 21 22 23 24
3 31 32 33 34

to
ID B C D E
1 11 12 13 14
2 21 22 23 24
3 31 32 33 34
11 13 14
12
21 23 24
22
31 33 34
32

based on the IDs of a third table. (I want to have only those IDs which are present in a third table)
third table
ID
1
3
21
31

I am able to do the union
proc sql ;
create table bb as
select * from first
union
select B, D, E from first
union
select C from first

;
quit;

here is where I am stuck. how to select only those IDs present in a third table.

A: Can't you just use a sub-query?
proc sql ;
  create table want as
     select B.*
     from
        (select * from first
         union
         select B, D, E from first
         union
         select C from first
        ) B
     inner join THIRD c on B.id = C.id
  ;
quit;

Plug whatever logic makes the second table inside the ().

A: You want to union FIRST and SECOND and then join to THIRD, or alternately join THIRD to both FIRST and SECOND; it's unclear if the SQL optimizer will do the latter for you if you do the first.
proc sql;
  create table want as
  select *
  from (
    select id,B,D,E
    from first
    union
    select id,B,D,E
    from second
  ) U
  right join
  select id
  from third
  on U.id=third.id
;
quit;


text:
Q: Convertir Labels a Inputs conservando Valor me gustaría saber como, dentro de una tabla puedo cambiar los labels de un tr en concreto (con varios td, cada uno con su label) , sin eliminar la tabla y conservando el valor de los labels.
-He estado probando con innerHTML, pero me remplaza la tabla...

  Label Ejemplo
  <button type="button" onclick="change();">Cambiar a input</button>

  Label Ejemplo1
  <button type="button" onclick="change();">Cambiar a input</button>

  Label Ejemplo2
  <button type="button" onclick="change();">Cambiar a input</button>

A: Puedes guardar el valor del label en una variable al hacer click en el botón y cambiar todo el contenido del td por un input con esa variable.

      Label Ejemplo

     <button type="button" onclick="change();">Cambiar a input</button>

A tu table le falta la etiqueta cerrar, tenlo en cuenta o te dará errores.
Como no sé si tienes o no más código o cómo es este, he cogido los tags con querySelector pero puedes usar id o class para que no tener problemas:
function change() {
var valor = document.querySelector("label").innerHTML;

document.querySelector("td").innerHTML = '<input type="text" value="' + valor + '"/>';
}


text:
Q: Binding different this scope to ES6 => function operator After experimenting with inheriting contexts with the => feature that ES6 gives us I noticed that the this context can never be changed.
Example:
var otherContext = {
  a: 2
};
function foo() {
  this.a = 1;

  this.bar = () => this.a;

}

var instance = new foo;
instance.bar(); // returns 1
instance.bar.bind(otherContext)(); // returns 1

Without the => operator and using the function keyword:
function foo() {
  this.a = 1;

  this.bar = function () {
    return this.a;
  }
}
var instance = new foo;
instance.bar(); // returns 1
instance.bar.bind(otherContext)(); // returns 2

Therefore, if we receive a function from an external call or just have a function in a variable, how can we be sure if we are going to be able to bind a different this to it or if it will just inherit it from somewhere?
It sounds dangerous that javascript does not tell you anything, one might fall for a VERY subtle and difficult bug.

A: When using the function keyword, the rules binding this are fairly straight forward.
Either the invoking call sets this (be it through .call, .apply or JavaScript setting this when the function is called as a method) or this gets a well-known value:

*

*In normal mode, this will be the window object.

*In strict mode, this will be undefined.

With arrow functions, the rule is even simpler.

*

*There is no this keyword.  (nor arguments, or a few others)

Which means that, inside an arrow function, this is always bound to the outside context, because that is where this comes from.
So, in summary:
When using arrow functions, the value of this always comes from the outside context.

A: It is effectively just new syntax for bind, so this doesn't introduce anything new in the way of gotchas.

var otherContext = {
  a: 2
};
function foo() {
  this.a = 1;
  this.bar = function () { return this.a }.bind(this);
}

var instance = new foo;
log(instance.bar()); // returns 1
log(instance.bar.bind(otherContext)()); // returns 1

function log(value) {
  document.body.appendChild(
    document.createTextNode(value)
  );
}

Therefore, if we receive a function from an external call or just have a function in a variable, how can we be sure if we are going to be able to bind a different this to it or if it will just inherit it from somewhere?

Because either:

*

*You'll have written that function in the first place or

*You'll have written a specification for how to call your function so that people know to pass in a function which makes use of this from a context you choose.


text:
Q: Porting Multiple Inheritance C++ Code to Java I created a library that extends off of another library written in C++, and now I'm porting this library over to Java (the original library that the C++ was written on top of already exists in Java). In the C++ code there is a purely virtual class called Stallable that is supposed to be used in order to add stall detection to a motor controller given a delta in voltage input. The class contains a purely virtual method getVoltage() which is used to supply a voltage source as they're several different motor controller classes, and some virtual functions to determine if there is a stall.
Classes would subclass this class, as well as a class from the original library (one that I do not have access to the code and for all intents and purposes otherwise can't modify), and would implement getVoltage(), and override any other methods that they might like. Then these objects can just be asked if there is a stall.
When I approach this problem from the Java side of things, my situation becomes a bit more tricky. I still can not touch the original class so refactoring the code is not an option, and users of my library should still be allowed to subclass or implement Stallable however they see fit.
Currently, the prospectives I see are as follows.

*

*Make Stallable an interface and reimplement the stall detection logic it uses. In order to create the original functionality that the C++ codebase has I'd have to have classes subclass the original library and implement Stallable. This would work but would require the logic in the original purely virtual C++ Stallable to be reimplemented among any subclasses that I'd include, and any subclasses that end users would write.

*Make Stallable an abstract class that holds an object reference to a motor controller class from the original library. This preserves some of the functionality from the C++ code such that some methods would have to be overridden, and some are optionally overridden, however transparency is lost between this code and the C++ code. In C++, Since every subclass was a Stallable and a derivation off of the original motor controller, it became easy to toss pointers around to the object when the motor controller was needed, and when a Stallable object was needed. In this case, some type of accessor function would have to be implemented that returns a Java reference to the original motor controller that each Stallable subclass would hold on to. Transparency would be lost, but stall detection would easily be added.

Obviously if I could modify the original classes for the various motor controllers this problem could easily be a matter of refactoring C++ code.
After researching the disparities between both languages' approach to OOP, I'm inclined to go with option 2 despite the friction it adds for my end users and the Stallable implementations I plan on including. I was asking if there was any other better ideas or insight before I start writing Stallable.java.

A: So basically what you want is that Java users of your lib to be able to implement an interface and behavior will be carried with it? That sounds like a job for AOP (Aspect Oriented Programming). With AOP (AspectJ, for instance) you can inject methods to classes that match certain criteria.
In your case, the criteria is "implementing the Stallable interface". The problem with AOP is that it is invasive. Your users will need to compile their classes using AOP or add AOP to their classpath if you opt to have runtime weaving.
Another option is to try to do some delegations using dynamic proxies.
Finally, you can try using bytecode manipulation http://asm.ow2.org/ in order to generate classes at run time.
Perhaps my answer can be less vague if you write a sample of how the Java code should look like.


text:
Q: Atoms of regular Borel measure  Let $X$ be locally compact Hausdorff space. Let $\mu$ be a Borel measure on it which is finite on compact and outer regular with respect to open sets and inner regular with respect to compact sets. Does an atom of such measure have to be a singleton (up to set of zero measure)?

A: Without loss of generality your atom $A$ is compact (by inner regularity). Call a point $a\in A$ negligible if it has a neighborhood with zero measure inside $A$. Clearly the set $B$ of negligible points is open in $A$. If it is $A$ itself, then choose finite subcovering by those neighborhoods to get that measure of $A$ is zero. So, $A\setminus B=C$ is a non-empty compact set in $A$. It has either measure 0 or measure equal to $|A|$ (let $|\cdot|$ denote measure.) If $|C|=0$, then choose a neighborhood $V$ of $C$ with measure at most $|A|/2$ by outer regularity. $V\cap A$ has measure strictly less then $|A|$, hence 0, hence each point of $C$ is negligible. A contradiction. So $|C|=|A|$. Then replace $A$ for $C$ and we get an atom $C$ in each no point is negligible. It may contain only one point, else take two points $u$, $v$ and their disjoint neighborhoods. Both must have positive measure in $C$, a contradiction.


text:
Q: How to structure mongoose schema within a schema? I'm new to mongodb and I have a data model like such
{
    last_updated: Date.now(),
    csgo_items:[
        {name: 'name', price: 1},
        {name: 'name', price: 1},
        {name: 'name', price: 1}
    ]
}

I have a 'last_updated' and then a giant list of csgo items I store.
My question is. Do I need two schemas? One for the two properties on the outer layer and one schema for my csgo item model?
How would my schemas look if I did it this way?
I have my item schema like such.
var ItemSchema = new Schema({
    price: Number,
    name: String,
});

Do I also need another schema to set for my outer schema like so?
var CsgoSchema = new Schema({
    last_updated: Date,
    item: Array,
});

Is this correct?

A: Since you have defined your item schemas as
var ItemSchema = new Schema({
    price: Number,
    name: String
});

which has elements of the parent document items array, you can define the parent schema as
var CsgoSchema = new Schema({
    last_updated: Date,
    items: [ItemSchema]
});

When you want to add the items to the parent document array, you don't have to save each item individually first before adding it to the Csgo model, this is done whenever the top-level parent document is saved, for example
var Csgo = mongoose.model('Csgo', CsgoSchema);
var csgo = new Csgo({
    last_updated: new Date(),
    items: [
        {name: 'name1', price: 1},
        {name: 'name2', price: 2},
        {name: 'name3', price: 3}
    ]
});

csgo.save(function (err) {
    if (err) return handleError(err)
    console.log('Success!');
});

You can also use MongooseArray methods such as push, unshift, addToSet to add the items to the parent document. For instance:
var Csgo = mongoose.model('Csgo', CsgoSchema);
var csgo = new Csgo;

// add an item using push
csgo.items.push({name: 'name4', price: 4});
var csgo_item = csgo.items[0];
console.log(csgo_item); // { _id: '56e2bc9f61fb33583128be07', name: 'name4', price: 4 }
csgo_item.isNew; // true

csgo.save(function (err) {
    if (err) return handleError(err)
    console.log('Success!');
});

You can also use the create method of MongooseArrays to add the items to the csgo document:.
var newcsgo = csgo.items.create({name: 'name', price: 1});


text:
Q: How to save byte[] in c# application settings I am trying to save a byte array (byte[]) in c# application settings that is returned by Object List View.
Can anyone give me a solution on how to save byte array in c# application settings?
or some trick on how to convert byte[] to something like a string then store, then retrieve and again convert it to byte array and give it back to object list view.

A: The canonical way to do this is to convert the byte[] to a string via base64 and the other way round.

A: One of the most common ways to make a string from an array of bytes is encoding them in Base-64:
string encoded = System.Convert.ToBase64String(toEncodeAsBytes);

Use
byte[] bytes = System.Convert.FromBase64String(encoded);

to get your bytes back.

A: By Different way you can convert Byte array to string and string to byte array. Like this :
1)
string asciiString = ASCIIEncoding.ASCII.GetString(byteArray);

byte[] byte = ASCIIEncoding.ASCII.GetBytes(asciiString);

2)
string base64String = System.Convert.ToBase64String(byteArray);

byte[] byte = System.Convert.FromBase64String(base64String);

3)
string utf8String = System.Text.Encoding.UTF8.GetString(byteArray);

byte[] byte = System.Text.Encoding.UTF8.GetBytes(utf8String);

you can also use System.Text.Encoding.BigEndianUnicode, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF32 for converting Byte Array  to string and string to Byte Array.
Hope, It should help you.


text:
Q: Potential Energy of a string (Wave Equation PDEs) This may turn out to be an elementary question, but I'm having trouble understanding where this actually comes from.
In my PDEs course, we're learning about the wave equation. We're given the following problem on our current homework set.

Consider a taught string $0 ≤ x ≤ L$ with constant density $\rho$ and constant tension $T$ whose vertical displacement at time $t$ and position $x$ is described by the function $u(x, t)$.
(a) Write down the integral representing the total kinetic energy in the segment $a ≤ x ≤ b$.
(b) Write a formula for the total potential energy in the segment $a ≤ x ≤ b$ assuming that the potential energy is proportional to the difference between the length of the stretched string on the interval $[a, b]$ and the equilibrium length of the string on the interval $[a, b]$, and explain using dimensional analysis why the constant of proportionality is the tension.
(c) Approximate the square root in your answer to (b) using Taylor's theorem.
(d) Derive the wave equation from conservation of energy.

My question is regarding part (b).  I've found a source online that says that
$$ dl = \sqrt{dx^2 + dy^2} - dx \approx \frac{1}{2} (\frac{\partial y}{\partial x})^2 dx $$
I understand that the change in length of the string is represented by its magnitude minus the change in position, i.e.
$$ dl = \sqrt{dx^2 + dy^2} - dx $$
But, I'm having trouble showing its equivalence to
$$ \frac{1}{2} (\frac{\partial y}{\partial x})^2 dx $$
My attempt at it is
$$ \sqrt{dx^2 + dy^2} - dx = \sqrt { 1 + (\frac{dy}{dx})^2 } dx -dx \neq \frac{1}{2} (\frac{\partial y}{\partial x})^2 dx $$
Any help towards the correct answer would be appreciated. I understand why you multiply by $T$ to get the potential energy, it's just showing the work up until that point.
Thank you.

A: Just use the approximation
$$
(1 + x)^p \approx 1 + px
$$
for $x \ll 1$. From this
$$
\sqrt{dx^2 + dy^2} - dx = dx\sqrt{1 + \left(\frac{\partial y}{\partial x} \right)^2} - dx \approx dx\left[ 1 + \frac{1}{2}\left(\frac{\partial y}{\partial x} \right)^2\right] - dx = \frac{1}{2}\left(\frac{\partial y}{\partial x} \right)^2dx
$$


text:
Q: Inserting the subdomain from current URL into PHP Hi all this is my first question, and it might be that Im currently over confusing matters.... I have got a database config file which specifies the SQL database that is used. What I want to do is make it so that the database name is the same as the subdomain. Thus meaning that the same php can be used to access different databases. If you get me. Any help greatly appreciated.
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'databaseserver',
    'username' => 'admin',
    'password' => 'password',
    'database' => 'subdomain',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


text:
Q: C++ function to return comparator-generic map type based on parameter? I assume I can use template magic to accomplish this, but I'm not sure how?
std::map<int,int,std::less> forward_map;
std::map<int,int,std::greater> reverse_map;

?? choose(bool forward)
{
    return forward_map ? forward : reverse_map;
}

A: You're not going to be able to use the ternary operator as the expression must return the same type on both sides of the :.  You also cannot have a function that returns different things on different paths unless they are co-variant which these are not.
Now what you can do is use a non type template and use a bool type and then specialize that template for true and false.  This will allows you to have different return types with the same function name.  Doing that would give you
template <bool forward> auto make_map();
template <> auto make_map<true>() { return std::map<int,int,std::less<int>>{}; }
template <> auto make_map<false>() { return std::map<int,int,std::greater<int>>{}; }

And you would use it like
int main()
{
    auto map = make_map<true>();
    auto reverse_map = make_map<false>();
}

The only issue with this is the template parameter must be known at compile time.

A: You cannot return different types from the same function. Use an higher-order function instead:
template <typename TF>
decltype(auto) choose(bool forward, TF&& f)
{
    return forward ? f(forward_map) : f(reverse_map);
}

Example:
choose(true,  [](auto& m){ /* `m` here is a `forward_map` */ });
choose(false, [](auto& m){ /* `m` here is a `reverse_map` */ });


text:
Q: How can I get the current_user from Devise in Rails for JS use I'm trying to figure out the best way to get the current_users username and id from devise in rails without having to store it in the DOM for later access.  Are there any techniques/strategies to accomplish this?

A: While Rails is just the backend on your server and javascript is the frontend on client-side you defenitely need to put something inside html or ajax it.
a few approaches:
1.
just write it into the body with an data attribute
<body data-username="<%= current_user.username %>

2.
making an ajax call to the server to receive that information (pseudocode)
$.ready() {
  $.getJSON(/api/user-information, function(data) {
    username = data.username
    settings = data.settings
    unread_messages = data.unread_messages_count
  }
}
# /api/user-information
def user_info
  render json: {username: current_user.name, settings: {enabled: false, wants_chat: true}, unread_messages: 10}
end

or 3. maybe this gem is helping you
https://github.com/kbparagua/paloma
if you need that information to make some ajax-calls on certain urls or whatever - i always would go with solution #1. thats why data-attributes exist in HTML5


text:
Q: How to insert multiple checkbox values into firebase using vue js I've a form that contains a textarea and a table with a list of many members (from a collection named Members). Each table's  contain two checboxes: one to mark the presence of the member and the second one to mark his payment. After clicking on the submit button I'd like to have in my firebase database something like this:

*

*Meeting collection:
associationId,
textareaValue,
createdAd

*Presence collection:
memberId,
meetingId,
present: true or false,
createAt

*Payment collection:
memberId,
meetingId,
payment: true or false,
createAt
<form @submit.prevent="handleSubmitNewMeeting">

Entrer le sujet principal de la réunion

                                            <textarea class="form-control" v-model="subjects" required rows="3"></textarea>

                                                <button @click="showForm=false" class="btn btn-danger" style="width: 100%">
                                                    Annuler
                                                </button>

                                                <button
                                                    type="button" class="btn btn-outline-secondary" @click="showFormPart2=true;
                                                    showFormPart1=false;">
                                                    Suivant
                                                </button>

Cocher les présences et payements

                                                        Nom
                                                        Prénom
                                                        Téléphone
                                                        Présence
                                                        Payment

                                                        {{ member.memberFirstname }}
                                                        {{ member.memberLastname }}
                                                        {{ member.memberPhoneNumber }}

                                                                <input type="checkbox" class="default" v-model="present">

                                                                <input type="checkbox" class="default" v-model="payment">

                                                    <button
                                                        type="button" class="btn btn-outline-secondary" @click="showFormPart2=false;
                                                        showFormPart1=true;">
                                                        Précédent
                                                    </button>

                                                    <button class="btn btn-secondary"> Valider </button>

                            </form>

How to do these with firebase using Vue Js please ? thanks !


text:
Q: CMake Error Using GLFW and GLAD: Found Relative Path While Evaluating Link Directories I have been attempting to play around with C and OpenGL and am currently attempting to write a simple Snake program using these two libraries.  Although I am on Windows, I prefer not to use Visual Studio and so am currently building my project with CMake (cross-platform compatibility, more general tool, VS is enormous, etc.)  I am running into an issue wherein CMake is refusing to build my project giving the following error message:

CMake Error in CMakeLists.txt:
Found relative path while evaluating link directories of "snake":
"Release"

Despite poking around the internet, I could not run into anyone who had a similar problem.  Here is my CMakeLists.txt.
cmake_minimum_required(
    VERSION 3.20.0
)

project(snake)

set(SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src")
set(LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor")
set(SOURCES "${SRC_DIR}/main.c" "${SRC_DIR}/queue.c" "${SRC_DIR}/game.c" "${SRC_DIR}/draw.c")

add_executable(${PROJECT_NAME} ${SOURCES})

# GLFW
set(GLFW_DIR "${LIB_DIR}/glfw")
set(GLFW_BUILD_EXAMPLES OFF CACHE INTERNAL "Build the GLFW example programs")
set(GLFW_BUILD_TESTS OFF CACHE INTERNAL "Build the GLFW test programs")
set(GLFW_BUILD_DOCS OFF CACHE INTERNAL "Build the GLFW documentation")
set(GLFW_INSTALL OFF CACHE INTERNAL "Generate installation target")

add_subdirectory(${GLFW_DIR})
target_link_directories(${PROJECT_NAME} PRIVATE
    "${CMAKE_CURRENT_BINARY_DIR}/vendor/glfw/src/${CMAKE_CONFIGURATION_TYPES}")
target_link_libraries(${PROJECT_NAME} glfw3 opengl32)
target_include_directories(${PROJECT_NAME} PRIVATE "${GLFW_DIR}/include")
target_compile_definitions(${PROJECT_NAME} PRIVATE "GLFW_INCLUDE_NONE")

# GLAD
set(GLAD_DIR "${LIB_DIR}/glad")
add_library(glad "${GLAD_DIR}/src/glad.c")
target_include_directories(glad PRIVATE "${GLAD_DIR}/include")
target_include_directories(${PROJECT_NAME} PRIVATE "${GLAD_DIR}/include")
target_link_libraries(${PROJECT_NAME} glad ${CMAKE_DL_LIBS})

This approach was working for me before but then suddenly stopped.  The build command I am using is:
cmake -S . -B out

where . is the directory my CMakeLists.txt is in.  I have checked to make sure all of the libraries are where they are supposed to be and that all my source files are loading correctly.
What do I need to do the fix this issue?  Thanks so much!


text:
Q: Redirect joomla url's to wordpress I moved an ex-site based on joomla to wordpress. Import worked fine but the problem is that the old links don't work anymore.
Because there is only 50 or so articles, i thought will be a good idea to put a rule for each post (in .htaccess).
Well... Not always things are like you want, so redirects dont work at all :(
Old joomla links looks like this:
http://site.com/index.php?option=com_content&task=view&id=49&Itemid=29
http://site.com/index.php?option=com_content&task=view&id=42&Itemid=29
http://site.com/index.php?option=com_content&task=view&id=68&Itemid=29

And need to be translated to:
http://site.com/?p=23
http://site.com/?p=24
http://site.com/?p=25

*

*basically no relations between old and new links, so i don't think a regex will help

*both old and new site are on the same domain
Ok, the problem is that any rule i've tried (and i tried a LOT!), none worked. in few cases i get 500 error, but most of times the redirect didn't work.
So, any of you guys had same problem? I don't necessary want to have nice permalinks, but if i can, that will be better. The problem is that i have many backlinks to old url's and i don't want to loose them.
Thanks a lot guys!

A: Since the conversion of your site over to Wordpress is relatively new, is there anything preventing you from using the old Joomla! ID's in your WP database table? This would allow you to use a regex fairly easily.
Another option would be to create a separate PHP script that handles the Joomla! URLs then redirects to the Wordpress ones. So you would have a regex in your Apache configuration detecting index.php?option=com_content&task=view URLs, finding the value for 'id', then redirecting to someotherscript.php that would have a map of your ids from Joomla! to Wordpress. This script would then use header('Location: ?p=' . $id) to redirect to the correct page in Wordpress.

A: Thnaks for the idea! I put this in index.php (wordpres default):
if(isset($_GET['option'])) {
    if(is_numeric($_GET['id'])){
        header ('HTTP/1.1 301 Moved Permanently');
        header("Location: http://www.site.com/?p={$_GET['id']}");
        die();
    }else {
        die('Hacking attempt');
    }
}

And works like... GREAT! :D

A: Another option might have been to use a redirection plugin to do this for you. Saves the solution breaking each time you change or update your theme.

A: I had a very similar issue with some unknown CMS to Joomla.
If you want to do it with .htaccess in Apache there is a way, but if there is absolute no relation between the old URL and the new URL than you have to write two lines for each URL pair.
RewriteEngine On
# now the first Example
RewriteCond %{QUERY_STRING} ^option=com_content&task=view&id=49&Itemid=29$
RewriteRule ^index\.php$ /?p=23 [R=301,L]
# Repeat last two lines for all your URLs

I'm not sure if you really have this kind of new URLs. Personally a SEF URL would be better e.g.: https://example.com/path/to/new/page
If you want to do this than you can do it, but you have to add a ? at the end of the destination otherwise the old Query string would be added to you new destination like this: https://example.com/path/to/new/page?option=com_content&task=view&id=49&Itemid=29
so for this example do it as follows:
RewriteCond %{QUERY_STRING} ^option=com_content&task=view&id=49&Itemid=29$
RewriteRule ^index\.php$ /path/to/new/page? [R=301,L]


text:
Q: Transform values from 1 column to multiple columns I have the following table:

and would like to convert the product column to something like:

How would you recomend I do this in pandas? Test df below
import numpy as np
import pandas as pd

test_dict = {'Acount': ['1', '2', '3', '4'], 'Product': [np.nan, 'A','A,B,C', 'C']}
df = pd.DataFrame.from_dict(test_dict)

A: For a single column you can use Series.str.get_dummies which allows you to specify the character that separates all categories. Set 'Acount' to the index so that appears in the output:
df.set_index('Acount')['Product'].str.get_dummies(sep=',')

        A  B  C
Acount
1       0  0  0
2       1  0  0
3       1  1  1
4       0  0  1

A: Let's use .str.split, explode and pd.crosstab:
df_count = df.assign(Product=df['Product'].str.split(',')).explode('Product')
pd.crosstab(df_count['Acount'], df_count['Product']).reindex(df['Acount'].unique(), fill_value=0)

Output:
Product  A  B  C
Acount
1        0  0  0
2        1  0  0
3        1  1  1
4        0  0  1

Details
Let's assign 'Product' as a list of elements using .str.split on commas.
Next, use explode to unnest the list in the 'Product' column.
Now, use pd.crosstab to count the occurrence for each value by 'Acount'.
Lastly, reindex to fill missing 'Acount' not present in crosstab.


text:
Q: How to use BundleConfig in WebSite project ok, that maybe a old question, but i really dont know how to use BundleConfig in website project.
not the webform project or mvc project.
i debug the code. it call the BundleConfig's add  method.
but it not work. something wrong?
this is my code:
add Global.asax in Root
add BundleConfig.RegisterBundles(BundleTable.Bundles) in Application_Start
add BundleConfig.vb class in App_Code
Public Class BundleConfig
    Public Shared Sub RegisterBundles(ByVal bundles As BundleCollection)
        bundles.Add(New StyleBundle("~/Content/css").Include("~/Content/site.css"))
    End Sub
End Class

add Default.aspx
add Content/site.css file.
and something?
OK, i knew what is happend.
i put my css file in Content/css/ folder.
this line:
bundles.Add(New StyleBundle("~/Content/css").Include("~/Content/css/site.css"))

so it not work.
and i change it to
bundles.Add(New StyleBundle("~/whatever/css").Include("~/Content/css/site.css"))

done.

A: Try registering the bundles in your Global.asax file by adding this line of code:
BundleConfig.RegisterBundles(BundleTable.Bundles);

Examine the Bundle.config file, which contains the markup to create CSS style bundles. You can add your own style bundles. e.g:
<?xml version="1.0" encoding="utf-8" ?>
<bundles version="1.0">
<styleBundle path="~/Content/css"><include path="~/Content/Site.css" /></styleBundle>
</bundles>

Now reference it in your page using:
<webopt:BundleReference runat="server" Path="~/Content/css" />


text:
Q: ¿Cómo relacionar las opciones de un 'select' con las opciones de otro? Tengo un formulario para un sistema de reserva de moteles, en un primer select se debe elegir el motel y en El Segundo el tipo de habitación, pero no todos los moteles tienen el mismo tipo de habitación.
Necesitaría que al seleccionar el motel 1, me muestre los tipos de habitación de ese motel y así sucesivamente.
¡Gracias!
    <form action="reserva.php" method="post">

          Elige el motel
          <select class="cs-select cs-skin-border" id="motel" name="motel" required>
            <option value="0" selected>Selecciona una opción...</option>
            <option value="Ibiza">Ibiza</option>
            <option value="Carpe" >Carpe Diem Barrio Abajo</option>
          </select>

A: Utiliza jquery ó javascript para obtener el valor del primer select y depues creas un método con el onchange del primer select para que al cambiar de valor este sea notificado y realice una operación.
$('#select1').on('change',function(){
 var valueSelectUno=document.getElementById('selectUno').value;
 //ejemplo de uso
if(valueSelectUno===1){
   //cargar datos en otro select
}else{
   //otra opción
}
});

Aunque en lo personal te recomiendo que brindes más información de tu proyecto por sobre todo si estas trabajando con base de datos ya que también es importante.

A: Lo que puede servirte es tener una lista de habitaciones predeterminada para cada hotel y con el evento change cambias las opciones del select dependiendo la opcion que sea seleccionada en el select hotel, te dejo un codigo de ejemplo que espero pueda ayudarte

<form action="" method="post">

   Elige el motel:
   <select class="cs-select cs-skin-border" id="motel" name="motel" required>
    <option value="0" selected>Selecciona una opción...</option>
    <option value="Ibiza">Ibiza</option>
    <option value="Carpe" >Carpe Diem Barrio Abajo</option>
  </select>

 Elige el Habitacion :
 <select class="cs-select cs-skin-border" id="Habitacion" name="Habitacion" required>
  <option value="0" selected>Selecciona una opción...</option>
 </select>

A: Puedes hacerlo con la propiedad class y data.
Ejemplo:

function h(){
opt = document.getElementsByClassName("hALL");
 for (i=0; i<opt.length; i++) {
 opt[i].style.display = "none";
 }

e = document.getElementById("hotel")
e = e[e.selectedIndex].dataset.hab.split(" ");
for (x=0;x<e.length;x++){
 opt = document.getElementsByClassName(e[x]);
  if (opt.length) {
   for (i=0; i<opt.length; i++) {
    opt[i].style.display = "";
   }
  }
 }
}
h("");
Seleccione Hotel:

<select id="hotel" onchange="h()">
 <option data-hab=""></option>
 <option data-hab="h1">Hotel A </option>
 <option data-hab="h1 h2" >Hotel B </option>
 <option data-hab="h1 h2 h3">Hotel C </option>
</select>

Numero de Habitaciones:

<select>
 <option></option>
 <option class="hALL h1">1 habitaciones</option>
 <option class="hALL h2">2 habitaciones</option>
 <option class="hALL h3">3 habitaciones</option>
</select>


text:
Q: Bash scripting and rsync: how to include just some folders and subfolders and what happends if I use ../ as path with --delete I have a bash script where I'm trying to copy some folders and archives in local with rsync. I have something like this:
RootFolder
  A
  B
  C
  D
     D1
     D2
     D3
     .
     .
     .
     DN
  E
  F

What I want/do:

*

*Clean the Destiny Folder before start which I do with option --delete

*Exclude some type of archives which I do with option --exclude.

*Exclude some folders which I do with option --exclude.

So until here I will have a copy Folders A, B, D and E.
But now I need to copy Only some subfolders in D and the list will change according to a list.
So Imagine I want:
 A
 B
 D
   D2
   D4
   D8
 E

I don't know how to do it as I've tried with --include but I'm doing something wrong.
I'm doing something like:
 rsync -av --delete --include=/D/D2 --include=/D/D4 --include=D8 --exclude=/C --exclude=/F RootFolder/ DestinyFolder

But It doesn't work well..... I've thought about doing some iterations or maybe I don't know if I could put all thee includes in a variable and pass it to rsync.
I have another doubt which is: As I get the destination Folder by param, what happens if the user uses "../" and I have the --delete option?? Will it delete the current folder? And if user just writes "/" will it delete everything?
Edit:
Having:
RootFolder
  A
     File.txt
     .HidenFile
  B
  C
  D
     D1
     D2
       File.txt
       .HidenFile
     D3
     .
     .
     .
     DN
  E
  F

I have something like
rsync -av --delete  --include=/D/D2 --include=/D/D4 --include=D8 --exclude=*.txt  --exclude=.* --exclude=/C --exclude=/F RootFolder/ DestinyFolder

A: The options for --include and --exclude are applied from left to right. The first options are always the strongest, so you can end a list with --exclude='*/' to stop any further processing of directories.
Once you use --exclude='*/' though, you will disable implicit processing of all files and directories, and you will need to state explicitly which files and folders to include.

*

*You want to include A, B, and E with all their files and folders,

*You want D and its files but not directories,

*You want D/D2, D/D4, /D/D8 and all their files and folders,

*Nothing else.

We can therefore construct the include/exclude statements like this
rsync --dry-run -av --delete

    --include '/A' --include '/A/**'
    --include '/B' --include '/B/**'
    --include '/E' --include '/E/**'

    --include '/D'

    --include '/D/D2' --include '/D/D2/**'
    --include '/D/D4' --include '/D/D4/**'
    --include '/D/D8' --include '/D/D8/**'

    -exclude '*/'

    src/ dst/

Since you are using bash, which is a shell that can handle arrays, you can build up the set of --include instructions safely. Here's an example:
# It's an array
includes=()

# Start with the fixed set of known directories
for known in A B E
do
    includes+=('--include' "/$known" '--include' "/$known/**")
done

# Special case
includes+=('--include' '/D')

# Now the changeable set of subdirectories. You might get this list elsewhere
for subdirs in D2 D4 D8
do
    includes+=('--include' "/D/$subdir" '--include' "/D/$subdir/**")
done

# Put it all together
rsync --dry-run -av "${includes[@]}" --exclude '*/' src/ dst/


text: Q: Split excel row values into multiple rows when specific column value has comma in python I have a Excel data with 5 columns and one of the column(say column 5th) has multiple values with comma separated(Say column 5th first row has values "A,B,C"). I would to check each rows in excel and write a separate entry for each values in excel file using openpyxl(expected output would be, 3 rows in excel now and column 5th 1st row value = A, column 5th 2nd row value = B, etc).


text:
Q: Cookies with string containing ; So I'm using cookies for my website (big surprise ;-) ), but what might be surprising is that I for some reason (don't ask me why) store some css style values in the cookie, which is all fine and dandy until you add a ; in there which is not supposed to be there.
So the cookie I've stored looks like this:
token=9d133691-a955-4980-bf1d-9492d3c64026;
user=2601;
config=JSON"{
    "socketAddress":"string",
    ...
    bunch more values
    ...
    "views":[{
        "showInMenu":true,
        "route":"Opgave Liste",
        "routeParameters":{"afdeling":true},
        "viewFunctions":{
            "itemList":{
                "css":{
                    "class":"bold",
                    "conditional":{
                        "condition":"[REG.TASK] === 'off'",
                        "false":{
                            "style":"background:red;"
                        }
                    }
                }
            }
        }
    }]
}";

and the way I get the cookie is like this:
    <script>
        function readCookie(){
            var cookie = document.cookie;
            console.info('base cookie : ', cookie);
        }
        readCookie();
    </script>

the result i get is the right cookie, it however is cut right after background:red. As I mentioned earlier I know why, my question is, is there a way to prevent this and still have the ; in the string. is there some kind of escape character like you have in string: ie. \"?

A: Try using encodeURIComponent(css) before doing the JSON stringification, and then using decodeURIComponent in order to get the real value.
For example:
{
    "style": encodeURIComponent("background:red;")
}

(You can/should automate this process with utility functions).


text:
Q: Using sizeof operator on structures Why does the sizeof operator when used on structures always gives different number of bytes
than actually used by the structure to store the data(what i expect)?

A: It doesn't always do that. It depends on the packing of the structure by the compiler. Paking depends upon the alignment rules of the architecture.

A: From THIS post

This is because of structure alignment. Structure alignment refers to
  the ability of the compiler to insert unused memory into a structure
  so that data members are optimally aligned for better performance.
  Many processors perform best when fundamental data types are stored at
  byte-addresses that are multiples of their sizes.
One can minimize the size of structures by putting the largest data types at the beginning of the structure and the smallest data types at the end of the structure


text:
Q: document scroll doesn't work in IE Neither this script:
$(window).scroll(function() {
    alert("works");
})

nor this:
$(document).scroll(function() {
    alert("works");
})

works in IE 8 and earlier.
I don't know why, could somebody help?

A: Mainly three things you should see
1.If you have given style as
overflow:hidden

2.If you have given height in page percentage.
3.if you have given float:static.
Fix this issue your IE 8 problem will be solved.
Reason :
IE 8 is different than nything else for CBC check IE frist! To the topic, IE 8 hides (only scrolling bar) of scroll bar if you have overflow as hidden, secoundly if you have places hight as 100% IE 8 takes overflow as hidden (can say takes by its own!) n float is element who can go beyond page size if you have it as inherit or relative but static dose not increase dynamicly.
Hope this helps...

A: Create jsfiddle and check it in browserstack:

*

*IE8 - window scroll works

*IE7 - window scroll works

Check what you don't have javascript errors on page.


text:
Q: pthread semaphore display nothing on linux I'm new to linux thread semaphore.
There is no error, no warning, and result output.
What cause this happen?
I suspect semaphore is blocked or infinite loop.
Anyone can see logic incorrect in some place?
initialise sem vlaue : bin_sem = 0, pile_sem = 0, fuel_sem = 0
sem_t bin_sem, pile_sem, fuel_sem;

int pile=0, fuel=0, wantedMineralVal=3, foundMineral=-1;

int isFound(void){
    srand(time(NULL));
    return (rand()%8+1);
}

void checkResource(){
    if(fuel!=0 && pile!=0)
        sem_post(&bin_sem);
}

void *deliverFuel(void *args){
    while(foundMineral!=wantedMineralVal){
        sem_wait(&fuel_sem);
        fuel+=24;
        checkResource();
    }
}

void *deliverPile(void *args){
    while(foundMineral!=wantedMineralVal){
        sem_wait(&pile_sem);
        pile+=12;
        checkResource();
    }
}

void *drilling(void *args){
    do{
        foundMineral =  isFound();
        if(pile == 0 || fuel==0){
            sem_post(&pile_sem);
            sem_post(&fuel_sem);
            sem_wait(&bin_sem);
        }

    pile-=2;
    fuel-=4;

    }while(foundMineral!=wantedMineralVal);

}


text:
Q: How to determine minimum sample size for Bernoulli trials at a given confidence level? I want to determine whether the true bounce rate of an email campaign (an email sent to many recipients) is <20%, at the 99% confidence level. I can send one "test batch" of randomly selected emails from the campaign and record the resulting binary bounce/no bounce outcomes before deciding whether to send the remaining emails.
If the campaign has true bounce rate >=20%, we want to flag it for manual review; if the campaign has <20% true bounce rate, we want to send the entire campaign without review. What is minimum number of emails I would need to send in the "test batch" to reach 99% confidence, and what should my threshold for manual review be?
My current thinking is to simulate draws from a Bernoulli process where the true fraction of positives is 0.2. Look at the lower bound of the 98% confidence interval (98%--not 99%--because we are only interested in unlikely outcomes in the leftmost tail). Because I want the resulting "rules" to be applied to all campaigns, regardless of the size of the campaign, I simulated the Bernoulli process 100 times to get a sense for the variance of that lower bound. I determined that if we use a test batch of 200, when the bounce rate of the test batch is <10% we can safely conclude that the true bounce rate of the campaign will be <20%.
Here's my Python code:
def mean_confidence_interval(data, confidence=0.90):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1+confidence)/2., n-1)
    return m-h #sample mean minus confidence interval

for i in range(100):
    data = np.random.binomial(1, 0.2, size=200) # simulate the data
    print(mean_confidence_interval(data, confidence=0.98))

Is there a better way to think about this?

A: Null and alternative hypotheses. Let's call 'bounce rate' $\theta.$ From your discussion about confidence intervals, it seems, based on a small pilot study, you want to test $H_0: \theta \le .1$ (pilot study OK) against
$H_a: \theta > .1$ (unsuccessful).
Significance level. It seems you want to test at level $\alpha = .05.$ That means you are unlikely to reject $H_0$ (and presumably re-do your web page), if the bounce rate really is below $0.1$ as a best case possibility.
Power. By contrast, you want to be reasonably sure to reject $H_0$ if $\theta$ is much
larger than $0.1.$ The question is how much greater should trigger rejection of $H_0?$  It seems
that you would want to be very sure to reject $H_0,$ if the true bounce
rate is as large as $\theta = 0.2.$ Perhaps you want the 'power' of the test
to be 95% or 99%. That means you want $P(\text{Reject } H_0 | \theta = 0.2) = 0.95$ or $0.99.$
Minitab power computation and power curve. Many statistical software programs will make power computations showing various
possibilities. Here is one from Minitab.
Power and Sample Size

Test for One Proportion

Testing p = 0.1 (versus > 0.1)
α = 0.01

              Sample  Target
Comparison p    Size   Power  Actual Power
         0.2     266    0.99      0.990166
         0.2     184    0.95      0.950160

Here is a related figure from Minitab, showing power for alternative
values other than $\theta = 0.2.$ The broken red line shows power $0.99$
at $\theta = 0.2$ for $n=266.$

Details of power computation. One computation (in R, where pbinom is a binomial CDF) goes as follows:  First, we find the critical value for the
test. If $\theta = 0.1,$ then how many 'bounces' out of $n = 200$ emails
does it take to trigger rejection at the 5% level?  That is, find $c$ such that
$P(X \ge c | \theta=0.1) = .05.$ Because the binomial distribution is discrete
we can't make the answer exactly $0.05;$ using $c = 27$ gives $0.067$ and
$c = 28$ gives $0.043;$ we use $[28, 200]$ as the 'rejection region'.
qbinom(.95, 200, .1)
[1] 27
1 - pbinom(26, 200, .1)
[1] 0.06722468
1 - pbinom(27, 200, .1)
[1] 0.0434285

Then to find the power against the alternative $\theta = 0.2,$ we find the power as
$P(X \ge 28 | \theta = 0.2) = 0.989.$
1 - pbinom(27, 200, 0.2)
[1] 0.9890492

So it seems your conclusion is correct:  $n \approx 200$ is an appropriate sample size
for a pilot study.
Here is a 'power curve' showing powers for various alternative values of
$\theta \in (.1, .25)$ for a test at level $\alpha = 0.043$ and emphasizing
the power against $\theta = 0.2$ (red dotted lines).


text:
Q: matlab: how to delete an element from a row vector I have written a function myMerge which merges two sorted row vectors, this works as it should.
I am now trying to write a new function MergedExp which calls myMerge and then checks to see if any of the elements are the same and if so removes one. for example if I input the two row vectors [1,3,5,6] and [2,5,7,8] myMerge would give [1,2,3,5,5,6,7,8] and i want MergedExp to produce [1,2,3,5,6,7,8]
 This is what I have so far
function [ answer ] = MergedExp( a,b )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

Merge=myMerge(a,b);
l=length(a)+length(b);

for i=1:l-1
    if (Merge(i)==Merge(i+1))
       Merge(i)=[];
    end
end
end

When i remove the semi colons in order to see each step of the function working it does give the answer i'm after but still shows an error message.
Any ideas on how to resolve this would be much appreciated.

A: I would recommend using MATLAB's inbuilt function unique.
For instance,
MergedList = [1 2 3 3 3 3 4 5]
MergedList = unique(MergedList)

Output:
MergedList =

     1     2     3     4     5

A: The error you have comes from the fact that you loop through the nearly whole vector, 1 to length(vector)-1, but while doing so, you remove some elements. Therefore at some point, the for loop reaches an index that do not correspond to a vector element anymore. And this causes an error.
One of the many solutions to this is store the indexes to remove, and remove them once the for loop is done.
ind_to_remove = [];
for i=1:l-1
  if (Merge(i)==Merge(i+1))
    ind_to_remove = [ind_to_remove i];
  end
end
Merge(ind_to_remove) = [];


text:
Q: Enabling continuous deployment in Azure Web App for containers via ARM template I have an ARM template set up to deploy a Docker Image to an Azure App Service, but I'm having trouble finding out how to enable continuous deployment via any method other than the UI. There's instructions here:
https://learn.microsoft.com/en-us/azure/app-service/containers/app-service-linux-ci-cd
But I want to use ARM templates so my setup is identical, repeatable and disposable - is there any way to do this?

A: To enable continuous integration you can simply set the DOCKER_ENABLE_CI app setting:
resource site 'Microsoft.Web/sites@2021-02-01' = {
  properties: {
    siteConfig: {
      appSettings: [
        {
          name: 'DOCKER_ENABLE_CI'
          value: 'true'
        }
      ]
    }
  }
}

A: You can use azure devops as below demo to deploy docker container app
https://www.azuredevopslabs.com/labs/vstsextend/docker/