text:
Q: boot manager is missing, ubuntu 12.04 I did a clean installation of ubuntu 12.04 from a usb stick. After installation, first boot was normal so i logged in installed some apps and lenses and downloaded updates. When I rebooted to install updates after bios screen it said boot manager is missing, press alt+ctrl+del to restart.
so how can i repair/install mbr?
thanx

A: The boot manager for Ubuntu, GRUB2, was probably broken when you were installing updates. Try using Boot Repair to fix it. First boot to the Ubuntu live CD. Open a terminal window and run the following code to install and run boot repair:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair
boot-repair

Then follow the instructions and options in the program to repair your boot.
You can visit http://www.howtogeek.com/114884/how-to-repair-grub2-when-ubuntu-wont-boot/ for more information.


text:
Q: Image refreshing not working in Windows 8 apps I want to display a banner via a URL. The URL is static but the image content can be changed so it's like an ad. I tried below code but it's not changing the image, it shows cached image. What's wrong with my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    ChangeImage();
    var ForcedAdtimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(60) };
    ForcedAdtimer.Tick += (ss, ee) => ChangeImage();
    ForcedAdtimer.Start();
}

private void ChangeImage()
{
    txt.Text += "Img Changed - " + DateTime.Now.ToString() + Environment.NewLine;
    Nullify();
    var bmp = new BitmapImage();
    bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
    bmp.UriSource = new Uri("http://myserver.net/myImage.png");
    img.Source = bmp;
}

