text:
Q: after navigate to another page, bootstrap dropdown become unusable I had 3 .php files, they are index.php, load_file.php,and register.php

*

*In index.php, contain navigation, and each navigation has dropdown list, i call this navigation and the dropdown from database. and also index.php has link to register.php, note : load_file.php included in this file

*In load_file.php, contain code to check value of page, by using if($_GET['page']),and trigger every value with switch-case

*register.php, just a normal form

My problem is, after I navigate to register.php by typing ?page=register in browser, my dropdown in index.php file become unusable

::UPDATE::
this is my index.php file

<?php
    session_start();
    require_once './model/functions.php';

    if(isset($_GET["category"])){
        $index_page= $_GET["category"];
        $index_sub_page= null;
    }elseif (isset ($_GET["sub_category"])) {
        $index_sub_page = $_GET["sub_category"];
        $index_page= null;
    }else{
        $index_sub_page= null;
        $index_page= null;
    }

    if($_POST){
        $username = $_POST["username"];
        $password = $_POST["password"];

        if(check_username_and_password_from_users($username, $password)){
            $_SESSION["username"] = $username;
        }
    }
?>
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Learn Bootstrap</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

                        <?php if(isset($_SESSION["username"])){ ?>

                            <?php echo $_SESSION["username"]; ?>

                                Logout

                        <?php }else{ ?>

                            Dropdown

                                <form id="loginform" method="post" action="index.php" class="form">

                                        <input class="form-control" type="text" name="username" id="username" placeholder="username">

                                        <input class="form-control" type="password" name="password" id="password" placeholder="password">

                                    <input type="submit" value="Submit">
                                </form>

Register

                        <?php } ?>

FAQs

Twitter

Facebook

                                <button class="btn btn-default" type="button">Go!</button>

                                <input type="text" class="form-control" placeholder="Search for...">

                        <?php
                            $subject_set =  find_all_subjects();
                            while($subject = mysqli_fetch_assoc($subject_set)){
                        ?>

                            <a id="dLabel" data-target="#" href="?subject=<?php echo urlencode($subject["id"]);?>" data-toggle="dropdown" aria-haspopup="true" role="button">
                                <?php echo $subject["name"];?>

                                <?php
                                    $page_set = find_pages_from_subjects($subject["id"]);
                                    while($page = mysqli_fetch_assoc($page_set)){
                                ?>

                                        <a href="?category=<?php echo urlencode($page["id"]);?>"><?php echo $page["name"];?>

                                            <?php
                                                $sub_page_set = find_sub_pages_from_pages($page["id"]);
                                                while($sub_page = mysqli_fetch_assoc($sub_page_set)){
                                            ?>

                                                <a href="?sub_category=<?php echo urlencode($sub_page["id"]);?>"><?php echo $sub_page["name"];?>

                                            <?php
                                                }
                                                clear_result($sub_page_set);
                                            ?>

                                <?php
                                    }
                                    clear_result($page_set);
                                ?>

                        <?php
                            }
                            clear_result($subject_set);
                        ?>

                <?php
                    include "load_files.php"; //this is to load the files
                ?>

to navigate register.html, i use this code

Register

as you can see, i put code on below in index.php
           <?php
                include "load_files.php"; //this is to load file
            ?>

and this is my load_files.php

<?php
    if($_GET){
        switch ($_GET['page']) {
            case 'register':
                if(!file_exists("register.html")){
                    die("Sorry Empty Page");
                }
                include 'register.html';
                break;
            default:
                break;
        }
    }
?>

A: Seems like an event handler issue. I'd look at how you are adding event handlers and see if the handler is getting wiped out somehow.

A: ::SOLVED::

My problem is, after I navigate to register.php by typing ?page=register in browser, my dropdown in index.php file become unusable

this problem happen because, i had 2

, inside index.php and register.html .by remove the one inside register.html will solve the problem


text:
Q: Hibernate query error <query name="getStudyTasksByParticipantId">
            from StudyTask st
            join (select max(lastUpdatedDate)as lastUpdatedDate, study, clinicalStudyRegistration from
                     StudyTask where clinicalStudyRegistration.participant.id in (:participantIds)
                     group by study, clinicalStudyRegistration ) lst
            where st.lastUpdatedDate = lst.lastUpdatedDate
            order by st.lastUpdatedDate desc

        </query>

When I run this query, it gives error like unexpected token: ( at line 3 col 30.
What's wrong in this query

A: The query is not valid HQL. The documentation says:

Note that HQL subqueries can occur only in the select or where
  clauses.

A join can only be done through an association between two entities.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating and populating custom nav menu (menu-item-position not working) Im automatically creating pages with the below code, after that I create a custom menu and insert all the pages to this menu.
$create_pages = array('Home', 'About', 'Contact'); // there will be more items
$count = 1;
foreach ($create_pages as $new_page) {
    $add_pages = array(
        'post_title' => $new_page,
        'post_content' => '',
        'post_status' => 'publish',
        'post_type' => 'page',
        'menu_order' => $count++ // incrementing the order value to overwrite default alphabetical ordering
    );
    $page_id = wp_insert_post($add_pages);
}

So far I managed to actually overwrite the default alphabetical ordering and now on the Pages screen, all the pages are ordered the way I want.
$main_nav_id = wp_create_nav_menu('Main menu', array('slug' => 'main-nav'));
set_theme_mod('nav_menu_locations', array('main-nav' => $main_nav_id));

$pages = get_pages();
$count = 1;
foreach($pages as $page) {
    $item = array(
        'menu-item-object-id' => $page->ID,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type',
        'menu-item-status' => 'publish',
        'menu-item-position' => $count++ // im trying to use the same approach
    );
    wp_update_nav_menu_item($main_nav_id, 0, $item);
}

So with this code, Im trying to use the same approach as I did before with the pages, but whatever I try, the menu items are still ordered in a weird way, I just want them to be ordered the same way as they are ordered on the Pages screen. How could I fix this?

A: You don't set sort_column to menu_order when you call get_pages, so it defaults to sorting on post_title.
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );


text:
Q: How to allow cyrillic in my package I am working on a package that includes an object that contains some text in cyrillic. Besides that, the package conforms to UTF-8.
Unfortunately, the cyrillic causes devtools::check to fail with:
> checking data for non-ASCII characters ... NOTE   Error in iconv(x,
> ...) :
>     embedded nul in string: 'P\024Q\vQ\0P:P0 P2 P<P0Q\002Q\aP5 (P;Q\016P1P0Q\017 P4Q\vQ\0P:P0 P1P>P;P5P5 1 Q\001P5P:) (P=Q\003P6P=P>
> Q\003P:P0P7P0Q\002Q\f P4P;P8Q\002P5P;Q\fP=P>Q\001Q\002Q\f)'   Calls:
> <Anonymous> ... format.check_package_datasets -> paste0 -> iconv0 ->
> paste0 -> iconv   Execution halted

This is solved when I remove the cyrillic text, but that text is actually needed.
I have tried to adapt the DESCRIPTION file to allow UTF-8 next to "russian", but that gives an error message of its own.
How can I allow "russian" next to "UTF-8" in a package, without it failing devtools::check?


text:
Q: Problems comparing two strings in C (Segmentation fault) Core dumped I've created a struct to group two pointer variables so I can store the address on those. Then I'm instantiating the struct and referring to the two variables from the main contest.
Comparing the two strings based on useroutput and return the desired result.
The code is here
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

typedef struct
{
    char *name;
    char *name2;
} names;

int main()
{
    names nm;
    printf("Please enter first string: ");
    scanf("%s", nm.name)
    printf("Please enter second string: ");
    scanf("%s", nm.name2);

    if(strcmp(nm.name, nm.name2) == 0)
        printf("Strings %s and %s do match\n", nm.name, nm.name2);
    else
        printf("Strings %s and %s do not match\n", nm.name, nm.name2);
    return 0;
}

I've tried to  printf("%s", &nm.name);
I am a novice C user.  Thanks!
Example that works without struct and pointer variables
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

int main()
{
    char name[20];
    printf("Please enter first string: ");
    scanf("%s", &name);
    char name2[20];
    printf("Please enter second string: ");
    scanf("%s", &name2);

    if(strcmp(name, name2) == 0)
        printf("Strings %s and %s do match\n", name, name2);
    else
        printf("Strings %s and %s do not match\n", name, name2);
    return 0;
}

gcc -Wall -Wextra -Wformat -pedantic -o strcmp strcmp.c

strcmp.c: In function 'main':
strcmp.c:10:2: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat]
strcmp.c:11:2: warning: ISO C90 forbids mixed declarations and code [-pedantic]
strcmp.c:13:2: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat]
strcmp.c:15:2: warning: implicit declaration of function 'strcmp' [-Wimplicit-function-declaration]

A: You need to allocate memory - this is a consensus here.
But no one pointed out to the buffer overflow problem. scanf("%s", pointer); may read more bytes than memory available in the buffer corrupting memory and causing program crush. Use field width specification to restrict number of characters to read:
char name[21];
scanf("%20s", name);

or if you want a dynamically allocated buffer
char *name = new char[21];
scanf("%20s", name);

The array must be large enough to accept all the sequence and the terminating NULL character. The input string stops at white space or at the maximum field width, whichever occurs first.
Address. You mentioned symbol &. This is an address operator. It is required in some examples you might have seen because scanf() expects a memory address.
int val;
scanf("%d", &val);

You are reading a string not an integer as in the example above
char name[21]; // name is an address of memory allocated for 21 bytes
char *name;    // same, name is an address, not allocated yet.
char name;     // is a char variable, it hols a single character.
               // If you need an address of the memory that holds that single character,
               // you need to use &
char *pointer  = &name; // Now pointer holds an address of name

Please read more about memory and variable declarations in C/C++. You wrote: printf("%s", &nm.name);
That will attempt to print a random memory area. If you are lucky it'll print garbage, if not it'll crash your program with memory access violation.
nm is a struct, name is a pointer to a character array. nm.name is a pointer to the character array. &nm.name is a pointer to the pointer to the array but printf interprets that as a pointer to the array.

