text:
Q: viewForSupplementaryElementOfKind not working because of empty array Sometimes (it does not occur everytime eventhough the data does not change), the headers/ footers in my uiCollectionView cannot be instantiated and the app crashes because I get the following error :
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

I set the size of my footer to 0 when it is in a odd-numbered section.
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view;
    NSLog(@"indexpath section %ld", (long)indexPath.section);
    if(kind == UICollectionElementKindSectionHeader){

        HeaderViewQuestion *headerView = [collectView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderViewQuestion" forIndexPath:indexPath];
        NSString *initial = [[NSString alloc] initWithFormat:@"Question %d : ",(int)indexPath.section+1];
        NSMutableString *text = [[NSMutableString alloc] initWithString:initial];
        [text appendString:[questions objectAtIndex:indexPath.section]];
        NSInteger _stringLength=[text length];

        NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:text];

        [attString addAttribute:NSFontAttributeName
                          value:[UIFont fontWithName:@"Helvetica" size:20.0]
                          range:NSMakeRange(0, _stringLength)];
        [attString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, _stringLength)];

        headerView.label.attributedText = attString;
        view = headerView;
    }
    if(kind == UICollectionElementKindSectionFooter){
        FooterView *footerview = (FooterView*)[collectView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
            footerview.addLine.tag = indexPath.section;
            [footerview.addLine addTarget:self action:@selector(addLine:) forControlEvents: UIControlEventTouchUpInside];
            view = footerview;
    }
    return view;
}

- (CGSize)collectionView:(UICollectionView *)collecView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if(section%2 !=0)
    {
        return CGSizeZero;
    }
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
    return CGSizeMake(flowLayout.itemSize.width, 100);
}
- (CGSize)collectionView:(UICollectionView *)collecView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
    return CGSizeMake(flowLayout.itemSize.width, 100);
}

A: I found the solution :
After removing the following lines :
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
        UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
        if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
            [flowLayout setItemSize:CGSizeMake(screenWidth-6, 50)];
        }else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
            [flowLayout setItemSize:CGSizeMake(screenHeight-24, 50)];
        }

in the method :
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectView cellForItemAtIndexPath:(NSIndexPath *)indexPath

the problem seems to be gone. I think the setting up of the cells in my UiCollectionView was taking to much time, which caused my problem with the footers/headers and the empty array.
This was my code :
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *view;
    if(indexPath.section %2 == 0){
        //create collection view cell
        QuestionCell *cell = (QuestionCell *)[collectView dequeueReusableCellWithReuseIdentifier:@"QuestionCell" forIndexPath:indexPath];
        [cell setTag:indexPath.section];
        //configure cell :
        [cell.textView setTag:indexPath.item];
        [cell.suppress setTag:indexPath.section];
        [cell.suppress addTarget:self action:@selector(deleteLine:) forControlEvents: UIControlEventTouchUpInside];
        view = cell;
    }else{
        YesNo *cell = (YesNo*)[collectView dequeueReusableCellWithReuseIdentifier:@"YesNo" forIndexPath:indexPath];
        UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
            UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
            if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
                [flowLayout setItemSize:CGSizeMake(screenWidth-6, 50)];
            }else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
                [flowLayout setItemSize:CGSizeMake(screenHeight-24, 50)];
            }
        [cell setTag:indexPath.section];

        view = cell;
    }
    return view;
}

And I changed it to this :
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *view;
    if(indexPath.section %2 == 0){
        //create collection view cell
        QuestionCell *cell = (QuestionCell *)[collectView dequeueReusableCellWithReuseIdentifier:@"QuestionCell" forIndexPath:indexPath];
        [cell setTag:indexPath.section];
        //configure cell :
        [cell.textView setTag:indexPath.item];
        [cell.suppress setTag:indexPath.section];
        [cell.suppress addTarget:self action:@selector(deleteLine:) forControlEvents: UIControlEventTouchUpInside];
        view = cell;
    }else{
        YesNo *cell = (YesNo*)[collectView dequeueReusableCellWithReuseIdentifier:@"YesNo" forIndexPath:indexPath];
        [cell setTag:indexPath.section];

        view = cell;
    }
    return view;
}


text:
Q: How to check which child was select In my TreeView I've several values, in particular, this is the structure:
Nations -> Championships (child of each nation) -> Teams (childs of each championship).

For Nation that's a root node I execute a method that perform particular task, the same for championship, but, how can I check if the user has select the Teams? So the child of a Championship?
Actually I do this:
TreeViewItem rootNode = (TreeViewItem)e.NewValue;
if (rootNode.Parent is TreeView)
{
     soccerSeason.getChampionshipsForTeams(e);
}
else
{
     teams.getTeam(e);
}

This working only for Nation and Championship, I want execute another method for each team selected, how I can do this? Because Actually if I select a child of Championship, was run the getTeam method.