private void Nullify()
{
    BitmapImage bitmapImage = img.Source as BitmapImage;
    if (bitmapImage != null)
    {
        bitmapImage.UriSource = null;
    }
    img.Source = null;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: reading property from gradle.properties to configuration.properties I have two properties file, gradle.proerties and configuration.properties, How can i read value from gradle.properties to configuration.properties,
Is it even possible syntactically

A: Properties properties = new Properties()
properties.load(project.rootProject.file('onfiguration.properties').newDataInputStream())
def sdkDir = properties.getProperty('your_key')


text:
Q: speeding up a non-equal join Inputs
> specialty.dt
   specialty        p1        p2
1:      ZKWM 0.0000000 0.7377049
2:      MZAY 0.7377049 1.0000000

> provider.dt
   provSysId       prob
1:        23 0.94225972
2:        16 0.39277028
3:         8 0.07162044
4:        25 0.42598790
5:         7 0.90370561
6:        12 0.71343887

Output
> prov_spec.dt
   provSysId       prob specialty        p1        p2
1:        23 0.94225972      MZAY 0.7377049 1.0000000
2:        16 0.39277028      ZKWM 0.0000000 0.7377049
3:         8 0.07162044      ZKWM 0.0000000 0.7377049
4:        25 0.42598790      ZKWM 0.0000000 0.7377049
5:         7 0.90370561      MZAY 0.7377049 1.0000000
6:        12 0.71343887      ZKWM 0.0000000 0.7377049

Code to create above tables is shown below.  For num.provider=5 and num.specialty=10000, it takes almost 30s to create the output.  I was wondering if there was a faster way to get the same result (without first doing a cartesian product because that would require a lot of memory).
require(data.table)

num.specialty <- 50
num.provider <- 10000

specialty.dt <- data.table(specialty=replicate(num.specialty, paste(sample(LETTERS, 4, replace=TRUE), collapse="")))[,
    cnt:=sample(1:50, .N, replace=T)][, prob:=cnt/sum(cnt)][, p2:=cumsum(prob)][, p1:=shift(p2,,0)][,
    c("specialty","p1","p2"), with=FALSE]

provider.dt <- data.table(provSysId=sample(seq(num.provider+1,num.provider*5), num.provider, replace=FALSE))[, prob:=runif(.N)]

system.time({
prov_spec.dt <- rbindlist(lapply(1:num.provider, function(n) {r <- provider.dt[n]; cbind(r,specialty.dt[p1 <= r[,prob] & r[,prob] < p2]) }))
})

A: Your rbindlist(lapply(...)) can be replaced with a non-equi join using version 1.9.7 of data.table
specialty.dt[ provider.dt, on = .(p1 <= prob, p2 > prob)]

This joins specialty.dt onto provider.dt directly, using the condition that p1 <= prob, and prob < p2.

References
Here's a list of similar questions
And here's a talk by Arun


text:
Q: Sticky Div within Container - no overlap with footer I am using this jsfiddle:
jsfiddle
In my site, I am getting the following error:
Uncaught TypeError: Cannot read property 'top' of undefined
The line where it breaks of the jsfiddle:
var sidebarTop = $sidebar.position().top;

What could be the reason?

Just to give an idea of what I am trying to solve. I have a div in top of page, and set its position to fixed. When user scroll to the bottom of page, this div overlaps with the footer. I need to to stop (stick) this div in some place and does not go more to the bottom once it passes some point

A: It's not breaking on either your jsfiddle or on my side. There might be possibility that you write your js script before the html is loaded. so try to write the js/jquery code at the end after your html page.
Refferences JavaScript on the bottom of the page?


text:
Q: Xboxdrv not able to start I installed the xbox controller drivers (for use with an XBox One controller) using
sudo apt install xboxdrv

However when I try to start/enable the service with
sudo systemctl start xboxdrv.service

I get the following error
Failed to start xboxdrv.service: Unit xboxdrv.service not found.

Any ideas?

A: First, try to enable the service with the following command:
sudo systemctl enable xboxdrv.service
and then try starting it with:
sudo systemctl start xboxdrv.service
If the service is not found, then the service needs to be created.
Make a file called "xboxdrv.service" in the /etc/systemd/system and copy/paste the following in it:
[Unit]
Description=Xbox controller driver daemon

[Service]
Type=simple
User=root
PIDFile=/var/run/xboxdrv.pid
ExecStartPre=/usr/share/ubuntu-xboxdrv/xboxdrv-pre
EnvironmentFile=/usr/share/ubuntu-xboxdrv/uxvars
ExecStart=/usr/bin/xboxdrv --daemon --silent --pid-file /var/run/xboxdrv.pid --dbus disabled $XBOXDRV_OPTIONS $PAD_OPTIONS $CONTROLLER0_OPTIONS --next-controller $PAD_OPTIONS $CONTROLLER1_OPTIONS --next-controller $PAD_OPTIONS $CONTROLLER2_OPTIONS --next-controller $PAD_OPTIONS $CONTROLLER3_OPTIONS

[Install]
WantedBy=multi-user.target

Then enable the service:
sudo systemctl enable xboxdrv.service
Followed by starting the service:
sudo systemctl start xboxdrv.service
Make sure the Xbox controller is connected when you start the service.

A: For Ubuntu 22.04:

*

*Note #1: If you have followed the previous answer, first stop and then disable the xboxdrv.service before editing the existing file to fix by the following steps:

$ sudo systemctl stop xboxdrv.service
$ sudo systemctl disable xboxdrv.service

*

*Note #2: Before setting up the systemctl app, make sure if you have installed correctly the xboxdrv by the steps in this website.

*

*Make a new file called "xboxdrv.service" in the directory /etc/systemd/system and copy/paste the following text in it:

[Unit]
Description=Xbox controller driver daemon

[Service]
Type=simple
User=root
ExecStart=/usr/bin/xboxdrv --silent

[Install]
WantedBy=multi-user.target

*Enable the service:

$ sudo systemctl enable xboxdrv.service

*

*Make sure the Xbox controller is connected before continuing the next steps.

*Start the service:

$ sudo systemctl start xboxdrv.service

*Check if xboxdrv is running by the service:

$ sudo systemctl status xboxdrv.service (Press "q" to end)

*

*Note #3: If you have forgotten to connect the controller before or the controller has been disconnected by accident and you have to reconnect it, just type:

$ sudo systemctl restart xboxdrv.service

*

*Note #4: If the previous command does not solve the problem to reconnect the controller, reboot the PC and try again.

*Note #5: It's not necessary to type in Terminal sudo xboxdrv --silent if the xboxdrv is running by the service, besides it runs every time when Ubuntu boots.


text:
Q: including functions in seperate file in arduino Noob qn.
I was using Arduino 1.6.5 and I had something like below that used to work.
main.ino
#include "oldFunctions.h"

#define BLAHBLAH
setup(){
  //....
}
loop(){
  //....
}

void newFunctionA(void){
//....
}

oldFunctions.h. This is a file I added over time, with new functions and stuff.
void test(void){
   newFunctionA();
}

This used to work in Arduino 1.6.5, but I upgraded to 1.6.8 and now I get the error saying newFunctionA was not declared in this scope
Can someone help?

A: It's ALWAYS a bad idea messing up with the files and then hoping that the compiler does some magic. What I suggest you is to use the files as they are meant to be used, so

*

*Header files (*.h, *.hpp) shall contain class definitions (but not implementations), global variables defined as extern, function prototypes. They shall use the common ifndef... to prevent multiple inclusions

*Source files (*.c, *.cpp, *.ino) shall contain the actual function implementations, the methods implementations, and the global variables definitions.

You should not avoid using this, otherwise you will enter a lot of possible troubles.
In your case, you should then have three files:
main.ino
#include "oldFunctions.h"

#define BLAHBLAH
setup(){
  //....
}
loop(){
  //....
}

void newFunctionA(void){
//....
}

oldFunctions.h
#ifndef OLD_FUNCTIONS_H
#define OLD_FUNCTIONS_H

void newFunctionA();
void test();

#endif

oldFunctions.cpp
#include "oldFunctions.h"

void test(void){
    newFunctionA();
}

Please note, however, that in the cpp file you should not use the BLAHBLAH you defined in main.ino. If you need it, move it to the oldfunctions.h file.
In newFunctionA is a new function you want to keep separated from the oldfunctions, just create a new header file and include it. The important part is that you do not rely on arduino joining the source files, because this can lead to unexpected behavior.


text:
Q: How to sort with multiple sort parameters? Refering to this question
Sadly I cannot comment because of low reputation but I have a question relating to this solution.
I want to sort ascending AND descending (on click), but keep an empty string (represents the second sort parameter) always on top of something written..
I want it like:

My code works only for ASCENDING, on descending the string is before the empty one..
SECOND_SORT {
    public int compare(String s1, String s2) {
        if (s1.equals("") && s2.equals("")) {
            return 0;
        }
        if (s1.equals("")) {
            return -1;
        }
        if (s2.equals("")) {
            return 1;
        }
        return s1.compareTo(s2);
    }

This is the sort..
if (mSortingIdentifier == SortingIdentifier.DESC) {
            Collections.sort(list, Comparator.descending(Comparator.getComparator(Comparator.FIRST_SORT, Comparator.SECOND_SORT)));
        } else {
            Collections.sort(list, Comparator.ascending(Comparator.getComparator(Comparator.FIRST_SORT, Comparator.SECOND_SORT)));
        }

A: I have found a solution for me that works..
I just added another SECOND_SORT_DESC where I swap the return value.. in the adapter when I sort I check if its ASC or DESC and use the enum I want...
fyi:
SECOND_SORT_ASC {
public int compare(String s1, String s2) {
    if (s1.equals("") && s2.equals("")) {
        return 0;
    }
    if (s1.equals("")) {
        return -1;
    }
    if (s2.equals("")) {
        return 1;
    }
    return s1.compareTo(s2);
},
SECOND_SORT_DESC {
public int compare(String s1, String s2) {
    if (s1.equals("") && s2.equals("")) {
        return 0;
    }
    if (s1.equals("")) {
        return 1;
    }        // swapped these two
    if (s2.equals("")) {
        return -1;
    }
    return s1.compareTo(s2);
} // Here is where I differ between asc and desc
if (mSortingIdentifier == SortingIdentifier.DESC) {
        Collections.sort(list, Comparator.descending(Comparator.getComparator(Comparator.FIRST_SORT, Comparator.SECOND_SORT_DESC)));
    } else {
        Collections.sort(list, Comparator.ascending(Comparator.getComparator(Comparator.FIRST_SORT, Comparator.SECOND_SORT_ASC)));
    }


text:
Q: Which style is better for a classic dynamic programming if-not-contains-then-put? It is quite normal in dynamic programming problems to have a map that contains previous cases, and every time you reach a new state you have to check if it is already in the map, if so use it, and if not add it. I would like to know what is better in performance and style between these two ways:
Value value;
if(!map.contains(key)){
    value = calculateValue();
    map.put(key, value);
} else {
    value = map.get(key);
}

and this one:
if(!map.contains(key)){
    map.put(key, calculateValue());
}
Value value = map.get(key);

The second one seems to be less efficient, but allows me to avoid having an uninitialized variable that could lead to errors some day.

A: The most readable way is Map.computeIfAbsent. It adds a function call only when the value is absent, which should be negligible.
The code would look like:
final Value value = map.computeIfAbsent(key, k -> calculateValue());


text:
Q: A puzzle in almost sure convergence Here is a classical question about a.s. convergence and GC Theorem(Uniform L.L.N):
Suppose that $X_1$, $X_2$,....,$X_n$ are i.i.d. with $E|X| < \infty$, and let $D_n := \frac{1}{n} \Sigma_{i=1}^{n} |X_{i} - \bar X_{n}|^r$ with $0<r<1$ fixed. Show that $D_n \rightarrow_{a.s.} d := E{|X_1 - \mu|^{r}}$ with $\mu = E(X_1)$.
Proof (in brief):
Let $\delta >0$. Then $\bar X_n \in [\mu -\delta, \mu +\delta]$ for n sufficiently large with probability 1, so we can consider the collection of functions $f(x,t) = f_t(x)=|x-t|^r$ with $t \in [\mu-\delta, \mu+\delta]$, namely:
$\tilde F = \{ f_t(x)=|x-t|^r: \mu-\delta \leq t \leq \mu+\delta \}$
Then apply uniform Law of large number and $C_r$- inequality :
$~~~~|D_n - d| \\
= |\frac{1}{n}\Sigma_{i=1}^{n} |X_{i} - \bar X_{n}|^r - E|X_1 - \mu|^{r} | \\
= |\mathbb{P}_n f_{\bar X_{n}} - P_n f_{\bar X_{n}} + P_n f_{\bar X_{n}} - P f_{\mu} | \\
\leq sup_{\mu-\delta \leq t \leq \mu+\delta}|\mathbb{P}_n f_t - P f_t| + |P f_{\bar X_{n}} - Pf_{\mu}|   \\
\rightarrow_{a.s} 0+0 = 0
$
I can understand the later part, but cannot understand the first part(the bold part): why after we know that $\bar X_n$ located in $[\mu-\delta, \mu+\delta]$ with probability 1, then we could just focus only on the function class $\tilde F$ and still ensure the conclusion work under almost surely convergence? (namely, how to ensure that the case $\bar X_n \notin [\mu-\delta, \mu+\delta]$ would not influence the convergence a.s ??)
I know this question may be simple to many of yours, but as a beginner in measure theory and statistics, it play an important role in understanding various modes of conv. Thank you for your help!!

A: Perhaps this will clear your doubt: if $x_n \to \mu$ and $\bar {x}_n =\frac {x_1+x_2+...+x_n} n$ then $\frac 1 n \sum_1 ^{n} |x_j -\bar {x}_n| \to 0$ and this is what is being proved here. This is a deterministic result and random variables are not involved in this argument. In fact you can also give a simpler proof using the fact that $(a+b)^{r} \leq 2^{r} (a^{r} +b^{r})$.


text:
Q: Ionic on Hold directive I have a div with collection repeat on which I apply an ng-class ng-class="$index%2 == '0' ? 'blue' : 'yellow'",I also apply an ionic on-hold directive asng-class="{'selected': column.selected}"?I want when the row is selected the red colour of selected class should get applied.The problem is if I write the second ng class first,red colour is applied but the first ng-class becomes invalid.Is there a way to achieve both of this

A: In ng-class you can insert any Angular expression: why not using a function (defined on the scope) which analyzes the condition you want and returning a string containing the right class names (space delimited)?
Here is an example:

angular.module('ionicApp', ['ionic'])

.controller('MyCtrl', function($scope) {
  console.log("MyCtrl");
  $scope.tasklist_records = [{
    id: 0,
    onHoldFlag: false
  }, {
    id: 1,
    onHoldFlag: false
  }, {
    id: 2,
    onHoldFlag: false,
    selected: true
  }, {
    id: 3,
    onHoldFlag: false
  }, {
    id: 4,
    onHoldFlag: false
  }, {
    id: 5,
    onHoldFlag: false
  }, {
    id: 6,
    onHoldFlag: false
  }];

  $scope.customClass = function(column, $index) {
    if (!column) return;
    var _class = "";
    if (column.id==0) _class += "firstrow ";
    if ($index % 2 == 0) _class += "grey ";
    if ($index % 2 == 1) _class += "white ";
    if (column.selected) _class += "selected ";
    console.log("customClass", column,_class);
    return _class;
  }

  $scope.onHold = function(column, $index) {
    console.log("onHold", column, $index);
    column.onHoldFlag = !column.onHoldFlag;
  }

  $scope.goToAccountDetailScreen = function(column, $index) {
    console.log("goToAccountDetailScreen", column, $index);
  }

});
.selected {
  color: red;
}
.white {
  background-color:white;
}
.grey {
  background-color:grey;
}
.firstrow {
  color: blue;
}

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Ionic List can swipe</title>
  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

  <ion-header-bar class="bar-positive">

Ionic List

  </ion-header-bar>

  <ion-content>
    <ion-list>

{{column.id}} - {{column.onHoldFlag}} - {{column.selected}}

    </ion-list>
  </ion-content>


text:
Q: Zombie/Infected movie ending with a lady and a child handing some kind of cure to someone in a "safe zone" The only thing I can remember that stood out was the ending. A lady and another adult or large child arrives to a place that looks like a safe haven and hands someone what looks like a cure. I can't remember anything else about the movie except that one part.

A: Question is a bit terse, but that immediately made me think of the theatrical ending of I Am Legend (2007). (note that there's an alternate ending which is more faithful to the book)
From IMDb:

Robert Neville is a scientist who was unable to stop the spread of the terrible virus that was incurable and man-made. Immune, Neville is now the last human survivor in what is left of New York City and perhaps the world. For three years, Neville has faithfully sent out daily radio messages, desperate to find any other survivors who might be out there. But he is not alone. Mutant victims of the plague -- The Infected -- lurk in the shadows... watching Neville's every move... waiting for him to make a fatal mistake. Perhaps mankind's last, best hope, Neville is driven by only one remaining mission: to find a way to reverse the effects of the virus using his own immune blood. But he knows he is outnumbered... and quickly running out of time.

The ending below has Anna, a female survivor, and her kid Ethan bringing a "cure" vial to a stronghold, after

 Neville successfully developed said cure, but died protecting them from the creatures.


text:
Q: shift particular rows of a particular column of pandas dataframe I have this dataframe
And am trying to shift rows which have NaNs in the first two columns to the left, so the values to the right now fill this column. Here is what i am currently trying to do:
(Note: the match dataframe was downloaded from this link: https://www.kaggle.com/hugomathien/soccer)
#original dataframe
<class 'pandas.core.frame.DataFrame'>
Int64Index: 21374 entries, 145 to 25978
Data columns (total 47 columns):
id                  21374 non-null int64
country_id          21374 non-null int64
league_id           21374 non-null int64
season              21374 non-null object
stage               21374 non-null int64
date                21374 non-null object
match_api_id        21374 non-null int64
home_team_api_id    21374 non-null int64
away_team_api_id    21374 non-null int64
home_team_goal      21374 non-null int64
away_team_goal      21374 non-null int64
goal                13325 non-null object
shoton              13325 non-null object
shotoff             13325 non-null object
foulcommit          13325 non-null object
card                13325 non-null object
cross               13325 non-null object
corner              13325 non-null object
possession          13325 non-null object
BSA                 11856 non-null float64
Home Team           21374 non-null object
Away Team           21374 non-null object
League              21374 non-null object
Country             21374 non-null object
home_player_1       21374 non-null object
home_player_2       21374 non-null object
home_player_3       21374 non-null object
home_player_4       21374 non-null object
home_player_5       21374 non-null object
home_player_6       21374 non-null object
home_player_7       21374 non-null object
home_player_8       21374 non-null object
home_player_9       21374 non-null object
home_player_10      21374 non-null object
home_player_11      21374 non-null object
away_player_1       21374 non-null object
away_player_2       21374 non-null object
away_player_3       21374 non-null object
away_player_4       21374 non-null object
away_player_5       21374 non-null object
away_player_6       21374 non-null object
away_player_7       21374 non-null object
away_player_8       21374 non-null object
away_player_9       21374 non-null object
away_player_10      21374 non-null object
away_player_11      21374 non-null object
winner              21374 non-null object
dtypes: float64(1), int64(9), object(37)
memory usage: 7.8+ MB

creating the dataframe
columns = match.columns[match.columns.get_loc('home_player_1'):match.columns.get_loc('away_player_1')+1].values
columns = list(columns)

player_appearences = match.groupby(columns[0]).size().reset_index()
player_appearences.rename(columns = {0:"Count_{}".format(player_appearences.columns[0][len(player_appearences.columns[0])-1])}, inplace = True, errors='raise')
player_appearences
for i in range(1,12):
    player_appearences2 = match.groupby(columns[i]).size().reset_index()
    player_appearences2
    player_appearences2.rename(columns = {0:"Count_{}".format(player_appearences2.columns[0][len(player_appearences2.columns[0])-1])}, inplace = True, errors='raise')
    player_appearences = player_appearences.merge(right = player_appearences2,how="outer",left_on ="{}".format(player_appearences.columns[0]),right_on = "{}".format(player_appearences2.columns[0]))
    player_appearences
    #overwrite nans in first column with names in current [i] player column

#select rows where first two columns give nan values
player_appearences.loc[(player_appearences.loc[:,"home_player_1"].isna()==True) & (player_appearences.loc[:,"Count_1"].isna()==True),["home_player_1","Count_1"]] = player_appearences.loc[(player_appearences.loc[:,"home_player_1"].isna()==True) & (player_appearences.loc[:,"Count_1"].isna()==True),["home_player_2","Count_2"]]

When I then print player_appearences the dataframe is unchanged. I'm unsure if its either not doing anything, or it is creating a copy of the original dataframe. Can anyone tell me why this isn't working/suggest a better way if there is one?

A: Use DataFrame.rename, then you only need DataFrame.stack (dropna = True by default) + DataFrame.unstack:
 df = (df.rename(columns = {'home_player_2':'home_player_1',
                           'Count_2':'Count_1'}).stack().unstack()
       .reindex(columns = df.columns[:2]))
print(df)
  home_player_1 Count_1
0         Aaron       1
1          Adam       2
2         Ziggy       3
3        Zoltan       4

Or DataFrame.shift with DataFrame.where:
df.where(df.notna(),df.shift(-1,axis = 1)).iloc[:,:2]

  home_player_1  Count_1
0         Aaron      1.0
1          Adam      2.0
2         Ziggy      3.0
3        Zoltan      4.0

Detail
print(df.where(df.notna(),df.shift(-1,axis = 1)))
  home_player_1  Count_1 home_player_2  Count_2
0         Aaron      1.0           NaN      NaN
1          Adam      2.0           NaN      NaN
2         Ziggy      3.0         Ziggy      3.0
3        Zoltan      4.0        Zoltan      4.0

A: You can use shift(-1, axis=1) to shift the columns and df[df.home_player_1.isna() & df.Count_1.isna()] to specify which rows to affect. The rows, which you are shifting, should be rewritten in the dataframe.
df = pd.DataFrame([['Aaron', 1, None, None],
                   ['Adam', 2, None, None],
                   [None, None, 'Ziggy', 3],
                   [None, None, 'Zoltan', 4]],
                  columns=['home_player_1', 'Count_1', 'home_player_2', 'Count_2'])

home_player_1   Count_1     home_player_2   Count_2
Aaron           1.0         None            NaN
Adam            2.0         None            NaN
None            NaN         Ziggy           3.0
None            NaN         Zoltan          4.0

df[df.home_player_1.isna() & df.Count_1.isna()] = df[df.home_player_1.isna() & df.Count_1.isna()].shift(-1, axis=1)

home_player_1   Count_1     home_player_2   Count_2
Aaron           1.0         None            NaN
Adam            2.0         None            NaN
Ziggy           3.0         NaN             NaN
Zoltan          4.0         NaN             NaN


text:
Q: jquery file extensions i need one thing to do:

failanosaukums.pdf

failanosaukums.exel

failanosaukums.doc

If file exstensions are pdf, add li class pdf, and doc, exel, mp3.
I  think something like this
var ext = ul li a each split (.)
$(this).parent().addClass(ext)

A: If you can't do this server side when generating the rest of the html, this should work
$("ul.files a").each(function() {
    var $this = $(this);
    var text = $this.text();
    var ext = text.substring(text.lastIndexOf('.') + 1);

    $this.parent().addClass(ext);
});

A: I'm not really sure if what you're wanting is a good idea, but this will do it for you.
var files = $("li a");

files.each(function(idx, el) { $(el).parent().addClass($(el).text().split(".").pop()) });

A: I agree with everybody else that server side is the way to go, but if you must do it client side:
$('.downloads li').addClass(function() {
    return $('a', this).text().split('.').pop();
});

Example - http://jsfiddle.net/RNvnL/3/


text:
Q: How to prove a 4D vector is a 4-Vector? This is a fairly open ended question.
Given a set of 4 Components, that is, a 4D Vector, what is the process for determining rather or not it is a "4-Vector" as defined in special relativity? I want to know the general method for answering this question. It is still unclear to me what additional constraints make 4-vectors "special".

A: A set of 4 components, that is a 4-dimensional vector, is a 4-vector if it is transformed as the position 4-vector between reference frames.
Related : Transformation of 4−velocity.

A: It is a 4-vector if and only if the components change by a Lorentz transformation when you pass from the coordinate system of one inertial frame to another.
However, if all you have is the 4 components, then you do not know how it transforms: you need further information.
The further information can come in several forms. Here are some that would suffice. The first three are mathematical, the fourth is physical.

*

*You can write an expression showing that your 4-component object can be written in terms of something else that you already know to be a 4-vector. e.g. four-velocity and four momentum:
$$
u^a = dx^a/d\tau,  \;\;\;\;\; p^a = m u^a
$$
if we already know $dx^a$ is a 4-vector and $d\tau$ and $m$ are invariants, then we
have 4-vector $u^a$ and $p^a$.

*Item 1 can be expanded more generally by using the quotient rule. If you have a valid tensorial expresson (i.e. one that obeys the rules of tensor analysis) in which everything else except your 4-component object is a tensor of some rank or other, and you know the expression holds in all coordinate systems, then your object is a 4-vector.

*You write your components in some frame of your choosing, and then you simply announce that it is a 4-vector by definition. The trouble with this method is that you may thus obtain a 4-vector of limited use in the rest of physics. However it can work out nicely sometimes. An example is the flux 4-vector $j^a$. There is a natural frame to pick: the rest frame of a fluid element. You give to $j^a$ the components $(\rho_0 c,0,0,0)$ in that frame where $\rho_0$ is proper density. Then you announce it is a 4-vector. Then your next job is to find out the physical meaning of the components in a general frame. In this example there is a natural physical meaning if it is the flux of something such as electric charge which is itself a scalar invariant. See a good textbook for more information. Actually this 4-vector can also be written $\rho_0 u^a$ so that is another way to prove it is a 4-vector, but the job of working out the physical significance of the components remains.

*You have a physical argument to show that the quantities you are considering are indeed the components of a 4-vector because they must transform the right way. For example, you can, with a bit of care, argue that the phase $\phi$ of an oscillation of a wave will be Lorentz-invariant (and therefore a tensor of rank zero). You then show that this same phase can be written $\phi = k^\mu x_\mu$ where $x^a$ is a position 4-vector. You may then deduce that $k^a$ is a 4-vector.

A: $k$-vectors represent physically relevant things: displacement, velocity, orientation, current, force, et al.  What physically relevant thing does your list of four components represent?  I ask, because whether you have a 4-vector depends on how the physically relevant thing you are representing transforms.
There is no way to go from a list of four numbers to the physically relevant thing it transforms, so there is no way to start from a list of four numbers and discern whether the physically relevant thing it represents transforms as a $4$-vector.  This transformation property is a property of the physically relevant thing, not of the list of numbers.


text:
Q: Is it possible to automate Gsutil login? Is it possible to automate gsutil based file upload to google cloud store so that the user intervention is not required for login?
My usecase is to have a jenkins job which polls a SCM location for changes to a set of files. If it detects any changes it will upload all files to a specific Google Cloud Store bucket.

A: After you configure your credentials once gsutil requires no further intervention. I suspect that you ran gsutil configure as user X but Jenkins runs as user Y. As a result, ~jenkins/.boto does not exist. If you place the .boto file in the right location you should be all set.
Another alternative is to use multiple .boto files and then tell gsutil which one to use with the BOTO_CONFIG environment variable:
gsutil config  # complete oauth flow
cp ~/.boto /path/to/existing.boto
# detect that we need to upload
BOTO_CONFIG=/path/to/existing.boto gsutil -m cp files gs://bucket

I frequently use this pattern to use gsutil with multiple accounts:
gsutil config  # complete oauth flow for user A
mv ~/.boto user-a.boto
gsutil config  # complete oauth flow for user B
mv ~/.boto user-b.boto
BOTO_CONFIG=user-a.boto gsutil cp a-file gs://a-bucket
BOTO_CONFIG=user-b.boto gsutil cp b-file gs//b-bucket


text:
Q: Put a beamer background image in the right bottom corner In beamer, I like to place a background image in all my slides. So I could use this:
\usebackgroundtemplate{
\tikz[overlay,remember picture] \node[opacity=0.3, at=(current page.center)] {
   \includegraphics[height=\paperheight,width=\paperwidth]{background.png}};
}

However, to put the background image at the right-bottom corner, what should I do? I guess I should change some how "current page.center" to something like "current page.south east". But, I want to match the right-bottom corner of the image file with the right-bottom corner of the slides.

A: Add anchor=south east together with at=(current page.south east). Moreover, you'd probably also want to set inner sep=0 to avoid unnecessary white spaces.
MWE
\documentclass{beamer}
\usepackage{tikz}
\usepackage{mwe} % provides example image

\usebackgroundtemplate{
  \tikz[overlay,remember picture]
  \node[opacity=0.3, at=(current page.south east),anchor=south east,inner sep=0pt] {
    \includegraphics[height=\paperheight,width=\paperwidth]{image}};
}

\begin{document}
\frame{frame content}
\end{document}

Output


text:
Q: Is automatic upgrades a realistic feature to expect from enterprise Web applications? Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature?

A: At my company we have enterprise installations ranging into the thousands of seats.  If we implemented an auto-upgrade, our customers would mutiny!
Large installations have peculiar issues that don't apply to small ones.  For example, with 2000 users (not all of whom are, let us say, the most sophisticated of tool users), tool-training is a big deal: training time, internal demos, internal process documents, etc..  They cannot unleash a new feature or UI change without a chance to understand how it fits in their process and therefore what their internal best practices are and how to communicate that to their users.
Also when applications fail, it's the internal IT team who are responsible.  Therefore, they want time to install a new version in a test area, beat it up, and deploy on a Saturday only when they're good and ready.
I can see the value in making minor patches more easy to install, particularly when the patch is just for a bug-fix and not for anything that would require retraining, and if the  admins still get final say over when it's installed.  But even then, I don't believe anyone has ever asked for this!  Whether because they don't want it or they are trained to not expect it, it doesn't seem worth it.

A: Well, it really depends on your business model but for a lot of applications the SaaS model can end up biting you. It's great for a lot of things but for some larger applications the users are not investing as significant amount up front and could possibly move to something else before you've made any money.
See
http://news.zdnet.com/2424-9595_22-218408.html
and here
http://www.25hoursaday.com/weblog/2008/07/21/SoftwareAsAServiceWhenYourBusinessModelBecomesAParadox.aspx
for more information

A: One of the primary reasons to implement an application as a web application is that you get automatic upgrades for free.  Why would users be getting prompted for upgrades on a web app?
For Windows applications, the "update is available, do you want to upgrade?" functionality is provided by Microsoft using ClickOnce, which I have used in an enterprise environment successfully -- there are a few gotchas but for the most part it is a good way to manage automatic deployment and upgrade of Windows apps.
For mobile apps, you can also implement auto-upgrades, although it is a little trickier.
In any case, to answer your question in a broad sense, I don't know if it is expected that all enterprise apps should make upgrading easy, but it certainly is worth the money from an IT support standpoint to architect them to allow for easy upgrading.

A: If you're providing a hosted solution, I wouldn't bother.  Let the upgrade happen silently (perhaps with a notice that you did it).  If you're selling an application that's hosted on their servers, let the upgrade decision be made by a single owner, not every user of the app.


text:
Q: Fish - A way to configure it such that it does not scroll through tab completions with tab If you have a directory structure like the below
./test/locationOne
./test/locationTwo
./test/locationThree

If, with bash, or fish, you type in
cd test/

then hit tab, it will autocomplete until test/location. In bash, if you hit tab again, it does the same autocomplete. However, with fish, it starts to scroll through the options. ie. Hit tab once more, and it selects ./test/locationOne, once more goes to locationTwo, etc. I find this quite difficult to work with and I'd like to disable it.
Is it possible?


text:
Q: How can I check if an SQL result contains a newline character? I have a varchar column that contains the string lol\ncats, however, in SQL Management Studio it shows up as lol cats.
How can I check if the \n is there or not?

A: For me, the following worked just fine in both MySQL Workbench & HeidiSQL (working with MySQL) without having to use the char() variation of \n:
SELECT * FROM table_name WHERE field_name LIKE '%\n%'

A: Use char(13) for '\r' and char(10) for '\n'
SELECT *
FROM your_table
WHERE your_column LIKE '%' + CHAR(10) + '%'

or
SELECT *
FROM your_table
WHERE your_column LIKE '%' + CHAR(13) + CHAR(10) + '%'

A: In Oracle, try the below command
SELECT * FROM table_name WHERE field_name LIKE ('%'||chr(10)||'%');

A: For any fellow MySQL users who end up here:
SELECT *
FROM your_table
WHERE your_column LIKE CONCAT('%', CHAR(10), '%')

A: SELECT *
FROM your_table
WHERE your_column LIKE '%' + CHAR(10) + '%'

Or...
SELECT *
FROM your_table
WHERE CHARINDEX(CHAR(10), your_column) > 0

A: SELECT *
FROM Table
WHERE PATINDEX('%' + CHAR(13) + CHAR(10) + '%', Column) > 0

A: SELECT * FROM mytable WHERE mycolumn REGEXP "\n";

A: select cc.columnname,right(cc.columnname,1),ASCII(right(cc.columnname,1)) ,cc.*
from table_name cc where
ASCII(right(cc.columnname,1)) = 13

here

*

*cc.columnname =>  Column name is column where you want to fine new
line or Carriage return.

*right(cc.columnname,1) => this will show only one char what is there
at the end. usually it display only blank

*ASCII(right(cc.columnname,1)) => here we get Acii value of that not
printable value.

by seeing this ascii value we can conclude which item it is. Example , if this acsci value is 13 then Carriage return , if it is 10 then NEw line  we have to use this to filter that record

*

*cc.* => this gives all the values from the table ( display purpose)

*where  ASCII(right(cc.columnname,1)) = 13 => here i found all the
values are 13 asci value so filtering ascii value 13

it is working for me .

A: For any fellow Redshift users who end up here:
select * from your_table where your_column ~ '[\r\n]+'


text:
Q: Is there a way to tick the "Use global Veracode user credentials" checkbox using a DSL groovy script? I am creating a Jenkins job with a DSL Groovy script to add the Veracode plugin. I am looking for a way to tick the "Use global Veracode user credentials" check box.
It works fine with the code I have and adds the checkbox but doesn't check it for me and is looking for credentials. I would like to use global credentials. I have added it under the publishers block. As you can see in my code, under the credentials section, I leave the  credentials blank as I don't want to specify any of those. Clicking the "Use global Veracode user credentials" check box, omits these params and uses the global params specified under manage jenkins.
My problem is how to get this checkbox ticked using the script.
    publishers {
            //extendedEmail Utilities.getExtendedEmail("Scan_Services", false, false)
            extendedEmail Utilities.getExtendedEmailRequester("Scan_Services", false, false)

            veracodeNotifier {
                // Enter the name of the application.
                appname("xDistributor")
                // Enter the business criticality for the application.
                criticality("Very High")
                // Enter a name for the static scan you want to submit to the Veracode Platform for this application.
                version("$BUILD_TIMESTAMP" + " Services_Scan")
                // Enter the filepaths of the files to upload for scanning, represented as a comma-separated list of    ant-style include patterns relative to the job's workspace root directory.
                uploadincludespattern("**/Services/webapps/services.war")
                createprofile(false)
                sandboxname("")
                createsandbox(false)
                filenamepattern("")
                replacementpattern("")
                uploadexcludespattern("")
                scanincludespattern("")
                scanexcludespattern("")
                waitForScan(false)
                timeout("")
                credentials {
                    vapicredential("")
                    vuser("")
                    vpassword("")
                }

            }
        }

A: I wasn't able to find any documentation from Veracode on this, so I ended up having to decompile the plugin to figure it out. This can be accomplished by setting the credentials object to a null value.
job('job-name') {
    publishers {
        veracodeNotifier {
            credentials(null)
        }
    }
}

The way this works, is the configuration settings for the Veracode plugin is not checking for a value of a field, it is checking that the credentials object is null, and that the global credentials are set.


text:
Q: Condition on a field that makes every subring an integrally closed domain
I want to know what condition would need to be additionally imposed on a field to make every subring of the field an integrally closed domain.


text:
Q: Apply Itô's Lemma to $\left| X_t\right|^2$ We start with the stochastic differential equation
$$\mathrm{d}X_t=\lambda X_t\mathrm{d}t + \sigma X_t \mathrm{d}W_t,$$
where $\lambda,\sigma\in\mathbb{C}$.
I would like to apply Itô formula to obtain an equation for $\mathrm{d}\left|X_t\right|^2.$
Here's my attempt (using the fact that $|X_t|^2 = \mbox{Re}(X_t)^2+\mbox{Im}(X_t)^2$):
$$\mathrm{d}\left|X_t\right|^2=2\lambda X_t \Big(\mbox{Re}(X_t)+\mbox{Im}(X_t)\Big)\mathrm{d}t + |\sigma|^2\left|X_t\right|^2\mathrm{d}t+\mathrm{d}M_t,$$
where $\mathrm{d}M_t$ is the martingale term.
However, the notes I'm looking at say that we get
$$\mathrm{d}\left|X_t\right|^2=(2\mbox{Re}(\lambda)+|\sigma|^2)\left |X_t\right|^2\mathrm{d}t+\mathrm{d}M_t.$$
How did they get that, and how does the real part of $\lambda$ come into play?

A: If we treat $X$ as an $\mathbb{R}^2$-valued process, Itô's lemma says the relevant drift term is given by $\nabla f(X_t) \cdot \lambda X_t dt$.
You're right that $\renewcommand{\Re}{\operatorname{Re}}\renewcommand{\Im}{\operatorname{Im}}\nabla f(X_t) = (2 \Re(X_t), 2 \Im(X_t))$.  But then $$\lambda X_t = (\Re(\lambda) \Re(X_t) - \Im(\lambda) \Im(X_t), \Re(\lambda) \Im(X_t) + \Im(\lambda) \Re(X_t)).$$  When you dot these, you find that the $\Im(\lambda)$ terms cancel and leave you with $$2 \Re(\lambda)(\Re(X_t)^2 + \Im(X_t)^2) = 2 \Re(\lambda) |X_t|^2.$$


text:
Q: How to set margins for h2 and buttons in HTML? I am new to HTML (I am working on Android). I try to create a web page. My web page contains  h2 (heading), table, image, edittext and buttons. One h2 is on the left side of the web page and another h2 is on the right side of the web page. I am using the following code:

<title>VacantTable And Waiter Status</title>

Allot Table Number

Table status style</h21>

but it is showing on the right side of the web page. I am able to display the table, but how to display a button at the bottom of the table?

A: Do one thing give each h2 different classes and apply css to them differently.

Allot Table Number

Table status style

Above is your html.Then in your css write :
h2.left_heading{
  color:orange;
  float:left;
}
h2.right_heading{
 color:orange;
 float:right;
}

A: You should play with id's (normally unique per page) or classes (non unique per page). That way you can differentiate between 2 sections sharing the same tag.
More info at the CSS section at W3schools
The sanest option here seems:

<title>VacantTable And Waiter Status</title>

Allot Table Number

Table status style</h21>

A: I see two main problems with the code as you have it. First off, in the actual HTML, the second h2 tag is closed with a </h21> instead of
.
Secondly, you seem to be misunderstanding a little about how CSS works. When you have two rules that 'overlap', then they get merged when a tag uses them. When two rules have different values for the same properties, CSS has several tricks for deciding which rule's property will be preserved.
The first trick is the 'weight' of the rule, which is just a count of the number of ids, then classes, then HTML tags in the rule. The second trick is the !important property, which tells the count that this rule is not weighted.
The third trick is the one you're running into here. If two rules have the same weight, then the last one defined takes precedence, which should mean that here, both of your h2 tags will be right aligned. You can look here for more information on CSS precedence.
Anyway, what you probably want to do is make different classes for your h2 tags, so that each has a class that gives it its properties that differ from standard h2 tags. That could be something like this:
CSS:
h2 {
  color:orange;
}
/* This .right is a class that can be included on any tag, no matter what type,
   and then that tag will inherit all these properties. */
.right {
  text-align: right;
}
.left {
  text-align: left;
}

HTML:

Allot Table Number

Table status style

A: There are many ways to apply styles, you can try this:

<title>VacantTable And Waiter Status</title>

Allot Table Number

Table status style


text:
Q: How to retrieve data collection from cloud firestore database I am trying to retrieve all the fields in my collection, but i am only able to retrieve one field in the collection personalinfo instead of the entire content of the collection. Is there a way to retrieve all the fields in the collection of personalinfo?
this are my code to save data to cloud firestore database
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grocery_shopping/pages/order_successful/order_successful.dart';

class PersonalInformation extends StatelessWidget {
   PersonalInformation ({Key? key}) : super(key: key);

  TextEditingController fullname = new TextEditingController();
   TextEditingController address = new TextEditingController();
   TextEditingController city = new TextEditingController();
   TextEditingController zipcode = new TextEditingController();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text("Checkout")),
      body: Container(
        padding: EdgeInsets.all(40.0),
        child: Center(
          child: Column(
            children: [
              TextFormField(
                controller: fullname,
                decoration: InputDecoration(
                hintText: "Full Name"
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              TextFormField(
                controller: address,
                decoration: InputDecoration(
                    hintText: "Address"
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              TextFormField(
                controller: city,
                decoration: InputDecoration(
                    hintText: "City"
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              TextFormField(
                controller: zipcode,
                decoration: InputDecoration(
                    hintText: "Zipcode"
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              TextButton(
                  onPressed: (){
                  Map <String,dynamic> data= {"field1": fullname.text,"field2": address.text,"field3": city.text, "field4": zipcode.text};
                  FirebaseFirestore.instance.collection("personalinfo").add(data);
                  } ,
                  child: Text("Submit"),
              ),

              TextButton(
                onPressed: () {
                 Navigator.push(context, MaterialPageRoute(builder: (BuildContext context)=> OrderSuccessful()));
                },

                child: Text("Continue"),
              ),

              ElevatedButton(
                onPressed: () => Get.to(() => OrderSuccessful()),
                child: Text('Continue'),
              ),
            ],
          ),
        ),
      )
    );
  }
}

this are my code for the data retrieve in cloud firestore database
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class OrderSuccessful extends StatefulWidget {
  @override
  _OrderSuccessfulState createState() => _OrderSuccessfulState();
}

  class _OrderSuccessfulState extends State<OrderSuccessful>{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Order Successful")),
      resizeToAvoidBottomInset: true,

      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('personalinfo').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
        if (!snapshot.hasData){
          return Text("no value");
        }
        return ListView(
          children: snapshot.data!.docs.map((document){
            return Text(document['field1']);
          }).toList(),
        );
        },
        ),
    );
  }
}

A: If you are able to access one field, then it means that you can access the remaining ones too.
If document['field1'] works, then you can write document['field2'] to get the second field & so on.
  class _OrderSuccessfulState extends State<OrderSuccessful>{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Order Successful")),
      resizeToAvoidBottomInset: true,

      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('personalinfo').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
        if (!snapshot.hasData){
          return Text("no value");
        }
        return ListView(
          children: snapshot.data!.docs.map((document){
            // You can use a different widget like ListTile here if you want
            return Text(document['field1'] + " " + document['field2'] + " " + document['field3'] + " " + document['field4']);
          }).toList(),
        );
        },
        ),
    );
  }
}

// using ListTile widget
return ListView.builder(
  itemBuilder: (BuildContext context, int index) {
    return ListTile(
      title: Text(data['item1']),
      subtitle: Text(data['item2']),
    );
  },
);


text:
Q: How to find compiler errors in C macros? We have a code base that relies on lots of generated code generated by C macros.
If something goes wrong and there is a error or a warning, the compiler points at the line of the first macro expansion without telling more about where it went wrong inside the expanded code. I my particular case they are those /analyze warnings in Visual Studio.
Are there any tricks and tips that help find problems in complex preprocessor macros?
EDIT:
If you wonder why this code base have complex macros.
This is an emulator project where the decoding phase and execution phase is separated. For example instead of finding out during the execution of each instruction what addressing mode or operand size, etc is used, we generate a function for each combination with a DEFINE_INSTRUCTION macro which in turn generate the functions for all combinations. And chain these functions.

A: *

*idea: dont ;) don't use macros that are complicated as you loose a lot of IDE support / compiler support

=> if you have such macros, refactor them into functions... maybe even inline functions
but seriously. to help you with the bad macros you're stuck with: As TripeHound said, there are flags to 'compile' C files only to the stage of preprocessed C files --
On the command line, clang -E foo.m will show you the preprocessed output.


text:
Q: Why does the UAC dialog take a long time to be displayed? I am working on a Windows installer using the WIX toolkit, and it takes FOR EVER (15-45 seconds) for the UAC dialog to pop up during an install. is there any way to speed this up?

A: Thanks to joegrage for pointing me in the right direction on this one.  The trick to this seems to be the MSIFASTINSTALL property.
The MSIFASTINSTALL property can be used to reduce the time required to install a large Windows Installer package. The property can be set on the command line or in the Property table to configure operations that the user or developer determines are non-essential for the installation.
The value of the MSIFASTINSTALL property can be a combination of the following values.
value  Meaning
-----  -----------------------------------------------------------
0      Default value
1      No system restore point is saved for this installation.
2      Perform only File Costing and skip checking other costs.
4      Reduce the frequency of progress messages.

In WIX, you can use a combination of these values like so:
<Property Id="MSIFASTINSTALL" Value="3" />

A more detailed write up about this property can be found on this blog post.

A: Everytime you install software using Windows Installer, a restore point is created prior to do the actual installation. Ref: http://msdn.microsoft.com/en-us/library/aa372060.aspx
You can turn this off in the registry: http://msdn.microsoft.com/en-us/library/aa369758.aspx

A: This happens because Windows is checking if the package has a digital signature.
Unfortunately the digital signature verification algorithm is not very good. Also, its performance depends on the package size. So a bigger package will have a longer delay.
To avoid the delay you can add a simple EXE bootstrapper to your MSI. It's purpose is to request elevation through an application manifest and launch the MSI next to it. If you don't include your MSI in it, the bootstrapper will have a small size. So the digital signature check will be very fast.


text:
Q: How to reverse the scroll movement? I try to make a reverse navigation. I show the page from the bottom with scrollTo.
I want reverse the wheel movement, when the whell movement is down the page goes to the top.
The body has a fix height so I use:
 window.scrollTo(0, 2000);

A: Prevent the default wheel event action and then  programmatically do the exact reverse of it using window.scrollTo method. Where use deltaX and deltaY to get scroll amount and scrollX and scrollY positithe on to get current scroll position.

document.getElementById('div').addEventListener('wheel', function(e) {
  e.preventDefault()
  window.scrollTo(window.scrollX - e.deltaX, window.scrollY - e.deltaY)
});
body {
  height: 100vh;
}

#div {
  height: 2000px;
  overflow: auto;
}

Check polyfill for making stable across different browsers.


text:
Q: It does not return the expected output The intention of my script is to print the users who have inactive days of more than 30. This is my script:
#!/bin/bash

max=30
grep -E ^[^:]+:[^\!*] /etc/shadow | awk -F: '{print $1" "$7}' | while read user days
do
    if [ $days -gt $max ]
    then
        echo $user
        echo $days
    fi
done

I created 2 users, test and test2 each with 30 days and 50 days inactivity respectively. This script returns me both when I only need to print test2 with 50 days of inactivity.

A: I think you are making this more complicated than needed.
Since you already have awk in your pipe, that can replace grep and compare to max.
Simple example.
Given:
cat file
dawg 2 3 4 5 6 45
boosh 2 3 4 5 6 25

You can do:
max=30
awk -v max="$max" '$7>max{print $1, $7}' shadow
dawg 2 3 4 5 6 45

I left out the grep portion but you can either keep that as a pipe (if it is working) or integrate into the awk.

If you want to compare two integers in Bash, you either need to use the correct test, which is (( arithmetic context ))
$ (( 1>2 )); echo $?
1
$ (( 10>2 )); echo $?
0
# 0 means TRUE

or the correct operator which is [ -gt ]:
$ [ 10 -gt 2 ]; echo $?
0
$ [ 1 -gt 2 ]; echo $?
1

But if you use > inside of [[ .. ]] you are actually comparing strings and may be the wrong answer:
$ [[ 10 < 2 ]]; echo $?
0                      # '0' means 'true' 10 < 2 only as strings

And you must use double [[ .. ]] to use > otherwise it is the redirection operator. (Thanks M. Nejat Aydin
...)


text:
Q: How to combine two data frames using dplyr or other packages? I have two data frames:
df1 = data.frame(index=c(0,3,4),n1=c(1,2,3))
df1
#  index n1
# 1    0  1
# 2    3  2
# 3    4  3

df2 = data.frame(index=c(1,2,3),n2=c(4,5,6))
df2
#   index n2
# 1     1  4
# 2     2  5
# 3     3  6

I want to join these to:
  index n
1     0 1
2     1 4
3     2 5
4     3 8  (index 3 in two df, so add 2 and 6 in each df)
5     4 3
6     5 0  (index 5 not exists in either df, so set 0)
7     6 0  (index 6 not exists in either df, so set 0)

The given data frames are just part of large dataset. Can I do it using dplyr or other packages in R?

A: Using data.table (would be efficient for bigger datasets).  I am not changing the column names, as the rbindlist uses the name of the first dataset ie. in this case n from the second column (Don't know if it is a feature or bug).  Once you join the datasets by rbindlist, group it by column index i.e. (by=index) and do the sum of n column (list(n=sum(n)) )
 library(data.table)
 rbindlist(list(data.frame(index=0:6,n=0), df1,df2))[,list(n=sum(n)), by=index]
     index n
 #1:     0 1
 #2:     1 4
 #3:     2 5
 #4:     3 8
 #5:     4 3
 #6:     5 0
 #7:     6 0

Or using dplyr.  Here, the column names of all the datasets should be the same. So, I am changing it before binding the datasets using rbind_list.  If the names are different, there will be multiple columns for each name.  After joining the datasets, group it by index and then use summarize and do the sum of column n.
 library(dplyr)
 nm1 <- c("index", "n")
 colnames(df1) <- colnames(df2) <- nm1
 rbind_list(df1,df2, data.frame(index=0:6, n=0)) %>%
                                          group_by(index) %>%
                                          summarise(n=sum(n))

A: This is something you could do with the base functions aggregate and rbind
df1 = data.frame(index=c(0,3,4),n=c(1,2,3))
df2 = data.frame(index=c(1,2,3),n=c(4,5,6))
aggregate(n~index, rbind(df1, df2, data.frame(index=0:6, n=0)), sum)

which returns
  index n
1     0 1
2     1 4
3     2 5
4     3 8
5     4 3
6     5 0
7     6 0

A: How about
names(df1) <- c("index", "n")                # set colnames of df1 to target
df3 <- rbind(df1,setNames(df2, names(df1)))  # set colnnames of df2 and join
df <- df3 %>% dplyr::arrange(index)          # sort by index

Cheers.


text:
Q: Ошибка при соединении с MSSQL из PHP Добрый день.
PHP 7, IIS 7.5 Windows Server 2008r2
при попытке подключения к MSSQL возникает ошибка:
PHP Fatal error:  Uncaught Error: Call to undefined function sqlsrv_connect() in C:\inetpub\путь\connect.php:4
Stack trace:
#0 {main}
  thrown in C:\путь\connect.php on line 4

в php.ini директива extension=php_mssql.dll отсутствует, самого php.ini в этом релизе нет, его заменили на php.ini-development и php.ini-production
Сам скрипт:
$serverName = "mssql02\";
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
     echo "Соединение удалось.<br />";
}else{
     echo "Соединение не удалось, ошибка:";
     die( print_r( sqlsrv_errors(), true));
}

то что нет имени сервера, пользователя, пароля и тд это не ошибка, просто убрал специально
PDO загрузил, закинул в папку ext:

в php конфиге добавил строчку:

но оно не хочешь работать
в выводе пхпинфо вообще нет PDO драйверов

A: ODBC драйвер в винду установите.
Вот тут куча ссылок куда и что устанавливать
http://fi2.php.net/manual/ru/ref.pdo-sqlsrv.php
Особенно полезные в комментариях (ODBC драйвер)
http://www.microsoft.com/en-us/download/details.aspx?id=20098


text:
Q: Deleting duplicates in a table based on a criteria only in SQL Let's say I have a table with columns:
CustomerNumber
Lastname
Firstname
PurchaseDate

...and other columns that do not change anything in the question if they're not shown here.
In this table I could have many rows for the same customer with different purchase dates (I know, poorly designed... I'm only trying to fix an issue for reporting, not really trying to fix the root of the problem).
How, in SQL, can I keep one record per customer with the latest date, and delete the rest?  A group by doesn't seem to be working for my case

A: ;with a as
(
select row_number() over (partition by CustomerNumber, Lastname, Firstname order by PurchaseDate desc) rn
from <table>
)
delete from a where rn > 1

A: This worked for me (on DB2):
 DELETE FROM my_table
 WHERE (CustomerNumber, Lastname, Firstname, PurchaseDate)
 NOT IN (
       SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate)
       FROM my_table
       GROUP BY CustomerNumber, Lastname, FirstName
 )

A: SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) LatestPurchaseDate
FROM Table
GROUP BY CustomerNumber, Lastname, Firstname