A: For your edited question, you are using scanf incorrectly:
scanf("%s", &name);

should be
scanf("%s", name);

You must have seen examples using scanf with &, but in this case, name is already an char [20], which decays into a char * when passing as function argument.

A: You need to make the pointers point to something, for example:
int main()
{
    char buff1[20];
    char buff2[20];
    names nm;
    nm.name = buff1;
    nm.name2 = buff2;

A: Change the struct as below , your code will work fine .
 typedef struct
 {
   char name[20];
   char name2[20];
 }names;


text:
Q: String.to_atom hardcodes the underlying erlang.binary_to_atom encoding option to :utf8, why? Why does String.to_atom hardcode the encoding option to :utf8 ?
https://github.com/elixir-lang/elixir/blob/d6bb3342b7ea8b921b3d4b69f65064c4158c99d7/lib/elixir/lib/string.ex#L1927

 def to_atom(string) do
    :erlang.binary_to_atom(string, :utf8)
  end

The available encoding options for erlang binary_to_atom are :
latin1 | unicode | utf8

http://erlang.org/documentation/doc-8.0-rc1/erts-8.0/doc/html/erlang.html#binary_to_atom-2

A: TL;DR
Because the Erlang universe is finally settling on UTF-8 everywhere.
Discussion
latin1 is going away and is largely a subset of UTF-8 (except a few characters), unicode is an old alias for utf8, and that leaves us with just one universally applicable option: utf8. This is important since UTF-8 atoms (and strings) are the way forward within Erlang and also within Elixir.
If you are dealing in old data with non-UTF-8 encodings then convert it before your call to binary_to_atom/2.
This also falls in line with the newer string and unicode module changes in Erlang's standard library -- which can finally settle on UTF-8 as a generally accepted standard after decades of uncertainty (because encodings are hard and there was not much agreement about this when Erlang was invented).
A word on coding practice
I work in Japan handling mostly business data, some of it quite old, and some of it in really crazy encodings. I tend to code mostly in Erlang (I prefer tiny languages). When some of the older string handling functions and unicode module were written strings fell into two categories:

*

*A list of code points in ASCII (that was implicitly extend to encompass latin1 quite a bit of the time because, well, European languages were a common use and CJK was a wild mess back then)

*Some waking nightmare of dragonfire and frost zombies (because there was zero agreement about anything else and a gazillion radically incomplete, half-baked, technically inaccurate "standards")

Times have changed. Now we know that strings are nearly always going to be in UTF-8 and everything in the Unixverse has finally settled on this which has had the pleasant effect of having (pretty much) every other meaningful system settle on that as well (if not internally, then through robust detection libraries that can pick between UTF-16 and UTF-8).
The cases where you actually do have non-UTF-8 data then you know this to be the case and should convert your data before sending it to a universal function such as binary_to_atom/2. I actually think we should shift next to including a binary_to_atom/1 and phase out binary_to_atom/2 entirely -- which is what has already happened with list_to_atom/1 as of Erlang R20 (yay!).
So how does that affect your code?
When you start dealing in ancient encodings the complexity of your code suddenly explodes and that needs to be contained right away lest it infect your entire codebase with insanity. The best way to do this is to keep the crazy outside of your business system proper and do conversions out at the edges. Whenever we deal in old data that comes in crazy encodings we already know and are prepared for that -- so we convert to UTF-8 explicitly right up front, so there isn't anything left to encounter later on deeper in the system.
You might think, "Why don't they just detect the encoding of every string?" Alas, there is no proper way to detect string encodings. It is just not possible with a high degree of confidence. It is also quickly becoming an obsolete task in the majority case as the vast majority of data generated today is UTF-8 (or UTF-16, but it is very rare to encounter this over the wire).


text:
Q: What exception would google app engine return if tried to add data in datastore that is already full What exception would google app engine return if tried to add data in datastore that is already full?

A: That would be an apiproxy_errors.OverQuotaError as described here.


text:
Q: How to make a requirejs module with multiple files I was wondering how to make a requirejs module with multiple files.
e.x. I require one file which then somehow gets multiple files.
I know I could do this:
define([all the other files], function () {
  var mod = {},
      files = [all the other files];
  arguments.forEach(function (i) {
    mod.[files[i]] = i;
  });
  return mod;

});

but I was wondering whether there was a better method?

A: You want a dynamic list of files(.txt,.tpl,.htm,.json), to avoid a change in JS source code to add more files.
I don't know if is there a way to do that, but you must take care about the time that will take to download all this files. I suggest you to create a json file with all files that you want to download, and iterate through this array of files using ajax to get them.
If you are try to get all module inside a directory, you need to create a js file: <package-all>.js that encapsulate an require([all files],function()); for example.
I believe that this is the only way to solve this.

A: first, write the modules like this,
define(function(){
    return {
        'mod-a' : require('modules/mod-a'),
        'mod-b' : require('modules/mod-b'),
        'mod-c' : require('modules/mod-c')

    }
})

then use r.js to optimize the above js to blow one (r.js will combine all module file to one), or, you can write like this directly :
define('modules/mod-a', [], function(){});
define('modules/mod-b', [], function(){});
define('modules/mod-c', [], function(){});

define('mod-all', ['modules/mod-a','modules/mod-b','modules/mod-c'], function(){

    return {
        'mod-a' : require('modules/mod-a'),
        'mod-b' : require('modules/mod-b'),
        'mod-c' : require('modules/mod-c')
    }
})

now, the modules 'mod-all' is the thing you wanted.


text:
Q: Multiple ToggleSwitch instances get same data from the List (ListView) using C# in UWP This is my first experience with ToggleSwitch. What I am trying to achieve is to show different data from the list using different ToggleSwitches.
I have a ListView with multiple TextBlocks and one ToggleSwitch for each row of data.
Then I populate ListView with data from List. (List is populated using class that forsees

public ToggleSwitch Switch {get; set;}

Here is how I try to get ToggleSwitch data from each row:
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
    {

        for (int a = 0; a < jointList.Count; a++)
        {
               jointList[a].Switch = sender as ToggleSwitch;
            if (jointList[a].Switch != null)
            {
                if (jointList[a].Switch.IsOn == true)
                {
                    ToggleTest.Text = jointList[a].ProductId.ToString();

                    ToggleTest.Visibility = Visibility.Visible;

                }
                else
                {

                    ToggleTest.Visibility = Visibility.Collapsed;
                }
            }
        }

    }

Unfortunately I am getting the same(last added) productId from all of the ToggleSwitches as if they were pointing to same place.
EDIT>
I have rewritten the code as touseef suggested:
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
    {

        for (int i = 0; i < jointList.Count; i++)
        {

                if (jointList[i].Value == true)
                {
                    ToggleTest.Text = jointList[i].ProductId.ToString();

                   // ToggleTest.Text = jointList[a].ProductId.ToString();
                    ToggleTest.Visibility = Visibility.Visible;

                }
                else
                {

                    ToggleTest.Visibility = Visibility.Collapsed;
                }

        }

    }

But now nothing shows up.
EDIT:
Here is another attempt to resolve the problem:
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
    {

        foreach (var record in jointList)
        {

            if (record.Value == true)
            {
                ToggleTest.Text = record.ProductId.ToString();

                ToggleTest.Visibility = Visibility.Visible;

            }
            else
                {

                    ToggleTest.Visibility = Visibility.Collapsed;
                }

        }

    }

And now only one ToggleSwitch works, the one that corresponds to the last added record (I was pulling ProductId of the jointList).
None of the other ToggleSwitches work. They don't return any data when using the code above.

A: Please use DataTemplate to populate a listview and within your datatemplate put a toggleswitch, and x:Bind the IsOn value for your toggleswitch with a bool property within your item's class. and to get the correct values in your c# object behind set two way databinding.
basic databinding : https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-quickstart
binding in depth : https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
you can bind with Binding or x:Bind the better way to bind in uwp is x:Bind though, see the links I provided you they will help you a lot :)
Instead of looping the list and getting sender as ToggleSwitch which will obviously give u same instance everytime. you should just loop over the list which you bind to the ListView, and then check your item.IsOn property and get ur item.ProductId and do whateer u want to with ur item object. note that this item came from the List of items which u are binding to the ListView. when u set two way databinding with toggleswitch, your item.IsOn property will automatically change when toggleswitch.IsOn changes, so you don't need to get any instance of toggleswitch in ur code.
INotify
in order to get notified about the propertychange and for two way databinding to work properly, you need to inherit your Product class from following class
public class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

and then in your IsOn property setter method, call onpropertychanged event like this.
 public class Product : Observable
{
    public int ProductId { get; set; }
    private bool isOn;

    public bool IsOn
    {
        get { return isOn; }
        set { isOn = value; Set(ref isOn, value, nameof(IsOn)); }
    }

}

Toggled Event
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
    //assuming productList is a List<Product> which was set as ListView.ItemSource
    foreach (var product in productList)
    {

        if (product.IsOn == true)
        {
            ToggleTest.Text = product.ProductId.ToString();
            ToggleTest.Visibility = Visibility.Visible;
        }
        else
        {
            ToggleTest.Visibility = Visibility.Collapsed;
        }

    }
}

if your problem still isn't solved, I will recommend you to put a simplistic app with this problem on the GitHub repo and share the link in your question so people can have a detailed look at it.