A: I think you can make something like this for team:
TreeViewItem rootNode = (TreeViewItem)e.NewValue;
if (rootNode.Parent is TreeViewItem
           && (rootNode.Parent as TreeViewItem).Parent is TreeView)
{
                //it's team do something
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split a dictionary where values of keys are multiple lists into train and test set Python Say I have a dictionary with two keys, spam and ham, for spam and ham text or email messages that looks like the following:
data = {
    'spam': [
        ['hi', "what's", 'going', 'on', 'sexy', 'thing'],
        ['1-800', 'call', 'girls', 'if', "you're", 'lonely'],
        ['sexy', 'girls', 'for', 'youuuuuu']],
    'ham': [['hey', 'hey', 'I', 'got', 'your', 'message,', "I'll", 'be', 'home', 'soon!!!'],
        ['Madden', 'MUT', 'time', 'boys']]}

I want to split the dictionary into training and test sets (starting with 80/20 training to test).  I want the split to be regardless of key, so just subset 80% of the total messages for my training set and 20% of the total messages for my test set.  In this small example we have 5 total messages (3 in spam and 2 in ham).  I've looked around for solutions, but haven't found anything yet that handles this type of situation.

A: Using the aptly named sklearn.model_selection.train_test_split():
from sklearn.model_selection import train_test_split

data = {
    'spam': [
        ['hi', "what's", 'going', 'on', 'sexy', 'thing'],
        ['1-800', 'call', 'girls', 'if', "you're", 'lonely'],
        ['sexy', 'girls', 'for', 'youuuuuu']],
    'ham': [['hey', 'hey', 'I', 'got', 'your', 'message,', "I'll", 'be', 'home', 'soon!!!'],
            ['Madden', 'MUT', 'time', 'boys']]}

all_messages = [(words, k) for k, v in data.items() for words in v]

train, test = train_test_split(list(all_messages), test_size=0.2)

You can, and probably should, use something more powerful, like Pandas:
import pandas as pd
from sklearn.model_selection import train_test_split

data_dict = {
    'spam': [
        ['hi', "what's", 'going', 'on', 'sexy', 'thing'],
        ['1-800', 'call', 'girls', 'if', "you're", 'lonely'],
        ['sexy', 'girls', 'for', 'youuuuuu']],
    'ham': [['hey', 'hey', 'I', 'got', 'your', 'message,', "I'll", 'be', 'home', 'soon!!!'],
            ['Madden', 'MUT', 'time', 'boys']]}

df = pd.DataFrame(data=((k, words) for k, v in data_dict.items() for words in v))

print(df)

train, test = train_test_split(df, test_size=0.2)

print(train)
print(test)

Output:
      0                                                  1
0  spam               [hi, what's, going, on, sexy, thing]
1  spam           [1-800, call, girls, if, you're, lonely]
2  spam                       [sexy, girls, for, youuuuuu]
3   ham  [hey, hey, I, got, your, message,, I'll, be, h...
4   ham                          [Madden, MUT, time, boys]

      0                                                  1
1  spam           [1-800, call, girls, if, you're, lonely]
2  spam                       [sexy, girls, for, youuuuuu]
0  spam               [hi, what's, going, on, sexy, thing]
3   ham  [hey, hey, I, got, your, message,, I'll, be, h...

     0                          1
4  ham  [Madden, MUT, time, boys]

A: You can convert the dict to a list of tuples and then make the split.
>>> l = [(sentence, k) for k,v in data.items() for sentence in v]
>>> random.shuffle(l)
>>> train_size = int(len(l)*0.8)
>>> train, test = l[:train_size], l[train_size:]
>>> len(train)
4
>>> len(test)
1

Each element is a pair (sentence, label)
>>> test[0]
(['Madden', 'MUT', 'time', 'boys'], 'ham')


text:
Q: Dynamic Roles and permissions based authorisation on angular 4 application I am creating an application with angular 4, Where my super-admin will create different roles and give access to different features(permissions) so both things will be dynamic.
Now I want to only display features that users have permissions based on the role he assigned and another thing is I also want to guard the route so a user will not access the feature with manually typing the URL.
I have checked ngx-permissions with that I can do this both things but I need to have the default name for role(that I don't have in my application) and need to know which user has what permissions(that is also I will not have)
Is there any way to do role-based authorization with dynamic role name and dynamic feature permissions?
Any help would be appreciated.

A: You can use route activate guards for this. See this


text:
Q: Table of Contents Titles Spanning Two Lines I have a table of contents with titles that span more than one line.  How can I get those page numbers to line up to the right?

A: It appears from your image, the page number is being forced to the next line (wrapping) because of the length and position of the title. The title appears to reach the margin on the right.
To resolve this, you can either shorten the title, reduce the indent or increase the margins on the page to accommodate the width required to get it on one line.


text:
Q: Stored procedure on the SqlDataSource is not working with single quotation inside SelectCommand with single quotation C# asp.net I am in trouble right now regarding on how to make my stored procedure work inside a SqlDataSource on aspx page.
This is my markup:
<asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server"
     ConnectionString="<%# _connection.strConnectionString %>"
     SelectCommand='<%# "EXEC dbo._GetCurrentSession " + Eval("Film_strCode") + " " %>' />

The above code is working fine though without single quotation in it. But when I tried to put a single quotation, It doesn't work. There will be an error on the tag.
See this markup :
<asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server"
     ConnectionString="<%# _connection.strConnectionString %>"
     SelectCommand='<%# "EXEC dbo._GetCurrentSession 'some_value_here' " %>' />

Please help me to know why stored procedure with single quotation does not work on aspx page? I need to make my code like this with single quotation but it doesn't work.
<asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server"
     ConnectionString="<%# _connection.strConnectionString %>"
     SelectCommand='<%# "EXEC dbo._GetCurrentSession '" + Eval("Film_strCode") + "'" %>' />

Are there any way to make it work? Please help me.

A: If you want to use a stored procedure from your SqlDataSource, you should use this approach - defining the command type to be StoredProcedure, and setting the parameters properly:
<asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server"
     ConnectionString="<%# _connection.strConnectionString %>"
     SelectCommand="dbo._GetCurrentSession"
     SelectCommandType="StoredProcedure">
    <SelectParameters>
        <asp:Parameter Name="SessionValue" Type="Int32" DefaultValue="0" />
    </SelectParameters>
</asp:SqlDataSource>


text:
Q: Let $ E: y^{2}=x^{3}+x+1 \pmod{193)} $ be an elliptic curve and $ P=(x,y) $ be a point on the curve of order $3$ Let $ E: y^{2}=x^{3}+x+1 \pmod{193} $ be an elliptic curve and $ P=(x,y) $ be a point on the curve of order $3$.  How do I find $x$ and $y$ if $P=(x,y)$ is of order $3$.
I know how to find the set $ E_{193}(1,1)$, but i have no idea how to find $x$ and $y$ , i.e; $(x,y)$ if the order of $(x,y)$ is $3$. Please help me.

A: This gets really messy by hand, but some code on SageMath I wrote indicates that the point $(108,66)$ and its inverse $(108, 127)$ both have order 3.
Here is the code:
E = EllipticCurve(GF(193),[0,0,0,1,1])

w = E.points()

for i in range(len(w)):
    P = w[i]
    o = P.order()
    if o == 3:
        print P, o


text:
Q: ExpressionChangedAfterItHasBeenCheckedError: Expression Error On Datepicker Value retrieve I keep getting this error and I can't seem to find a way to fix this. I using this angular 4 datepicker in my project and in this error occurs when it detects change on the dateChanged event.
Here's my full error:

EditApplicationComponent.html:522 ERROR Error:
  ExpressionChangedAfterItHasBeenCheckedError: Expression has changed
  after it was checked. Previous value: '[object Object]'. Current
  value: ''.

Here's my html.

<my-date-picker name="from" [options]="DocDatePickerOptions" (dateChanged)="onDocDateChanged($event, rpr)" [ngModelOptions]="{standalone: true}" [placeholder]="placeholder"
            [ngModel]="rpr.SD_VALID_FROM" ></my-date-picker>

Here's how I binded and get value to the datepicker. in sample.ts
OnInit(){

  this.DocDateRetreive();
}

DocDateRetreive() {
    console.log("came here", this.DocumentMode);
    for (var i = 0; i < this.DocumentMode.length; i++) {
      if (this.DocumentMode[i].SD_VALID_FROM == null) {
        // this.validFrom[i] = new Date();
      }
      else {
        console.log("from:", this.DocumentMode[i].SD_VALID_FROM);

        var validFromTemp = [new Date(this.DocumentMode[i].SD_VALID_FROM)];

        for (var j = 0; j < validFromTemp.length; j++) {
          console.log("valid from temp:", validFromTemp[j]);
          this.validFrom[i] = { date: { year: validFromTemp[j].getFullYear(), month: validFromTemp[j].getMonth() + 1, day: validFromTemp[j].getDate() } };
        }
        console.log("valid", this.validFrom[i]);
        this.DocumentMode[i].SD_VALID_FROM = this.validFrom[i];
      }
    }
  }

  onDocDateChanged(event: IMyDateModel, rpr) {

      var date = event.formatted;
      rpr.SD_VALID_FROM = date;
      console.log("changed", rpr.SD_VALID_FROM);

  }

readThis(inputValue: any, rpr): void {

      myReader.onloadend = (e) => {
        this.FileString = myReader.result;
        // rpr.SD_VALID_FROM = this.validFrom.formatted;
        for (var i = 0; i < this.DocumentMode.length; i++) {
          if (this.DocumentMode[i].DOC_ATTCHE_PATH == rpr.DOC_ATTCHE_PATH) {

            this.DocumentMode[i].SD_VALID_FROM = rpr.SD_VALID_FROM.formatted;
            this.DocumentMode[i].SD_VALID_UNTIL = rpr.SD_VALID_UNTIL;
            this.DocumentMode[i].IS_CHECK = true;
          }
        }
      }
      myReader.readAsDataURL(file);

  }

The Datepicker works fine but when it first loads the DOM the error occurs. How do I resolve this issue. Help would be appreciated.

A: Try doing this this.DocDateRetreive(); after view init.
 there is an angular lifecycle hook called AfterViewInit. You need to implement the inteface in your component class.
export class YourComponent implements AfterViewInit{
constructor(){
/*Whatever*/
}

    ngAfterViewInit(): void{
    this.DocDateRetreive();
    }
}

This should solve your problem.
If the incoming data you use is making the problem, then you need to go for
AfterContentInit
export class YourComponent implements AfterContentInit {
    constructor(){
    /*Whatever*/
    }

        ngAfterContentInit (): void{
        this.DocDateRetreive();
        }
    }


text:
Q: Moving config props from META-INF/context.xml out of web app I am working with an ancient legacy web app which I need to prepare for continuous integration by separating resource configuration from the app itself (so that we can make a single WAR file that works on every environment assuming config file presence in some predetermined filesystem locations outside the app server).
Unlike our other, more modern web apps that use a Spring context, this one gets its database configuration via app server context and it is located in META-INF/context.xml, which looks something like
<?xml version='1.0' encoding='utf-8'?>
<!--
    Context configuration file for the Tomcat Administration Web App
-->

<Context docBase="axis2" reloadable="true" crossContext="true">
    <Resource
        name="jdbc/GWSDEV"
        auth="Container"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
        username="myuser"
        password="mypasswd"
        driverClassName="org.postgresql.Driver"
        url="jdbc:postgresql://my.server.com/mydb"
        maxActive="100"
        maxIdle="30"
        maxWait="10000" />
</Context>

I would like to move this config somewhere outside the Tomcat app and reconfigure the app to load a properties file from something like /etc/myancientapp/datasource.props so that I can build a single WAR file without embedded config in Jenkins and deploy the same war in every environment and not have to build a separate one for each environment differing only in that one file. Then the config would be different in every environment but I can live with a fixed path (/etc/myancientapp/datasource.props).
How can I separate this configuration out of my app and replace it with a pointer to a config file that is to be loaded from outside the app?


text:
Q: ffmpeg -vf: command not found I am still a semi-novice at ffmpeg. I can  do the basics with 1-pass crf encoding but as I am venturing into 2-pass encoding, I am running into an error I cannot solve. Any help is appreciated.
In short, when I run the following script in Ubuntu,
IFS=$'\n'

for i in `ls  *.{ts,mkv,mpeg,mpg,mov,avi,mp4,m2t,mts}`
    do
        #Output naming scheme
        extension=`echo "$i" | egrep -o '\.(ts|mkv|mpeg|mpg|mov|avi|mp4|mts)$'`
        extensionFreeFileName=$(echo "$i" | awk -F `echo ${extension}` '{print $1}')
        newFileName="$extensionFreeFileName"

        #Extract proper frame rate from source video
        testFrameFormat='/'
        testFramsString=`mediainfo "$i" | grep "Frame rate  "`

        if [[ "$testFramsString" =~ "$testFrameFormat" ]]; then
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F '[()]' '{print $2}' | head -1`
        else
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F "\: " '{print $2}' | awk -F " " '{print $1}' | awk -F " " '{print $1}' | head -1`
        fi

        #Video bit rate lookup and calculations
        videoBitRate=`mediainfo "$i" | grep "Bit rate  " | head -1 | tail -1 | awk -F' : ' '{print $2}' | awk -F' kb/s' '{print $1}' | sed 's| ||g'`
        videoBitRate=$((videoBitRate * 1024))

        avc35BitRate=$((videoBitRate * 35 / 100))
        avc25BitRate=$((videoBitRate * 25 / 100))
        hevc30BitRate=$((videoBitRate * 30 / 100))
        hevc27BitRate=$((videoBitRate * 27 / 100))
        hevc24BitRate=$((videoBitRate * 24 / 100))
        hevc21BitRate=$((videoBitRate * 21 / 100))
        hevc17BitRate=$((videoBitRate * 17 / 100))

        #check to ensure calculations are being performed as expected
        echo -e "\n\n\n\n"
        echo -e "$i"
        echo -e "$frameRate"
        echo -e "$videoBitRate"
        echo -e "$avc35BitRate"
        echo -e "$avc25BitRate"
        echo -e "$hevc30BitRate"
        echo -e "$hevc27BitRate"
        echo -e "$hevc24BitRate"
        echo -e "$hevc21BitRate"
        echo -e "$hevc17BitRate"
        echo -e "\n\n\n"

        #Encoding command (two-pass, multiple outputs)
        ~/bin/ffmpeg -analyzeduration 500000000 -probesize 500000000 -i "$i" -preset veryslow \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc30BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc30" -an -f matroska /dev/null \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc27BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc27" -an -f matroska /dev/null \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc24BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc24" -an -f matroska /dev/null \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc21BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc21" -an -f matroska /dev/null \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc17BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc17" -an -f matroska /dev/null \
            -vf yadif -r "$frameRate" -map 0:v -c:v libx265 -b:V "$avc35BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName avc35" -an -f matroska /dev/null \
            -vf yadif -r "$frameRate" -map 0:v -c:v libx265 -b:V "$avc25BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName avc25" -an -f matroska /dev/null &&
        ~/bin/ffmpeg -analyzeduration 500000000 -probesize 500000000 -i "$i" -preset veryslow \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc30BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc30" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 30pct).mkv" \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc27BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc27" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 27pct).mkv" \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc24BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc24" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 24pct).mkv" \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc21BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc21" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 21pct).mkv" \
            -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc17BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc17" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 17pct).mkv" \
            -vf yadif -r "$frameRate" -map 0:v -c:v libx265 -b:V "$avc35BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName avc35" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (AVC 35pct).mkv" \
            -vf yadif -r "$frameRate" -map 0:v -c:v libx265 -b:V "$avc25BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName avc25" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (AVC 25pct).mkv"
done;

I get the following errors:
TwoPassConvert_A-Z.sh: line 50: -vf: command not found
TwoPassConvert_A-Z.sh: line 58: -vf: command not found

which reference the following lines in the script, respectively:
-vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc24BitRate" -x265-params pass=1 -passlogfile "$extensionFreeFileName hevc24" -an -f matroska /dev/null \
-vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -b:V "$hevc24BitRate" -x265-params pass=2 -passlogfile "$extensionFreeFileName hevc24" -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 24pct).mkv" \

Any help you can provide in correcting this error would be appreciated.

Additionally, when the script runs, I get the following prompt:
File '/dev/null' already exists. Overwrite ? [y/N]

Is there a way I can always answer 'yes' when running the script?

PS Any suggestions on how to write the ffmpeg portion of the script more efficiently/readable (without losing intended functionality) would also be welcomed.
Thanks!

PPS
I can successfully run the following, similar, one-pass 'crf' script without problems:
IFS=$'\n'

for i in `ls  *.{ts,mkv,mpeg,mpg,mov,avi,mp4,m2t,mts}`
    do

        extension=`echo "$i" | egrep -o '\.(ts|mkv|mpeg|mpg|mov|avi|mp4|mts)$'`
        extensionFreeFileName=$(echo "$i" | awk -F `echo ${extension}` '{print $1}')
        newFileName="$extensionFreeFileName"

        testFrameFormat='/'
        testFramsString=`mediainfo "$i" | grep "Frame rate  "`

        if [[ "$testFramsString" =~ "$testFrameFormat" ]]; then
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F '[()]' '{print $2}' | head -1`
        else
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F "\: " '{print $2}' | awk -F " " '{print $1}' | awk -F " " '{print $1}' | head -1`
        fi

         echo -e "\n\n\n\n\n$frameRate\n\n\n\n\n\n"

                ~/bin/ffmpeg -analyzeduration 500000000 -probesize 500000000 -i "$i" -preset veryslow \
                    -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -crf 24 -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 24).mkv" \
                    -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -crf 26 -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 26).mkv" \
                    -vf bwdif=0:0:0 -r "$frameRate" -map 0:v -c:v libx265 -crf 30 -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (HEVC 30).mkv" \
                    -vf yadif -r "$frameRate" -map 0:v -c:v libx264 -crf 28 -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (AVC 28).mkv" \
                    -vf yadif -r "$frameRate" -map 0:v -c:v libx264 -crf 26 -map 0:a -c:a copy -map 0:s? -c:s copy "./$newFileName (AVC 26).mkv"
done;

UPDATE 11/3/2018
There were problems in my original script beyond the original problem I posted. I have since corrected the other errors and I am posting my final solution to help others who might come across this in the future when trying to build their own two-pass script.
CAUTION: Use at your own risk. I make no warranty or guarantee that this script will work for your specific needs in your computing environment. Be sure to backup files you are encoding and execute this in a safe environment to ensure that this works correctly for you before adapting it to your production needs
note: The following would be easier to read if copied and pasted into your preferred bash script editor (I personally like gedit which offers nice color coding if saved with an .sh extension)
IFS=$'\n'

#Script is designed to accept zero or one argument when executing.
#The argument is the path that contains the files you want to encode; syntax: user#bash script.sh [argument-path]
#The following commands ensure that if an argument is entered, it has a trailing '/'
#If no argument is present, it executes from the path your are currently in.

path=$1
pathLength=`echo $path | wc -c`
if [[ "$path" == "" ]]; then
    path="./"
    elif [[ "${path:$((pathLength - 2)):1}" == "/" ]]; then
        path="$path"
    else
        path="$path/"
fi

pathLength=`echo $path | wc -c`

#for i in `ls *.{ts,mkv,mpeg,mpg,mov,avi,mp4,m2t,mts}` #alternative to loop through multiple file extensions

for i in `ls "$path"*.mts`
    do

        #move file to local machine (useful if original file) exists on network)
        cp "$i" /tmp && echo "success"
        #format $i variable to work correctly with commands below
        i="${i:$((pathLength - 1))}"
        #assign $j variable to work with the file cp to /tmp to avoid unwanted actions on original file
        j="/tmp/$i"

        #determines file extension, base file name (without extenion), and creates newFileName variable as base file name
        extension=`echo "$i" | egrep -o '\.(ts|mkv|mpeg|mpg|mov|avi|mp4|mts)$'`
        extensionFreeFileName=$(echo "$i" | awk -F `echo ${extension}` '{print $1}')
        newFileName="$extensionFreeFileName"

        #get frame rate of original video in order to match frame rate when encoding (designed to work with only one video stream))
        #requires 'mediainfo' to be installed
        testFrameFormat='/'
        testFramsString=`mediainfo "$i" | grep "Frame rate  "`

        if [[ "$testFramsString" =~ "$testFrameFormat" ]]; then
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F '[()]' '{print $2}' | head -1`
        else
            frameRate=`mediainfo "$i" | grep "Frame rate  " | awk -F "\: " '{print $2}' | awk -F " " '{print $1}' | awk -F " " '{print $1}' | head -1`
        fi

        #Visual confirmation that frame rate extracted from original video makes sense (either fractional 30000/1001 or decimal 29.970 format)
        echo -e "\n\n\n\n\n$frameRate\n\n\n\n\n\n"

            #Video bit rate lookup and calculations for desire output bitrate (5 percent in this instance)
            videoBitRate=`mediainfo "$i" | grep "Bit rate  " | head -1 | tail -1 | awk -F' : ' '{print $2}' | awk -F' kb/s' '{print $1}' | awk -F' Mb/s' '{print $1}' | sed 's| ||g'`
            videoBitRate=`echo "$videoBitRate *1024 * 1024" | bc | awk -F'.' '{print $1}'`

            #Note: 5 percent of original video bit rate won't work in most situations
            #My video is highly static (virtually no movement) and does not require a high bit rate for quality output
            #For encoding MPEG-2 original with moderate level of movement, I recomment a minimum of 50% for AVC and 25% for HEVC
            #For enciding AVC original with moderate movement to HEVC, I recommend a minimum of 50%
            #Ideally, you should experiment with a smaller extracted portion of video with highest motion using:
            # user# ffmpeg -ss [start time in 00:00:00.000 format] -i source -t [duration in seconds] \
            #           [video codecs like those shown below]
            #After determining what is acceptable to you, modify the target bitrates in the next two lines

            hevc05BitRate=`echo "$videoBitRate * 5 / 100" | bc | awk -F'.' '{print $1}'`
            avc05BitRate=`echo "$videoBitRate * 5 / 100" | bc | awk -F'.' '{print $1}'`

            # ffmpeg command and options

            ~/bin/ffmpeg -y -analyzeduration 500000000 -probesize 500000000 -i "$j" -preset slow \
                -map 0:v -c:v libx265 -b:v "$hevc05BitRate" -x265-params pass=1:stats=/tmp/passA -an -f matroska /dev/null \
                -map 0:v -c:v libx264 -b:v "$avc05BitRate" -x264-params pass=1:stats=/tmp/passB -an -f matroska /dev/null && \
            ~/bin/ffmpeg -y -analyzeduration 500000000 -probesize 500000000 -i "$j" -preset slow \
                -vf bwdif=0:0:0 -map 0:v -c:v libx265 -b:v "$hevc05BitRate" -x265-params pass=2:stats=/tmp/passA -map 0:a -c:a copy -map 0:s? -c:s copy "/tmp/$newFileName (HEVC 05pct).mkv" \
                -vf yadif -map 0:v -c:v libx264 -b:v "$avc05BitRate" -x264-params pass=2:stats=/tmp/passB -map 0:a -c:a copy -map 0:s? -c:s copy "/tmp/$newFileName (AVC 05pct).mkv"

            # When two-pass is complete, move the newly encoded files to their target destination
            mv "/tmp/*AVC*" "/media/WinE/School Videos/"
            mv "/tmp/*HEVC*" "/media/WinE/School Videos/"
            # Remove temporary source file (NOTE: original file should still be untouched)
            rm "$j"
done;

A: Remove the trailing spaces after \ on line 49 and 57.
The backslash is to escape the newline that follows (not the extraneous spaces).
To overwrite file, assume yes to overwrite with -y (eg. ffmpeg -y ...).


text:
Q: IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id I'm trying to implement a comment section in my blog that looks as follows:

I don't have a user or post name input because it should take as input the request user and the post ID of the post where it's making the comment.
My Comment model:
class Comment(models.Model):
post = models.ForeignKey(
    Post, on_delete=models.CASCADE)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
approved_comment = models.BooleanField(default=False)

class Meta:
    ordering = ['-created_on']

def __str__(self):
    max_len = 75

    if len(self.body) > max_len:
        string = self.body[:max_len] + "..."
    else:
        string = self.body
    return string

Comment form:
class CommentForm(forms.ModelForm):

class Meta:
    model = Comment
    fields = ('body',)
    exclude = ['user', 'post', ]

View function:
def get_post_details(request, post_id):

unique_post = Post.objects.get(id=post_id)
all_comments = Comment.objects.filter(post=unique_post)

new_comment = None

if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)

    if comment_form.is_valid():
        new_comment = comment_form.save(commit=True)
        new_comment.post = unique_post
        new_comment.user = request.user
        new_comment.save()
        return get_post_details(request, post_id)
else:
    comment_form = CommentForm()

context_dict = {
    'post': unique_post,
    'comments': all_comments,
    'new_comment': new_comment,
    'comment_form': comment_form
}

return render(request, 'blog/post_details.html', context=context_dict)

I'm not sure what's missing, but when I try to add a comment I get the below error:
    Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/blog/5

Django Version: 4.1
Python Version: 3.10.6
Installed Applications:
['blog',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: blog_comment.post_id) was the direct cause of the following exception:
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/workspaces/76966637/Personal/blog_project/diyblog/blog/views.py", line 49, in get_post_details
    new_comment = comment_form.save(commit=True)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/forms/models.py", line 548, in save
    self.instance.save()
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/base.py", line 831, in save
    self.save_base(
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/base.py", line 882, in save_base
    updated = self._save_table(
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/base.py", line 1025, in _save_table
    results = self._do_insert(
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/base.py", line 1066, in _do_insert
    return manager._insert(
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/query.py", line 1790, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1657, in execute_sql
    cursor.execute(sql, params)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
    return super().execute(sql, params)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/workspaces/76966637/Personal/blog_project/blogenv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /blog/5
Exception Value: NOT NULL constraint failed: blog_comment.post_id

I've searched all over stackoverflow and the issue always seemed to be that the user was forgetting to add the comment.post = post section on the view, but I have that defined.
Any help is appreciated!

A: The reason this fails is because the commit=True, which thus aims to save the item.
But likely a more robust way to do this, is to inject that data in the instance wrapped in the form directly, so:
from django.shortcuts import get_object_or_404, redirect

def get_post_details(request, post_id):
    unique_post = get_object_or_404(Post, pk=post_id)
    all_comments = Comment.objects.filter(post=unique_post)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST, request.FILES)
        if comment_form.is_valid():
            comment_form.instance.post = unique_post
            comment_form.instance.user = request.user
            comment_form.save()
            return redirect(get_post_details, post_id)
    else:
        comment_form = CommentForm()

    context = {
        'post': unique_post,
        'comments': all_comments,
        'comment_form': comment_form
    }
    return render(request, 'blog/post_details.html', context)


text:
Q: Is there an event that is fired when a view exits? In asp.net mvc appliction, is there an event that is fired when a view exits? I want to save some screen settings when the view exits.
This can happen when a user clicks on any other (page/view) link in the nav bar or logs off.

A: So i am doing it on window.onbeforeunload event. Thanks to madalin and this answer.
<script type="text/javascript">
 window.onbeforeunload = function (e) {

    var dataItems = [...];
    var model = JSON.stringify({ 'model': dataItems });

    $.ajax({
        url: "@Url.Action("SaveDefaultSettings", "Maps")",
        type: 'get',
        data: { defaultSettings: model },
    success: function (data) {

    }
});
};
</script>


text:
Q: Run scripts automatically in server after ssh connection how to run a script automatically in server soon after client system establish ssh connection with the server
for ex:
suppose a user will logon to my computer from another system(connected via lan) using ssh connection. At that time, A script(python or shell) should be run automatically in my system to perform some validation?
How to run the script automatically in server system?

A: You can create a /etc/ssh/sshrc file. See man 8 ssh.
If you want this for a single user, use ~/.ssh/rc.
Here is a sample /etc/ssh/sshrc that will notify you via dbus when someone logs in on your machine. Don't forget to chmod +x:
#!/bin/bash

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

notify-send -u CRITICAL "SSH connection from ${ip}" "User $USER just logged in from $ip"

A: You can do so by adding the following parameter to your config file (/etc/ssh/sshd_config).

 ForceCommand
         Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present.  The command is invoked by using the user's login shell
         with the -c option.  This applies to shell, command, or subsystem execution.  It is most useful inside a Match block.  The command originally supplied by the client is available in the
         SSH_ORIGINAL_COMMAND environment variable.  Specifying a command of "internal-sftp" will force the use of an in-process sftp server that requires no support files when used with
         ChrootDirectory.

An other option is to use the .ssh/rc files on a per user basis.
To use the ForceCommand method you just add ForceCommand /usr/bin/ownscript at the bottom of the file /etc/ssh/sshd_config (on the server).
The script looks like this:
#!/bin/bash
#Script file for ssh
#
#put your commands here
echo "test" > /tmp/test.txt
#
#exit by calling a shell to open for the ssh session
/bin/bash

Don't forget to chmod the script sudo chmod +x /usr/bin/ownscript

A: For execution of a script during logon, add it as a call from within the /etc/profile script.  This is executed for every logon, not only for ssh logons.


text:
Q: Java Implement byte range serving without servlets using only Java api I have been writing a http server in Java for quite some time(almost two years now?) and I am still having issues getting byte range requests to work. I am only using the socket's input and output stream for raw byte data transfer(i.e. file downloads/uploads), and a PrintWriter for sending response headers/strings to connecting clients(such as HTTP/1.1 200 OK and so forth).
I do not wish to use any servlets or apis(such as HTTPURLConnection or whatever). I want to do it "vanilla style".
I am able to serve normal web pages quite nicely and quickly(such as file browsing, uploads and downloads, watching movies, listening to music, viewing pdf files, text, pictures, gif files, etc.), so that is not an issue.
However, whenever I try implementing byte range requests, the server receives the client's request perfectly, parses the given data, prepares the file input stream for sending, and then when I send the data to the client, the client always drops the connection with software caused connection abort: socket write error.(I need byte range requests for cases such as: watching an hour long video, then the dang wifi signal drops out and you don't want to re-watch the entire video from square one, resuming a 'paused download', etc.)
This really has me stumped, and I have indeed searched for java examples of serving byte range requests, all of which fail when I try to implement them. I have even tried starting from scratch and testing that, and it produces the same result. Here are the code snippets relevant to what I am trying to accomplish:
Sending and receiving normal web pages(works fine, this is an example):
    ...
        OutputStream outStream = client.getOutputStream();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8), true);
        out.println("HTTP/1.1 200 OK");
        out.println("Content-Type: text/html; charset=\"UTF-8\"");
        String responseStr = "<!DOCTYPE html><title>Hello, world!</title><string>This is a simple example webpage!</string>";
        if(acceptEncoding.contains("gzip") && responseStr.length() > 33) {
            out.println("Content-Encoding: gzip");
            byte[] r = StringUtil.compressString(responseStr, "UTF-8");
            out.println("Content-Length: " + r.length);
            out.println("");
            if(protocol.equalsIgnoreCase("GET")) {
                outStream.write(r);
            }
        } else {
            out.println("Content-Length: " + responseStr.length());
            out.println("");
            if(request.protocol.equalsIgnoreCase("GET")) {
                out.println(responseStr);
            }
        }
        out.flush();
        //followed by closing resources, etc.
    ...

Byte range serving(after client request data is parsed):
public static final long copyInputStreamToOutputStream(InputStream input, OutputStream output, long startBytes, long endBytes) throws IOException {
    byte[] buffer = new byte[20480];//1024
    long count = 0;
    int read;

    input.skip(startBytes);
    long toRead = (endBytes - startBytes) + 1;

    while((read = input.read(buffer)) > 0) {
        if((toRead -= read) > 0) {
            output.write(buffer, 0, read);//Socket error happens on this line mostly
            output.flush();
        } else {
            output.write(buffer, 0, (int) toRead + read);//but also on this line sometimes
            output.flush();
            break;
        }
        count += read;
    }
    return count;
}

For anyone that is interested, the server running on this basic code is online at redsandbox.no-ip.org (points to my server), and at the moment I have byte requests disabled with Accept-Ranges: none instead of Accept-Ranges: bytes, but I can turn it on again to test it.
If I need to add more code in, please let me know! Thank you for your time.
Alternately, if you wish to view my server's code in full, you can view it on github: https://github.com/br45entei/JavaWebServer

A: Would this read-write loop work fine, sure looks streamlined? This is out of my head so minor syntax errors may be found. I am expecting startIdx+endIdx both are inclusive indicies.
public static final long copyInputToOutput(InputStream input, OutputStream output, long startIdx, long endIdx) throws IOException {
    final long maxread = 24*1024;
    byte[] buffer = new byte[(int)maxread];
    input.skip(startIdx);
    long written=0;
    long remaining = endIdx-startIdx+1;
    while(remaining>0) {
        int read = input.read(buffer, 0, (int)Math.min(maxread, remaining));
        output.write(buffer, 0, read);
        remaining -= read;
        written += read;
    }
    output.flush();
    return written;
}

A: So I figured out what my issues were, thanks in part to Whome. Firstly, I wasn't sending the correct Content-Length: header to the client, and secondly, my endbytes variable was being calculated incorrectly. Here is the working code:
public static final long copyInputStreamToOutputStream(InputStream input, OutputStream output, long startBytes, long endBytes, final long contentLength, boolean debug) throws IOException {
    byte[] buffer = new byte[20480];//1024
    long count = 0;
    int read;
    long skipped = input.skip(startBytes);//I tested this quite a few times with different files and it does indeed skip the desired amount of bytes.
    final long length = (endBytes - startBytes) + 1;
    if(debug) {
        println("Start bytes: " + startBytes + "; End bytes: " + endBytes + "; Skipped bytes: " + skipped + "; Skipped equals startBytes: " + (skipped == startBytes) + "; Length: " + length + "; Total file size: " + contentLength);
    }
    long toRead = length;
    while((read = input.read(buffer)) != -1) {
        count += read;
        long bytesLeft = length - count;
        if(debug) {
            println("read: " + read + "; toRead: " + toRead + "; length: " + length + "; count: " + count + "; bytesLeft: " + bytesLeft);
        }
        toRead -= read;
        if(bytesLeft >= buffer.length) {//Changed the if statement here so that we actually send the last amount of data to the client instead of whatever is leftover in the buffer
            output.write(buffer, 0, read);
            output.flush();
        } else {
            output.write(buffer, 0, read);//Send the currently read bytes
            output.flush();
            bytesLeft = length - count;//recalculate the remaining byte count
            read = input.read(buffer, 0, (int) bytesLeft);//read the rest of the required bytes
            count += read;
            if(debug) {
                println("[Last one!]read: " + read + "; toRead: " + toRead + "; length: " + length + "; count: " + count + "; bytesLeft: " + bytesLeft);
            }
            output.write(buffer, 0, read);//and send them over
            output.flush();
            break;
        }
    }
    return count;
}

Since the endBytes variable in my case was one more than it needed to be, I was trying compensate by adjusting the code around it. I needed to simply subtract one from it, however. The if statement with the buffer.length is to ensure that the last of the bytes are sent to the client. In my tests without it, the client(google chrome) hangs and waits for the remaining bytes, but never receives them, then when the 30 second time out closes the connection, the webpage resets. I have yet to test this with other browsers, but I think it should work.


text:
Q: Parse url path of indeterminate length So Im looking for way to convert string into var...
I need do get data from array $Map
As key I use $URL that get data from real URL and seperate it... $URL = explode("/",$URL);
So when I access values of $Map it need to be written like this:
$Map[$URL[0]][$URL[1]][$URL[2]][$URL[3]][$URL[4]][$URL[5]]

So I decide to create function that generate amount of [$URL[0]]'s like
function GenerateURl($i){for ($x = 0; $x <= $i; $x++){
        $URls.='$URL['.$x.']';
        }
        return($URls);}

Why? I have map of pages that can host visit , thats what $MAP contains, each dimension has style and content setting, but I really dont want to type every single dimension manually + its pain to maintace it...
if($Map[$URL[0]){ #Check if first dimension exist (Index.php/example)
   if....... #this take much more steps to verify if there is request for child, and if child exist, ofc there is else method that redirect to closest parent page
   $Style="style_for_page.css";
   $Contend="style_for_page.css";
}
else{
header("Location: https://example.com");
}

I dont know what I do wrong... But when I call my function GenerateURl(5)
output is string... not working var... so its like
$URL[0]$URL[1]$URL[2]$URL[3]$URL[4]

and not like
Profile User Settings Privacy Examle...... (example.com/Profile/User/Settings/Privacy/Examle)
Update:
To simplify my question...
I need this:
$MAP = array(........) ;
$URL = array("example");
$var = "[$URl[0]]"; #$URL need to be transferred as text to print part
Print($Map[$var]);

A: You can't quite do this in exactly the way you're imagining - PHP can't generate an executable set of array access code (well, you could, and then execute it using eval, but you really don't want to do that unless there's no other option).
A better way is to pass the arguments to a helper function which will then iterate through the target array gradually using each of the arguments provided.
The other task of course is to split the URL string into parts using explode. It looks like you want to ignore the first parts (protocol and domain) and just look at the elements of path.
This code should do what you need, I think:
function flatCall($data_arr, $data_arr_call){
    $current = $data_arr;
    foreach($data_arr_call as $key){
        $current = $current[$key];
    }

    return $current;
}

$MAP = array("profile" => array("setting" => array("test" => array("idknow" => "someValue"))));
$urlString = "www.example.com/profile/setting/test/idknow";

$URL = explode("/", $urlString); //split URL string into an array
array_shift($URL); //remove first element
$result = flatCall($MAP, $URL);
echo $result;

Live demo: https://3v4l.org/A3Z1H

Credit to https://stackoverflow.com/a/36334761/5947043 for the helper function - read that answer for an explanation of how it works.


text:
Q: Displaying a picture from a URL into wxPython Can anyone tell me how I can download a picture from a URL and display it on one my wxPython?
Thanks

A: Use wx.Image and load the image data using a method like LoadStream or LoadMimeStream from an input stream or a file-like object.
To fetch the image data itself, use urllib2 or requests.


text:
Q: 'IN' operator is not working correctly while getting SQL rule in Query Builder Jquery I am trying to use multiple selection in jquery query builder then create the Sql rule as you see below

I have an issue with multiple selection while creating the sql rule. for example here instead of getting country IN('Australia','Germany') I am getting country IN('Australia,Germany') which is causing issue when I extrat my data based on this rule.
It's like taking all the selected items as one string. Here is my code
<!DOCTYPE html>

  <title>x86 Query Builder</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link href="http://querybuilder.js.org/dist/selectize/dist/css/selectize.bootstrap3.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-formhelpers/2.3.0/css/bootstrap-formhelpers.css" rel="stylesheet" />

  <link href="http://querybuilder.js.org/dist/jQuery-QueryBuilder/dist/css/query-builder.default.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">

   <button class="btn btn-info" id="btn-get-sql">SQL</button>

I was searching in many forums, I found this value_separator: ',' to add it my filter but it wasn't working. I tried also to create a value setter and customize it but I wasn't successful to make it work.
Any suggestion please ? Thank you very much.

A: It's been three months since this question was asked. But in case anyone is struggling with the same issue, the solution below solved my problem:
input: 'select', // this is important
multiple: true, // this is too

Here is the GitHub issue


text:
Q: A little help with $ x_n = \frac{1}{n^2} \sum_{k=1}^{n} \left[ k \alpha \right] $ So I have this little problem I want to solve that says the following:
For every number $\alpha \in \mathbb{R} $, analyze the following sequence
$$ \{ x_n \} = \frac{1}{n^2} \sum_{k=1}^{n} \left[ k \alpha \right] ,$$ where $ \left[ x \right] $ is the floor function. Calculate for which values of $ \alpha $ does $ x_n $ converges, or if it diverges. If it converges, calculate the limit of the sequence.
My first thought was to prove that this sequence converges, or diverges, for every possible value of $ \alpha $, that is, when $ \alpha \in \mathbb{Z} ,$ $ \alpha \in \mathbb{Q} ,$ and when $ \alpha \in \mathbb{I} ,$ in other words, $ \alpha $ is irrational.
So when $ \alpha \in \mathbb{Z} $ I got the following:
If $ \alpha \in \mathbb{Z} $ then $ \left[ \alpha \right] = \alpha ,$ therefore
$$ \{ x_n \} = \frac{1}{n^2} \sum_{k=1}^{n} k \alpha = \frac{\alpha}{n^2} \sum_{k=1}^{n} k = \frac{\alpha}{n^2} \frac{n(n+1)}{2} = \frac{\alpha (n+1)}{2n} ,$$
thus, $ \{ x_n \} $ converges to $$ \{ x_n \} = \frac{\alpha (n+1)}{2n} ;$$
since it converges, then we can calculate the limit as follows
$$ \lim_{n \to \infty} \{ x_n \} = \lim_{n \to \infty} \frac{\alpha (n+1)}{2n} = \frac{\alpha}{2} \lim_{n \to \infty} \frac{n+1}{n} = \frac{\alpha}{2} \lim_{n \to \infty} \frac{1 + \frac{1}{n}}{1} = \frac{\alpha}{2} \left[ \lim_{n \to \infty} 1 + \lim_{n \to \infty} \frac{1}{n} \right] = \frac{\alpha}{2} .$$
So, first of all, is this proof correct? If so, how can I proceed to prove the sequence when $ \alpha \in \mathbb{Q} $ or when it's irrational? Should I prove the floor function for rational and irrational numbers and then apply this to the sequence?

A: For $\alpha \in \mathbb{R}^+$ we have $\lfloor k \alpha\rfloor \leqslant k \alpha < \lfloor k \alpha \rfloor +1 \implies   k\alpha -1 < \lfloor k \alpha \rfloor \leqslant k \alpha.$
Hence,
$$\alpha\frac{n(n+1)}{2n^2} - \frac{n}{n^2} =\frac{ 1}{n^2}\sum_{k = 1}^n (\alpha k - 1) < \frac{1}{n^2}\sum_{k = 1}^n \lfloor k \alpha \rfloor \leqslant \frac{ 1}{n^2}\sum_{k = 1}^n \alpha k = \alpha\frac{n(n+1)}{2n^2}.$$
Apply the squeeze theorem to evaluate the limit.  The cases where $\alpha \leqslant 0 $ is similar


text:
Q: Change default text editor for crontab to vim I'm using ubuntu 9.10 and the default text editor is nano, which i hate.  (doesn't everyone?)
Normally it's not a problem as i just vi or gedit everything but crontab -e is opening with nano.  I tried changing it to vim using sudo update-alternatives --config editor and selecting option 3 ("/usr/bin/vim.basic").  This has changed it for sudo and non-sudo alike.  But crontab -e still opens nano.  Any ideas?  max

A: export EDITOR=vi && crontab -e

works on debian squeeze

A: The better choice is to set alternative of editor (not just one user) :
sudo update-alternatives --install /usr/bin/editor editor /usr/bin/vim 100

A: Unfortunately I can not comment or vote.
On Ubuntu the configuration file is called ~/.selected_editor
With the following command you can select the default editor again:

$ select-editor

Removing the file in your home directory also works.

$ rm ~/.selected_editor

Only setting the variables $VISUAL or $EDITOR will work but is only persistent if you write it to a script which is executed in your environment.
Add to your rc file

$ echo "export VISUAL=/usr/bin/vi" >> ~/.bashrc

But i wouldn't recommend to use the last solution.

A: If you hate nano so much you can just uninstall it:
sudo apt-get remove nano

crontab should then just default to the next EDITOR (for me it was vim.basic).

A: The crontab -e command will check the environment variables $EDITOR and $VISUAL for an override of the default text editor, so...
export VISUAL=vim

or
export EDITOR=vim

should do the trick.

A: From man crontab:

The -e option is used to edit the  current  crontab  using  the  editor
specified  by  the  VISUAL  or EDITOR environment variables.  After you
exit from the editor, the modified crontab will be installed  automati‐
cally.  If  neither  of  the environment variables is defined, then the
default editor /usr/bin/editor is used.

Add to your ~/.bashrc:
export EDITOR=vim

A: In ubuntu, try run: select-editor, which interactively creates ~/.selected_editor:
# Generated by /usr/bin/select-editor
SELECTED_EDITOR="/usr/bin/vim.basic"

A: You should best remove the ~/.sensible_editor file and then running crontab -e will prompt you to choose the preferred editor. From then on your preference will be remembered in the ~/.sensible_editor file.

A: Easiest would be to get rid of the product you don't want in its entirety.
All other config changes would be automatical.
apt-get install vim -y && apt-get remove nano -y

A: The first answer worked for me, but I had to do this after saving changes in
~/.bashrc
source ~/.bashrc

That way you refresh your configuration.

A: for Debian, use :
sudo update-alternatives --config editor command

and
 ----------------------------------------------------------
06  * 0          /bin/nano            40
07  1            /bin/nano            40
08  2            /usr/bin/vim.basic   30
09  3            /usr/bin/vim.tiny    10

select '2'  and press enter. Got it!

A: On older machines like some Debian ones, this works also and is the most portable solution.
mv /usr/bin/editor /usr/bin/.editor
ln -s $(which vim) /usr/bin/editor


text:
Q: Inconsistent behavior of promisified server call through a loop I have a file set inside a directory. I loop through each file, read file content, make a POST request to a remote server and then obtain the response for each call for other tasks. I am facing an inconsistent behavior of getting the response for each file. Let's name these files
a.txt,
b.txt
c.txt
d.txt
e.txt

If I use a console.log inside the loop, I can see my loop reads each file correctly before making the service call. Problem is with the response of the service call. If I check the response of the service call (I am making 5 service calls), I am getting multiple responses for some files while not getting any response for some. ex: I am checking each response console.log(details.name); where I print the name property of each response which should be equal to the file name of the corresponding request. Sometimes I am getting
   a
   a
   a
   b
   e

And another time
   a
   b
   c
   d
   d

I am getting 5 responses, but multiple for some files (requests) and nothing for some requests. This is worst if I increase the number of files but I am getting expected output if I use one or two files at a time. I tried each file and every request is giving response individually. What is the reason for this behavior when I try it with multiple files (requests).
Following is the code
var request = require("request");
var userDetails;

function initialize(content) {

  return new Promise(function(resolve, reject) {
    request.post({
      url: 'http://xxx/yyy',
      form: {
        content: content
      }
    }, function(err, resp, body) {
      if (err) {
        reject(err);
      } else {
        resolve(JSON.parse(body));
      }
    })
  });
};

function main() {
  let filenames = fs.readdirSync(dir);
  filenames.forEach(function(filename) {
    console.log(filename);
    let fileContent = fs.readFileSync(dir + filename, 'utf-8');
    var initializePromise = initialize(fileContent);
    initializePromise.then(function(result) {
      details = result;
      .......
      console.log(details.name);
    }, function(err) {
      console.log(err);
    });
  });
}

main();


text:
Q: Dirac Delta from cartesian to polar coordinates An infinitely long wire carries a constant electric current $I$ along the $z$ axis. Thus, the current density $\mathbf{j}$ of the wire is given by, in cartesian coordinates:
$$\mathbf{j}(\mathbf{r})=I\delta(x)\delta(y)\mathbf{\hat{z}}$$
I am required to calculate the following integral:
$$\mathcal{I}=\iint_S\mathbf{j}(\mathbf{r})\cdot\mathbf{\hat{z}}\ \text{d}S$$
Where $S$ is a circle with radius $R>0$ on the $[XY]$ plane. Calculating $\mathcal{I}$ in cartesian coordinates gives:
$$\mathcal{I}_{\text{cartesian}}=I\int_{-R}^{+R}\int_{-\sqrt{R^2-x^2}}^{+\sqrt{R^2-x^2}}\delta(x)\delta(y)\ \text{d}y\text{d}x\underbrace{=}_{0\in(-\sqrt{R^2-x^2},+\sqrt{R^2-x^2})}I\int_{-R}^{+R}\delta(x)\ \text{d}x\underbrace{=}_{0\in[-R,+R]}I$$
However, when I try to calculate the integral using polar coordinates, where:
$$\delta(x)\delta(y)=\frac{\delta(r)}{2\pi r}$$
I get:
$$\mathcal{I}_{\text{polar}}=I\int_{0}^{2\pi}\int_{0}^{R}\frac{\delta(r)}{2\pi r}\ r\text{d}r\text{d}\theta=I\int_0^R\delta(r)\ \text{d}r$$
Because of course $\mathcal{I}_{\text{cartesian}}=\mathcal{I}_{\text{polar}}$, the integral I got should be equal to $1$, but I don't understand why. From my personal experience, integrals like this, where the zero of the argument of the dirac-delta function is one of the integral limits, are not well-defined. Why then in this case it is equal to $1$? I suspect my construction of the integral is wrong, but I'm not sure where I was wrong.
Thanks!

A: This comes from the fact that the Dirac delta is not a function but a measure and so one should not use the integral notation with upper and lower bounds to be rigorous. In particular, with this integral notation one cannot make the difference between $\delta_0([0,1]) = \int_{[0,1]} \delta_0(\mathrm{d}x) = 1 ≠ \int_{(0,1)} \delta_0(\mathrm{d}x)= 0$. This is a property of the Lebesgue measure and of any measure absolutely continuous with respect to the Lebesgue measure. For such an absolutely continuous measure $ \mu$, there exists a function $f_\mu$ such that $\mu(\mathrm{d}x) = f(x)\,\mathrm{d}x$ and then
$$
\mu([a,b]) = \int_{[a,b]} \mu(\mathrm{d}x) = \int_a^b f(x)\,\mathrm{d}x = \int_{(a,b)} \mu(\mathrm{d}x).
$$
With that in mind, you understand that in the same way for your double integral, the change of variable in polar coordinates changes $\mathbb{R}^2$ into $([0,2\pi)× (0,\infty)) \cup \{0\}$.

A: $\def\vr{{\bf r}}$Consider the integral
$$I = \int_{\mathbb{R}^d}
g(\vr)\delta(\vr-\vr_0)dV_d.$$
(Here $dV_d = \prod_{i=1}^d dx_i$ is the $d$-dimensional volume element in Euclidean space.)
A standard delta sequence on $\mathbb{R}$ is
$$\delta_n(x)=\sqrt{\frac{n}{\pi}}e^{-nx^2}$$
so $I = \lim_{n\to\infty}I_n$ where
\begin{align*}
I_n &= \int_{\mathbb{R}^d}
g(\vr)
\left(
\prod_{i=1}^d \delta_n(x_i-x_{i0}
\right)
dV_d \\
&= \int_{\mathbb{R}^d}
g(\vr)
\left(\prod_{i=1}^d
\sqrt{\frac{n}{\pi}}e^{-n(x_i-x_{i0})^2}
\right)
dV_d \\
&= \int_{\mathbb{R}^d}
g(\vr)
\left(\frac{n}{\pi}\right)^{d/2}
e^{-n(\vr-\vr_0)^2} dV_d.
\end{align*}
Now assume that
$\vr_0 = {\bf 0}$ and
$g = g(r)$.
Then
\begin{align*}
I_n &= \int_{\mathbb{R}^d} g(r)
\left(\frac{n}{\pi}\right)^{d/2}
e^{-n r^2} dV_d \\
&=
\int_{\textrm{solid angle}} \int_0^\infty
g(r) \left(\frac{n}{\pi}\right)^{d/2}
e^{-n r^2} r^{d-1}  dr \,d\Omega_d
    & (\textrm{hyperspherical coordinates})\\
&= \Omega_d \int_0^\infty
g(r) \left(\frac{n}{\pi}\right)^{d/2}
r^{d-1} e^{-n r^2}  dr
    & (\textrm{$g=g(r)$ used}) \\
&= \frac {2 \pi^{d/2}} {\Gamma (d/2)}
\int_0^\infty
g(r) \left(\frac{n}{\pi}\right)^{d/2}
r^{d-1} e^{-n r^2}  dr
    & (\textrm{known result for $\Omega_d$})\\
&= \int_0^\infty
g(r)
\frac{2 n^{d/2}}{\Gamma(d/2)}
r^{d-1} e^{-n r^2}  dr.
\end{align*}
Thus,
$$\delta_n(r) = \frac{2 n^{d/2}}{\Gamma(d/2)}
r^{d-1} e^{-n r^2}$$
must be a delta sequence for $\delta(r)$.
Critically, note that
$$\int_0^\infty \delta_n(r) dr = 1$$
for any $n>0$.
Also, for $d>1$ we have $\delta_n(0) = 0$ and
$\operatorname{argmax}\,\delta_n(r) = \sqrt{\frac{d-1}{2n}} > 0$.
This gives us the fruitful intuition that the "spike" for $\delta(r)$ is not at $r=0$, but at $r=0^+$.
For $d=2$ we find
$$\delta_n(r) = 2 n r e^{-n r^2} dr.$$
Below we give a plot of $\delta_n(r)$ for $d=2$ and $n=10,100,1000$.

Figure 1. $\delta_n(r)$ for $d=2$ and  $n=10,100,1000$.


text:
Q: html5 accessibility for screen readers How can I add accessibility to this
Text:
Buttons and Images and anchors:

    <button class="btn btn-default">

        john
    </button>
    <button class="btn btn-default">
         Log out

    </button>

    Change recipient

A: Too little information provided. Context needed. That being said:

*

*Add an alt attribute to the ,

*make sure the link has a valid href,

*don't rely on FontAwesome icons to convey critical information,

*maybe dump the role attribute as it may not be needed (context necessary to know if needed).

A: Only you are suited to properly add semantics to your code and content, so we really can't do this for you. But, here are some important things to remember/do/follow:

*

*Your HTML is not event valid, so start by correcting that.

*Don't ever use an HTML element because of the way it makes the
visible page look (i.e. using a heading like
 to make text
small and bold). CSS should be used for all layout and presentation.

*Use the most appropriate HTML elements to convey the semantics of the content you have. For
example, go ahead and use the
 element if you actually are
trying to display tabular data and use
 and
 to make menus.

*Despite the (many) myths, the HTML5 sectioning elements (section,
article, nav, aside) are not recognized by most screen readers. Their use actually makes creating a valid document outline much more difficult.

*The proper use of heading (
...
) elements is the best
thing you can do to convey a proper document structure.

*Use WAI-ARIA landmark roles where applicable as that has been a
standard for many years and all the major screen readers understand
it.

A: For images, provide the alt attribute to the  tag, which is a description of the image. For example, .
For semantics, use  instead of  and  instead of .
Also, look into ARIA (Accessible Rich Internet Applications). A useful ARIA attribute is the role attribute. It provides extra content about the element's purpose and functionality.


text:
Q: SCP command giving some path error I want to copy an ISO image from my file server to my xen server using scp. I gave the below command in my xen server console but it gaves me error, dont know whats going wrong.
Console on XEN server where I want to copy:
[root@xenserver ISOz]# scp user@192.168.1.155:/home/user/ISOz/12.04\ LTS /Server/12.04\ 64\ LTS.iso .

user@192.168.1.155's password:

scp: /home/user/ISOz/12.04: No such file or directory

scp: LTS: No such file or directory

cp: cannot stat `/Server/12.04 64 LTS.iso': No such file or directory

This is the file location on my file server I am trying to copy:
user@server:~/ISOz/12.04 LTS /Server$ ls

12.04 64 LTS.iso  list  list~  ubuntu-12.10-server-i386.iso

user@server:~/ISOz/12.04 LTS /Server$
user@server:~/ISOz/12.04 LTS /Server$ pwd
/home/user/ISOz/12.04 LTS /Server

can anyone please correct my scp command

A: You should use
# scp user@192.168.1.155:/home/user/ISOz/12.04\ LTS\ /Server/12.04\ 64\ LTS.iso

or
# scp "user@192.168.1.155:/home/user/ISOz/12.04 LTS /Server/12.04 64 LTS.iso"

The reason is a non-escaped space inside your path.
The second problem is because you specified source file (file1) but did not specify the target file. Probably, you have to type something like this:
# scp "user@192.168.1.155:/home/user/ISOz/12.04 LTS /Server/12.04 64 LTS.iso" "user@192.168.X.Y:/path/to/12.04 64 LTS.iso"

A: I hope, the problem may be with the spaces in the path filename that you might have missed some where. So for the ease, follow the below steps.
Try Following steps :

*

*Copy the iso file to the /home/user/ and

*Rename the iso file to a simple file name with out spaces like "ubuntu.iso "

*If you have done the above steps, do the following:
rsync -avr --progress user@192.168.1.155:/home/user/ubuntu.iso .

Hope this might help you.


text:
Q: Clarification on Timer(s) that does not block or sleep the UI thread I have a program that needs to periodically perform a quick operation. I would prefer it to run every 1 second. If a certain condition is met in the operation, it needs to then perform a specific action.
This periodic operation must not interfere with the UI in any way and must run for the life of the program. Not sure if I should use System.Timers.Timer or the BackgroundWworker in some fashion. If there is something better than those two, by all means tell me.
EDIT:
I forgot to mention that under a certain condition, a Message Box needs to popup with an "exit" button that WILL block the UI and then shut down the entire program when the button is clicked.

A: System.Timers.Timer sounds like the ticket unless you need to update the UI with results from the background thread.  But you say it must not interfere with the UI in any way, so presumably you won't have this need.
To address your edit and comment on the question: you can still use System.Timers.Timer, but make sure you use Control.Invoke or Control.BeginInvoke to call the AlertAndExit (or whatever you call it) method.  (Instead of invoking something on the GUI thread, you could also just set a flag that's protected by a lock, but then you'd have to have a System.Windows.Forms.Timer running just to check whether the flag had changed, which it sounds like you'd like to avoid.)

A: The answer depends on what you need done. If you don't need to marshal to the UI thread then a System.Timers.Timer will suffice. It runs on a separate thread from the UI thread so you could have it elapse/tick every second with no issues.


text:
Q: Issue with inserting / arranging columns using VBA I have an excel worksheeet which has a number of columns, typically from A to AZ. I've written something in VBA which is supposed to arrange and clean this worksheet by calling other subroutines, each which perform an individual task such as formatting, deleting rows, inserting new columns and moving and renaming existing ones.
I'm very new to VBA, so a lot of what I have written is what I've managed to find on here or google. I'm not sure whether the way I have written this is the best way of performing the task.
The problem I have is that the first part one of the subs (arrangeColumns) which is supposed to insert a new column at A somtimes works. The other times it appears to copy the entire worksheet and duplicate it so that my columns now go from A - AZ and are duplicated again from BA - CZ.
From what what little knowledge I have I've managed to find out that when I run this sub on its own it does work, however when this sub is called from my main part it doesnt peform as it should.
Apart from the very first column not being inserted correctly the rest of the code seems to work. Any help or suggestions welcome! thanks
Sub ArrangeColumns()

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("test")

'inserts Index column at A. This is the part that seems to fail and duplicates the worksheet
ws.Range("A1").EntireColumn.Insert
ws.Range("A1").Value = "Index"

'identifies last column
Dim lastColumn As Long
lastColumn = ws.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).column

'Finds the column Timestamp: Time and moves to B, renames to Date
Dim column As Range
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "Timestamp: Time" Then
       column.EntireColumn.Cut
       ws.Range("B1").Insert shift:=xlToRight
       ws.Range("B1").Value = "Date"
       Exit For
   End If
Next column

'inserts Time column at C
ws.Range("C1").EntireColumn.Insert
ws.Range("C1").Value = "Time"

'inserts blank column at D
ws.Range("D1").EntireColumn.Insert
ws.Range("D1").Value = "Blank"

'finds the column Body and moves to E
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "Body" Then
       column.EntireColumn.Cut
       ws.Range("E1").Insert shift:=xlToRight
       Exit For
   End If
Next column

'find the From column and moves to F
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "From" Then
       column.EntireColumn.Cut
       ws.Range("F1").Insert shift:=xlToRight
       ws.Range("F1").Value = "From User"
       Exit For
   End If
Next column

'inserts From Attributed column at G
ws.Range("G1").EntireColumn.Insert
ws.Range("G1").Value = "From Attributed"

'find th To column and moves to H, renames to To User
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "To" Then
       column.EntireColumn.Cut
       ws.Range("H1").Insert shift:=xlToRight
       ws.Range("H1").Value = "To User"
       Exit For
   End If
Next column

'inserts To Attributed at I
ws.Range("I1").EntireColumn.Insert
ws.Range("I1").Value = "To Attributed"

'finds Participants column and moves to J
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "Participants" Then
       column.EntireColumn.Cut
       ws.Range("J1").Insert shift:=xlToRight
       Exit For
   End If
Next column

'Finds Source column and moves to K
For Each column In ws.Range("A1:" & Split(ws.Cells(1, lastColumn).Address, "$")(1) & "1").Cells
   If column.Value = "Source" Then
       column.EntireColumn.Cut
       ws.Range("K1").Insert shift:=xlToRight
       Exit For
   End If
Next column

End Sub

Sub deleteFirstRow()
'deletes the first row of the worksheet

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("test")

ws.Rows(1).Delete

End Sub

Sub convertToRange()
'loops throught the worksheet to find all tables and converts to range

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("test")

Dim table As ListObject
For Each table In ws.ListObjects
   table.Range.Copy
   table.Unlist
Next table

End Sub

Sub clearFilter()
'removes all filters on activesheet

On Error Resume Next
ActiveSheet.ShowAllData

End Sub

Sub formatting()
'if this sub is called after cleaning the columns, then the index will be blank. This uses the column titled '#' to find the lastrow

Dim lastRow As Long
Dim lastColumn As Long
Dim col As Range

Set col = Rows(1).Find("#", LookIn:=xlValues, lookat:=xlWhole)

lastRow = Cells(Rows.Count, col.column).End(xlUp).Row
lastColumn = Cells(1, columns.Count).End(xlToLeft).column

Dim rngAll As Range
Set rngAll = Range(Cells(1, 1), Cells(lastRow, lastColumn))

Dim rngTopRow As Range
Set rngTopRow = Range(Cells(1, 1), Cells(1, lastColumn))

Dim rngSecondRowDown As Range
Set rngSecondRowDown = Range(Cells(2, 1), Cells(lastRow, lastColumn))

With rngAll
   .Borders.LineStyle = xlContinuous
   .Borders.Weight = xlThin
   .Borders.ColorIndex = xlAutomatic

   .HorizontalAlignment = xlCenter
   .VerticalAlignment = xlCenter

   .Borders(xlInsideHorizontal).LineStyle = xlContinuous
   .Borders(xlInsideHorizontal).Weight = xlThin
   .Borders(xlInsideHorizontal).ColorIndex = xlAutomatic

   .Borders(xlInsideVertical).LineStyle = xlContinuous
   .Borders(xlInsideVertical).Weight = xlThin
   .Borders(xlInsideVertical).ColorIndex = xlAutomatic
End With

'sets the colour, font and row size of the first row
With rngTopRow
   .Interior.Color = RGB(48, 84, 150)
   .Font.Color = vbWhite
   .Font.Bold = True
   .RowHeight = 40
End With

'sets colour, borders and row size of rows 2 to lastrow
With rngSecondRowDown
   .Interior.Color = RGB(255, 255, 255)
   .RowHeight = 50
End With

End Sub

Sub splitDateTime()
'if this sub is called after cleaning the columns, then the index will be blank. This uses the column titled '#' to find the lastrow
'Splits the values in column B from 'dd/mm/yyyy hh:mm:ss' by space and moves 'hh:mm:ss' to column c

Dim lastRow As Long
Dim col As Range

Set col = Rows(1).Find("#", LookIn:=xlValues, lookat:=xlWhole)
lastRow = Cells(Rows.Count, col.column).End(xlUp).Row

For i = 2 To lastRow
   Cells(i, 3).Value = Mid(Cells(i, 2).Value, 12, 16)
   Cells(i, 2).Value = Left(Cells(i, 2).Value, 10)
Next i

End Sub

Sub columnWidth()

columns("a").columnWidth = 15
columns("b").columnWidth = 11
columns("c:d").columnWidth = 15
columns("e").columnWidth = 30
columns("f:i").columnWidth = 22
columns("j").columnWidth = 40

End Sub

Sub applyFilter()

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("test")
Dim rngAll As Range

Dim lastRow As Long
Dim lastColumn As Long
Dim col As Range

Set col = Rows(1).Find("#", LookIn:=xlValues, lookat:=xlWhole)

lastRow = Cells(Rows.Count, col.column).End(xlUp).Row
lastColumn = Cells(1, columns.Count).End(xlToLeft).column

Set rngAll = Range(Cells(1, 1), Cells(lastRow, lastColumn))
rngAll.AutoFilter

End Sub

Sub arrangeWorksheet()

Call clearFilter
Call deleteFirstRow
Call convertToRange
Call ArrangeColumns
Call formatting
Call splitDateTime
Call columnWidth
Call applyFilter

End Sub

A: There is a bunch of repeated logic/steps in your ArrangeColumns which could be pushed out into a separate reusable method.
For example:
Sub arrangeWorksheet()
    Call ArrangeColumns
End Sub

Sub ArrangeColumns()

    Dim ws As Worksheet, rwHeaders As Range
    Set ws = ThisWorkbook.Sheets("test")

    Set rwHeaders = ws.Rows(1) 'headers are here

    MoveOrAddColumn rwHeaders, "", "Index", "A"
    MoveOrAddColumn rwHeaders, "Timestamp: Time", "Date", "B"
    MoveOrAddColumn rwHeaders, "", "Time", "C"
    MoveOrAddColumn rwHeaders, "", "Blank", "D"
    MoveOrAddColumn rwHeaders, "Body", "", "E"
    MoveOrAddColumn rwHeaders, "From", "From User", "F"
    MoveOrAddColumn rwHeaders, "", "From Attributed", "G"
    MoveOrAddColumn rwHeaders, "To", "To User", "H"
    MoveOrAddColumn rwHeaders, "", "To Attributed", "I"
    MoveOrAddColumn rwHeaders, "Participants", "", "J"
    MoveOrAddColumn rwHeaders, "Source", "", "K"

End Sub

'With all headers in range `rwHeaders`...
'Move a column named `existingColName` to `destColLetter` (if existingColName is supplied)
'Otherwise insert a new column at position `destColLetter`
'Moved/inserted column is given header `newColName` (if supplied)
Sub MoveOrAddColumn(rwHeaders As Range, existingColName, newColName, destColLetter)
    Dim m, colRng As Range, f As Range, cDest As Range, moving

    Set cDest = rwHeaders.Columns(destColLetter) 'destination if moving, or new column
    moving = Len(existingColName) > 0

    If moving Then 'moving an existing column?
        Set f = rwHeaders.Find(what:=existingColName, lookat:=xlWhole)
        If f Is Nothing Then
            MsgBox "Column header '" & existingColName & "' not found!"
            Exit Sub
        Else
            If f.column <> cDest.column Then 'check if already in the requested postion
                cDest.EntireColumn.Insert shift:=xlToRight
                Set cDest = cDest.Offset(0, -1) 're-point reference
                f.EntireColumn.Copy cDest
                f.EntireColumn.Delete
            End If
        End If
    Else
        cDest.EntireColumn.Insert shift:=xlToRight
        Set cDest = cDest.Offset(0, -1) 're-point reference
    End If
    If Len(newColName) > 0 Then cDest.Value = newColName
End Sub

A: I managed to find the problem, which was in the converToRange() sub. I was copying the table before converting it to range, which meant when the next sub was called it was pasting it instead of inserting a new column!


text:
Q: Android RelativeLayout: how to put a view below another view when both aren't at the same container I had a TitleBar(#lotTopTitleBar) in the LinearLayout, and the LinearLayout will be full size of the screen, now, I want show a View(#lotFloatView) reference the TitleBar below, but both view aren't at the same level container, so the layout_below doesn't work, if anybody know about that, please help me a change.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical">

        <LinearLayout android:id="@+id/lotTopTitleBar"
                      android:layout_width="match_parent"
                      android:layout_height="50dp">
        </LinearLayout>

        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="0dp"
                      android:layout_weight="1">
        </LinearLayout>

        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="50dp">
        </LinearLayout>

    </LinearLayout>

    <LinearLayout android:id="@+id/lotFloatView"
                  android:layout_width="120dp"
                  android:layout_height="wrap_content"
                  android:layout_below="@id/lotTopTitleBar">
        <Button android:layout_width="match_parent"
                android:layout_height="60dp"
                android:background="@null" />
        <Button android:layout_width="match_parent"
                android:layout_height="60dp"
                android:background="@null" />
    </LinearLayout>

</RelativeLayout>

A: I think you can achieve this by using relative layout instead of linear layout. I have not tested it but it should work.
    <RelativeLayout android:layout_width="match_parent"
              android:layout_height="match_parent"
              >

       <LinearLayout android:id="@+id/lotTopTitleBar"
                  android:layout_width="match_parent"
                  android:layout_height="50dp">
    </LinearLayout>
    <LinearLayout android:id="@+id/lotFloatView"
              android:layout_width="120dp"
              android:layout_height="wrap_content"
              android:layout_below="@id/lotTopTitleBar">
    <Button android:layout_width="match_parent"
            android:layout_height="60dp"
            android:background="@null" />
    <Button android:layout_width="match_parent"
            android:layout_height="60dp"
            android:background="@null" />
</LinearLayout>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:layout_below="@id/lotTopTitleBar"
                  android:id="@+id/lotLL"
                  android:layout_weight="1">
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_below="@id/lotLL"
                  android:layout_height="50dp">
    </LinearLayout>

</RelativeLayout >

EDIT
    <LinearLayout android:layout_width="match_parent"
                  android:layout_below="@id/lotLL"
                  android:layout_alignParentBottom="true"
                  android:id="@+id/lotLastLL"
                  android:layout_height="50dp">
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:layout_below="@id/lotTopTitleBar"
                  android:layout_above="@id/lotLastLL"
                  android:id="@+id/lotLL"
                  >
    </LinearLayout>


text:
Q: is there a method to find all the solutions to, $y^2-6y+\sqrt{y}+4=0$ is there a method to find all the solutions to the following set of irrational equations,
$\sqrt{x}+y=3$
$x+\sqrt{y}=5$
NOTE: $(4-1)=(2-1)(2+1)=3$ and $(4+1)=(2^2+1^2)=(3^2-2^2)=(3-2)(3+2)=5$

A:
...is there a method to find all the solutions[?]

Yes, there is: draw the graphs of the functions $x\mapsto3-\sqrt{x}$ and $x\mapsto(5-x)^2$ on $[0,5]$, these intersect at $(4,1)$ and there only hence the unique solution of your system is $(x,y)=(4,1)$.

A: For the question in the title, you can move the $\sqrt y$ to the other side, square, and get a quartic which yields to the rational root theorem.

A: If you make the change of variables
$$\begin{equation*}
u=\sqrt{x}\geq 0,\qquad v=\sqrt{y}\geq 0,
\end{equation*}$$
then you need to solve
$$\begin{equation*}
\left\{
\begin{array}{c}
u+v^{2}=3 \\
u^{2}+v=5
\end{array}
\right.
\end{equation*}$$
or
$$\begin{eqnarray*}
&&\left\{
\begin{array}{c}
u=3-v^{2} \\
v^{4}-6v^{2}+v+4=0
\end{array}
\right.  \\
&\Leftrightarrow &\left\{
\begin{array}{c}
u=3-v^{2} \\
\left( v-1\right) \left( v^{3}+v^{2}-5v-4\right) =0.
\end{array}
\right.
\end{eqnarray*}$$
So $u=2,v=1$ is a solution, i.e. $x=4,y=1$ in the original variables. And
since $v^{3}+v^{2}-5v-4=0$ has 3 real solutions, one positive $v_{1}\approx
2.164\,2\gt \sqrt{3}$ and two negative $v_{2}\approx -2.391\,4,v_{3}\approx
-0.772\,87$, there are no other solutions because $u=3-v_{1}^{2}<0$.

A: $(3-y)^2+\sqrt{y}=5$
$y^2-6y+\sqrt{y}+4=0$
$(\sqrt{y}-1)(y\sqrt{y}+y-5\sqrt{y}-4)=0$
i.e. $\sqrt{y}=1$, and $x=4$ is a solution


text:
Q: How to animate element height in React with ReactCSSTransitionGroup? I'm trying to animate element height with ReactCSSTransitionGroup,
so this is what I would want the animation looks like:
http://jsfiddle.net/cherrry/hgk4Lme9/
The problem is that I don't always know the element height,
so I tried to hack the scrollHeight, clientHeight or something similar during componentDidMount and try to set node.style.height or add rules to stylesheet
http://jsfiddle.net/cherrry/dz8uod7u/
Leaving animation looks good, however when element enters, it flash a bit and the scaling animation looks strange
It should be because of asking node.scrollHeight caused the rendering occur immediately, so is there anyway to get the same information and inject css rules before animation start? Or should I think other way round?
I'm not very satisfied with the max-height solution, as the resulting animation speed will be very strange when max-height is not close to or smaller to height, and my components' height do vary a lot.
I could imagine the final solution could be a bit messy,
but I think making it into a Mixin will be nice enough to reuse it anywhere

A: I had a same problem and ended up writing a standalone component for animating height.
You can see the demo here:
https://stanko.github.io/react-animate-height/
It is much easier to use, and whole library is really small (~200 lines)
<AnimateHeight
  duration={ 500 }
  height={ 'auto' }
>

Your content goes here

Put as many React or HTML components here.

</AnimateHeight>

Sorry for the shameless self promotion, but I think it can save you a lot of time if you have more than one component to animate.
Cheers!

A: A very easy and nice approach is by handling scaleY instead of height.
The hover should set the attribute transform: scaleY(1)  (originally => transform: scaleY(0) to hide it) and the animation should target transform attribute.

A: After a bit more experiment, I've come up with a solution by using the low-level API ReactTransitionGroup instead of high-level ReactCSSTransitionGroup
Here's the JSFiddle with a working solution: http://jsfiddle.net/cherrry/0wgp34cr/
Before the animation, it's doing 3 things:

*

*get computed height, paddings and margins

*hide the element with display: none and add .anim-enter to set height to 0

*create css rule for .anim-enter-active
To start the animation, it's doing 2 things:

*

*unhide the element

*add .anim-enter-active to start the animation

Some numbers and class name in JSFiddle were hard-coded, but it should be easy enough to transform the "mixin" into a React class as a replacement of ReactCSSTransitionGroup

A: If you dont want to import a module or use qjuery, here is a template using React ref (https://reactjs.org/docs/refs-and-the-dom.html)
Basically you get the height it will be, grow to that height, switch back to auto.  On the way back switch to the height it is, then back to 0.
class CollapsibleSectionBlock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showContent: false,
            height: "0px",
            myRef: null,
        };
    }

    componentDidUpdate = (prevProps, prevState) => {
        if (prevState.height === "auto" && this.state.height !== "auto") {
            setTimeout(() => this.setState({ height: "0px" }), 1);
        }
    }

    setInnerRef = (ref) => this.setState({ myRef: ref });

    toggleOpenClose = () => this.setState({
        showContent: !this.state.showContent,
        height: this.state.myRef.scrollHeight,
    });

    updateAfterTransition = () => {
        if (this.state.showContent) {
            this.setState({ height: "auto" });
        }
    };

    render() {
        const { title, children } = this.props;
        return (

 this.toggleOpenClose()}>
                    {title}

 this.updateAfterTransition()}
                    style={{
                        height: this.state.height,
                        overflow: "hidden",
                        transition: "height 250ms linear 0s",
                    }}
                >
                    {children}

        );
    }
}


text:
Q: MongoEngine: 'ListField' object has no attribute 'in_bulk' Given the following setup (reduced):
class Parent(db.Document):
    _id = db.ObjectIdField(required=True, default=lambda: ObjectId(), primary_key=True)
    name = db.StringField(required=False)
    test = db.MapField(db.EmbeddedDocumentField('Child'), required=False)

class Child(db.EmbeddedDocument):
    _id = db.ObjectIdField(required=True, default=lambda: ObjectId(), primary_key=True)
    ref = db.ReferenceField('Parent')

parent = Parent.objects(_id=x).first()
return jsonify(parent.test)

I get the following error: AttributeError: 'ListField' object has no attribute 'in_bulk'
  File "/home/me/testSetup/test.py", line 310, in get
    return jsonify(parent.test)
  File "/home/me/lib/python3.7/site-packages/mongoengine/base/fields.py", line 329, in __get__
    value = _dereference(value, max_depth=1, instance=instance, name=self.name)
  File "/home/me/lib/python3.7/site-packages/mongoengine/dereference.py", line 97, in __call__
    self.object_map = self._fetch_objects(doc_type=doc_type)
  File "/home/me/lib/python3.7/site-packages/mongoengine/dereference.py", line 174, in _fetch_objects
    references = collection.objects.in_bulk(refs)
AttributeError: 'ListField' object has no attribute 'in_bulk'

I'm not quite sure why this is happening. I did not use a ListField at all. I can access name and _id and this setup worked with other classes before. return jsonify(parent) does also work and it includes the test field with all its values. Does someone have an idea?
EDIT: I am silly and removed/censored the part that is causing the error from the reduced example. The field test was actually called objects. Renaming it resolved the error.

A: Using raw mongoengine (no flask-mongoengine), from a fresh database, and from a simple terminal, the following code is working
from mongoengine import *
from bson import ObjectId

connect("testdb")

class Parent(Document):
    _id = ObjectIdField(required=True, default=lambda: ObjectId(), primary_key=True)
    name = StringField(required=False)
    test = MapField(EmbeddedDocumentField('Child'), required=False)

class Child(EmbeddedDocument):
    _id = ObjectIdField(required=True, default=lambda: ObjectId(), primary_key=True)
    ref = ReferenceField('Parent')

p = Parent(name='aa', test={}).save()
p2 = Parent(name='bb', test={'test': Child(ref=p), 'test2': Child(ref=p)}).save()

print(Parent.objects(_id=p.id).first().test)

print(Parent.objects(_id=p2.id).first().test)

I'd recommend you to start from there, add more complex code until you can pinpoint what causes it to break.
side note, since ObjectId is a callable, you don't need to wrap it in a lambda and can simply use default=ObjectId in your field definition, thus ObjectIdField(required=True, default=ObjectId, primary_key=True)