The MAX will select the highest (latest) date and show that date for each unique combination of the GROUP BY columns.
EDIT: I misunderstood that you wanted to delete records for all but the latest purchase date.
WITH Keep AS
(
    SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) LatestPurchaseDate
    FROM Table
    GROUP BY CustomerNumber, Lastname, Firstname
)
DELETE FROM Table
WHERE NOT EXISTS
(
    SELECT *
    FROM Keep
    WHERE Table.CustomerNumber = Keep.CustomerNumber
    AND Table.Lastname = Keep.Lastname
    AND Table.Firstname = Keep.Firstname
    AND Table.PurchaseDate = Keep.LastPurchaseDate
)


text:
Q: LSTM pytorch not learning I am learning LSTM and language models, I developed the following code for a character level text generation:
Here is the model class:
class RNN(nn.Module):
    def __init__(self, input_size, embedding_dim, hidden_size, num_layers, output_size):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
                 # Layers:
        self.embed = nn.Embedding(input_size, embedding_dim, padding_idx=0)
        self.dropout = nn.Dropout(0.5)  # regularization to reduces overfitting and to increase stability
        self.lstm = nn.LSTM(embedding_dim, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)
        self.o = nn.Softmax(dim=1)

    def forward(self, x, hidden, cell):
        out = self.embed(x)
        out = self.dropout(out)
        out, (hidden, cell) = self.lstm(out.unsqueeze(1), (hidden, cell))
        out = self.fc(out.reshape(out.shape[0], -1))
        out = self.o(out)
        return out, (hidden, cell)

    def init_hidden(self, batch_size):
        hidden = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
        cell = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
        return hidden, cell