text:
Q: iOS SDK: Adding AVCaptureVideoDataOutput to AVCaptureSession causes it to slowly leak memory indefinitely I have a super basic AVCaptureSession set up with an AVCaptureVideoDataOutput and AVCaptureStillImageOutput. AVCaptureVideoDataOutput does not have a buffer delegate. There's nothing fancy going on, just setting up a standard issue AVCaptureSession. If I just compile the app and let it sit there for about 10 minutes, the available memory drops by like 1mb every minute or so. I've started the app with 72mb free, and after just letting it sit on my desk, I've seen free memory get as low as 33mb.
If I comment out the piece where I add AVCaptureVideoDataOutput to the session, available memory stays around 70-72mb.
So I set up a button to remove AVCaptureVideoDataOutput from the session, and after tapping the button, available memory immediately jumps back up to when the app was first run (~72mb). Has anyone else seen this and know of a workaround? I have iOS 5.0 on my iPhone and the latest beta SDK.
Edit: Here's the code that adds AVCAptureVideoDataOutput:

...

NSNumber *rgbNum = [NSNumber numberWithInt:kCVPixelFormatType_32BGRA];
NSDictionary *videoSettings = [NSDictionary dictionaryWithObject:rgbNum forKey:(id)kCVPixelBufferPixelFormatTypeKey];

dataOutput = [AVCaptureVideoDataOutput new];
[dataOutput setAlwaysDiscardsLateVideoFrames:YES];
[dataOutput setVideoSettings:videoSettings];
_videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", NULL);
[dataOutput setSampleBufferDelegate:self queue:_videoDataOutputQueue];
dispatch_release(_videoDataOutputQueue);

if ([session canAddOutput:dataOutput]) {
  [session addOutput:dataOutput];
} else {
  NSLog(@"couldn't add av data output");
}
...

Commenting out the buffer delegate doesn't seem to make a difference.
Just tried this again and it went from ~70mb free to ~54mb free within 6 minutes. :(

A: I'm not sure you should care so much about current available memory in this case. iOS may cache something on it's own decision or keep memory reserved for some purposes.
To check memory leaks - it's better to use profiler with leaks tracker, but not just current memory available.
Also, it's good idea to check the behavior on released iOS SDK - the beta may have some issues since it's beta...

A: Apparently there's no workaround for this - filed a bug w/ Apple.
Edit:
This question is a bit old, but in case it helps anyone: I'm not 100% positive, but I think the reason I was seeing this is because I had zombie objects turned on! Make sure you don't have zombie objects enabled in Xcode and see if that helps! Go to "Edit Scheme..." then choose the Diagnostics tab.


text:
Q: I want to count the number of presses of the button(switch) before it executes my code only executes the case 1. i need if i press 3 times. it will execute my case 3. thank you so much
int pushButton = 13;

void setup() {
  Serial.begin(9600);
  pinMode(pushButton, INPUT);
for(int pin=10;pin<=12;pin++){
  pinMode(pin,OUTPUT);
}
}

void loop() {
  int ctr=0;
  int buttonState = digitalRead(pushButton);

 if(buttonState ==1)
  {
    ctr+=1;
    Serial.println(ctr);

  }
  switch (ctr) {
  case 1:
  Serial.println("00000000000000000000");
     blinking();
    break;
  case 2:
  Serial.println("AAAAAAAAAAAAAAAA");
    running();

    break;
  case 3:
    incremental();
  default:
    Serial.println("push the button");
}

}

void blinking(){

    for(int z=0;z<=3;z++){
    for(int i=10;i<=12;i++){
      digitalWrite(i,HIGH);
    }delay(500);
    for(int i=10;i<=12;i++){
      digitalWrite(i,LOW);
    }delay(500);
    }

}

void running(){
 for(int z=0;z<=2;z++){
   for(int i=10;i<=12;i++){
     digitalWrite(i,HIGH);
     delay(500);
     digitalWrite(i,LOW);
  }
 }

}

void incremental(){
 for(int z=0;z<=2;z++){
    int d=1500;
   for(int i=10;i<=12;i++){
    digitalWrite(i,HIGH);
    delay(d); d-=500;
   }
   for(int i=10;i<=12;i++){
    digitalWrite(i,LOW);
   }delay(500);
  }

}

my code only executes the case 1. i need if i press 3 times. it will execute my case 3. thank you so much

A: Change int ctr=0 to static int ctr=0
It is the same thing as declare ctr with global scope.
It will not reset to 0 each time loop function is called.
Button debounce  should be checked.

A: Apart from the fact that ctr is assigned zero every time loop() runs, you also have the problem that if the button is held down, ctr will increment continuously, which may not be what you want. It also increments ctr past three, when the default case will run indefinitely.  It is not clear that you intended case 3 to fall-through to the default case; it is generally considered bad practice or a mistake, so worth a comment if it is deliberate.
The following code makes ctr static so it is nor always assigned zero, and increments ctr only when the button is pressed down, and will not increment it if it is merely held-down or stuck.  It also returns ctr to zero in the default case so you can cycle the states (which may not be your intent).  I have removed the debug output for clarity.
void loop()
{
  static int ctr = 0 ;
  static bool button_down = false ;
  int button_state = digitalRead(pushButton) == 1 ;

  if( !button_down && button_state = 1 )
  {
    ctr++ ;
    button_down = true ;
  }
  else if( button_state = 0 )
  {
     button_down = false ;
  }

  switch( ctr )
  {
    case 1:
      blinking();
    break;

    case 2:
      running();
    break;

    case 3:
      incremental();
    break ;

    default:
        ctr = 0 ;
    break ;
  }
}


text:
Q: How to 'Find And Push' element in an array inside of another array in a document using LINQ to MongoDb I want to push an element to an array inside another array inside a document using LINQ with latest MongoDb driver
here is the code:
public class Contract : BaseDocument
{
    public ObjectId Id {get;set;}
    ...
    public List<Payment> Payments {get;set;}
}

public class Payment : BaseDocument
{
    public ObjectId Id {get;set;}
    public double TotalPaymentAmount {get;set;}
    public DateTime PaymentWorthDate {get;set;}
    ...
    public List<PaymentTransaction> PaymentTransactions {get;set;}
}

public class PaymentTransaction
{
    public double AmountPaid {get;set;}
    public DateTime TransactionDateTime {get;set;}
}

So how to push new PaymentTransaction to a specific Payment in a particular Contract using 'LINQ Expression' ?
Thanks!

A: LINQ stands for Language-Intergrated Query while you're trying to update the document so actually you need UpdateOne method. Since you have more than one nested array you can leverage regular query to identify Contract along with the $ positional operator to indicate which Payment (nested object) should be modified.
.NET MongoDB driver offers a special syntax where you can pass -1 as an index to indicate that this item will be identified based on filtering condition. Try:
var filterBuilder = Builders<Contract>.Filter;
var filter = filterBuilder.Eq(x => x.Id, contractId) &
                filterBuilder.ElemMatch(doc => doc.Payments, el => el.Id == paymentId);

var updateBuilder = Builders<Contract>.Update;
var update = updateBuilder.Push(doc => doc.Payments[-1].PaymentTransactions, new PaymentTransaction());

col.UpdateOne(filter, update);


text:
Q: Including Azure Blob storage library causes problems in Spring I have a spring application which, when I include the latest azure storage blob library:
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-blob</artifactId>
        <version>12.14.0</version>

It changes my responses from Controllers to XML. I found this issue (https://github.com/Azure/azure-sdk-for-java/issues/7694) which seemed to fix my problem by excluding the XML data formatter like so:
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-blob</artifactId>
        <version>12.14.0</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
            </exclusion>
        </exclusions>

My responses changed back to JSON, but when I try to use the library, I get a NoClassDefFoundError error:
Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/dataformat/xml/XmlMapper$Builder
    at com.azure.storage.blob.implementation.util.ModelHelper.<clinit>(ModelHelper.java:53)
    at com.azure.storage.blob.BlobUrlParts.parse(BlobUrlParts.java:371)
    at com.azure.storage.blob.BlobServiceClientBuilder.endpoint(BlobServiceClientBuilder.java:147)
    at com.azure.storage.blob.BlobServiceClientBuilder.connectionString(BlobServiceClientBuilder.java:286)
    at util.AzureUtil.blobClient(AzureUtil.java:47)
    at util.AzureUtil.getSecureReadParams(AzureUtil.java:24)
    at util.AzureUtil.getFullSecuredURL(AzureUtil.java:35)
    at RestServer.fabric.FilesFabric.getPresignedGetUrl(FilesFabric.java:37)
    at RestServer.controllers.api.FilesController.getSecureFileUrl(FilesController.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
    ... 96 more
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.dataformat.xml.XmlMapper$Builder
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 116 more

I could, theoretically, decorate all my Controllers' @RequestMapping with produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE to tell the controllers to use JSON, but this seems like a hacky workaround. Is there any way to get the Azure Blob library to leave my responses alone, but still work?

A: Seems like your xml configuration picks up instead of json.
You can try by changing this configuration like follows!
Create the following bean inside an existing @Configuration class
@Bean
public WebMvcConfigurer customConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
        }
    };
}

or you can create a seperate @Configuration class
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }
}


text:
Q: Fibonacci Matrix For calculating a fibonacci sequence in O(logn) we use matrix exponential since the term
fn = fn-1 + fn-2 is linear but what is the matrix required if we want to find nth term of
fn = fn-1 + fn-2 + a0 + a1*n + a2*n^2 + ... an*n^n
which is a dependent on polynomial???
Here a0,a1,... an are constants

A: Look here for implementation in Erlang which uses formula

. It shows nice linear resulting behavior because in O(M(n) log n) part M(n) is exponential for big numbers. It calculates fib of one million in 2s where result has 208988 digits. The trick is that you can compute exponentiation in O(log n) multiplications using (tail) recursive formula (tail means with O(1) space when used proper compiler or rewrite to cycle):
% compute X^N
power(X, N) when is_integer(N), N >= 0 ->
    power(N, X, 1).

power(0, _, Acc) ->
    Acc;
power(N, X, Acc) ->
    if N rem 2 =:= 1 ->
            power(N - 1,   X,     Acc * X);
        true ->
            power(N div 2, X * X, Acc)
    end.

where X and Acc you substitute with matrices. X will be initiated with  and Acc with identity I equals to .