n_chars, embedding_dim, hidden_size, num_layers, output_size = 55, 20, 256, 2, 55
model = RNN(n_chars, embedding_dim,  hidden_size, num_layers, n_chars).to(device)

And this is the train function, where I have the problem:
def train(model, optimizer, criterion, epochs=10, every=5):
    for epoch in range(epochs):
        k = random.randint(0,len(data))
        x, y = get_batch(k)
        xt, yt = tensorize(x,y)
        mean_loss = 0
        L = len(xt)

        for i in range(L):
            hidden, cell = model.init_hidden(batch_size)  # not doing this will cause an error
            out, (hidden, cell) = model(xt[i].unsqueeze(0), hidden, cell)
            target = yt[i].unsqueeze(0)

            loss = criterion(out, target)

            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
            mean_loss += loss.item()

        if epoch % every == 0:
            print("epoch = ", epoch ," mean loss = ", mean_loss/L)

However, the loss seems to not change at all. What did I do wrong, please?
Note: I am giving the model character by character and not the entire batch at once.


text:
Q: c# and sql how to show selected item price in textbox enter image description here
what i need is when i selected item in combobox to show in listbox and his price in the cost textbox and sum price if i choose another items
this is my code
public void fill_listbox()
{
SqlDataAdapter da = new SqlDataAdapter("select TestCost,TestName from TestTbl", con);
DataSet dt = new DataSet();
da.Fill(dt, "TestName");
TestidCb.DataSource = dt.Tables["TestName"];
TestidCb.DisplayMember = "TestName";
TestidCb.ValueMember = "TestCost";
TestidCb.Text = "Select NorTest";
    }

    string TR = "";
    int GrdCost = 0;
    private void OkBtn_Click(object sender, EventArgs e)
    {
        if (LabidCb.SelectedIndex == -1 )
        {
            MessageBox.Show("select the Test And Lab");
        }
        else
        {
            TR = TR + "|" + TestidCb.Text;
            TestTb.Text = TR;
            GrdCost = GrdCost +Cost;
            CostTb.Text = "" + GrdCost;
            //TestidCb.SelectedIndex = -1;
            //LabidCb.SelectedIndex = -1;
            //StNameTb.Text = "";
            Reset1();
        }

}

A: This will get you started. The ExecuteNonQuery has been removed because it serves no purpose.
I added "TestPrice" to the SELECT statement.
I have bound the DataTable to the combobox instead of added items in a loop.
I set both a DisplayMember and ValueMember. The user will only see TestName, but the value of the items is the price.
public void fill_list()
{
    try
    {
        con.Open();
        using(SqlCommand cmd = con.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select TestName, TestPrice from TestTbl";

            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);

            TestidCb.DataSource = dt;
            TestidCb.DisplayMember = "TestName";
            TestidCb.ValueMember = "TestPrice";
        }
    }
    finally
    {
        con.Close();
    }
}

Now, in the selected changed event for instance, you can get both TextName and the price and do whatever you need:
private void TestidCb_SelectedIndexChanged(object sender, EventArgs e)
{
    string name = ((ComboBox)sender).Text;
    string price = ((ComboBox)sender).SelectedValue.ToString();

    MessageBox.Show($"Name: {name}, Price: {price}");
}

A: create a class myProductListItem having 2 properties, name and price
get both the name and the price in your query (select testname, price from TestTbl)
put these in an instance of myProductListItem and put that in your combobox.items
        public class myListItem
        {
            public string Name { get; set; }
            public decimal Price { get; set; }

            public override string ToString()
            {
                return Name;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add(new myListItem(){Name = "myname",Price = 10});
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selected = comboBox1.SelectedItem as myListItem;
            if (selected != null)
            {
                textBox1.Text = selected.Price.ToString();

            }
        }


text:
Q: How to maintain order of data frame when making pandas pivot table trying to make a heat map out of a pivot table but am having trouble keeping the order of how I sorted my original data frame. Below is a sample code of what my data looks exactly like and how I made my pivot table.
simple_df = pd.DataFrame({'Skill 1': ['Python','Python','Python','Communication','Communication','Communication','Data Governance','Data Governance','Data Governance'], 'Skill 2': ['Python','Communication','Data Governance','Python','Communication','Data Governance','Python','Communication','Data Governance'],'Score':[1,0.9,0.4,0.9,1,0.4,0.4,0.4,1],'Skill 1 Type':['Programming','Programming','Programming','Written','Written','Written','Cyber','Cyber','Cyber']})
simple_df=simple_df.sort_values(by = ['Skill 1 Type'], ascending = [True], na_position = 'first')
test=simple_df.groupby(['Skill 1','Skill 2'], sort=True)['Score'].sum().unstack('Skill 2')

Since I sorted on "Skill 1 Type", I would like to have the pivot table's y-axis labels keep the same order of how "Skill 1" appears in my sorted dataframe. So ideally, I would have (Data Governance, Python, Communication) rather than (Communication, Data Governance, Python) on my y axis. What are some ways I can do this? Thank you!

A: You can save the original order and then use reindex to swap the columns and rows.
original_order = simple_df["Skill 1"].unique()
(simple_df.pivot(index="Skill 1", columns="Skill 2", values="Score")
 .reindex(index=original_order, columns=original_order))

Skill 2          Data Governance  Python  Communication
Skill 1
Data Governance              1.0     0.4            0.4
Python                       0.4     1.0            0.9
Communication                0.4     0.9            1.0


text:
Q: Using Athena Terraform Scripts Amazon Athena reads data from input Amazon S3 buckets using the IAM credentials of the user who submitted the query; query results are stored in a separate S3 bucket.
Here is the script in Hashicorp site https://www.terraform.io/docs/providers/aws/r/athena_database.html
resource "aws_s3_bucket" "hoge" {
  bucket = "hoge"
}

resource "aws_athena_database" "hoge" {
  name = "database_name"
  bucket = "${aws_s3_bucket.hoge.bucket}"
}

Where it says
bucket - (Required) Name of s3 bucket to save the results of the query execution.

How can I specify the input S3 bucket in the terraform script?

A: You would use the storage_descriptor argument in the aws_glue_catalog_table resource:
https://www.terraform.io/docs/providers/aws/r/glue_catalog_table.html#parquet-table-for-athena
Here is an example of creating a table using CSV file(s):
resource "aws_glue_catalog_table" "aws_glue_catalog_table" {
  name          = "your_table_name"
  database_name = "${aws_athena_database.your_athena_database.name}"
  table_type    = "EXTERNAL_TABLE"

  parameters = {
    EXTERNAL = "TRUE"
  }

  storage_descriptor {
    location      = "s3://<your-s3-bucket>/your/file/location/"
    input_format  = "org.apache.hadoop.mapred.TextInputFormat"
    output_format = "org.apache.hadoop.mapred.TextInputFormat"

    ser_de_info {
      name                  = "my-serde"
      serialization_library = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"

      parameters = {
        "field.delim"            = ","
        "skip.header.line.count" = "1"
      }
    }

    columns {
      name = "column1"
      type = "string"
    }

    columns {
      name = "column2"
      type = "string"
    }

  }
}

A: The input S3 bucket is specified in each table you create in the database, as such, there's no global definition for it.
As of today, the AWS API doesn't have much provision for Athena management, as such, neither does the aws CLI command, and nor does Terraform. There's no 'proper' way to create a table via these means.
In theory, you could create a named query to create your table, and then execute that query (for which there is API functionality, but not yet Terraform). It seems a bit messy to me, but it would probably work if/when TF gets the StartQuery functionality. The asynchronous nature of Athena makes it tricky to know when that table has actually been created though, and so I can imagine TF won't fully support table creation directly.
TF code that covers the currently available functionality is here: https://github.com/terraform-providers/terraform-provider-aws/tree/master/aws
API doco for Athena functions is here: https://docs.aws.amazon.com/athena/latest/APIReference/API_Operations.html


text:
Q: How to upload a series of Excel 2013 files using ASP.NET and C# I am trying to use Microsoft Visual Studio Express 2013 for Web to create a C# program that can process through a list of Excel files (*..xlsx) and read in data from the files.
To begin, I created a webform with a FileUpload control I use to select a file and a Button control I can click to start the import process.  I also have a GridView control to display the data.
I can upload and display data from a single file, but when I upload a second file, click the button control to display the data, I get an error message. "External table is not in the expected format"
Note that I am running a 32-bit version of Excel 2013 on a 64-bit computer.
Below is my code.
Any suggestions???
JBIT
namespace Test
{
    public partial class WebForm3_ExcellImport_Aymiee : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string connectionString = "";
            if (FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string fileLocation = Server.MapPath("~/ExcelFile/" + fileName);
                TextBox1.Text = fileLocation;
                FileUpload1.SaveAs(fileLocation);
                if (fileExtension == ".xls")
                {
                    connectionString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                    + fileLocation + ";Extended Properties = \"Excel 8.0;HDR=YES\"";
                }
                else if (fileExtension == ".xlsx")
                {
                    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                      fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                }
                OleDbConnection con = new OleDbConnection(connectionString);
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = con;
                OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
                DataTable dtExcelRecords = new DataTable();
                try
                {
                    con.Open();
                    cmd.CommandText = "SELECT [ID],[Name],[Designation] from [Sheet1$]";
                    dAdapter.SelectCommand = cmd;
                    dAdapter.Fill(dtExcelRecords);
                    GridView1.DataSource = dtExcelRecords;
                    GridView1.DataBind();
                    TextBox1.Text = "Succeeded";
               }
               catch (Exception exp)
               {
                   throw exp;
               }
               finally
               {
                   dAdapter.Dispose();
                   con.Close();
                   con.Dispose();
               }

            }
        }
    }
}