text:
Q: How can I do a crossfade with angular animate and ngFor? I'm triggering an animation when I update the collection I pass into *ngFor:
//JS
state : string = 'a';
colors = {
  a: ['red','blue','green','yellow'],
  b: ['orange']
}

public onClick (){
  this.state = this.state === 'a' ? 'b' : 'a';
}

//HTML
<div *ngFor="let color of colors[state]"
   [@animationState]="state"
   (click)="onClick()">
     {{color}}
</div>

The problem: While the animation is happening, colors from both a and b display, which makes the animation jerky.
I've tried:

*

*setting transform: scale(0) or display:none before the void => * animation begins

*delaying the void => * animation by the duration of the * => void animation

I want: to smoothly fade and/or slide out my existing content before (or while) the new content fades/slides in.
Here's a plunkr that demonstrates the problem: https://plnkr.co/edit/IDE6q6lJ84QI2Zirvn4P?p=preview

A: I managed to make it work, but it feels like a hack. Instead of setting the ngFor collection to the new value immediately, I

*

*store the new value in a temp variable

*set the ngFor collection to an empty collection

*when the animation to an empty collection completes, update the collection to the value stored in the temp variable

This triggers two animations instead of one, but seems to work well.
//JS
state : string = 'a';
temp : string;
colors = {
  a: ['red','blue','green','yellow'],
  b: ['orange'],
  empty: []
}

public onClick (){
  this.temp = this.state === 'a' ? 'b' : 'a';
  this.state = 'empty'
}

public animationComplete(){
  if(this.temp){
    this.state = this.temp;
    this.temp = undefined;
  }
}

//HTML
<div *ngFor="let color of colors[state]"
   [@animationState]="state"
   (@animationState.done)="animationComplete()"
   (click)="onClick()">
     {{color}}
</div>


text:
Q: updating multiple value in third table JobPost_Skill
JobPost_Skill_ID    JobPost_ID  Skill_ID
 -----------        -----------  -----------
      1                1             1
      2                1             2
      3                1             3
      4                2             3
      5                2             5

This my third table where JobPost_ID ,Skill_ID are foreign key
now i want to update query which will only update two rows of Skill_ID where JobPost_ID=1.
this means my output should be
JobPost_Skill_ID    JobPost_ID  Skill_ID
 -----------        -----------  -----------
      1                1             4
      2                1             5
      3                1             3
      4                2             3
      5                2             5

A: you can update using below query
updete JobPost_Skill
set Skill_ID =New Skill_ID
where JobPost_ID=JobPost_ID
and Skill_ID = oldSkill_ID

Note: Replace
JobPost_ID the job post id you need to update
New Skill_ID  new value for skill id
oldSkill_ID  old value of skill id
ie
       updete JobPost_Skill set Skill_ID = 4 where JobPost_ID=1 and Skill_ID = 1;

        updete JobPost_Skill set Skill_ID = 5 where JobPost_ID=1 and Skill_ID = 2,


text:
Q: Class path issue in Spring: File Not Found Exception I have a simple Java Spring IO project where a class  should read from a csv file and for each record read,  the parameters are stored into a list of  account objects.
I'm using Force IDE Luna and the Class CsvAccountDao that reads the file is in the same package as the csv file which is defined in the first bean of the xml file.  The xml file is also located under the same package. Here is the bean file:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <bean id="accountDao"
    class="com.springinpractice.ch01.model.dao.csv.CsvAccountDao">
    <property name="csvResource" value="accounts.csv"></property>
    </bean>
    <bean id="accountService"
            class="com.springinpractice.ch01.service.AccountService">
            <property name="accountDao" ref="accountDao"</property>
        </bean>
</beans>

and here is the class file CscAccountDao:
package com.springinpractice.ch01.model.dao.csv;
import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.core.io.Resource;
import com.springinpractice.ch01.model.Account;
import com.springinpractice.ch01.model.dao.AccountDao;

public class CsvAccountDao implements AccountDao {
    private Resource csvResource;

    public CsvAccountDao() {
        // TODO Auto-generated constructor stub
    }
    public void setCsvResource(Resource csvFile){
        this.csvResource = csvFile;
    }
    @Override
    public List<Account> findAll() throws Exception {
        List<Account> results = new ArrayList<Account>();

        DateFormat fmt = new SimpleDateFormat("MMddyyyy");
        BufferedReader br = new BufferedReader(
                new FileReader(csvResource.getFile()));
        String line;
        while((line = br.readLine()) != null){
            String[] fields = line.split(",");

            String accountNo = fields[0];
            BigDecimal balance = new BigDecimal(fields[1]);
            Date lastPaidOn = fmt.parse(fields[2]);
            Account account =
                        new Account(accountNo, balance, lastPaidOn);
            results.add(account);
        }
        br.close();
        return results;
    }
}

Note where method setCsvResource assigns the csv file to the resource object is where the exception problem begins. I get an exception error in the stack trace  that says:
Jun 20, 2015 7:59:42 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@177e4b0: defining beans [accountDao,accountService]; root of factory hierarchy
Exception in thread "main" java.io.FileNotFoundException: class path resource [accounts.csv] cannot be resolved to URL because it does not exist

Q) Is there a problem where I would have to updated the XML file where the first bean uses accounts.csv by adding a full path? Since the both the class,xml,  and the csv files are within the same package I thought I didn't need to be more specific.

A: Some background on resource loading.
In Java, to load a classpath resource, you call getResource or getResourceAsStream on a classloader with a resource name. A resource name is:

The name of a resource is a '/'-separated path name that identifies the resource.

So to get a resource from a package you use:
classloader.getResource("org/com/resource.jpg")

A java class also has convenience methods to load resources from it's class loader. If you use ClassA.class.getResource("resource.jpg"), it will prefix the '/'-joined package of ClassA to "resource.jpg" and delegate to the classloader. If your resource string starts with a '/' it is interpreted as an absolute path, the starting '/' is removed and then it delegates to the classloader.
So then we get to spring where you are supplying accounts.csv as a value to be converted into a resource. Spring uses DefaultResourceLoader to find your resource. Here is the logic it uses to find your resource:
@Override
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    if (location.startsWith("/")) {
        return getResourceByPath(location);
    }
    else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
    }
    else {
        try {
            // Try to parse the location as a URL...
            URL url = new URL(location);
            return new UrlResource(url);
        }
        catch (MalformedURLException ex) {
            // No URL -> resolve as resource path.
            return getResourceByPath(location);
        }
    }
}

In your case it falls all the way through to the catch(MalformedURLException ex) and then tries to look it up as a classpath resource. When the ClasspathResource is eventually asked for an URL or input stream it passes "account.csv" to the classloader. The classloader is looking for it in the root of the classpath.
So in your spring xml you need to tell it what package it is in. It will not be relative to the xml. So change it to "/package/account.csv" or "classpath:/package/account.csv"
For reference: I'm looking at Spring 4.0.9.RELEASE and oracle jdk8.


text:
Q: Setting up container registry for kubeflow I am using ubuntu 20.04
while following book -> https://www.oreilly.com/library/view/kubeflow-for-machine/9781492050117/
on page 17, it says the following (only relevant parts) which I don't understand....

You will want to store container images called a
container registry. The container registry will be accessed by your Kubeflow cluster.

I am going to use docker hub as container registry. Next

we'll assume that you've set your container registry via an environment variable
$CONTAINER_REGISTRY, in your shell" NOTE: If you use registry that isn't on Google Cloud
Platform, you will need to configure Kubeflow pipelines container builder to have access to
your registry by following the Kaniko configuration guide -> https://oreil.ly/88Ep-

First, I do not understand how to set container registry through environment variable, am I supposed to give it a link??
Second, I've gone into Kaniko config guide and did everything as told -> creating config.json with "auth":"mypassword for dockerhub". After that In the book it says:

To make sure your docker installation is properly configured, you can write one line Dc and
push it to your registry."

Example 2.7 Specify the new container is built on top of Kubeflow's
container

FROM gcr.io/kubeflow-images-public/tensorflow-2.1.0-notebook-cpu:1.0.0

Example 2.8 Build new container and push to registry for use

IMAGE="${CONTAINER_REGISTRY}/kubeflow/test:v1"
docker build  -t "${IMAGE}" -f Dockerfile . docker push "${IMAGE}"

I've created Dockerfile with code from Example2.7 inside it, then ran code from Example 2.8 however not working.

A: Make sure that:

*

*You set the environment variable using export CONTAINER_REGISTRY=docker.io/your_username in your terminal (or in your ~/.bash_profile and run source ~/.bash_profile).

*Your .docker/config.json does not have your password in plain text but in base64, for example the output of echo -n 'username:password' | base64

*The docker build and the docker push are two separate commands, in your example they're seen as one command, unlike the book.


text:
Q: Not working in putting the text in the middle of the box in CSS3 I want to put text in the middle of the box in CSS3, but it's not working for some reasons.
Here's my code snippet (with code from Angularjs):

            {{i.b}} {{i.c}}

And here's my css:
.b {
display: inline-block;
float: left;
margin: 8px;
height: 20px;
width: 100px;
}

And even if I add vertical-align: middle; to the above CSS, it doesn't put the text in the middle of the box... why?
Thanks.

A: You need to use css table-cell
DEMO http://jsfiddle.net/LstNS/31/
.b {
    display: table-cell;
    vertical-align: middle;
}
.a {
    display: table;
    height: 200px;
    border: black thin solid;
}

A: vertical-align requires a lot of things to work right...
easiest method , and what I do, is just use line-height
so do
.b {
    line-height: 20px;
}

adjust number of pixels accordingly, but that will center the text vertically for you