text:
Q: Input file doesn't inherit the main language settings I want to create a multi language document using the fontspec package and building the document with XeLaTeX. Even though multi language characters work fine in the main .tex file, if they be inserted via an \input method, they are unrecognizable.  Here's the main file:
\documentclass[a4paper,11pt,oneside]{book}
\usepackage[a4paper, top=1.75cm, bottom=1.75cm, left=1.5cm, right=1.5cm]{geometry}
\usepackage{graphicx}
\setlength{\parskip}{\baselineskip}%
\setlength{\parindent}{0pt}%

\usepackage{fontspec}
\fontspec{Arial}
\setmainfont{Arial}
\setmainfont[Mapping=tex-text]{Arial}

\begin{document}

\input{chapter_01_test}

...............................

one two three four five

ein zwei drei vier fünf

ένα δύο τρία τέσσερα πέντε

\end{document}

and here is the external file chapter_01_test.tex :
 one two three four five

 ein zwei drei vier fünf

 ένα δύο τρία τέσσερα πέντε

this is the outcome:

So the question is why the imported file is unable to inherit the language settings as described on the main file?
Any ideas would be appreciated.


text:
Q: SQL querying for segment positive values and negative and sum the value for distinct name
My querying is as following:
SELECT DISTINCT name, money CASE
         WHEN [money] < 0 THEN SUM(money) GROUP BY name
       END AS "sum_of_withdraws"
       CASE
         WHEN [money] >= 0 THEN SUM(money) GROUP BY name
       END AS "sum_of_deposits"
FROM table

Can anyone show a correct querying or improve my querying?

A: I think you want:
SELECT name,
       SUM(CASE WHEN [money] < 0 THEN money
           END) AS sum_of_withdraws,
       SUM(CASE WHEN [money] >= 0 THEN money
           END) AS "sum_of_withdraws"
FROM table
GROUP BY name;

The CASE expression is an argument to SUM().  And GROUP BY is an entirely separate clause that follows FROM.

A: Find this query...
SELECT
    [name],
    SUM(CASE WHEN [money] >=0   THEN [Money] else 0 END)    sum_of_deposits,
    SUM(CASE WHEN [money] <0    THEN [Money] else 0 END)*-1 sum_of_withdrawals
FROM
    transfers
GROUP BY
    [name]


text:
Q: Ext JS: Scroll reset on Tab Change I'm using Ext JS v4.2.1 to draw a Tab panel in Screen and show some content -that can get quite big- in each tab. For that, Iuse something like this:
var createTab = function (tabName, panelName){
                    return {xtype: 'container',
                            title: tabName,
                            autoScroll: true,
                            layout: {
                                type: 'vbox',
                                align: 'stretch'
                            },
                            items: [
                                {
                                    title: panelName,
                                    items: [Ext.create( 'MyLongView' )]
                                }
                            ]};
            };

var tabPanel = new Ext.tab.Panel({
            renderTo: 'testDiv',
            flex: 1,
            border: false,
            itemId: 'tabPanel',
            items: [createTab('First Tab', 'First Panel'),
                    createTab('Second Tab', 'Second Panel')]
        });

When I tried that code in Internet Explorer, each Tab Change resets the scroll position to the top, a Bug that doesn't happen nor in Chrome or in Firefox. To reproduce it, follow this steps in an IE Window:

*

*Create a Tab Panel, with to Tabs inside them.

*In the first Tab, scroll down to the bottom.

*Then, select the Second Tab.

*Finally, return to the first tab. You'll see that the scroll that you left in the bottom is now in the top.

The expected behavior is that the scroll stays where you left it. Searching through Sencha forums, I found that they suggest the use of hideMode: 'offsets' but that doesn't work for me. Any ideas?
PS: I created a Fiddle to show the bug. Please, only try that on IE (I don't know why it doesn't work on Chrome/Firefox).


text:
Q: HTML Layout Cleanup? I making a jsp which ncludes 5 jsp's all together.  On my 4th one..it's operational but.. my design looks a lil clunky.  Can you point out any suggestions to make it look better or cleaner?  Any suggestions would be appreciated.  Thanks
CSS
    table.det
{ }

 table.det td
 {
 border: none;

 }

fieldset.det
{
display:block;
float:left;

font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
margin-top:20px;
margin-left:20px;
border:2px solid #CCCCCC;

}
 fieldset.det legend
   {
    padding:2px 5px;
    border:2px solid #CCCCCC;

   }

jsp:

Filters

    Workload Year: <select size="1" name="wYearSelect">
                            <option value="2007">2007</option>
                            <option value="2008">2008</option>
                            <option value="2009">2009</option>
                            <option value="2010">2010</option>
                            <option value="2011">2011</option>
                            <option selected value="2012">2012</option>
                            <option value="2013">2013</option>
                            <option value="2014">2014</option>
                       </select>
    Fiscal Year: <select size="1" name="wYearSelect">
                            <option value="2007">2007</option>
                            <option value="2008">2008</option>
                            <option value="2009">2009</option>
                            <option value="2010">2010</option>
                            <option value="2011">2011</option>
                            <option selected value="2012">2012</option>
                            <option value="2013">2013</option>
                            <option value="2014">2014</option>
                       </select>

    Condition Code: <select size="1" name="condCodeSelect">
                            <option selected value=""> </option>
                            <option value="2007">A</option>
                            <option value="2008">B</option>
                            <option value="2009">C</option>
                            <option value="2010">D</option>
                            <option value="2011">E</option>
                            <option value="2012">F</option>
                            <option value="2013">G</option>
                            <option value="2014">H</option>
                       </select>

    Customer: <select size="1" name="customerSelect">
                            <option selected value=""> </option>
                                                       </select>

    Repair Facility: <select size="1" name="repFacSelect">
                            <option selected value=""> </option>
                                                          </select>

    Work Type: <select size="1" name="workTypeSelect">
                            <option selected value=""> </option>
                            <option value="10">Rebuild</option>
                            <option value="11">IROAN</option>
                            <option value="12">SOAR</option>
                            <option value="13">Special</option>
                       </select>
    Special Indicator: <select size="1" name="specIndSelect">
                            <option selected value=""> </option>
                            <option value="RST">RESET</option>
                       </select>
    WBS: <select size="1" name="wbsSelect">
                    <option selected value=""> </option>

              </select>

    Appropriation: <select size="1" name="appropSelect">
                            <option selected value=""> </option>
                                                        </select>

    MWSLIN: <input type="text" name="mwslin" value=""/>
    Serial #: <input type="text" name="mwslin" value=""/>
    <input type="checkbox" name="include_carryover">Include Carryover</input>

    <fieldset>
        <legend>Standard Materiel filter structure here</legend>
    NSN: <input type="text" name="nsn" value=""/>
    TAMCN: <input type="text" name="tamcn" value=""/>
    PGD/Group: <input type="text" name="pgd" value=""/>
    SAC : <select size="1" name="condCodeSelect">
                            <option selected value=""> </option>
                            <option value="2011">1</option>
                            <option value="2012">2</option>
                            <option value="2013">3</option>
                        </select>

    Nomenclature: <input type="text" name="nomen" value=""/>
    </fieldset>

    <fieldset class="det">
        <legend>Source of Repair</legend>
        <input type="checkbox" name="sorCodes" value="A">MCA   </input>
               </fieldset>
    <fieldset class="det">
        <legend>Schedule Type</legend>
        <input type="checkbox" name="schedType" value="1">Regular</input>

        <input type="checkbox" name="schedType" value="2">Lot Job</input>

        <input type="checkbox" name="schedType" value="3">Batch Job</input>
    </fieldset>
    <fieldset class="det">
        <legend>Workload Type</legend>
        <input type="checkbox" name="workloadType" value="1">SMC Workload</input>

        <input type="checkbox" name="workloadType" value="2">Other Workload</input>
    </fieldset>
    <fieldset class="det">
        <legend>Closure Level</legend>
        <input type="checkbox" name="workloadType" checked value="1">Open</input>

        <input type="checkbox" name="workloadType" value="1">Physically Complete</input>

        <input type="checkbox" name="workloadType" value="2">Financially Complete</input>
    </fieldset>

<button name="Generate Report" value="Generate Report">Generate Report</button>

<button name="Clear Criteria" value="Clear Criteria">Clear Criteria</button>

A: At a first glance, getting rid of the tables would be somewhere to start if you can.
I am headed to work will look over it more thoroughly there.
Cheers!
EDIT - You could take out the border on your fieldset.det legend, it should cascade down from fieldset.det
On your div id=filtering, couldn't you add the extra styling to the filtering id?
EDIT - Here is something I threw together, not saying it is ANYWHERE near perfect. It gives you a div layout and ways to easily change the layout through CSS. Also, check out this site  for best form practices, http://blog.sherpawebstudios.com/2009/06/17/top-10-html-form-layout-best-practices/.
CSS:
#wrapper{ width: 1040; overflow:hidden; }
#filter {
    cursor: hand;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}

.formLabel {
    font-weight: bold;
    text-align: right;
    width: 160px;
    float: left;
}

.field {
    float: left;
}

.content:before,
.content:after {
    content: "";
    display:table;
}

.content:after {
    clear: both;
}
/*IE 6/7 */
.content { zoom:1;margin-bottom: 10px;}

.subset {
    float: left;
    margin: 0 15;
}

.subset div.formLabel {
    width:100px;
}

#generate {
    margin-right:15px;
}