A: float kills display and so vertical-align if avalaibe.
inline-blocks element can be vertical-align aside text, other inline-boxes or on the line-height.
In your case , line-height alone will give height of parent (if unprecised) and set the link on it, right in the middle :), no need to give an inline-block display to  unless you need it to size it for instance (or whatever else style that needs layout) .
If .a has an height, give it an equal line-height.
Line-height works fine as long as you have one line of text.
if you want to use inline-block, and set middle alignement from itself it won'nt work, you need at least 2 elements as another inline-boxe, so it can center from something ... an extra box or pseudo-element might help.

.a {height:300px;}
.a:before {
content:'';
height:100%;
}
.a:before, .a a {
display:inline-block;
vertical-align:middle;
}

Else, vertical-align works on content of  or element wich receive a display:table-cell;. .a could then receive a display:table-cell and vertical-align and eventually an height. Usually it needs a parent as display:table to work fine.

.a {
display:table-cell;
height:200px;
vertical-align:middle;
}

I have no special links on tutorial for vertical-align , on W3C it is confusing somehow since both vertical-align for inline-box and cell content are dispatched in different documents.


text:
Q: pre-load / pre-require directories of .js route files Using Express with Node.js, we might do something like this:
app.use('api/:controller/:action/:id', function(req,res,next){

   var controller = req.params.controller;
   var action = req.params.action;

   var route = require('./routes/' + controller + '/' + action);

   route(req,res,next);

}

now this is all fine and well, except there is at least one problem: the route file is dynamically loaded at runtime if this file has not been 'require'd yet. Which means it's a little bit slower at least.
Does someone have a script that recurses through a directory and pre-loads/pre-requires all the .js files when a server first starts up?
I have a similar problem for the front-end as well, using RequireJS. The solution seems to be to write a bash script that writes out all the .js filepaths in a directory and its subdirectories to a text file. then when the server starts up, it reads that text file and requires all the files in the directory that are listed in the text file. Is that the best way to do it?

A: If you can use io.js, it can preload modules using command-line -r or --require:
iojs -r <module_name> server.js

A: I created an NPM module that does this for the front-end, doing it for Node.js / CommonJS is another story.
https://www.npmjs.com/package/requirejs-metagen
you can use it like so:
var grm = require('requirejs-metagen'); //you can use with Gulp

var controllersOpts = {
        inputFolder: './public/static/app/js/controllers/all',
        appendThisToDependencies: 'app/js/controllers/',
        appendThisToReturnedItems: '',
        eliminateSharedFolder: true,
        output: './public/static/app/js/meta/allControllers.js'
    };

grm(controllersOpts,function(err){
  //handle errors your own way
});

it generates a corresponding AMD/RequireJS module like so:
define(
    [
        "app/js/controllers/all/jobs",
        "app/js/controllers/all/users"
    ],
    function(){

        return {

            "jobs": arguments[0],
            "users": arguments[1]
        }
  });

you can also require subdirectories and all that stuff like so:
 var allViewsOpts = {
        inputFolder: './public/static/app/js/jsx',
        appendThisToDependencies: 'app/js/',
        appendThisToReturnedItems: '',
        eliminateSharedFolder: true,
        output: './public/static/app/js/meta/allViews.js'
    }

 grm(allViewsOpts );

which generates output like so:
define([
        "app/js/jsx/BaseView",
        "app/js/jsx/reactComponents/FluxCart",
        "app/js/jsx/reactComponents/FluxCartApp",
        "app/js/jsx/reactComponents/FluxProduct",
        "app/js/jsx/reactComponents/Item",
        "app/js/jsx/reactComponents/Job",
        "app/js/jsx/reactComponents/JobsList",
        "app/js/jsx/reactComponents/listView",
        "app/js/jsx/reactComponents/Picture",
        "app/js/jsx/reactComponents/PictureList",
        "app/js/jsx/reactComponents/RealTimeSearchView",
        "app/js/jsx/reactComponents/Service",
        "app/js/jsx/reactComponents/ServiceChooser",
        "app/js/jsx/reactComponents/todoList",
        "app/js/jsx/relViews/getAll/getAll",
        "app/js/jsx/relViews/jobs/jobsView",
        "app/js/jsx/standardViews/dashboardView",
        "app/js/jsx/standardViews/overviewView",
        "app/js/jsx/standardViews/pictureView",
        "app/js/jsx/standardViews/portalView",
        "app/js/jsx/standardViews/registeredUsersView",
        "app/js/jsx/standardViews/userProfileView"
    ],
    function(){

        return {

            "BaseView": arguments[0],
            "reactComponents/FluxCart": arguments[1],
            "reactComponents/FluxCartApp": arguments[2],
            "reactComponents/FluxProduct": arguments[3],
            "reactComponents/Item": arguments[4],
            "reactComponents/Job": arguments[5],
            "reactComponents/JobsList": arguments[6],
            "reactComponents/listView": arguments[7],
            "reactComponents/Picture": arguments[9],
            "reactComponents/PictureList": arguments[10],
            "reactComponents/RealTimeSearchView": arguments[11],
            "reactComponents/Service": arguments[12],
            "reactComponents/ServiceChooser": arguments[13],
            "relViews/getAll/getAll": arguments[14],
            "relViews/jobs/jobsView": arguments[15],
            "standardViews/dashboardView": arguments[16],
            "standardViews/overviewView": arguments[17],
            "standardViews/pictureView": arguments[18],
            "standardViews/portalView": arguments[19],
            "standardViews/registeredUsersView": arguments[20],
            "standardViews/userProfileView": arguments[21]
        }
  });

I need to update the library so it returns the stream so you can handle when it completes, otherwise it works great.


text:
Q: Scan beacons in background on iOS and Android with Delphi I have an aplication that scans Beacons on run time, but the intention is to look for the beacons in background on iOS and Android.
On android application i almost got there by using an Android service to search beacons and show notifications with TNotificationCenter. But the androuid service only starts when i open the application, i think it could be independent, is it possible to do?
On iOS Platform its not possible create service like on Android, so i dont know what to do.
Best regards


text:
Q: Mean deviation gives better results when deviations are taken from the median, why?
The mean deviation gives better resuls when deviations are taken from the median instead from the mean, because the sum of the deviations from the median is less than the sum of the deviations from the mean

$$
\operatorname{M.D.}(M)=\frac{\sum|x_i-M|}{N}=\frac{\sum f_i|x_i-M|}{\sum f_i}
$$
This is a widely used statement when defining mean deviation. I understand the proof by which we can say the mean deviation is minimized when deviations are taken from the median. But how come that somehow leads to the statement "mean deviation gives better resuls when deviations are taken from the median instead from mean as the former minimizes the sum of absolute deviations" ?
Screen shot of sample reference
Please check link for the reference.

A: Whether item 3 under "merits" is a merit depends on what the purpose is.
Item 3 under "limitations" is nonsense. It does in fact not take into account whether an observation is more than the mean or less, at least after the point where the mean is computed, but why would that be a reason to consider anything mathematically incorrect?
Item 2 under "limitations" also depends on what the purpose is.
Item 1 under "limitations" may be subtle.
Now imagine a normally distributed population has standard deviation $\sigma,$ and $\sigma$ is not observable but a finite random sample of $n$ observations is available. The expect value of the mean absolute deviation of the sample is a known scalar multiple of $\sigma.$ Multiplying the mean absolute deviation of the sample by the reciprocal of that known scalar yields an unbiased estimator of of $\sigma.$ Similarly, multiplying the sample standard deviation by another known scalar yields an unbiased estimator of $\sigma.$
Theorem: The one based on the standard deviation has a smaller variance than the one based on the mean absolute deviation.
So that's one thing that could be called a demerit of the mean absolute deviation.
However if the population distribution is only slightly different from normal, that is no longer true.
These lists of "merits" and "limitations" look like something written by a person with little understanding of the subject matter.


text:
Q: wrap text around an image or shape from both sides How can I have a text wrapping around an arbitrarily positioned image or shape within a single block of text?

image is property of https://www.sarasoueidan.com/blog/css-shapes/

Note that I am not looking for a solution that involves separate columns of text such as this one which exploits left/right floats with shape-outside.

A: At this moment, this behaviour is not supported, however, there is a draft for it.
More reading:
https://css-tricks.com/exclusions-will-hopefully-be-like-more-powerful-grid-friendly-floats/
https://www.sarasoueidan.com/blog/css-shapes/
https://drafts.csswg.org/css-exclusions-1/

CSS Exclusions Module Level 1
Editor's Draft, 16 January 2020
CSS Exclusions define arbitrary areas around which inline content can flow.

CSS Shapes Module Level 2
Note that there also was a shape-inside property, which would have been possible to use as a workaround with a proper polygon, but its support was removed and implementation postponed until https://drafts.csswg.org/css-shapes-2/. So right now, it is only possible to use shape-outside with a float-ing element.

images property of https://www.sarasoueidan.com/blog/css-shapes/

The initial Shapes specification included a property shape-inside for creating shapes inside an element. This property, along with the possibility of creating shapes on non-floated elements, has been moved to level 2 of the specification. As the shape-inside property was initially in Level 1 of the specification, you may find tutorials on the web detailing both properties.
  ~ MDN


text:
Q: Nesting Cascading lists/Subtypes in QGIS? Has anyone got any experence in creating nested cacading lists/subtypes in QGIS? (QGIS - 3.22.10-Białowieża)
I am trying to create a form that allows user to select a type of survey from a list, then chose catogeries from within that survey and finally a correlating code.
However, while the use of the "relation, query" widget works for the first section (Survey to Catogery), the cascade list fails to populate for the second section (Catogery to Code). Failing to populated the list at all.

Value relation widget in QGIS
The filter expressions for both the Survey to Catogrey & Catogrey to Code are set up using the current_value expression as demonestrated in the above post.


text:
Q: Possible to loop through tables in mySQL (using PHP) with table name containing a variable? I'm pretty new to programming and trying to design a web application which provides a front-end to update data for an online course database (tables incl. users, assignments, questions, answers, etc). All data is coming into this database upon submission via course management system. Currently working with dummy data for development purposes.
The idea is to allow a user to update from the front end, rather than have updates occur automatically from the back end (as in using triggers). This is because we have a relatively small data set, and will just need the updated tables for users not familiar with mysql to export into data analysis programs.
Using multiple joins, I've created a list of assignments already taken by users, which looks like this:
+----+---------------+---------------------------------------+
| id | assignment_id | quiz_name                             |
+----+---------------+---------------------------------------+
|  1 |             2 | Guidance Counselors (Post-Assessment) |
|  2 |             3 | Guidance Counselors (Pre-Assessment)  |
|  3 |             4 | Guidance Counselors (Pre-Assessment)  |
+----+---------------+---------------------------------------+

In PHP, I've coded a basic front-end for displaying and updating these assignments in a multi-selection dropdown, which looks like this:
Assignment list table
Whenever a user wants to update the list, php runs this if statement (the same one used to generate the above table):
  //update assignment list when button is clicked
  if(isset($_POST['updatelist'])){
  //query to update the assignment list
  $sql_update = "DELETE FROM assignment_list;";
  $sql_update .= "TRUNCATE assignment_list;";
  $sql_update .= "INSERT INTO assignment_list....
  #values added from joined assignment, quizzes, and user_quizzes tables
  SELECT...
  INNER JOIN ...
  INNER JOIN ...
   ...
  GROUP BY assignment_id";

      $update_result = mysqli_multi_query($conn,$sql_update);

      //success and error messages here

    }

ETA: Which is then reflected in the dropdown menu. This menu then should allow users to select one or more assignments for which to update data, let's say if there are new user submissions and scores available for that assignment (i.e. the data contained within each assignment -- structurally they are all the same).
Updating the list seems to be working, but I am struggling to figure out the best way to update what we're calling "consolidated data" tables (appended with "_(assignment_id)" for each individual assignment. So when a user selects "update data", the data in the table for the selected assignment(s) above should update. As an example, consolidated_data_4 looks like this (some fields omitted for better readability):
+------------------+---------+---------------+---------+-----------------------------+----------------------------+--------------------------------------+-----------+
| consolidation_id | user_id | assignment_id | quiz_id | assignment_pass_score_point | assignment_pass_score_perc | quiz_name                            | answer_id |
+------------------+---------+---------------+---------+-----------------------------+----------------------------+--------------------------------------+-----------+
|                1 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175973 |
|                2 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175981 |
|                3 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175985 |
|                4 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175991 |
|                5 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175995 |
|                6 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    175999 |
|                7 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    176002 |
|                8 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    176009 |
|                9 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    176015 |
|               10 |      34 |             4 |      50 |                        5.00 |                      50.00 | Guidance Counselors (Pre-Assessment) |    176021 |
+------------------+---------+---------------+---------+-----------------------------+----------------------------+--------------------------------------+-----------+

Each table is currently identified by its assignment id, e.g. "consolidated_data_4" is a table in which assignment_id = 4 for every record in that table.
I tried looping through each table (using a foreach loop) and performing a similar query as the one above for the assignments list, but I receive an error unless I separate the queries out like so (also abridged):
//for each assignment user selects, start with an empty table and join data from corresponding course database tables

    foreach($_POST['selectassign'] as $assignment){
  $table = "quiz_data_update_application.consolidated_data_".$assignment;
  //query updates consolidated data table(s) for selected assignments
  $sql_del = "DELETE FROM $table";
  $sql_trunc = "TRUNCATE $table";

  //records added from joining tables in course db
  $sql_ins = //sql omitted here for brevity
  ....
  $del_sel_res = mysqli_query($conn,$sql_del);
  $trunc_sel_res = mysqli_query($conn,$sql_trunc);
  $ins_sel_res = mysqli_query($conn,$sql_ins);
}

(The only difference between this and the code that doesn't work is that the queries are combined in the same fashion as the first PHP snippet above; this seems redundant to post here).
Using single queries seems inefficient and will slow down the application. I am wondering if there is a better way to approach this than using part of a table name as a variable in PHP loops. (Don't see too many people asking about this or iterating through actual tables as opposed to fields) It seems there's either some silly syntax mistake I'm missing, or mysqli_multiquery() can't be used in loops/is overall a poor approach?
Some of the higher-ups where I am working have suggested either:
(1) creating separate loops - one to temporarily create a new table based on a users' selection of assignments, and another to split that up into separate tables by assignment (this part they are saying is required for optimal data analysis. IMO this makes everything more challenging than having a large "master" table of data for ALL assignments -- which I did in fact have success doing -- but alas this is how they're requesting it be done). Those tables would then be deleted after an update completes;
(2) Using stored procedures. This I am not as familiar with, and not sure how that'd work, but if it's more feasible than (1), I could look into it more.
Any other alternative, more feasible suggestions would be appreciated as well. I've made a lot of progress with this, but have been stuck here the past few weeks and not finding much in the way of online resources.
Apologies for the length of the post. I thought it necessary to provide more context rather than less.

A: Single queries is the way to go.  The perceived inefficiency is not there -- the operations are more costly than the mysqli_query.
If you have thousands of tables that to work with, then I question the wisdom of having multiple similar tables.  Instead, have an extra column to indicate which thing is involved.
DELETE (all of a table) and TRUNCATE have virtually the same effect; there is no need to do both.  TRUNCATE is faster.
And deleting one indexed row from a table is a lot faster than truncate + insert.
Furthermore, batching the deletes into a single SQL statement is even faster.  So is batch inserting multiple rows at once.  This is easily 10 times as fast.

A: @Rick James here is SHOW CREATE TABLE for one of the tables, although the structure is the same for all of them.
+---------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table               | Create Table                                                                                |
+---------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| consolidated_data_2 | CREATE TABLE `consolidated_data_2` (
  `consolidation_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `assignment_id` int(11) NOT NULL,
  `quiz_id` int(11) NOT NULL,
  `assignment_pass_score_point` decimal(10,2) DEFAULT NULL,
  `assignment_pass_score_perc` decimal(10,2) DEFAULT NULL,
  `quiz_name` varchar(3800) NOT NULL,
  `question_id` int(11) NOT NULL,
  `question_text` varchar(3800) CHARACTER SET utf8 NOT NULL,
  `question_type_id` int(11) NOT NULL,
  `answer_id` int(11) DEFAULT NULL,
  `answer_textA` varchar(800) CHARACTER SET utf8 DEFAULT NULL,
  `answer_added_ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `group_id` int(11) DEFAULT NULL,
  `user_answer_text` varchar(3800) CHARACTER SET utf8 DEFAULT NULL,
  `answer_image` varchar(800) DEFAULT NULL,
  `is_correct` int(11) DEFAULT NULL,
  `correct_answer_text` varchar(3800) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`consolidation_id`)
) ENGINE=InnoDB AUTO_INCREMENT=128 DEFAULT CHARSET=latin1 |
+---------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

The reason for having multiple tables is so that there's one table unique to each assignment id, so each assignment table can be updated separately/selectively for analysis purposes.
It isn't necessarily just updating one row, since each assignment is typically 10 questions. So each new user submission would add 10 more rows in most cases.
I am attaching an ER diagram which shows all the tables that have source data for the consolidated data tables.
ER Diagram for consolidated_data tables
(Blue = fields used for joins; yellow = all other fields included in the table; data type info on some for reference)


text:
Q: Elements in a field Prove that there exists a field with $16$ elements.
I know that there is a theorem that states that a finite field can only have $$ p^k $$
Where $p$ is a prime and $k$ is any positive integer.  But I'm not sure how I would start going about proving this statement.

A: Finite fields will always have cardinality equal to a power of a prime $p$, and in particular the finite field with $p^k$ elements will be an extension of $\mathbb{Z}_p$.
Now recall that if a polynomial $f$ is irreducible over a field $F$, then $F[x]/ \langle f(x) \rangle \cong F[\alpha]$, where $\alpha$ is a root of $f$.  Furthermore, $F[\alpha]$ is a degree $\deg(f)$ extension of $F$.
Using this information, you should construct an extension of $\mathbb{Z}_2$ with $16 = 2^4$ elements.  If you first convince yourself that a degree $n$ extension of $\mathbb{Z}_p$ will have $p^n$ elements, you should be well on your way to finishing up.

A: If a field $F$ is finite then its characteristic is a prime number say $p$ then its prime subfield(i.e intersection of all subfields ) is isomorphic to $\mathbb Z_p$.
So we can think $F$ as a finite dimensional vector space over the field $\mathbb Z_p$ say $n$
Then any element of $F$ can be expressed uniquely as $c_1\alpha_1+c_2\alpha _2+...+c_n\alpha_n$ where $c_i$ has $p$ choices each.
So $F$ has $p^n$ elements


text:
Q: function loop for each unique value in column and concat every line to new df Just trying to analyze DF and now creating from data a new DF with needed information.
The idea is just to take every unique ID from the column and for each ID apply some functions.
As output it should be new DF with needed information
here is my code:
headers = list(df.columns)
python_db_df = pd.DataFrame()
materials = list(df[headers[2]].unique())
python_db_df['Material'] = materials
python_db_df['Description'] = ''
python_db_df['Business'] = ''

for i in range(len(materials)):
    tmp = df.loc[df[headers[2]] == materials[i]].reset_index(drop=True)
    python_db_df.at[i, 'Description'] = tmp.iloc[0][headers[3]]
    python_db_df.at[i, 'Business'] = tmp.iloc[0][headers[5]]

    df_wo = tmp.loc[tmp[2] == 'no_promo']
    df_akt =  tmp.loc[tmp[2] != 'no_promo']

    python_db_df['mean'] =df_wo['BV_LastIssue'].mean()
    python_db_df['akt_mean'] =df_akt['BV_LastIssue'].mean()
    python_db_df['akt_mean_ul'] = python_db_df['akt_mean'] / python_db_df['mean']

    python_db_df['w_mean_sum'] = df_wo['BV_LastIssue'].sum() / df_wo.weekofyear.unique().size
    python_db_df['w_akt_mean_sum'] =df_akt['BV_LastIssue'].sum()  / df_akt.weekofyear.unique().size
    python_db_df['w_akt_mean_ul'] = python_db_df['w_akt_mean_sum'] / python_db_df['w_mean_sum']

It creates DF and I see unique values in first columns, however calculations are the same in each line. It took results only for one of unique material and put it in each line.
How to create or update the code in order to get calculations for each unique ID/line.
Can anyone help with that?


text:
Q: How do splitting fields over different field extensions "fit" inside each other Suppose $F'/F$ is a field extension. And suppose $f \in F[x]$ is a polynomial. Then $f \in F'[x]$ of course.
So now we may consider two splitting fields for $f$: $K$ over $F$, and $K'$ over $F'$. How does $Gal(K'/F')$ relate to $Gal(K/F)$.
In particular, can we embed $Gal(K'/F')$ into $Gal(K/F)$? How does one construct the homomorphism?


text:
Q: What are the differences between form_for @project_profile and form_for :project_profile I just started to learn rails. My rails version is 3.0.7. I am wondering what are the differences between <% form_for :project_profile %> and <% form_for @project_profile %>. I have this question because I went into the following situation:

*

*If I use <% form_for :project_profile %>, it doesn't give me an error, but the form is actually not working.

*If I use <% form_for @project_profile %>, I will get an error: undefined method `project_profile_path' for #<#:0x00000103546d80>

*If I use <%= form_for @project_profile, :url => "/projects/#{params[:project_id]}/profile/update" do |f| %>, it will work but the code is ugly.

You can refer to the following codes to understand the context of my problem better.
I have a project model and a project_profile model. One project has one project_profile.
The following two lines are from my routes.rb.
match '/projects/:project_id/profile/edit' => "project_profiles#edit"
match '/projects/:project_id/profile/update' => "project_profiles#update"

This is from my project_profiles_controller.rb
class ProjectProfilesController < ApplicationController
  def edit
    @project_profile = Project.find(params[:project_id]).project_profile
  end
  def update
    @project_profile = Project.find(params[:project_id]).project_profile

    respond_to do |format|
      if @project_profile.update_attributes(params[:project_profile])
        format.html {}
      else
        format.html { render :action => "edit" }
      end
    end
  end
end

The following code is from _form.html.erb
<%= form_for @project_profile, :url => "/projects/#{params[:project_id]}/profile/update" do |f| %>

      <%= f.label :title %>

      <%= f.text_field :title %>

      <%= f.submit %>

<% end %>

A: You should learn about resource and nested resource routing in Rails.
The way you define controller is also not conventional. There is an article on Rails Guides on Getting Started section that covers that too.

A: Basically spoken, form_for @project_profile is an advanced (resource-oriented), nowadays preferred style. If you want to dig a little deeper into this, the API itself explains the difference pretty well.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for
cheers


text:
Q: date difference in years between two date picker content controls word 2016 vba code I've got two date picker content controls titled dateofbirth and another titled datefirstseen. i tried determining the difference in years to be computed into a text box content control on the-same first page of the form titled ageasatlastbirthday
i tried this code
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim CCtrl As ContentControl, DtStart As Long, DtEnd As Long
With ContentControl
  If .Title = "DateofBirth" Then
    If IsDate(.Range.Text) Then
      DtStart = CDate(.Range.Text)
      With ActiveDocument.SelectContentControlsByTitle("DateRecruitedDateFirstSeen ")(1)
        If IsDate(.Range.Text) Then DtEnd = CDate(.Range.Text)
        ActiveDocument.SelectContentControlsByTitle("Ageatlastbirthday ")(1).Range.Text = Int((DtEnd - DtStart) / 365)
      End With
    End If
  End If
  If .Title = "DateRecruitedDateFirstSeen" Then
    If IsDate(.Range.Text) Then
      DtEnd = CDate(.Range.Text)
      With ActiveDocument.SelectContentControlsByTitle("DateofBirth")(1)
        If IsDate(.Range.Text) Then DtStart = CDate(.Range.Text)
        ActiveDocument.SelectContentControlsByTitle("Ageatlastbirthday ")(1).Range.Text = Int((DtEnd - DtStart) / 365)
      End With
    End If
  End If
End With
End Sub

I imputed this code into the 'thisdocument' section as a document with ContentControlOnExit format but it still doesn't work.
Please help modify into a workable code.

A: For starters, you don't need "Dim CCtrl As ContentControl".
Both ContentControls passed in to the Sub better be date Content Controls. If the .Range.Text is not a date, your routine will do nothing. You better issue a  dire warning if the .Range.Text is not a date. Yep, you better put in some diagnostic messages to see what's going wrong, such as
Debug.Print .Range.Text


text:
Q: H264 with multiple PPS and SPS I have a card that produces a H264 stream with a SPS (Sequence Parameter Set) and a PPS (Picture Parameter Set), in that order, directly before each I-Frame. I see that most H264 streams contain a PPS and SPS at the first I-Frame.
Is this recommended? Do decoders/muxers typically support multiple PPS and SRS?

A: H.264 comes in a variety of stream formats. One variation is called "Annex B".
(AUD)(SPS)(PPS)(I-Slice)(PPS)(P-Slice)(PPS)(P-Slice) ... (AUD)(SPS)(PPS)(I-Slice).
Typically you see SPS/PPS before each I frame and PPS before other slices.
Most decoders/muxers are happy with "Annex B" and the repetition of SPS/PPS.
Most decoders/muxers won't do anything meaningful if you change the format and SPS/PPS midstream.
Most decoders/muxers parse the first SPS/PPS as part of a setup process and ignore subsequent SPSs.
Some decoders/muxers prefer H.264 without the (AUD), start codes and SPS/PPS.
Then you have to feed SPS/PPS out of band as part of setting up the decoders/muxers.

A: An IDR frame, or an I-slice can not be decoded without a SPS and PPS. In the case of a container like mp4, the SPS and PPS is stored away from the video data in the file header. Upon playback the mp4 is parsed, the SPS/PPS is used to configure the AVC decoder once, then video can be played back starting at any IDR/I-slice.
There is a second scenario, Live video. With live video, there is no file header, because there is no file. So when a TV tunes into a channel, where does it get the SPS/PPS? Because television is broadcast, meaning the television has no way to request the SPS/PPS, it is repeated in the stream.
So when you start encoding video, your encoder does not know what you intend to do with the video. Now if the extra SPS/PPS show up in an mp4, the decoder just ignores them, but if you are streaming to a TV, without them the stream would never play. So most of the default to repeating SPS/PPS just in case.

A: I know about matroska(mkv) spec so here SPS and PPS are stored only once as codec private data section. So they are not repeating with every i frame or IDR frame.
If your h264 stream's each i frame/IDR frame has SPS/PPS then matroska muxer will store only 1 copy in codec private data.
So while storing usecase based container format suggest to use only one copy of SPS/PPS but broadcasting and streaming based container formats suggest send SPS/PPS before every iFrame/IDR frame or whenever any codec changes change in h264 stream at that time


text:
Q: Batch file delete oldest folder if there are more than 3 folders in root I have now a batch file where all folders older then 22 days will be deleted. When the batch file is running every week there is no problem, there will always be four folders in the root.
But when there is holiday, the system is turned off up to three weeks. When the file is running after that holiday, there will be deleted three folders.
I am now searching for a command where only the oldest folder will be deleted, so I will keep four folders for backup at all time.
The folders are named like backup_YYYY-MM-DD.

A: This task can be easily done by using the following batch code with more or less a single command line:
@echo off
for /F "skip=4 eol=| delims=" %%I in ('dir "C:\Temp\backup_????-??-??" /AD /B /O-N 2^>nul') do rd /Q /S "C:\Temp\%%I"

The command DIR returns because of option /AD just directory names (attribute directory) in bare format because of option /B and ordered reverse by name because of option /O-N found in the directory C:\Temp with a name matched by the wildcard pattern backup_????-??-??.
The reverse order by name results automatically also in a reverse order by date on using the date format YYYY-MM-DD in the folder names. The name of the newest backup folder is output first and the name of the oldest folder is output last by command DIR.
The command FOR skips the first four lines of output of command DIR and therefore ignores the four newest backup folders. All other backup folders are processed by FOR resulting in removing them with command RD. There is nothing to process by FOR if there are not at least five folders found by DIR with name matching the pattern backup_????-??-??. So there are always at least four backup folders, except a user deletes backup folders manually.
The command DIR outputs an error message to STDERR if it can't find any folder matching the pattern backup_????-??-??. This error message is suppressed with 2>nul by redirecting the error message from STDERR to device NUL. The redirection operator > must be escaped here with ^ as otherwise the Windows command processor would interpret > as redirection for command FOR positioned wrong which would result in a syntax error message.
Note: Command DIR returns here just the backup folder names without path and therefore the parent folder path must be written twice in code, on command DIR and also on command RD.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*dir /?

*for /?

*rd /?
And see also the Microsoft documentation about Using command redirection operators.


text:
Q: Where does the name "xs" for pattern matching come from?
Possible Duplicate:
What is the history of the variable names x and xs?

Where does the canonical name "xs" in pattern matching come from?
e.g. in
reverse' []     = []
reverse' [x]    = [x]
reverse' (x:xs) = reverse' xs ++ [x]

Is it supposed to be the plural of "x" ?

A: That's the way I've always read it, you have the singular and the plural, So x:xs or y:ys etc.
It doesn't actually have any meaning by itself, it's just a convention.
IIRC it's also mentioned in Learn You a Haskell.

Edited
My mistake - it's actually in Real World Haskell in the chapter on types and functions.


text:
Q: Docker - cannot access container from Mac Host I can't seem to access a simple Docker container running locally on my mac. I can run curl localhost from the container and see that the default Apache page is served up, but I can't hit it from my machine's browser.
I'm wondering if I have a VirtualBox config issue or something. Any help diagnosing the problem?
Dockerfile
# Build the image of ubuntu 12.04 LTS
from ubuntu:precise

# Run apt-get update
run apt-get -y update

# Install LAMP
run DEBIAN_FRONTEND=noninteractive apt-get -y install lamp-server^
run apt-get -y install vim-tiny curl wget

# Put custom scripts in the container and give proper permissions to them
add ./startup.sh /usr/local/bin/startup.sh
run chmod 755 /usr/local/bin/startup.sh

add site.vhost /etc/apache2/sites-available/site
run a2ensite site

# Expose port 80 to the host machine
expose 80

site.vhost
<VirtualHost *:80>

    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        #Order allow,deny allow from all
    </Directory>

    # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg.
    LogLevel warn
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

startup.sh
#!/bin/bash

a2dissite default
apache2ctl graceful
/usr/bin/mysqld_safe &

To start...
I'll build the image with docker build -t test1 . - which seems to run fine.
On initial setup, I run docker run -d -v $(pwd)/mysql:/tmp/mysql test1 /bin/bash -c "cp -rp /var/lib/mysql/* /tmp/mysql" to setup MySQL.
Then I run docker run -i -t -v $(pwd)/mysql:/var/lib/mysql -v $(pwd)/www:/var/www -p 8080:80 test1 /bin/bash to start the actual instance.
Once at the terminal, I run service apache2 start and everything seems to be running great. If I run curl localhost I get the default page just fine.
Everything seems great, it's just hitting it from the Host that doesn't work. I should be able to navigate to http://127.0.0.1:8080 and have that forward to the container on port 80, right?

A: You'll need to forward the port from the VM to the host. An example for the default "random" range from docker is:
(from http://docs.docker.io/en/latest/installation/mac/#forwarding-vm-port-range-to-host)
# vm must be powered off
for i in {49000..49900}; do
 VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port$i,tcp,,$i,,$i";
 VBoxManage modifyvm "boot2docker-vm" --natpf1 "udp-port$i,udp,,$i,,$i";
done

But if you want to forward specifically 8080:
VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port8080,tcp,,8080,,8080"

etc. You might want to pick a different port if you also use 8080 for testing things on your Mac itself.

A: For those looking at this thread who are running Docker 1.8 or newer, the syntax from Andy's and Muneeb's comments no longer work (the theory is the same), since boot2docker has been deprecated and replaced with docker-machine and the docker VM name changed [1].
Forwarding a single port Mac -> VM -> container
If you just want to forward port 80 inside a container using the default network options to port 8080 on your Mac, do this:
a) Expose port 80 either with an EXPOSE 80 in the Dockerfile or --expose=80 in docker run. Add /udp for UDP ports.
b) Map the ports from the container to the VM with -p 8080:80 in docker run. Add /udp for UDP ports.
c) Tell the docker VM (now called "default") to add a NAT mapping between port 8080 on the VM and port 8080 on your Mac:
    VBoxManage controlvm default natpf1 'port8080,tcp,,8080,,8080'. The first port is on your Mac; the second port is on the VM.
To delete the rule use VBoxManage controlvm default natpf1 delete port8080.  Note: VBoxManage controlvm changes a running VM, modifyvm changes a VM that is stopped.
Getting the IP address of your docker VM
New syntax is docker-machine ip default (default is the name of docker VM).
[1] https://docs.docker.com/installation/mac/

A: You're trying to view it on localhost (127.0.0.1) which is your Mac OS X. The docker is running inside a Virtualbox VM. Try:

boot2docker ip

That'll give you the IP address of the VM and then you can connect to docker using ip_address:port e.g., 192.168.59.103:8080 (if 192.168.59.103 was the IP assigned to the Virtualbox VM)

A: I just wrote a tutorial of how to use a host-only network and TCP routing to make this pretty easy.  This way you don't have to map every specific port.
http://ispyker.blogspot.com/2014/04/accessing-docker-container-private.html


text:
Q: How to upgrade to ubuntu 18.04 version from 16.04 using terminal I want to upgrade to ubuntu version 18.04 from 16.04.I have taken the backup.
My question is whether update manager will give options to select which version 18.04 or 20.04
as both are available and i don't want to upgrade to 20.04.
Upon some searching in askubuntu i found below steps to be followed to upgrade.
Step1:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt install update-manager-core
Step2:
sudo vi /etc/update-manager/release-upgrades
Step3:
sudo do-release-upgrade
Can anyone please let me know if i am following correct steps.Is there any other steps i need to  follow to do upgrade to 18.04

A: You can use Update Manager or the shell.
Both will offer to update you only to the next LTS of Ubuntu. They won't offer to skip releases.
To prepare for a release-upgrade:

*

*Return your system to as close to stock condition as possible.
If you have added PPAs or non-Ubuntu sources, remove them and uninstall the packages that came from those sources.

*Upgrade your system on the old release: sudo apt update and sudo apt upgrade.
If you have held broken packages, packages not upgraded, or ANY error message, then stop. Seek help in AskUbuntu before proceeding. Release-upgrading a broken system rarely fixes the problem, and often makes things worse.

*(Optional) Backup your data and prepare an Ubuntu install USB stick.
This step provides insurance from unexpected problems. If you are inexperienced in data recovery, have limited recovery resources on hand, or have a history of package/upgrade problems, then definitely take a few minutes to do this step!

*Launch the upgrade process using Update Manager or do-release-upgrade


text:
Q: How to handle an exception from MethodInvokingFactoryObject Spring.NET? I have Spring.Configuration like that:
<objects xmlns="http://www.springframework.net">
    <!-- Create SQLite connection -->
    <object id="SqlConnection" type="System.Data.SQLite.SQLiteConnection, System.Data.SQLite">
        <constructor-arg index="0" value="Data Source=MyDatabase.db"/>
    </object>
    <!-- Open connection -->
    <object type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core">
        <property name="TargetObject">
            <ref local="SqlConnection" />
        </property>
        <property name="TargetMethod" value="Open"/>
    </object>
</objects>

So how do I handle an exception from the method Open() if this throws since MethodInvokingFactoryObject is created and invoked?


text:
Q: Error during sbt execution: java.lang.NoClassDefFoundError: sbt/State$Next I am trying to run sbt package to build my scala project but after downloading the jars from repository its throwing me following error-

java.lang.NoClassDefFoundError: sbt/State$Next
          at sbt.xMain.run(Main.scala:28)
          at xsbt.boot.Launch$$anonfun$run$1.apply(Launch.scala:109)
          at xsbt.boot.Launch$.withContextLoader(Launch.scala:128)
          at xsbt.boot.Launch$.run(Launch.scala:109)
          at xsbt.boot.Launch$$anonfun$apply$1.apply(Launch.scala:35)
          at xsbt.boot.Launch$.launch(Launch.scala:117)
          at xsbt.boot.Launch$.apply(Launch.scala:18)
          at xsbt.boot.Boot$.runImpl(Boot.scala:41)
          at xsbt.boot.Boot$.main(Boot.scala:17)
          at xsbt.boot.Boot.main(Boot.scala) Caused by: java.lang.ClassNotFoundException: sbt.State$Next
          at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
          ... 10 more Error during sbt execution: java.lang.NoClassDefFoundError: sbt/State$Next

My sbt file looks like-
name := "Simple Project"

version := "1.0"

scalaVersion := "2.10.4"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.2.0"

Please let me know how to resolve the issue, I am new to scala and sbt concept. Thanks


text:
Q: getelementbyid innerHTML to bbcode? Anyway to convert innerHTML to bbcode?
Something like that
document.getelementbyid.('div').bbcode

or a way to replace %0A to [br] in the current link of the page?
I've tried this with no luck
window.location.replace('%0A', '[br]');

A: .bbcode is not a valid function (or property how you've written it), unless of course you are including some kind of external library that you haven't told us about?
With regards to the window.location.replace you are not assigning it to anything so where would you expect to see the change? Though you should also use
 window.location.href.replace(needle,haystack);

see http://jsfiddle.net/9LGRP/1/ for a quick example or replace working to replace the word "show" with "foo"
Please note the syntax is slightly different for global replacements e.g
            window.location.href.replace(/foo/g, 'bar')

would replace all instances of foo. You can also add the modifier 'i' after the 'g' to    ignore case  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Perhaps you need to elaborate more on your question and show more context if this doesn't address your needs.


text:
Q: Error formatting a lucee-spreadsheet: The maximum number of cell styles was exceeded I am using lucee-spreadsheet, which is a great tool. I am making a very large spreadsheet (multiple sheets in a workbook with thousands of row per sheet). Everything is working as expected. I have populated the sheets with data, and created blank rows in between groups that the client wants. I am now going back and trying to apply some formatting and I am running into the error:

The maximum number of cell styles was exceeded. You can define up to
  4000 styles in a .xls workbook

The problem is that I have only tried to apply one style:
spreadsheet.formatColumns(workbook=workbook, format={dataformat="$##,####0.00"},range='5-20');
There are a number of other styles I need to apply.  I am guessing that since there are over 500 rows and this style is being applied to 16 columns that the style is actually formatting each cell and not the column.
Is there a different way that I could be or should be applying this style?

A: Looking at the lucee-spreadsheet source code, formatColumns is creating a new cell style for every cell it formats. Unfortunately this is suboptimal, and the limits in Apache POI on styles in a spreadsheet are being hit for the Excel 97 (HSSF) spreadsheet format. It would be better to use formatCellRange, which reuses cell styles, until such time as the maintainers implement a better formatColumns function to take advantage of style re-use.

A: One thing that may help is switching the output format from .xls to .xlsx.  Using the .xls format, I was only seeing formatting on the first 156 rows of my spreadsheet.  This was a limitation of the .xls file format.  I used spreadsheet.newXlsx() instead of spreadsheet.new(), and was able to generate an xlsx file, and the formatting appeared correctly for the 750 rows I was working with.