HTML:

        Filters

            Workload Year:

    <select size="1" name="wYearSelect">
            <option value="2007">2007</option>
            <option value="2008">2008</option>
            <option value="2009">2009</option>
            <option value="2010">2010</option>
            <option value="2011">2011</option>
            <option selected value="2012">2012</option>
            <option value="2013">2013</option>
            <option value="2014">2014</option>
        </select>

        Fiscal Year:

        <select size="1" name="wYearSelect">
            <option value="2007">2007</option>
            <option value="2008">2008</option>
            <option value="2009">2009</option>
            <option value="2010">2010</option>
            <option value="2011">2011</option>
            <option selected value="2012">2012</option>
            <option value="2013">2013</option>
            <option value="2014">2014</option>
        </select>

        Condition Code:

        <select size="1" name="condCodeSelect">
            <option selected value=""> </option>
            <option value="2007">A</option>
            <option value="2008">B</option>
            <option value="2009">C</option>
            <option value="2010">D</option>
            <option value="2011">E</option>
            <option value="2012">F</option>
            <option value="2013">G</option>
            <option value="2014">H</option>
        </select>

        Customer:

        <select size="1" name="customerSelect">
            <option selected value=""> </option>
        </select>

        Repair Facility:

        <select size="1" name="repFacSelect">
            <option selected value=""> </option>
        </select>

        Work Type:

        <select size="1" name="workTypeSelect">
            <option selected value=""> </option>
            <option value="10">Rebuild</option>
            <option value="11">IROAN</option>
            <option value="12">SOAR</option>
            <option value="13">Special</option>
        </select>

        Special Indicator:

        <select size="1" name="specIndSelect">
            <option selected value=""> </option>
            <option value="RST">RESET</option>
        </select>

        WBS:

        <select size="1" name="wbsSelect">
            <option selected value=""> </option>
        </select>

        Appropriation:

        <select size="1" name="appropSelect">
            <option selected value=""> </option>
        </select>

        MWSLIN:

        <input type="text" name="mwslin" value=""/>

        Serial #:

        <input type="text" name="mwslin" value=""/>

        Include Carryover:

        <input type="checkbox" name="include_carryover"></input>

Standard Material filter structure here

                NSN:

                <input type="text" name="nsn" value=""/>

                TAMCN:

                <input type="text" name="tamcn" value=""/>

                PGD/Group:

                <input type="text" name="pgd" value=""/>

                SAC :

                <select size="1" name="condCodeSelect">
                    <option selected value=""> </option>
                    <option value="2011">1</option>
                    <option value="2012">2</option>
                    <option value="2013">3</option>
                </select>

                Nomenclature:

                <input type="text" name="nomen" value=""/>

Source of Repair

            MCA

        <input type="checkbox" name="sorCodes" value="A"></input>

Schedule Type

            Regular

        <input type="checkbox" name="schedType" value="1"></input>

            Lot Job

        <input type="checkbox" name="schedType" value="2"></input>

            Batch Job

        <input type="checkbox" name="schedType" value="3"></input>

Workload Type

            SMC Workload

        <input type="checkbox" name="workloadType" value="1"></input>

            Other Workload

        <input type="checkbox" name="workloadType" value="2"></input>

Closure Level

            Open

        <input type="checkbox" name="workloadType" checked value="1"></input>

            Physically Complete

        <input type="checkbox" name="workloadType" value="1"></input>

            Financially Complete

        <input type="checkbox" name="workloadType" value="2"></input>

<button name="Generate Report" value="Generate Report" id="Generate">Generate Report</button>
<button name="Clear Criteria" value="Clear Criteria">Clear Criteria</button>


text:
Q: Multiple Requests Causing Pod to Crash due to OOM - isn't this the job of a load balancer? I have 2-3 machine learning models I am trying to host via Kubernetes. I don't get much usage on the models right now, but they are critical and need to be available when called upon.
I am providing access to the models via a flask app and am using a load balancer to route traffic to the flask app.
Everything typically works fine since requests are only made intermittently, but I've come to find that if multiple requests are made at the same time my pod crashes due to OOM. Isn't this the job of the load balancer? To make sure requests are routed appropriately? (in this case, route the next request after the previous ones are complete?)
Below is my deployment:
apiVersion: v1
kind: Service
metadata:
  name: flask-service
  labels:
    run: flask-service
spec:
  selector:
    app: flask
  ports:
  - protocol: "TCP"
    port: 5000
    targetPort: 5000
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask
spec:
  selector:
    matchLabels:
      app: flask
  replicas: 1
  template:
    metadata:
      labels:
        app: flask
    spec:
      containers:
      - name: flask
        imagePullPolicy: Always
        image: gcr.io/XXX/flask:latest
        ports:
        - containerPort: 5000
        resources:
          limits:
            memory: 7000Mi
          requests:
            memory: 1000Mi

A:
Isn't this the job of the load balancer? To make sure requests are routed appropriately?

Yes, you are right. But...

replicas: 1

You only use a single replica, so the load balancer has no options to route to other instances of your application. Give it multiple instances.

I've come to find that if multiple requests are made at the same time my pod crashes due to OOM

It sounds like your application has very limited resources.
    resources:
      limits:
        memory: 7000Mi
      requests:
        memory: 1000Mi

When your application uses more than 7000Mi it will get OOM-killed (also consider increase request value). If your app need more, you can give it more memory (scale vertically) or add more instances (scale horizontally).
Horizontal Pod Autoscaler

Everything typically works fine since requests are only made intermittently

Consider using Horizontal Pod Autoscaler, it can scale up your application to more instances when you have more requests and scale down when there is less requests. This can be based on memory or CPU usage for example.
Use a queue

route the next request after the previous ones are complete?

If this is the behavior you want, then you need to use a queue e.g. RabbitMQ or Kafka to process your requests one at a time.


text:
Q: How to sync iCloud Keychains between ios7 and OSX10.9 I am trying to write a program which shares keychain items between iOS7 & OSX 10.9. The 2 devices are a ipad3 & a Mac Pro sharing the same Apple ID.
    I specified the "kSecAttrSynchronizable" key with kCFBooleanTrue before calling the "SecItemAdd" API.
    Actually, items saved by iOS was visible in Mac Keychain Access utility.However, they could not be read because its "access group" is related to the TEAM ID of the app producing them. If I save items on OSX 10.9, their access group was "appleaccount", which could be read by iOS neither.
   Also, I tried the "kSecAttrAccessGroup" attr, but in vain.
   So, anything I missed? I'll appreciate that if any hints are proposed.


text:
Q: Display number of sold variation product in WooCommerce I made variation product (ticket) in WooCommerce and I need to display how many tickets of its variations Ive already sold.
So for example Ive got 1 ticket which has two variations:
'male' and 'female'.
There is any chance I can get counter for each variation ticket sold and display it on my page? So other customers can see how many tickets are bought by males and how many by famales.
**EDIT
I don't really know much about php, but to be more specific:
I made product with variations. So when customers buying it, they can choose between Male and Female. There is 10 tickets for Male and 10 for Females (20 total). I want to display number of product bought by Males and Females, separately.
Ive got something like this
add_action( 'woocommerce_single_product_summary', 'wc_product_sold_count', 11 );
function wc_product_sold_count() {
    global $product;
    $units_sold = get_post_meta( $product->id, 'total_sales', true );
    echo '<p>' . sprintf( __( 'Units Sold: %s', 'woocommerce' ), $units_sold ) . '</p>';
}

But first of all its for number of total sold product, not their variations. Secondly it will display in single product page, there is chance to put it somewhere else?

A: Your question is vague. But to answer your question in its current form, you just have to loop each of the variations and display or echo out $product->get_total_sales();


text:
Q: If $f$ analytic in $G$ and $\exists \lambda >0$, $|f(z)| = \lambda, \forall z \in \partial G \Rightarrow \exists z, f(z) = 0$ Let $f$ be a non-constant analytic function in $G\subseteq \mathbb{C}$ (connected, bounded and open) and cont. in $\overline{G}$ such that
$$\exists \lambda >0, \text{ with } |f(z)| = \lambda, \forall z \in \partial G$$
Then
$$\exists z \in G, \text{ with } f(z) = 0$$
I have two different approaches designed by me and I want to see if I got both right.
First:
Since $f$ is analytic in $G$ and continuous in $\overline{G}$ by the Maximum Modulus Theorem (Second version of Conway's book)
$$\max_{z \in \overline{G}}\{|f(z)|\} = \max_{z \in \partial G}\{|f(z)|\}$$
Then we have that $|f(z)| \leq \lambda, \forall z \in \overline{G}$.
Now consider the function
$$g(z) = \frac{1}{f(z)} $$
Assume $f(z) = 0$ has no solutions in $G$, then $g(z)$ is analytic in $G$ and continuous in $\overline{G}$ because $f$ is, also $g$ satisfies
$$|g(z)| = \frac{1}{|f(z)|} \leq \frac{1}{\lambda}, \forall z \in \overline{G}$$
By the Maximum modulus theorem (first version of Conway's book), there exists $z_m \in \overline{G}$ such that $|g(z_m)| = \frac{1}{\lambda} \geq g(z)$ for all $z \in \overline{G}$. Thus, $g$ is constant which implies that $f$ is constant and we get a contradiction.
Second proof:
Since $f$ is analytic in $G$ and continuous in $\overline{G}$ by the Maximum Modulus Theorem (Second version of Conway's book)
$$\max_{z \in \overline{G}}\{|f(z)|\} = \max_{z \in \partial G}\{|f(z)|\}$$
Also, $f$ is non-constant and by the Open Mapping Theorem, $f$ must map open sets to open sets, but the modulus of $f$ is bounded for every point in $G$, then $f(G) \subset \{z \in \mathbb{C} : |z| < \lambda\}$ and because $f$ is continuous in $\overline{G}$, then $f(\partial G)$ is the border of the disk or contained in it.Hence, the $\operatorname{Range}(f) = \{z \in \mathbb{C}: |z| \leq 1 \}$, and disk pass through the origin, and must exist a point in $G$ such that f(z) = 0.
I will want to make a better description of the second one, but I think that it is enough. Which one is better for a qualifying exam and if I have to fix some details please let me know.

A: First version is not accurate, specifically

... there exists $z_m\in \overline{D}$ such that
  $|g(z_m)|=\frac{1}{λ}\geq g(z)$ for all $z∈\overline{D}$. Thus, $g$ is
  constant ...

$\overline{D}$ is closed, MMP restricts the result to open sets, consequence of this is that $g$ reaches the maximum at the boundary $\partial G \subset \overline{D}$. So $z_m \in \partial G \subset \overline{D}$, no contradictions so far.
To fix the problem, you need to fix a point $z_0 \in D$ (open set!) for which $|f(z_0)|<\lambda$ (you already deducted this), thus $|g(z_0)|=\left|\frac{1}{f(z_0)}\right| > \frac{1}{\lambda} \geq |g(z)|$. So $\exists z_0 \in D$ such
that $|g(z_0)|\geq |g(z)|, \forall z \in D$ and only now you can conclude that $g$ is constant in $D$.