text:
Q: R rvest Can't Get html_node I have some experience using the rvest package to scrape data I need from the web, but am hitting an issue with this page:
https://www.nytimes.com/interactive/2020/us/covid-college-cases-tracker.html
If you scroll down a bit, you'll see a portion where all the schools are located.

I would like to have the school, cases and location data. I should note that someone asked on the NYT GitHub publishing this as a csv and they recommended that the data is all in the page and can just be pulled from there. Thus, I think it is OK to scrape from this page.
But I can't get it to work. Let's say I just want to start with a simple selector for that first school. I use the inspector to find the xpath.

I get no results:
library(rvest)

URL <- "https://www.nytimes.com/interactive/2020/us/covid-college-cases-tracker.html"
pg <- read_html(URL)

# xpath copied from inspector
xpath_first_school <- '//*[@id="school100663"]'

node_first_school <- html_node(pg, xpath = xpath_first_school)

> node_first_school
{xml_missing}
<NA>

I get {xml_missing}.
I obliviously have a lot more to do to generalize this and gather data for all
schools, but with web scraping, I usually try to start simple and specific and then broaden out. But even my simple test isn't working. Any ideas?

A: Setting up Rselenium can take some time. First you have to download chromedriver (https://chromedriver.chromium.org/), select the version your current chrome is the closest too. Then unpack it to your R working directory.
I tried using a package called decapitated where it can scrape javascript rendered websites but because this website contains "show more" which needs to be physically clicked before all data are shown, I had to use Rselenium to "click" that before I get the page source then use rvest for parsing
Code:
library(rvest)
library(tidyverse)
library(RSelenium)

url <- "https://www.nytimes.com/interactive/2020/us/covid-college-cases-tracker.html"

driver <- rsDriver(browser = c("chrome"), chromever = "85.0.4183.87", port = 560L)
remote_driver <- driver[["client"]]
remote_driver$navigate(url)

showmore <- remote_driver$findElement(using = "xpath", value = "//*[@id=\"showall\"]/p")
showmore$clickElement()

test <- remote_driver$getPageSource()

school <- read_html(test[[1]]) %>%
  html_nodes(xpath = "//*[contains(@id, \"school\")]/div[2]/h2") %>%
  html_text() %>%
  as.tibble()

case <- read_html(test[[1]]) %>%
  html_nodes(xpath = "//*[contains(@id, \"school\")]/div[3]/p") %>%
  html_text() %>%
  as.tibble()

location <- read_html(test[[1]]) %>%
  html_nodes(xpath = "//*[contains(@id, \"school\")]/div[4]/p") %>%
  html_text() %>%
  as.tibble()

combined_table <- bind_cols(school,case = case[2:nrow(case),],location = location[2:nrow(location),])
names(combined_table) <- c("school", "case", "location")

combined_table %>% view()

Output:
# A tibble: 913 x 3
   school                                      case  location
   <chr>                                       <chr> <chr>
 1 University of Alabama at Birmingham*        972   Birmingham, Ala.
 2 University of North Carolina at Chapel Hill 835   Chapel Hill, N.C.
 3 University of Central Florida               727   Orlando, Fla.
 4 University of Alabama                       568   Tuscaloosa, Ala.
 5 Auburn University                           557   Auburn, Ala.
 6 North Carolina State University             509   Raleigh, N.C.
 7 University of Georgia                       504   Athens, Ga.
 8 Texas A&M University                        500   College Station, Texas
 9 University of Texas at Austin               483   Austin, Texas
10 University of Notre Dame                    473   Notre Dame, Ind.
# ... with 903 more rows

Hope this works for you!

A: So I am going to provide an answer here which violates a very important rule described here and is generally an ugly solution. But it is a solution that allows us to avoid having to use Selenium.
To use html_nodes on this, we need to initiate JS actions which requires Selenium. @KWN's solution seems to work on their machine, but I can't get the chromedriver to work on mine. I can get almost there using Docker with Firefox or Chrome, but can't get the result. So I would check that solution out first. And if that fails, give this a shot. Pretty much, this site has the data I need exposed as a JSON. So I pull the text of the site which I use a regex to isolate the JSON and then jsonlite to parse.
library(jsonlite)
library(rvest)
library(tidyverse)

url <- "https://www.nytimes.com/interactive/2020/us/covid-college-cases-tracker.html"

html_res <- read_html(url)

# get text
text_res <- html_res %>%
  html_text(trim = TRUE)

# find the area of interest
# find the area of interest
data1 <- str_extract_all(text_res, "(?<=var NYTG_schools = ).*(?=;)")[[1]]

# get json into data frame
json_res <- fromJSON(data1)

# did it work?
glimpse(json_res)

Rows: 1,515
Columns: 16
$ ipeds_id    <chr> "100663", "199120", "132903", "100751"...
$ nytname     <chr> "University of Alabama at Birmingham",...
$ shortname   <chr> "U.A.B.", "North Carolina", "Central F...
$ city        <chr> "Birmingham", "Chapel Hill", "Orlando"...
$ state       <chr> "Ala.", "N.C.", "Fla.", "Ala.", "Ala."...
$ county      <chr> "Jefferson", "Orange", "Orange", "Tusc...
$ fips        <chr> "01073", "37135", "12095", "01125", "0...
$ lat         <dbl> 33.50199, 35.90491, 28.60258, 33.21402...
$ long        <dbl> -86.80644, -79.04691, -81.20223, -87.5...
$ logo        <chr> "https://static01.nyt.com/newsgraphics...
$ infected    <int> 972, 835, 727, 568, 557, 509, 504, 500...
$ death       <int> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,...
$ dateline    <chr> "n", "n", "n", "n", "n", "n", "n", "n"...
$ ranking     <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,...
$ medicalnote <chr> "y", NA, NA, NA, NA, NA, NA, NA, NA, N...
$ coord       <list> [<847052.5, -406444.3>, <1508445.93, ...


text:
Q: cmake: special targets like "all" and "test" having the same name in multiple places in the build tree? cmake does not allow you to create multiple targets having the same name at different places in the build tree using add_custom_target().
However, it does provide special targets with that property notably:

*

*all

*test

*install

Each of these when run within a sub-tree will apply to just that sub-tree.
Is there a way achieve the same for user targets?
Here is a simplified example:
toplevel CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)

add_custom_target(thing)

add_subdirectory(sub1)
add_subdirectory(sub2)

sub1/CMakeLists.txt:
add_executable(foo foo.cpp)

add_custom_target(thing.sub1 DEPENDS foo)
add_dependencies(thing thing.sub1)

sub2/CMakeLists.txt:
add_executable(bar bar.cpp)

add_custom_target(thing.sub2 DEPENDS bar)
add_dependencies(thing thing.sub2)

I can get almost the behaviour I want in that:

*

*make thing at the top level builds thing.sub1 & thing.sub2

*make thing.sub1 at the top level or in sub1 builds thing.sub1

*make thing.sub2 at the top level or in sub2 builds thing.sub2

What I would like is to be able to just run make thing and have it apply to the
current sub-directory like the all target does.
Is this possible?
If not is it a missing feature or would it be a misfeature and if so why?

Solution (almost)
@zuafi's direction led me to a solution.
It is currently possible but only using deprecated behaviour from policy CMP0002.
There is effectively a missing feature for adding local targets which is covered by this open ticket.
My workaround is to implement add_local_target() for myself is as follows:
# determine whether local targets should be legal
if("${CMAKE_GENERATOR}" MATCHES "Make")
  cmake_policy(SET CMP0002 OLD)
  # property seems to be deprecated
  set_property(GLOBAL PROPERTY ALLOW_DUPLICATE_CUSTOM_TARGETS 1)
  set(ALLOW_LOCAL_TARGETS 1)
  message("using Makefile generator")
else()
  cmake_policy(SET CMP0002 NEW)
  message("Generator=${CMAKE_GENERATOR}")
endif()

# add a custom target with the same name as another (posssibly global) target iff permitted
# see http://stackoverflow.com/questions/35489093/cmake-special-targets-like-all-and-test-having-the-same-name-in-multiple-pl
function(add_local_target target)
  if(ALLOW_LOCAL_TARGETS)
    set(dependencies "${ARGN}")
    foreach(dependency IN LISTS dependencies)
       if(TARGET ${dependency})
          list(APPEND targets ${dependency})
       else()
          message("${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt: warning: dependency ${dependency} for add_local_target(${target}) is NOT a target")
       endif()
    endforeach()
    add_custom_target(${target} DEPENDS ${targets})
  endif()
endfunction()

This combines well with target paths like target.subdir which can be used as a fall-back if using a non Makefile generator.
I just use:
add_local_target(thing DEPENDS thing.sub1)

Update
I think this solution may be subtly broken. If you attempt to build a 'local' target it may build some other 'local' targets as well. However, it will build at minimum what it is supposed to build. It will also build less than a global project wide target with the same name would build. I haven't managed to track this down yet as the makefiles generated by cmake are somewhat gnarly.

A: Yes, it is possible... but not with all generators. Particularly it is Ok w/ UNIX Makefiles (see CMP0002 description). And as for me I want to have all unit tests in my project tree to have the same name (I have a bash completion for that name :), so I use the following macro helping me to declare executables:
macro(set_unit_test_target_name OUTPUT_VARIABLE DEFAULT_VALUE)
    cmake_policy(GET CMP0002 _may_use_same_name)
    if(_may_use_same_name STREQUAL "OLD")
        set(${OUTPUT_VARIABLE} "unit_tests")
    else()
        set(${OUTPUT_VARIABLE} ${DEFAULT_VALUE})
    endif()
endmacro()

# usage example
set_unit_test_target_name(UNIT_TESTS someTestExecutable)
add_executable(${UNIT_TESTS} ... )

so for *NIX builds all executables would be named unit_tests, and have unique names for other generators…

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have a window that has been set to open in 'window.top' - need to open in a new window Need to open final destination URL in a new window - not in "window.top".  What do I need to change below? (someone else wrote this and is inaccessible).
<script>
if (window.self === window.top) {
    var finalDest = 'https://www.amazon.com',
        iframes = document.querySelectorAll('iframe'),
        iframeLoaded = 0;

    [].forEach.call(iframes, function(item) {
        item.onload = function() {
            loadFrames();
        }
    })
}
function loadFrames() {
    iframeLoaded++;

    if (iframeLoaded === iframes.length) {
        location.href = finalDest;
    }
}
</script>


text:
Q: links inside Rails3 flash are escaped I would like to render a link inside a flash message in Rails 3.  I'm setting the flash message in the controller like this:
flash.notice = render_to_string 'shared/message_with_a_link', :layout => nil

This works just fine.
But then let's say I already have a flash message to render, and I just want to append the message with the link.  I tried switching = to +=, like so
flash.notice += render_to_string 'shared/message_with_a_link', :layout => nil

And now the flash div contains both messages, but the link has been escaped, so it shows up as google instead of google.
Does anyone know why the flash would be escaped in the second case but not the first?

A: Use .html_safe on your string.
More info here.


text:
Q: Captured images from front-facing camera are rotated - Windows Phone 8 I do basic Windows Phone application. I need capture photos by front facing camera.
Preview is OK, but captured phoho is rotated(90°).
CS:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)
        {
            cam = new PhotoCamera(CameraType.FrontFacing);
            cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
            viewfinderBrush.SetSource(cam);
        }
        else
        {
            txtMessage.Text = "No front camera";
        }
    }

XAML:
<Canvas x:Name="viewfinderCanvas" Height="640" Width="480" Tap="viewfinder_Tapped" Margin="0,138,0,46" Grid.RowSpan="2">
        <Canvas.Background>
            <VideoBrush x:Name="viewfinderBrush">
                <VideoBrush.RelativeTransform>
                    <CompositeTransform
                        x:Name="viewfinderTransform"
                        CenterX="0.5"
                        CenterY="0.5"
                        Rotation="-90"/>
                </VideoBrush.RelativeTransform>
            </VideoBrush>
        </Canvas.Background>
    </Canvas>

Sorry for my English...

A: Try Removing the SupportedOrientations and Orientation from the page and check. then changing the rotation to 90


text:
Q: syntax of switch statment in Unix SunOS 5.9? I have been searching for the proper Syntax to a switch statement for Unix SunOS. It seems I'm out of luck, perchance anyone can post an example?

A: In bash there is the case statement
case string1 in
str1)
   commands;;
str2)
   commands;;
*)
   commands;;
esac

A: The switch statement in bash is called case. See help case for details.
case "$1" in
  -p) echo 'Hello, world!' ; exit 0 ;;
  -h|*) usage ; exit 1 ;;
esace


text:
Q: Is it safe to remove gnome-shell? I've installed Ubuntu 19.04 Desktop. I don't actually need/want the desktop environment, but I don't have a keyboard so am only able to install it with a mouse, and onscreen keyboard, which I obviously can't do on the server edition (..?).
There is no functioning Ethernet connectivity on it either, so it has to connect to my network via WiFi, so I can't set it up via SSH, as I'll have to tell it my WiFi password, which will have to be done with the on screen keyboard.
Anyway... So, when viewing htop, I notice that gnome-shell is using about 70%-100% of my CPU all the time after reboot, so I kill it, and all is well.
Am I able to uninstall gnome-shell and have Ubuntu still function properly for my CLI purposes? Or is it integral to the OS? Is it only related to the GUI aspect of my desktop installation, or does it play a role in everything (my docker services, server apps, etc.)?

A:
Am I able to uninstall gnome-shell and have Ubuntu still function properly for my CLI purposes?

Yes. I can offer an alternative: disable the desktop.

Or is it integral to the OS? Is it only related to the GUI aspect of my desktop installation, or does it play a role in everything (my docker services, server apps, etc.)?

Nope. Though you will also remove all the graphical related tools to your services.

The difference between a server and desktop is only a systemd setting and this will make your system show a login:
sudo systemctl enable multi-user.target --force
sudo systemctl set-default multi-user.target

You can then still start the desktop (command is startx).

To revert back to graphical logon:
sudo systemctl enable graphical-user.target --force
sudo systemctl set-default graphical-user.target

The current active option is shown with:
$ systemctl get-default
graphical.target

And ALL the available options are:
RunLevel Units
  0      runlevel0.target, poweroff.target  Shut down and power off
  1      runlevel1.target, rescue.target    Set up a rescue shell
2,3,4    runlevel[234].target, multi-user.target    Set up a nongraphical multi-user shell
  5      runlevel5.target, graphical.target Set up a graphical multi-user shell
  6      runlevel6.target, reboot.target    Shut down and reboot the system

So you can also use runlevel{number}.target where {number} is the run level.

A: You can remove any desktop, and even the graphics server, and you will be left with a fully functional operating system that can be used through the terminal and any terminal based application. You need a keyboard or remote shell access (with keyboard) to operate that, however. If you need a mouse and a virtual keyboard, leave a shell in place with the virtual keyboard software. You may always change to a lighter desktop environment, though any system operation may be difficult and sometimes impossible with only a mouse.


text:
Q: Redux subscribe() is not fired when the changes are made to the component that is not dispatching anything, just lsitens? I am just a couple days into learning Redux, and it seems pretty easy. However, there is one thing that does not work for me, and I do not know why:
Let me give you an example with the switch element, that toggles theme, and the buttons, which are the theme listeners.
My switch dispatches the theme rducer and, whne I getState() inside the switch element: it works with no issues.
But, I want to listen to the theme changes and change the buttons' colors accordingly. So, I subscribe each button to the store and try to getState(). However, it never fires. console.log() is never fired, nothing works. Why? I would appreciate any details.
Thank you in advance! The code is below:
Buttons that do not work (buttons data is in
    import { createStore } from "redux";
import { RootReducer } from "src/scripts/Redux/CommonReducer";
import { MEMBERS_BAR_BUTTONS } from "./Buttons";
import styles from "./MembersBar.module.css";
import { changeButtonsStyle } from "./MembersBarActions";

const store = createStore(RootReducer);

export default class MembersBar {
  root: HTMLElement;
  constructor(root: HTMLElement) {
    this.root = root;
    this.render();
  }

  renderButtons(container: HTMLDivElement) {
    MEMBERS_BAR_BUTTONS.forEach((button) => {
      const btn = document.createElement("button");
      btn.className = button.class;
      btn.textContent = button.defaultLabel;
      const theme = store.getState().theme;
      changeButtonsStyle(theme, btn, button.id);
      this.manageButtonStyle(btn, button.id);
      container.append(btn);
    });
  }

  manageButtonStyle(button: HTMLButtonElement, id: string) {
    store.subscribe(() => {
      console.log("something changed!");
      const newTheme: string = store.getState().theme;
      changeButtonsStyle(newTheme, button, id);
    });
  }

  render() {
    const div = document.createElement("div");
    div.className = styles["members-bar-wrapper"];
    this.renderButtons(div);
    this.root.append(div);
  }
}

Theme switch code that works:
import styles from "./ThemeSwitch.module.css";
import { RootReducer } from "src/scripts/Redux/CommonReducer";
import { createStore } from "redux";
import { setTheme } from "src/scripts/Redux/Actions";
import { changeStyle } from "./ThemeSwitchActions";

const store = createStore(RootReducer);
const body = document.querySelector("body");

export default class ThemeSwitch {
    root: HTMLElement;
    constructor(root: HTMLElement) {
        this.root = root;
        this.render()
    }
    renderSwitch (parent: HTMLDivElement) {
        const div = document.createElement("div");
        div.className = styles["theme-switch-element"];
        const span = document.createElement("span");
        span.className = styles["span"];
        this.renderTheme(span)
        div.addEventListener("click", () => {
            this.changeTheme()
        });
        div.append(span);
        parent.append(div);
    }
    renderTheme (span: HTMLSpanElement) {
        store.subscribe(() => {
            const currentTheme = store.getState().theme;
            changeStyle(currentTheme, body, span)
        })
    }
    changeTheme () {
        const theme = store.getState().theme;
        const newTheme = (theme === "dark" ? "light" : "dark");
        store.dispatch(setTheme(newTheme));
    }
    render () {
        const div = document.createElement("div");
        div.className = styles["theme-switch-wrapper"];
        this.renderSwitch(div);
        this.root.append(div);
        this.changeTheme()
    }
}

A: The problem was that I was creating a new store in every component.


text:
Q: Count the absolute number and the percentage of NAs for every column in a dataframe I have the dataframe below and I want to create a new dataframe based on this with 3 columns. The first will be named "Field" and will contain the column names of this dataframe (col1,col2,col3). The second will be named "Absolute" and will contain the absolute number of missing values of this column and the third will be named Percentage and will contain the percentage of the missing values of this column. The number of columns and rows in my real dataframe is bigger.
col1<-c("as","df",NA)
col2<-c("ds",NA,NA)
col3<-c(NA,NA,NA)
df<-data.frame(col1,col2,col3)

A: Try,
data.frame(field = names(df),
           Absolute = colSums(is.na(df)),
           Percentage = 100 * (colSums(is.na(df)) / nrow(df)),
           row.names = seq(nrow(df)))

     field Absolute Percentage
   1  col1        1   33.33333
   2  col2        2   66.66667
   3  col3        3  100.00000

A: Tidyverse approach (though I prefer @Sotos' solution):
library(dplyr)
library(tidyr)

df %>%
  summarize(across(
    everything(),
    list(
      Absolute = ~ sum(is.na(.x)),
      Percentage = ~ mean(is.na(.x)) * 100
    )
  )) %>%
  pivot_longer(
    everything(),
    names_to = c("Field", ".value"),
    names_sep = "_"
  )

# A tibble: 3 × 3
  Field Absolute Percentage
  <chr>    <int>      <dbl>
1 col1         1       33.3
2 col2         2       66.7
3 col3         3      100


text:
Q: Hibernate is not saving H2 schema I'm using Hibernate to manage a small file-based H2 database fully, letting it create the schema and all. I'm just using a simple class to populate the database and print what it saved to the console and that works fine. But if I try to pull results from anything else (another class) the database is empty except for the H2-created information. So the database file is being created fine, but the schema creation does not seem to work and no information stays in the database.

A: What is your database URL? The problem might be related to this: http://h2database.com/html/faq.html#database_files


text:
Q: Linked list loops endlessly I'm writing a simple linked list implementation for the sake of learning. My linked list consists of node structures that contain an int value and a pointer to the next node. When I run my code, it loops endlessly even though it should terminate when it reaches a NULL pointer. What am I doing wrong?
#include <stdio.h>

struct node {
  int value;
  struct node *next_node;
};

struct node * add_node(struct node *parent, int value)
{
  struct node child;
  child.value = value;
  child.next_node = NULL;

  parent->next_node = &child;
  return parent->next_node;
}

void print_all(struct node *root)
{
  struct node *current = root;

  while (current != NULL) {
    printf("%d\n", current->value);
    sleep(1);
    current = current->next_node;
  }
}

int main()
{
  struct node root;
  root.value = 3;

  struct node *one;
  one = add_node(&root, 5);
  print_all(&root);
}

A: Your program exhibits undefined behavior: you are setting a pointer to a locally allocated struct here:
struct node child;
child.value = value;
child.next_node = NULL;

parent->next_node = &child;
return parent->next_node;

Since child is on the stack, returning a parent pointing to it leads to undefined behavior.
You need to allocate child dynamically to make it work:
struct node *pchild = malloc(sizeof(struct node));
// In production code you check malloc result here...
pchild->value = value;
pchild->next_node = NULL;

parent->next_node = pchild;
return parent->next_node;

Now that you have dynamically allocated memory, do not forget to call free on each of the dynamically allocated nodes of your linked list to prevent memory leaks.

A: add_node returns a pointer to a local variable which immediately goes out of scope and may be reused by other functions.  Attempting to access this in print_all results in undefined behaviour.  In your case, it appears the address is reused by the current pointer, leaving root->next_node pointing to root.
To fix this, you should allocate memory for the new node in add_node
struct node * add_node(struct node *parent, int value)
{
    struct node* child = malloc(sizeof(*child));
    if (child == NULL) {
        return NULL;
    }
    child->value = value;
    child->next_node = NULL;

    parent->next_node = child;
    return child;
}

Since this allocates memory dynamically, you'll need to call free later.  Remember not to try to free root unless you change it to be allocated using malloc too.


text:
Q: ASP.Net Sorting a Gridview even after going to next page Hi all I am having trouble with the sorting of my gridview. Let's say my gridview has 10 rows of data and 2 columns, Name and Age. Paging is set to 5 rows of data a page. When i click on Name, it is sorted correctly. However when i click on the next page, it becomes "unsorted" again. Help please! I have attached the event handlers below.
    protected void SearchResultGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["SearchDS"] == null)
            Response.Redirect("PESearh.aspx");
        DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];

        string sortExpression = e.SortExpression;

        if (ViewState["SearchSort"] != null && ViewState["SearchSort"].ToString().Length > 0)
        {
            if (!ViewState["SearchSort"].ToString().Contains(sortExpression))
                GridViewSortDirection = SortDirection.Descending;
        }
        else
        {
            GridViewSortDirection = SortDirection.Descending;
        }

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            sortExpression += " DESC";
            SearchDT.DefaultView.Sort = sortExpression;
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            sortExpression += " ASC";
            SearchDT.DefaultView.Sort = sortExpression;
        }
        ViewState["SearchSort"] = sortExpression;

        this.SearchResultGridView.DataSource = SearchDT;
        this.SearchResultGridView.DataBind();
    }

and for my pagechanging
    protected void SearchResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        SearchResultGridView.DataSource = ViewState["SearchDS"];

        SearchResultGridView.PageIndex = e.NewPageIndex;
        SearchResultGridView.DataBind();
    }

I need help so that the previous sorting also sorts the next page. Please help thanks!
Note: I do not want to sort the data before binding because I want the user to see the data first and then decide what to bind.

A: You seem to be saving the sort expression in ViewState["SearchSort"]. When you change the page index, the value should still remain in the ViewState variable, so you can just grab it and set it again with:
SearchDT.DefaultView.Sort = ViewState["SearchSort"].ToString();

Before sorting the data though, may want to get the DataTable first like so:
DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];

Then, instead of assigning ViewState["SearchDS"] the DataSource of your GridView directly, you can use the new DataTable instead:
SearchResultGridView.DataSource = SearchDT;

Together, you have something like this:
protected void SearchResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];
    SearchDT.DefaultView.Sort = ViewState["SearchSort"].ToString();
    SearchResultGridView.DataSource = SearchDT;

    SearchResultGridView.PageIndex = e.NewPageIndex;
    SearchResultGridView.DataBind();
}

To be safe though, you may want to check to may sure ViewState["SearchSort"] exists first before assigning (if not, then you can give it a default value).


text:
Q: Trying to get NSStream to dispaly in NSlog I am able to connect to a stream but I am unable to display this information.  If I connect using terminal I can see the stream in xml format, however in this code I would like to see it in NSLog
Here is my code any help would be great
#import "_CViewController.h"

@interface _CViewController ()

@end

@implementation _CViewController
@synthesize inStreamDictionary=_inStreamDictionary;

-(NSMutableDictionary *)inStreamDictionary{
    if(!_inStreamDictionary){
        _inStreamDictionary=[[NSMutableDictionary alloc] init];
    }
    return _inStreamDictionary;
}

    - (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *deviceAddress = @"192.168.0.5";
    int devicePort=80;

//open stream
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)deviceAddress, devicePort   , &readStream, &writeStream);

//CFReadStreamSetProperty(readStream,kCFStreamNetworkServiceTypeVoIP,kCFBooleanTrue);
//CFWriteStreamSetProperty(writeStream,kCFStreamNetworkServiceTypeVoIP,kCFBooleanTrue);

inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;

connectToServerUsingCFStream:portNo:

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];

NSString *soapBody=
@"<s:Envelope><s:Body><u:Subscribe xmlns:u=\"urn:udi-com:service:X_Insteon_Lighting_Service:1\"><reportURL>REUSE_SOCKET</reportURL><duration>infinite</duration></u:Subscribe></s:Body></s:Envelope>\n";

NSString *msgLength = [NSString stringWithFormat:@"%d", [soapBody length]];
//NSLog(@"Length: %@", msgLength);
NSString *soapMessageComplete = [NSString stringWithFormat:

                                 @"Post /services HTTP/1.1\n"
                                 "Host: %@:%i\n"
                                 "Authorization: Basic YWRtaW46YWRtaW4=\n"
                                 //"TIMEOUT:Second-infinite\n"
                                 //"CALLBACK:<REUSE_SOCKET>\n"
                                 "Content-Length: %@\n"
                                 "Content-Type: text/xml; charset=\"utf-8\"\r\n\r\n%@"
                                 ,deviceAddress, devicePort, msgLength,soapBody
                                 ];

NSLog(@"Subscribe message: %@", soapMessageComplete);
// subscribe: send soap message
NSData *data = [[NSData alloc] initWithData:[soapMessageComplete dataUsingEncoding:NSUTF8StringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];

NSLog(@"%@", data);
// Do any additional setup after loading the view, typically from a nib.

}

-(void)endSubscription{
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
[outputStream setDelegate:nil];

inputStream = nil;
outputStream = nil;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

A: You don't appear to be setting the delegate of your streams, so I'm not clear how you'd get the data back.
Also, it seems like you could just use an NSURLRequest and do all this in like three lines of code.


text:
Q: Error when creating a code between 3 options I'm in the middle of creating a code that prompts a user to choose between 3 options with an assigned number to each:
Example: Primary: 1, Secondary: 2, Master: 3) and making the number an integer.
The code I have tried thus far is:
print("1: Primary")
print("2: Secondary")
print("3: Master")
if inp == 1:
inp = "Primary"
elif inp == 2:
inp = "Secondary"
elif inp == 3:
inp = "Master"
other:
print("Invalid input!")
inp = int(input("Enter a number: "))
inp=int(input( ))

The output is works well. However, when I enter a number in the output, nothing happens. I'm trying to get make it so after the number is entered, the output shows You have entered 1: Primary or the level for the chosen number.
Can someone help?

A: Try this:
f=0
print("1: Primary")
print("2: Secondary")
print("3: Master")
inp = int(input("Enter a number: "))
if inp == 1:
    out = "Primary"
elif inp == 2:
    out = "Secondary"
elif inp == 3:
    out = "Master"
else:
    f=1
    print("Invalid input!")
if f==0:
    print("You have entered " + str(inp) + ": " + out)


text:
Q: JMeter: How to run the https request by providing client certificates I would like to test the https request by providing client certifacates. I have certificates of type .pem. how should I pass the certificates to the request?

A: This blog article will give you all the details :

*

*https://flood.io/blog/mutual-two-way-ssl-with-jmeter/
Also read this:

*

*http://jmeter.apache.org/usermanual/component_reference.html#Keystore_Configuration


text:
Q: How can we make sure the polynomial is identically zero? There is a theorem about one variable polynomials which tells a polynomial of degree $n$ has at most $n$ roots which helps us to recognize polynomials that are identically zero. At this problem we had:
$A(a,b,c)\implies cQ(ab,c^2+1)+aQ(bc,a^2+1)+bQ(ca,b^2+1)=0$
for non-zero $a,b,c$ and we concluded it for all real numbers. More generally when can we do that in multivariable polynomials?


text:
Q: Base64 & JSON Encode array in PHP, use as HTML data attribute, decode and parse in JavaScript .... with proper Escaping I'm looking to pass an arbitrary array from PHP to JavaScript while properly escaping. I'm leaning on using base64 and I imagine that base64 isn't data attribute safe, so as a good developer I am esc_attr the data. Is there a right way to make sure that the base64 data maintains its integrity in JavaScript?
Here's a contrived example -- that works fine -- because the esc_attr does not modify the integrity of the base64 encoding.
<?php

$array = [
    [
        'the' => 'quick',
        'brown'  => 'fox'
    ],
    [
        'test' => 'test',
        'foo'  => 'bar'
    ]
];
$values_json = base64_encode( json_encode( $array ) );
?>

<input id="check" type="checkbox" data-value="<?php esc_attr_e( $values_json ); ?>"> Foobar

<script>
    var checkbox = document.getElementById(id);
    checkbox.addEventListener('click',
        function () {
            console.log(JSON.parse(atob(this.dataset.value)));
        }
    );
</script>

In my research I came across this solution for handling this using JSON - however the way I am getting the data I don't have an easy way to key the data to retrieve it by using the key as a data attribute.

A: The possible output of base64_encode() contains a-zA-Z0-9+/ and possibly = or == appended.
Testing with
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';

we find that:
esc_attr( $str ) === $str

is true, so it looks like esc_attr() preserves base64 encoded strings.
There are possible regexes to help with validation, but according to this answer by @BoltClock, we could check it with the second strict parameter of:
base64_decode( $str, $strict = true )

We could then wrap it in a function like:
function is_base64( $str )
{
    return base64_decode( $str, true) !== false;
}

to validate it in PHP.


text:
Q: Error: Schema must contain uniquely named types but contains multiple types named "DateTime" I'm trying to generate a GraphQL schema.
I have the following Resolvers. The 3 of them are in different files. 2 of them are for gathering data while one of them is just a trigger API to have them collect more data from a data source.
@Resolver()
export class RefreshDataSchema{
    constructor(
        private readonly aggregatedDataService : AggregateDataService
    ){}

    @Mutation(() => Boolean)
    async refreshTransactions() : Promise<Boolean>{
        Logger.info("Refresh transactions mutation received.");
        return await this.aggregatedDataService.fetchAndAggregateTransactions();
    }

    @Mutation(() => Boolean)
    async refreshAccounts() : Promise<Boolean>{
        Logger.info("Refresh accounts mutation received.");
        return await this.aggregatedDataService.fetchAndAggregateAccounts();
    }
}

@Resolver(() => Account)
export class AccountSchema extends Account{

    @Query(() => Account)
    async getAccount(
        @Arg('query', () => AccountQuery)
        query: AccountQuery,
    ) {
        const data = await Account.findOne({ where: query });
        if (data === undefined) {
            throw new Error(`Account for query "${JSON.stringify(query)}" could not be found!`);
        }
        return data;
    }

    @Query(() => [Account])
    async getAccounts(
        @Arg('query', () => AccountQuery)
        query: AccountQuery,
        @Arg('first', { defaultValue: 10 })
        first: number = 10,
        @Arg('offset', { defaultValue: 0 })
        offset: number = 0,
    ) {
        Logger.info(`GraphQL Query: get accounts. @First: ${first} @Offset: ${offset} received.`);
        const data = Account.find({
            take: first,
            skip: offset,
            order: { balance_in_cents: 'DESC' },
            where: query,
        });

        if(data === undefined){
            throw new Error(`Account for query "${JSON.stringify(query)}" could not be found!`);
        }

        return data;
    }

};

@Resolver(() => Transaction)
export class TransactionSchema extends Transaction{

    @Query(() => [Transaction])
    async getTransactions(
        @Arg('query', () => TransactionQuery)
        query: TransactionQuery,
        @Arg('first', { defaultValue: 10 })
        first: number = 10,
        @Arg('offset', { defaultValue: 0 })
        offset: number = 0,
    ) {
        Logger.info(`GraphQL Query: get transactions. @Query: ${query} @First: ${first} @Offset: ${offset} received.`);
        try{
            let data = await Transaction.find({
                take: first,
                skip: offset,
                order: { executed_on: 'DESC' },
                where: query
            })
            Logger.info("Transaction data retrieved succesfully.");
            return data;
        } catch(err) {
            Logger.error(err);
            return err;
        }

    }

}

And the code to generate the schema, which is federated, looks like this:
import { buildSchemaSync} from 'type-graphql';
import {createResolversMap} from 'type-graphql/dist/utils/createResolversMap';
import {
    TransactionSchema, AccountSchema, RefreshDataSchema
} from '../graphql';
import { printSchema, buildFederatedSchema } from '@apollo/federation';
import { gql } from 'apollo-server-express';

const compiledSchema = buildSchemaSync({
    resolvers: [
        TransactionSchema,
        AccountSchema,
        RefreshDataSchema
    ],
});

export const schema = buildFederatedSchema(
    {
      typeDefs: gql(printSchema(compiledSchema)),
      resolvers: createResolversMap(compiledSchema) as any
    }
  );

When I attempt to generate, the error I get is this:
Error: Schema must contain uniquely named types but contains multiple types named "DateTime".

Not sure where it's getting this "DateTime" from.
Thanks

A: This error usually occurs if you have named two or more of your Object Types with the same name.
For example,
const X = new GraphQLObjectType({
   name: 'Hello',
   ...
});

const Y = new GraphQLObjectType({
   name: 'Hello',
   ...
});

Both X and Y Object Types have the same name which is not allowed in GraphQL.
Try using different names.

A: I know it has been a long time since this has been posted. I have been using NestJS + GraphQL + Prisma and I faced the same issue, but I thought of posting something that helped me, since I spent a hefty amount of time trying to fix it.
In my case deleting the /dist folder. If you want to know about what exactly causes this, you can find it here

A: If you got this error by using Graphql + Nestjs + typeorm
maybe go to the entity which you got the error, add a name into the @InputType
this issue cz you try to use code first strategy for graphql, the entity by typeorm and InputType by graphql will create schema with same name
So, to fix this, give the graphql input type a name, as follow:
@InputType('name', {isAbstract: true})
...

A: This is the official way to create type definitions and a resolver map from your resolver classes:
import { buildTypeDefsAndResolvers } from 'type-graphql';

const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({
  resolvers: [FirstResolver, SecondResolver],
});

This is shown in the docs here.

A: There is an issue with Type-Graphql. Try to use "type-graphql": "^0.18.0-beta.10".

A: Well you could equally provide a folder with the __dirname


text:
Q: I'm trying to get my While loop working with some scenarios? some help appreciated The Scenarios is as follows however my while loop keeps printing the files out twice for the first if statement.
2nd Scenario - Restoring Full and Diff
Logical Order: Full Backup with No Recovery and Diff With Recovery
3rd Scenario - Restoring Full and Logs
Logical Order: Full with No Recovery and Last Log with Recovery and logs                  before No Recovery
4th Scenario - Restoring Full, Diffs and Logs
Logical Order: Full with No Recovery and Latest Diff with No Recovery and logs            before last log No Recovery and Last Log with Recovery.
Last File needs to be in Recovery
DECLARE @Counter INT
SET
  @Counter = 1
  /*EXEC master..sp_executesql @FullBackupSQL */
  WHILE (
    @Counter <= (
      SELECT
        COUNT(*)
      FROM
        Files
    )
  ) BEGIN
SELECT
  *
FROM
  Files
WHERE
  @Counter = ID
SET
  @Counter = @Counter + 1 IF @DiffBackupFile IS NOT NULL
  AND @FullBackupFile IS NOT NULL
  AND @LogbackupFile IS NULL BEGIN
SET
  @FullBackupSQL = 'RESTORE DATABASE ' + @DatabaseNameCopy + '  FROM DISK = ''' + @FullBackupFile + ''' WITH  NORECOVERY,  MOVE ''' + @DatabaseName + ''' TO ''' + @FullBackupFileCopy + ''', MOVE ''' + @FullBackupFileCopyldf + '''
 TO ''' + @FullBackupFileCopylocationldf + ''' , NORECOVERY,NOUNLOAD, REPLACE, STATS = 5' PRINT '139,' + @FullBackupSQL
  /*EXEC master..sp_executesql @FullBackupSQL */
SET
  @DiffBackupSQL = 'RESTORE DATABASE ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @DiffBackupFile + ''' WITH  FILE = 1,  RECOVERY,  NOUNLOAD,  STATS = 5' PRINT '143,' + @DiffBackupSQL
  /* EXEC master..sp_executesql @DiffBackupSQL */
SET
  @Counter = @Counter + 1 END IF @FullBackupFile IS NOT NULL
  AND @LogbackupFile IS NOT NULL
  AND @DiffBackupFile IS NULL BEGIN
SET
  @FullBackupSQL = 'RESTORE DATABASE ' + @DatabaseNameCopy + '  FROM DISK = ''' + @FullBackupFile + ''' WITH  NORECOVERY,  MOVE ''' + @DatabaseName + ''' TO ''' + @FullBackupFileCopy + ''', MOVE ''' + @FullBackupFileCopyldf + '''
 TO ''' + @FullBackupFileCopylocationldf + ''' , NORECOVERY,NOUNLOAD, REPLACE, STATS = 5' PRINT '152,' + @FullBackupSQL
  /*EXEC master..sp_executesql @FullBackupSQL */
SET
  @LogBackupSQL = 'RESTORE LOG ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @LogbackupFile + ''' WITH FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 5' PRINT '156,' + @LogBackupSQL
  /*  EXEC master..sp_executesql @LogBackupSQL */
SET
  @LogBackupSQL = 'RESTORE LOG ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @LogbackupFile + ''' WITH FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 5' PRINT '160,' + @LogBackupSQL
  /*  EXEC master..sp_executesql @LogBackupSQL */
  END IF @FullBackupFile IS NOT NULL
  AND @LogbackupFile IS NOT NULL
  AND @DiffBackupFile IS NOT NULL BEGIN
SET
  @FullBackupSQL = 'RESTORE DATABASE ' + @DatabaseNameCopy + '  FROM DISK = ''' + @FullBackupFile + ''' WITH  NORECOVERY,  MOVE ''' + @DatabaseName + ''' TO ''' + @FullBackupFileCopy + ''', MOVE ''' + @FullBackupFileCopyldf + '''
 TO ''' + @FullBackupFileCopylocationldf + ''' , NORECOVERY,NOUNLOAD, REPLACE, STATS = 5' PRINT '171,' + @FullBackupSQL
  /*EXEC master..sp_executesql @FullBackupSQL */
SET
  @DiffBackupSQL = 'RESTORE DATABASE ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @DiffBackupFile + ''' WITH  FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 5' PRINT '175,' + @DiffBackupSQL
  /* EXEC master..sp_executesql @DiffBackupSQL */
SET
  @LogBackupSQL = 'RESTORE LOG ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @LogbackupFile + ''' WITH FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 5' PRINT '179,' + @LogBackupSQL
  /*  EXEC master..sp_executesql @LogBackupSQL */
SET
  @LogBackupSQL = 'RESTORE LOG ' + @DatabaseNameCopy + ' FROM  DISK = ''' + @LogbackupFile + ''' WITH FILE = 1,  RECOVERY,  NOUNLOAD,  STATS = 5' PRINT '183,' + @LogBackupSQL
  /*  EXEC master..sp_executesql @LogBackupSQL */
SET
  @Counter = @Counter + 1 END END

A: The purpose of the loop and the SELECT * is entirely unclear: you aren't actually using the data from them anyway.
All you need to do is restore each part using WITH NORECOVERY then use a final RESTORE WITH RECOVERY to get the database online.
Note also

*

*RESTORE and BACKUP can be fully parameterized, there is no need for sp_executesql. And even if you did need it you must make sure to escape your names using QUOTENAME.

*Make sure your object names are sysname or nvarchar(128), and your filenames are nvarchar(255).

*You can also simplify the code by nesting your IF statements (you cannot restore a diff without a full backup anyway).

*NOUNLOAD is only relevant for TAPE devices.

IF @FullBackupFile IS NOT NULL
BEGIN
    RESTORE DATABASE @DatabaseNameCopy
    FROM DISK = @FullBackupFile
    WITH NORECOVERY,
      MOVE @DatabaseName TO @FullBackupFileCopy,
      MOVE @FullBackupFileCopyldf TO @FullBackupFileCopylocationldf,
      NORECOVERY, REPLACE, STATS = 5;

     IF @DiffBackupFile IS NOT NULL
    BEGIN
        RESTORE DATABASE @DatabaseNameCopy
        FROM DISK = @DiffBackupFile
        WITH FILE = 1, NORECOVERY, STATS = 5;
    END;
END;

IF @LogbackupFile IS NOT NULL
BEGIN
    RESTORE LOG @DatabaseNameCopy
    FROM DISK = @LogbackupFile
      WITH FILE = 1, NORECOVERY, STATS = 5
END;

RESTORE DATABASE @DatabaseNameCopy
WITH RECOVERY;

If you need to loop through a list of files, the easiest way to do it is using a cursor.
DECLARE @crsr CURSOR;
SET @crsr = CURSOR FAST_FORWARD FOR
    SELECT Filename
    FROM Files;

OPEN @crsr;

FETCH NEXT @crsr INTO @LogbackupFile;
WHILE @@FETCH_STATUS = 0
BEGIN
    RESTORE LOG @DatabaseNameCopy
    FROM DISK = @LogbackupFile
      WITH FILE = 1, NORECOVERY, STATS = 5

    FETCH NEXT @crsr INTO @LogbackupFile;
END;


text:
Q: how to prove linear independence for time shifted functions If we have two linearly independent functions $ f_1(x), f_2(x) $, I need to prove the linear independence of these functions $\{f_1(x)f_1(x+t), f_2(x)f_2(x+t), f_1(x)f_2(x+t)\}$, where $t$ is a shift operator.
Do you have any idea where to start? and what kind of assumption i should put on the basic functions in order to hold the independence of the functions family.
Note: What is needed just a start point in this direction. Any hints would be appreciated.


text:
Q: Firefox add-on sdk uninstall hook I keep some user data in simple-storage. When the user uninstalls the add-on I want to remove this user data. Is there some event or something similar?

A: This will work in every file:
require("sdk/system/unload").when(function(reason) {
  if (reason == "uninstall") {
    // do uninstall stuff..
  }
});

A: Try this:
exports.onUnload = function(reason) {
   //do stuff for unload here
}


text:
Q: How to filter the result that include null value in the query? Hallo, I have a table which have the following item:
CODE UPDATE_DT
---- ---------
APP  08-APR-11
REJ  null
CAN  null

If I have to filter it by date, lets say for this month, 1-APR-2011 to 30-APR-2011. The output of the query will be like following:
CODE UPDATE_DT
---- ---------
APP  08-APR-11

Is it possible for me to select query result that could include null value just like the table locate at the top most of this question?
THanks @!

A: I think you require "IS NULL", for example, add this to your filter:
OR UPDATE_DT IS NULL

A: SELECT code,
       update_dt
  FROM tableName
 WHERE update_dt BETWEEN <your current filter dates>
    OR update_dt IS NULL

A: add OR UPDATE_DT IS NULL at the end of you where clause

A: You need to bracket your where statement to apply the OR
WHERE (update_dt between [dates] or update_dt IS NULL)


text:
Q: How to create special ROOT_OPS in Template-Toolkit? I use Locale::TextDomain in a Dancer environment with Template-Toolkit.
And yes, I know Dancer-Plugin-I18N and tried it, but I don't wan't to use it!
I read Defining_Custom_Virtual_Methods and adjusted it do my needs.
# load Template::Stash to make method tables visible
use Template::Stash;

$Template::Stash::ROOT_OPS->{ 'localize' }    = sub {
    return __(shift);
};

and in a view
[% localize("Hello")  %]

That works very well.
But I would like to wrapp all the Locale::TextDomain functions like:
$Template::Stash::ROOT_OPS->{__}    = sub { return __x(shift) };
$Template::Stash::ROOT_OPS->{__x}   = sub { return __x(shift, @_) };
$Template::Stash::ROOT_OPS->{__n}   = sub { return __n(shift, shift, shift) };
$Template::Stash::ROOT_OPS->{__nx}  = sub { return __nx(shift, shift, shift, @_) };
$Template::Stash::ROOT_OPS->{__xn}  = sub { return __xn(shift, shift, shift, @_) };
$Template::Stash::ROOT_OPS->{__p}   = sub { return __p(shift, shift) };
$Template::Stash::ROOT_OPS->{__px}  = sub { return __px(shift, shift, @_) };
$Template::Stash::ROOT_OPS->{__np}  = sub { return __np(shift, shift, shift, shift) };
$Template::Stash::ROOT_OPS->{__npx} = sub { return __npx(shift, shift, shift, shift, @_) };

but unfortunately it is not possible the use '__' or '__x'
as token.
So my question: How do I create '__' (and friends) root operations in Template-Toolkit?

A: Template Toolkit doesnt export functions that start with _ because they are considered private. You can get around this by setting the following before your Stash operations:
$Template::Stash::PRIVATE = 0;

A: The lexer does not recognize them as identifiers. Changing the module to accept leading _ appears to be far from trivial.


text:
Q: Cannot start "ssh-keygen" Interactive console applications are not supported. Powershell I am having troubles getting a ssh key pair in Powershell. I tried two ways but both didn't work.
PS C:\WINDOWS\system32> ssh-keygen
Cannot start "ssh-keygen". Interactive console applications are not supported.
To run the application, use the Start-Process cmdlet or use "Start PowerShell.exe" from the File menu.
To view/modify the list of blocked console applications, use $psUnsupportedConsoleApplications, or consult online help.
At line:0 char:0

I tried $psUnsupportedConsoleApplications as well, and it does show both ssh-keygen and ssh-keygen.exe .
I also tried the following, and it seemed stuck after "Generating public/private rsa key pair" and doesn't move forward nor gives any error.
PS C:\WINDOWS\system32> ssh-keygen -m PEM -t rsa -b 2048
Generating public/private rsa key pair.

Any insight unblocking this issue would be much appreciated!


text:
Q: How to run a function and load Viewbag on every page load? Here is my issue.  On my _Layout, I have a help button that shows up on every page in my MVC application.  Is there a way to assign the Viewbag with my simple model without having to put in every ActionResult method throughout my application?  A global method?
public ActionResult Index()
{
    var query = db.OnlineHelp.Where(a => a.PageUrl == Request.RawUrl).FirstOrDefault();
    ViewBag.htmlraw = query.PageContent
}

and on my _Layout.chtml
@Html.Raw(@ViewBag.htmlraw)

The Request.RawUrl tracks the user and depending on the page, the database is queried and returns the result such as /Home/Index


text:
Q: jquery dynamic select box + clone row please help!
I need use two jquery scripts - dynamic select box and clone row.
Each of them work fine but I cannot find the way to use it together in one script.
Thank you for any suggestion! Petr

//SCRIPT ADD ROW

$(function(){
            // start a counter for new row IDs
            // by setting it to the number
            // of existing rows
            var newRowNum = 0;

            // bind a click event to the "Add" link
            $('#addnew').click(function(){
                // increment the counter
                newRowNum += 1;

                // get the entire "Add" row --
                // "this" refers to the clicked element
                // and "parent" moves the selection up
                // to the parent node in the DOM
                var addRow = $(this).parent().parent();

                // copy the entire row from the DOM
                // with "clone"
                var newRow = addRow.clone();

                // set the values of the inputs
                // in the "Add" row to empty strings
                $('input', addRow).val('');

                // replace the HTML for the "Add" link
                // with the new row number
                $('td:first-child', newRow).html(newRowNum);

                // insert a remove link in the last cell
                $('td:last-child', newRow).html('Remove');

                // loop through the inputs in the new row
                // and update the ID and name attributes
                $('input', newRow).each(function(i){
                    var newID = newRowNum + '_' + i;
                    $(this).attr('id',newID).attr('name',newID);
                });

                // insert the new row into the table
                // "before" the Add row
                addRow.before(newRow);

                // add the remove function to the new row
                $('a.remove', newRow).click(function(){
                    $(this).parent().parent().remove();
                    return false;
                });

                // prevent the default click
                return false;
            });
        });

//SCRIPT SELECT BOX

function makeSublist(parent,child,isSubselectOptional,childVal)
{
    $("body").append("");
    $('.'+parent+child).html($("."+child+" option"));

    var parentValue = $('.'+parent).attr('value');
    $('.'+child).html($("."+parent+child+" .sub_"+parentValue).clone());

    childVal = (typeof childVal == "undefined")? "" : childVal ;
    $("."+child).val(childVal).attr('selected','selected');

    $('.'+parent).change(function(){
        var parentValue = $('.'+parent).attr('value');
        $('.'+child).html($("."+parent+child+" .sub_"+parentValue).clone());
        if(isSubselectOptional) $('.'+child).prepend(" -- Select -- ");
        $('.'+child).trigger("change");
        $('.'+child).focus();
    });
}

$(document).ready(function()
{
    makeSublist('child','grandsun', true, '');
    makeSublist('parent','child', false, '1');

        $("#selectListButton1").click(function(){
        alert( 'Value is: ' + $('.parent').val() );
    });
    $("#selectListButton2").click(function(){
        alert( 'Text is: ' + $('.child :selected').text() );
    });
});

A: It won't be exactly suited to your needs but you should be able to customise it pretty easily.
I just finished a project of my own where I was doing this but I wasn't aware there were two separate plugins to perform this functionality but you can see my code here:
http://jsfiddle.net/5ubTe/80/


text:
Q: What is document in SOLR terminology? I am new to SOLR and reading its documentation. I am not able to figure out what they mean when they use term document. It almost felt like record initially but then more i read i can relate it to different things like actual document (word,pdf etc.. ) or field.. can someone clarify what it really refers to?
for example http://lucene.apache.org/solr/ under detail feature -> schema they are calling something as document. I also checked their terminology page which did not have the reference. http://wiki.apache.org/solr/SolrTerminology

A: I was also confused by the term document when I was looking into MongoDB :-). You can see https://en.wikipedia.org/wiki/Document-oriented_database.
Solr document is roughly equivalent to a row in a database table. But Solr (and MongoDB) document can better be thought as an "aggregate" row. (NoSQL Distilled uses the term aggregate-oriented database.)
In DB world, you may store data from different tables into an aggregate table for easy data retrieval. Similarly, you may bring data from different DB tables and store in a Solr document for faster searching or rich text analysis or faceting or any other Solr feature that is either infeasible or inefficient with a database (or your existing data store).
You can also think of Solr (and Mongo) documents as JSON objects, or more simply as key-value pairs. While Mongo allows you to store nested documents, Solr does not.
An example nested Mongo document:
{
Title: NoSQL Distilled,
Authors: [{name: Pramod Sadalage, age: 35},
          {name: Martin Fowler, age: 40}],
PubYear: 2012,
Preface: <preface contents>,
BodyText: <entire content of the book>
}

You can see the Authors field itself contains 2 documents.
But in Solr, nesting is not allowed, so, you may store that document like (making sure the indices match for Authors and AuthorAges):
{
Title: NoSQL Distilled,
Authors: [Pramod Sadalage, Martin Fowler],
AuthorAges: [35, 40],
PubYear: 2012,
Preface: <preface contents>,
BodyText: <entire content of the book>
}

The above document may be stored in the database world in a "normalized" manner and you may use JOINs to fetch all the above fields. For example, books table may only have the unique fields title and pubYear with a book_id primary key. You will have another table authors that has primary key author_id and name and age. Then you will have a table book_authors and map the authors to the book. Then you JOIN across these tables to fetch the fields you want. In the "document" world, you bring all these fields into a single document.


text:
Q: gvim: replace lower case words not starting with to with upper case I am trying to replace lower case words not starting with [ to upper case, I think I am very close.
I have tried this approach: :%s/\(\[\)\@![a-z]\+\>/\U&/g
It's not quite right, and I have stared it down for too long - hence this 'phone a friend'.
I think it's matching the [a-z]\+ regardless..

A: The \@! is a zero-width match at the current position, but you need a match before the current position. What \[\@<![a-z] (you don't need the grouping) says is not an opening bracket and a lowercase character; the second branch implies the first. Instead use \@<! to say a lowercase character and before than not an opening bracket. (That's also called negative look-behind.)
A second problem is that this will now match on the second character of a word, so it turns [fix to [fIX. One solution is to assert a start of a keyword with \<:
:%s/\[\@<!\<[a-z]\+\>/\U&/g

Another is to disallow lowercase characters (in addition to the opening bracket) before the word, too:
:%s/[[a-z]\@<!\<[a-z]\+\>/\U&/g


text:
Q: Displaying full date with momentJs i want to have a format like this "Lundi , 11 Janvier 2016 , 12.45 " in moment
i have done this
<script type="text/javascript">

    moment.locale('fr');
    moment().format("LLLL");
    $(document).ready(function () {
        $('#sdate').daterangepicker({
            singleDatePicker: true,
            timePicker: false,
            timePicker24Hour: true,
            firstDay: 1
        });
    });

</script>

the month is in frensh and the shortname of the week " Lu Ma Me ..." all is ok but when i click the date to obtain the format in the top i have this "01/11/2016" .

help plz .

A: You can solve your issue adding format option when you initialize the daterangepicker

$('#sdate').daterangepicker({
    locale: {
        format: 'LLLL'
    },
    singleDatePicker: true,
    timePicker: false
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/locale/fr.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />

<script type="text/javascript" src="https://cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<input type='text'id="sdate">


text:
Q: Full screen video url youtube android not working I want to show fullscreen youtube video in videowebview in my app , I've tried this code:
 youtubeVideos.add( new YouTubeVideos("<iframe width=\"100%\" height=\"100%\" src=\"https://www.youtube.com/embed/"VIDEO-URL" frameborder=\"0\" allowfullscreen></iframe>") );

But unfortunately its not working(in web browser its working).
can someone help me?


text:
Q: How to create a web app with plug-ins capabilities I have an MVC web application that I would like to allow users to upload their own plugins/Packages. Looking for ideas on how to structure that. I've seen many other web apps with that capabilities and hoping to get direction on best practices.
I've looked into creating web apis and allowing users to upload Javascript libraries that can integrate with the api calls but wasn't sure what's the best way to achieve this functionality.


text:
Q: Why I can't reshape my 1d array to 2d array in my code? Numpy I have a problem and I was hoping you can help me.
So I'm writing a code to calculate the shortest path length using networkx and numpy, so I create a function to do this,
def costos(red, precios):
    pathlength = []

    for i in redes: #3d array with 100 2D arrays
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        pathlength.append(nx.shortest_path_length(graph, 0, 1, weight = 'weight'))
        y = np.array(pathlenght)
        z = np.shape(y)

    return y, z

and when I print the result I got the next output
[25, 10, 32, ..., 20] #A 1D array with 100 elements (shortest path length)
(100,) #Shape of the 1D array

What I want is to transform this 1D array with size of (100,) to a 2D array of size (10, 10), I know I can use np.reshape but when I add this to my function like this
for i in redes: #3d array with 100 arrays
    graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
    pathlength.append(nx.shortest_path_length(graph, 0, 1, weight = 'weight'))
    y = np.array(pathlenght)
    z = np.shape(y)
    w = np.reshape(y, (10,10))

I get the next Value Error

cannot reshape array of size 1 into shape (10,10)

What I'm doing wrong? I tried different things but nothing seems to work, so any help will be appreciated, thank you!

A: Because of the fact, that I can't duplicate your error. I created my own output:
    import numpy as np
arr = np.arange(100)
print(arr.shape)
print(arr.dtype)

which return the size of:
    (100,)
    int64
And when I now use np.reshape, it works like that.
print(arr.reshape((10, 10)))

with the following output:
[[ 0  1  2  3  4  5  6  7  8  9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]

If that example doesn't help, please specify an example to replicate or at least specify the dtype of the array and the type of the produced data.


text:
Q: Count rows minus 1 Im making a counter that will count the data on attendance table
on database and display it on my homepage, I manage to work it
by counting the number of rows on the datatable, Now im having
trouble of how i can subtract the number of rows -1 if a student
fill-in the time-out column. For example a student fill-in the time-in
it will diplay to 1 on the counter and if that student fill-in time-out it will minus to
1 and in the counter it will display 0. I hope you can help me or give me a better approach
to achieve this.  Advance thanks.
here is what ive done so far.

Students

                           <?php include_once('connection.php');
                           $sql = mysqli_query($conn,"SELECT timeout, timein, count(timein) As total FROM student_att ") ;
                           $values = mysqli_fetch_assoc($sql);
                           $num_rows=$values["total"];
                           echo $num_rows;
                           ?>

A: Why don't you do the same count for timeout then subtract them,
<?php include_once('connection.php');
  $sql = mysqli_query($conn,"SELECT timeout, timein, count(timein) As total,count(timeout) as totalTimeout FROM student_att ") ;
  $values = mysqli_fetch_assoc($sql);
  $num_rows=$values["total"];
  $num_timeout = $values["totalTimeout "];
  echo ($num_rows-$num_timeout);
 ?>


text:
Q: Makefile Awk using $ for column gets syntax error, while it works fine on console I'm using the below line perfectly fine on the console, but when i use it in a makefile i get the below error. I have tried different things for last hour, nothing helps me. Also i have to use  '@' before the command in makefile, that is normal only. Any help is greatly welcome.
Command on console
cpio -itv < rootfs.cpio | awk '!/^d/{$8="";print}' | sort -k8 > rootfs.layout.trim

Error
awk: !/^d/{="";print}
awk:       ^ syntax error

In makefile
log-rootfs:
# copy the layout dump with all the modification needed to sync with stb output
# get the file list from cpio file => remove the lines with directory name => sort the output and store the same in layout file
cpio -itv < $(ROOTFS_CPIO_FILE) | awk '!/^d/{$8="";print}' | sort -k8 > $(ROOTFS_LAYOUT)
@echo $(ROOTFS_LAYOUT) is created

A: make is looking for a variable/macro named $8.  In general, $ needs to be escaped in the makefile, and if you want to pass a literal $ to the shell, you should use $$ in the makefile.  In other words, try:
rule:
  ... awk '!/^d/{$$8="";print}' ...


text:
Q: tar - command different to 10 years ago? With this question am asking "old rabbits" of Ubuntu resp. of Debian.
Am puzzled by the "newer" use of command tar - I know that 10 years ago it was possible
to tar a file to 1/3 of size or even less ! simply by this :

tar -zcf filename.tgz filename.extension .

( important is point at end after space ! - this was compressing very strong.)
Now point has no effect any more - instead it has effect of compressing all given files in the current directory together to one bundle ?
Today I only can use tar like this :

tar -zcf filename.tgz filename.extension

( without space and without point ) - this way the file is only compressed slightly to 2/3 of size ?!
Am I doing something wrong - or has the old feature with tar-command been forgotten about this feature with point after space ?!

A: *

*Such a syntax has never been documented with GNU tar.

*It would have break compatibility with the established de facto tar standard.
Given both of these points, my best guess is either you are confusing this with something else or you were using a customized tar version / wrapper.


text:
Q: QML-How to add another command to onClick in ui.qml? I want to add another command to itemDelegate.onClick .
Here is my code:
ListView {
        id: beam_viewer
        x: 8
        y: 18
        width: 188
        height: 374
        delegate: ItemDelegate {
            id: delegate_item
            width: 180
            height: 25
            Text {
                text: modelData
                anchors.verticalCenter: parent.verticalCenter
            }
            onClicked: img_footprint.source = applicationPath +
                       "footprints/" + modelData + ".webp"

        }
    }

I use onClicked for change my image source and I want to use modelData  for myText.text . I use ui.qml and it doesn't allow to use { } after onClicked because it reject using javascript.
How can I add to onClicked myText.text = modelData.
Thank you!

A: You probably need to move the code that uses JavaScript (e.g. the contents of the ItemDelegate that contains the Text item and whatnot) into its own .QML file that Qt Quick Designer can't see. For example:
MainForm.ui.qml:
ListView {
    id: beam_viewer
    x: 8
    y: 18
    width: 188
    height: 374
    delegate: MyDelegate {}
}

MyDelegate.qml:
ItemDelegate {
    id: delegate_item
    width: 180
    height: 25
    Text {
        text: modelData
        anchors.verticalCenter: parent.verticalCenter
    }
    onClicked: img_footprint.source = applicationPath +
               "footprints/" + modelData + ".webp"
}

Personally I just wouldn't use ui.qml files. I know that's not a very satisfying answer, but it seems to just slow me down.


text:
Q: How to specify a 'Or' conditional element specifier in Watir? We can specify an "And" specifier in Watir, like
ie.link(:innertext=>"google",:href=>"http://www.google.com").click

Can we specify an "Or" specifier? like
ie.link(:innertext=>"google"||:href=>"http://www.google.com").click

A: You can try like that:
(ie.link(:innertext=>"google") || ie.link(:href=>"http://www.google.com")).click

A: if browser(:text => "google").exist?
  browser(:text => "google").click
elsif browser(:href => /google/).exist?
  browser(:href => /google/).click
end


text:
Q: Normal approximation of Poisson using asymptotics on mass function I have an excercise in probability and I need your help:

Let $X \sim Poi(\lambda )$. Use asymptotics on the mass function directly to prove that, as $\lambda \to \infty$,
$\sqrt{\lambda}\cdot\Pr \{ X=\lfloor\lambda +x\sqrt\lambda\rfloor\}=\frac{1}{\sqrt{2\pi}}\exp (-x^2 /2)+\mathcal{O}(\lambda^{-1/2})$
(HINT: First argue
  that the floor is not important, then apply Stirling's formula)

I did it up to a certain point where I'm stuck now. Here is the last developement I found (by using Stirling from the Poisson mass function):
$\sqrt{\lambda}\cdot\Pr \{ X=\lfloor\lambda +x\sqrt\lambda\rfloor\}=\sqrt\lambda\frac{\lambda^{\lambda+x\sqrt\lambda}\exp(-\lambda)}{(\lambda+x\sqrt\lambda)!}
=\frac{1}{\sqrt{2\pi}}\exp(x\sqrt{\lambda})\frac{1}{(\lambda ^2+x\lambda\sqrt{\lambda})^{\frac{1}{2}+\lambda+x\sqrt{\lambda}}}$
I tried to develop with Newton's Binomial then reuse Stirling but it's a mess.
Please I need help,
thank you

A: Let $z=\lambda + x \sqrt{\lambda}$, with $x$ fixed and $\lambda \to \infty$
Then, assumming $z$ is an integer, $$P(X=z)= e^{-\lambda}\frac{\lambda^z}{z!}=e^{-\lambda} \frac{1}{\sqrt{2\pi z}} \left(\frac{\lambda e}{z}\right)^z (1+O(1/z)) \tag{1}$$
Now consider
$$\begin{array}{rcl} \displaystyle\log \left(\frac{\lambda e}{z}\right)^z &=&\displaystyle(\lambda +x\sqrt{\lambda})\left(1-\log\left(1+\frac{x}{\sqrt{\lambda}}\right)\right)\\
&=&\displaystyle(\lambda +x\sqrt{\lambda})\left(1-\frac{x}{\sqrt{\lambda}}+\frac{x^2}{2\lambda} + O(\lambda^{-3/2})\right) \\
&=&\displaystyle\lambda -\frac{x^2}{2} + O(1/\sqrt{\lambda}) \tag{2}
\end{array}
$$
(Notice that a cancelation of terms occurs here - that's why you need to take the second order Taylor expansion of the logarithm)
Hence $$e^{-\lambda}  \left(\frac{\lambda e}{z}\right)^z = e^{-x^2/2+ O(1/\sqrt{\lambda}) } \tag{3}$$
Can you go on from here?


text:
Q: EMQTT - emq_plugin_template POST to API (SQL) issue with gateway client only I have followed a tutorial from Ravi Pujar on passing MQTT messages to SQL using EMQ and an api interface (he has also got some help from here to make the relevant plugin work).
I am entirely new to Erlang + EMQ, any help on resolving why only my gateway's messages aren't saved when posted from EMQ plugin is appreciated :

*

*When I post with postman through HTTP API the log is saved fine into
SQL fine.

*When I connect to the broker and publish using MQTTfx to the topic it
gets saved fine into SQL as well (which is through the plugin).

*When my gateway publishes to the topic the published messages aren't
logged into the SQL (through the plugin again) but publish fine on the topic.
SQL table has just one string field which allows null.
Example gateway message (Saves fine if posted from postman to api or published on topic from MQTTfx):
$GPRP,745HHBCC5FF,EC16CRH9FFC,-54,0201135644GG46E0082D8A80EFD6EAD1E9A1B132BE1,153656726
I am using "emq_plugin_template.erl" and "on_message_publish" to send my request. Plugin compiles with no errors,EMQ restarted, plugin enabled on the board and it runs smoothly. I am also subscribed to the correct topic of course on the gateway.
on_message_publish(Message, _Env) ->
    io:format("publish ~s~n", [emqttd_message:format(Message)]),

MessageBin = element(12, Message),
MessageStr = binary_to_list(MessageBin),

inets:start(),
Method = post,
URL = "http://127.0.0.1/api/v2/GatewaySQL/1234",
Header = [{"X-DreamFactory-Api-Key", "1234"}],
Type = "application/json",
%%Body = MessageStr, %%just that didn't work with gateway
Body = "{\"resource\":[{\"TagRAW\":\"" ++ MessageStr ++ "\"}]}",
HTTPOptions = [],
Options = [],
R = httpc:request(Method, {URL, Header, Type, Body},HTTPOptions,Options),
    {ok, Message}.

Checking QOS:
I have confirmed QOS  (QOS 0 messages) topic subscribe is correct should i check somewhere else for a mismatch?     Same QOS from MQTTfx saved fine into SQL though and published on the topic.
Removing commas in received message:
I have just in case tried removing commas from the message  (and the $ in one of the attempts below, had more attempts some compiled fine but then the broker might have got stuck):
%%lists:delete($$,MessageStr),
%%lists:flatten(MessageStr),            %%tried without flattening it as well
%%Segmented = string:tokens(MessageStr, ","),
%%lists:flatten(Segmented),

%%IOMessageStr = io_lib:format("~w",[MessageStr]),
%%Flattened = lists:flatten(IOMessageStr),

Thank you for your time :)

A: Try to replace
MessageBin = element(12, Message),

with
MessageBin = element(8, Message),

Hope, this will work for you.


text:
Q: How to observe all programmatical changes of textarea content? I'm developing a chrome extension for Blogger.com, and I need to perform some actions when textarea with post is changed programmaticaly by Blogger modules. For example after image insert. Some changes made by raw XmlHttpRequest, other made in some mystical way that I don't understand.
jQuery on change, on input etc don't work, because changes aren't made by user. MutationObserver doesn't catch any mutations related to textarea, because they aren't affect DOM. Periodically check textarea value looks like brute workaround for me. Right now, I'm observing moment when specific modal windows, for example image upload windows is closed, and then check whether textarea value was changed. But this mutation can easily occur in other circumstances too.
Is there any more appropriate technique?


text:
Q: Is it possible to set a command button to have a 3D disabled graphic in Visual Studio 2008? I've recently started a WinForms project in Visual Studio 2008 and I notice that when I disable a command button, it flattens out the button and leave the text black. This is quite an unexpected change from my experiences in VB6 and VS2005 where the button simply grays itself out.
Is there a setting that would allow me to make the disabled state of the command button 3D like the enabled state? I have the FlatStyle set to Standard, though System results in the same behavior. I also noticed that UseVisualStyleBackColor needs to be set to True for the button to appear correctly in its Enabled state.
Any help is greatly appreciated.

A: The painting code for a button is locked up tight in internal classes, you can't override it nor re-use it.  The public ButtonRenderer class doesn't handle disabled buttons.
One thing that could work is playing games with the BackgroundImage property.  Add a new class to your project and paste the code shown below.  Drop the new control from the top of the toolbar onto your form.
using System;
using System.Drawing;
using System.Windows.Forms;

public class MyButton : Button {
  protected override void OnSizeChanged(EventArgs e) {
    base.OnSizeChanged(e);
    Bitmap bmp = new Bitmap(this.Width, this.Height);
    using (Graphics gr = Graphics.FromImage(bmp)) {
      ButtonRenderer.DrawButton(gr,
        new Rectangle(0, 0, bmp.Width, bmp.Height),
        System.Windows.Forms.VisualStyles.PushButtonState.Normal);
    }
    if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
    this.BackgroundImage = bmp;
  }
}


text:
Q: php table colour rows group by date New to stackoverflow.
About 5 years ago I built a booking site and haven't touch php since, so very very rusty. All is working well with it. However I want to make some updates. As part of the update I have a table that is grouped by date from a Mysql table. This table can now have 1, 2, 3 or 4 results for the same date. To make things clearer for the user I would like to colour the rows by date. It can be grey for one date, white for the next, grey for the next as so on. I do have code to colour all the dates, unfortunately I can end up with consecutive dates with the same colour.
while ($row = mysqli_fetch_assoc($results)) {
    $id_array[] = $row["id"];
    $Fltnum_array[] = $row["fltnum"];
    $Date_array[] = $row["Date"];
    $Name_array[] = $row["Name"];
    $Lesson_array[] = $row["vouchertype"];
    $Vnum_array[] = $row["vnum"];
    $Phone_array[] = $row["phone"];
    $Email_array[] = $row["email"];
    $Ten_array[] = $row["Ten"];
    $Ten1_array[] = $row["Ten1"];
    $Eleven_array[] = $row["Eleven"];
    $Twelve_array[] = $row["Twelve"];
    $Thirteen_array[] = $row["thirteen"];
    $Fourteen_array[] = $row["Fourteen"];
    $Fithteen_array[] = $row["Fifteen"];
    $Sixteen_array[] = $row["Sixteen"];

}

<?php
    echo "<form action='#' name='mainForm' method='post'>

                Name
                Flight Type
                Date
                10:00
                10:00
                11:00
                12:00
                13:00
                14:00
                15:00
                16:00

";
    for ($i = 0; $i < count($id_array); $i++) {
        $id = $id_array[$i];
        $Fltnum = $Fltnum_array[$i];
        $Date = $Date_array[$i];
        $Name = $Name_array[$i];
        $Lesson = $Lesson_array[$i];
        $Vnum = $Vnum_array[$i];
        $Phone = $Phone_array[$i];
        $Email = $Email_array[$i];
        $Ten = $Ten_array[$i];
        $Ten1 = $Ten1_array[$i];
        $Eleven = $Eleven_array[$i];
        $Twelve = $Twelve_array[$i];
        $Thirteen = $Thirteen_array[$i];
        $Fourteen = $Fourteen_array[$i];
        $Fithteen = $Fithteen_array[$i];
        $Sixteen = $Sixteen_array[$i];
        $set_checked = ($Ten < 1) ? 'checked="checked"' : '';
        $set_checked0 = ($Ten1 < 1) ? 'checked="checked"' : '';
        $set_checked1 = ($Eleven < 1) ? 'checked="checked"' : '';
        $set_checked2 = ($Twelve < 1) ? 'checked="checked"' : '';
        $set_checked3 = ($Thirteen < 1) ? 'checked="checked"' : '';
        $set_checked4 = ($Fourteen < 1) ? 'checked="checked"' : '';
        $set_checked5 = ($Fithteen < 1) ? 'checked="checked"' : '';
        $set_checked6 = ($Sixteen < 1) ? 'checked="checked"' : '';
        $newDate = date("d-m-Y", strtotime($Date));
    echo "
        <input type='hidden' name='id[]' value='$id'>
        <input type='hidden' name='Fltnum-$id' value='$Fltnum'>
        <input input type='text' name='Name-$id' value='$Name'>
        <input input type='text' name='Lesson-$id' value='$Lesson'>
        <input type='text' name='Date-$id' value='$newDate'>
        <input type='hidden' name='vnum-$id' value='$Vnum'>
        <input type='hidden' name='Phone-$id' value='$Phone'>
        <input type='hidden' name='Email-$id' value='$Email'>";
        ...
        echo
        "
";
        }
        echo "
<input type='submit' name='submit' value='Make Booking' >

";
    echo "</form>";
 ?>

I have spent a couple of days on this also looking through the forums.
To Add a little more detail, This is the result as is:

and this is what I would like:

A: It appears as though you want to alternate colors for the rows, but only if the date is different than the previous row (so consecutive dates that are the same will appear the same color).
You could do something like this by comparing the date in your loop with the previous date and then applying a color from an array based on whether or not they are the same.
$backgrounds = ["#FFFFFF", "#EEEEEE"];
$currentBackground = 0;

for ($i = 0; $i < count($id_array); $i++) {
  $id = $id_array[$i];
  $Fltnum = $Fltnum_array[$i];
  $Date = $Date_array[$i];
  $Name = $Name_array[$i];
  $Lesson = $Lesson_array[$i];
  $Vnum = $Vnum_array[$i];
  $Phone = $Phone_array[$i];
  $Email = $Email_array[$i];
  $Ten = $Ten_array[$i];
  $Ten1 = $Ten1_array[$i];
  $Eleven = $Eleven_array[$i];
  $Twelve = $Twelve_array[$i];
  $Thirteen = $Thirteen_array[$i];
  $Fourteen = $Fourteen_array[$i];
  $Fithteen = $Fithteen_array[$i];
  $Sixteen = $Sixteen_array[$i];
  $set_checked = ($Ten < 1) ? 'checked="checked"' : '';
  $set_checked0 = ($Ten1 < 1) ? 'checked="checked"' : '';
  $set_checked1 = ($Eleven < 1) ? 'checked="checked"' : '';
  $set_checked2 = ($Twelve < 1) ? 'checked="checked"' : '';
  $set_checked3 = ($Thirteen < 1) ? 'checked="checked"' : '';
  $set_checked4 = ($Fourteen < 1) ? 'checked="checked"' : '';
  $set_checked5 = ($Fithteen < 1) ? 'checked="checked"' : '';
  $set_checked6 = ($Sixteen < 1) ? 'checked="checked"' : '';
  $newDate = date("d-m-Y", strtotime($Date));

  // Only check previous value if we are not on the first row
  if($i > 0) {
    // If the date is the same, do not change backgrounds
    // Otherwise, toggle between backgrounds
    $currentBackground = ($Date_array[$i] == $Date_array[$i-1]) ? $currentBackground : ($currentBackground == 0) ? 1 : 0;
  }
  // This just sets the color from our backgrounds array
  $background = $backgrounds[$currentBackground];

  echo "

      <input type='hidden' name='id[]' value='$id'>
      <input type='hidden' name='Fltnum-$id' value='$Fltnum'>
      <input input type='text' name='Name-$id' value='$Name'>
      <input input type='text' name='Lesson-$id' value='$Lesson'>
      <input type='text' name='Date-$id' value='$newDate'>
      <input type='hidden' name='vnum-$id' value='$Vnum'>
      <input type='hidden' name='Phone-$id' value='$Phone'>
      <input type='hidden' name='Email-$id' value='$Email'>

";
}


text:
Q: How to select consecutive rows from a multi-index pandas dataframe? I have a multi-index pandas dataframe (groupbydataframe) as below:
Store  Year  Month
1      2013  1         4922.0
             2         5315.5
             3         5603.0
             4         4625.0
             5         4995.0
             6         4407.0
             7         4421.0
             8         4494.0
             9         4212.0
             10        4148.5
             11        5033.5
             12        6111.0
       2014  1         4547.5
             2         4726.5
             3         4455.0
             4         4577.5
             5         4909.0
             6         4788.0
             7         4507.0
             8         4124.0
             9         3970.5
             10        4431.0
             11        5220.0
             12        6466.0
       2015  1         4690.0
             2         4467.5
             3         4294.5
             4         4256.0
             5         4529.0
             6         4102.0
                       ...
1112   2013  2        10991.0
             3        12322.0
             4        10705.0
             5        12096.0
             6        11029.0
             7        10419.0
             8         8994.0
             9         9448.0
             10        9019.0
             11        9294.0
             12       11163.0
       2014  1         8156.5
             2         8862.5
             3         8606.5
             4         9662.0
             5        10375.0
             6         8755.0
             7         8262.0
             8         8454.0
             9         7621.5
             10        8779.0
             11        9638.0
             12        9592.0
       2015  1         9345.0
             2         8466.5
             3         8457.0
             4         8715.0
             5         9125.0
             6         8528.0
             7         7728.0

The last column is "Sales".

*

*If FindYear=2014 and FindMonth=01 how do I extract  sales for 2013-12 to 2014-02 for Store=1?

*if FindYear and FindMonth are lists with length(FindYear)=length(Store). How do do (1) without looping through all stores individually?

*Or am I looking at this the wrong way? do I need to unstack() and go from there?

A: You can first convert second and third level of Multiindex to_period:
s = pd.Series({(1, 2013, 2): 5315.5, (1, 2014, 8): 4124.0, (1, 2014, 9): 3970.5, (1112, 2013, 8): 8994.0, (1, 2013, 12): 6111.0, (1, 2015, 3): 4294.5, (1112, 2014, 10): 8779.0, (1, 2014, 10): 4431.0, (1112, 2013, 9): 9448.0, (1112, 2014, 12): 9592.0, (1, 2015, 2): 4467.5, (1, 2014, 11): 5220.0, (1112, 2013, 10): 9019.0, (1, 2015, 1): 4690.0, (1112, 2013, 11): 9294.0, (1112, 2015, 2): 8466.5, (1, 2013, 9): 4212.0, (1112, 2015, 1): 9345.0, (1112, 2013, 4): 10705.0, (1, 2013, 8): 4494.0, (1112, 2014, 9): 7621.5, (1112, 2013, 5): 12096.0, (1, 2014, 4): 4577.5, (1, 2013, 11): 5033.5, (1, 2015, 6): 4102.0, (1112, 2013, 6): 11029.0, (1, 2014, 5): 4909.0, (1, 2013, 10): 4148.5, (1, 2015, 5): 4529.0, (1112, 2014, 8): 8454.0, (1112, 2013, 7): 10419.0, (1, 2014, 6): 4788.0, (1, 2015, 4): 4256.0, (1, 2014, 7): 4507.0, (1112, 2014, 5): 10375.0, (1112, 2015, 3): 8457.0, (1112, 2014, 4): 9662.0, (1, 2013, 5): 4995.0, (1112, 2013, 2): 10991.0, (1, 2014, 1): 4547.5, (1112, 2014, 7): 8262.0, (1, 2013, 4): 4625.0, (1112, 2013, 3): 12322.0, (1, 2014, 2): 4726.5, (1112, 2014, 6): 8755.0, (1, 2013, 7): 4421.0, (1, 2014, 3): 4455.0, (1112, 2014, 1): 8156.5, (1, 2013, 6): 4407.0, (1112, 2014, 11): 9638.0, (1, 2014, 12): 6466.0, (1, 2013, 1): 4922.0, (1112, 2015, 7): 7728.0, (1112, 2013, 12): 11163.0, (1112, 2014, 3): 8606.5, (1112, 2015, 4): 8715.0, (1112, 2014, 2): 8862.5, (1, 2013, 3): 5603.0, (1112, 2015, 6): 8528.0, (1112, 2015, 5): 9125.0})

per = pd.DatetimeIndex(s.index.map(lambda x: pd.to_datetime(str(x[1])
                                                          + str(x[2]), format='%Y%m')))
        .to_period('m')

print (per)
PeriodIndex(['2013-01', '2013-02', '2013-03', '2013-04', '2013-05', '2013-06',
             '2013-07', '2013-08', '2013-09', '2013-10', '2013-11', '2013-12',
             '2014-01', '2014-02', '2014-03', '2014-04', '2014-05', '2014-06',
             '2014-07', '2014-08', '2014-09', '2014-10', '2014-11', '2014-12',
             '2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06',
             '2013-02', '2013-03', '2013-04', '2013-05', '2013-06', '2013-07',
             '2013-08', '2013-09', '2013-10', '2013-11', '2013-12', '2014-01',
             '2014-02', '2014-03', '2014-04', '2014-05', '2014-06', '2014-07',
             '2014-08', '2014-09', '2014-10', '2014-11', '2014-12', '2015-01',
             '2015-02', '2015-03', '2015-04', '2015-05', '2015-06', '2015-07'],
            dtype='int64', freq='M')

Then assign new Multiindex, where second level is PeriodIndex:
new_index = list(zip(df.index.get_level_values('Store'), per))
s.index = pd.MultiIndex.from_tuples(new_index, names = ('Store','Period'))
print (s)
Store  Period
1      2013-01     4922.0
       2013-02     5315.5
       2013-03     5603.0
       2013-04     4625.0
       2013-05     4995.0
       2013-06     4407.0
       2013-07     4421.0
       2013-08     4494.0
       2013-09     4212.0
       2013-10     4148.5
       2013-11     5033.5
       2013-12     6111.0
       2014-01     4547.5
       2014-02     4726.5
       2014-03     4455.0
...
...
...

Selecting with loc:
print (s.loc[1,pd.Period('2014-01')])
4547.5

print (s.loc[1,pd.Period('2013-12'):pd.Period('2014-02')])
Store  Period
1      2013-12    6111.0
       2014-01    4547.5
       2014-02    4726.5
Name: Sales, dtype: float64

per1 = pd.Period('2014-01')
per2 = pd.Period('2015-01')
per = [per1, per2]

print (s.loc[1, per1 - 1: per1 + 1])
Store  Period
1      2013-12    6111.0
       2014-01    4547.5
       2014-02    4726.5
Name: Sales, dtype: float64

Multiple selecting by list comprehension:
print ([s.loc[1, x - 1: x + 1] for x in per])
[Store  Period
1      2013-12    6111.0
       2014-01    4547.5
       2014-02    4726.5
Name: Sales, dtype: float64, Store  Period
1      2014-12    6466.0
       2015-01    4690.0
       2015-02    4467.5
Name: Sales, dtype: float64]

which can be concated:
print (pd.concat([s.loc[1, x - 1: x + 1] for x in per]))
Store  Period
1      2013-12    6111.0
       2014-01    4547.5
       2014-02    4726.5
       2014-12    6466.0
       2015-01    4690.0
       2015-02    4467.5
Name: Sales, dtype: float64


text:
Q: Arcpy Result object - status Waiting, Cancelling, etc? This is a question similar to Using ArcPy Result object associated with Currently Running Script.
I'm curious about how result objects in arcpy can have certain statuses that indicate a geoprocess in process. Statuses such as Submitted, Waiting, Executing, Cancelling, and Deleting. As I understand them, result objects can't be accessed until a geoprocess has completed. Is there a way to access such information mid-process with the result object?

A: As commented by @Vince:

ArcGIS Server jobs can have those statuses.

and by @dslamb:

This help page shows the use of a while loop to pause your script till
  the status changes. See example 2.
  http://pro.arcgis.com/en/pro-app/arcpy/classes/result.htm


text:
Q: .net Entity Framework wont include all list elements in json Im trying to set up a REST API in .net core and im struggeling including all elements in the list inside 'Person'
Person class:
public class Person
{
    public Person()
    {
        LoanRequests = new List<LoanRequest>();
    }

    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string BirthNumber { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Phone { get; set; }

    public virtual IList<LoanRequest> LoanRequests { get; set; }
}

LoanRequest Class:
public class LoanRequest
{
    [Required, Key]
    public int Id { get; set; }

    [Required]
    public float Amount { get; set; }

    [Required]
    public int Years { get; set; }

    [Required]
    public RequestStatus Status { get; set; }

    [Required]
    public Person Person { get; set; }

    public enum RequestStatus
    {
        NotLookedAt,
        Approved,
        Declined
    }
}

Method that includes the elements:
public List<Person> GetAllPersons()
    {
        try
        {
            return _loanDbContext.Persons
                                 .Include(l => l.LoanRequests)
                                 .ToList();
        }
        catch (Exception e)
        {
            return new List<Person>();
        }

    }

Method inside the controller
 [HttpGet]
    public List<Person> Get()
    {
        return _dbAccess.GetAllPersons();
    }

Im using postman to test the api and after adding multiple persons and multiple LoanRequests to them this is whats displayed:
[{
    "birthNumber": "0123456783",
    "email": "test@test.com",
    "phone": "99999999",
    "loanRequests": [{

      "id": 1,
      "amount": 123456,
      "years": 0,
      "status": 2
    }]
}]

I am notifyig its always displaying the first person and loanRequests.
I have tried debugging and there all the elements are included.


text:
Q: Build package for debian stable on old-stable I'm running Debian Buster where I build some packages with the devscripts package. I want to build these packages for the current stable Debian release (bullseye) without upgrading my system. I'm not sure where to start. Update my build packages? Set some flag in the build scripts?

A: You can use pbuilder for this; install it, then run
sudo pbuilder create --basetgz /var/cache/pbuilder/bullseye.tgz --distribution bullseye

to initialise the Debian 11 build tarball. Then use pdebuild to build your package:
pdebuild -- --basetgz /var/cache/pbuilder/bullseye.tgz

See the pbuilder tricks page on the Debian wiki for a more general solution; you'll have to adjust it to match the current stable and oldstable.


text:
Q: PHP preg_replace confusion I'm currently scraping code from a website and I like to mark something, so I need to add a new class to a table row if a cell inside the row does match a pattern.
Structure of the table with the key to search for:

MY KEY

This should be transformed to the following:

MY KEY

I tried the following:
preg_replace('#
(.*)MY KEY	(.*)
#', '
$1MY KEY	$2
', $html);

This is not working, and I can't get it to work. I tried some other variations with an eye on the PHP documentation about the function, but these were even worse.
EDIT: The problem is, that too many rows get marked even those which doesn't have this MY KEY	.
Someone may help me?
Thanks in advance.
Regards

A: From the previous comments I understand you cannot show the full code because it holds private data.
Then I had the idea to ask you for only one example of an "alien" row (one being selected though not containing your "MY KEY". At this time I realized that in fact "MY KEY" itself might probably hold private data.
And it leads me to this hypothesis: the real content of "MY KEY" might include some regex-significant characters. If so, did you pay attention to carefully escape them?

A: This should work :
preg_replace('#
(.*)MY KEY	(.*)
#', '
$1MY KEY	$2
', $html);


text:
Q: Prevent loading symbols in VisualStudio I am using Visual Studio 2015.
I want to prevent symbols loading for all the core dlls like System.Net, System.Web etc..., I just want to load symbols only for the dlls which are in my solution.
I have already done this setting:

i.e in Tools >> Options >> Debugging >> Symbols >> Only specified modules
I have added my few dlls for which I want symbols to be loaded.
But when I run my solution I still see in the VS status bar that it is loading symbols for the core libraries like System.Net, System.Web etc...

How can I prevent that?
I just want symbols of my 4 dlls which are in my solution to be loaded since my intention is to debug those dlls only and not the System core dlls.
Is this even possible?
Or will VS will always load symbols of core files.

A: The following steps solved my similar issue:
At Tools -> Options -> Debugging -> Symbols
a. Enable the "Microsoft Symbol Server" option
b. Click "Empty Symbol Cache"

A: if you have a environment variable named "_NT_SYMBOL_PATH" this could be the reason. Symbols will load regardless of the visual studio setting as far as I know. More information about this variable is found here


text:
Q: HTML5 game on Android - Audio and Video problems I have searched high and low for several days for this problem and I just can't figure it out, hopefully someone else has solved this.
The problem is simple, I have created a web-based game using mainly createjs, preloadjs, and soundjs. The plan was to load the content inside a UIWebView on iOS and WebView on Android to create the two apps.
The problem occurs on Android 4.4 and lower. Neither the videos or the sounds are playing. I'm starting with the simplest scenario; I have an image on a web page, attached a preloaded sound to play onclick;
init:
createjs.Sound.registerSound("sounds/sound_must_be_on.mp3", "soundOn");
$('.btn.sound').click(soundMustBeOn);

onclick listener:
function soundMustBeOn() {
   createjs.Sound.setMute(false);
   createjs.Sound.setVolume(1);
   createjs.Sound.play("soundOn");
}

This works perfect on all modern desktop browsers, iOS and Android 5.x and higher. But on Android 4.4 (on a WebView) it just crashes. What have I missed? I have tried Cordova, Phonegap, SoundJS CordovaAudioPlugin, file:// paths, resources outside the android_asset folder, and plenty of other things. My quess is that I have used Phonegap totally wrong, I could really use a "for dummies" example.

A: Solved it.
I did what I didn't want to do, but I guess it had to be done. I encapsulated my entire web application within Cordova/Phonegap, downloaded and added the CordovaAudioPlugin.js file from SoundJS and simply registered the plugin as others have already done (also updated the file path)
createjs.Sound.registerPlugins([createjs.CordovaAudioPlugin]);
createjs.Sound.registerSound("/android_asset/www/sounds/sound_must_be_on.mp3", "soundOn");


text:
Q: Extract all ip addresses with sed and awk from a string It is simple to extract all ip addresses with grep from a string.
string="221.11.165.237xxxx221.11.165.233\n
219.158.9.97ttttt219.158.19.137"
echo $string |grep -oP "(\d+\.){3}\d+"
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137

The regrex pattern is simple  (\d+\.){3}\d+.
Do the same job with sed and awk.
For sed:
echo $string | sed 's/^\(\(\d\+\.\)\{3\}\d\+\)$/\1/g'
221.11.165.237xxxx221.11.165.233\n 219.158.9.97ttttt219.158.19.137

For awk:
echo $string |gawk 'match($0,/(\d+\.){3}\d+/,k){print k}'
echo $string |awk '/(\d+\.){3}\d+/{print}'

How to fix it for sed and gawk(awk)?
The expect output is the same as grep.
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137

A: Very few tools will recognize \d as meaning digits. Just use [0-9] or [[:digit:]] instead:
$ echo "$string" | awk -v RS='([0-9]+\\.){3}[0-9]+' 'RT{print RT}'
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137

The above uses GNU awk for multi-char RS and RT. With any awk:
$ echo "$string" | awk '{while ( match($0,/([0-9]+\.){3}[0-9]+/) ) { print substr($0,RSTART,RLENGTH); $0=substr($0,RSTART+RLENGTH) } }'
221.11.165.237
221.11.165.233
219.158.9.97
219.158.19.137

A: This might work for you (GNU sed):
sed '/\n/!s/[0-9.]\+/\n&\n/;/^\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\n/P;D' file

Insert newlines either side of strings consisting only of numbers and periods. If a line contains only an IP address print it.
An easier-on-the-eye rendition uses the -r option:
sed -r '/\n/!s/[0-9.]+/\n&\n/;/^([0-9]{1,3}\.){3}[0-9]{1,3}\n/P;D' <<<"$string"

A: As you weren't specific about what could be between the ip addresses, I went with the fact that only numbers and periods will be in the ip:
echo "$string" | sed -r 's/[^0-9.]+/\n/'

echo "$string" | awk '1' RS="[^0-9.]+"


text:
Q: how does flyway lock a postgres schema? I am using Flyway with Postgres and I have noticed that if I have my tomcat server running, and I try to execute a DROP SCHEMA foo it does not work until tomcat shuts down. I am assuming that flyway has some mechanism to block modifications to the schema after it runs. How is the blocking of other clients modifying the schema accomplished in flyway.

A: Flyway doesn't lock the schema.
When it starts applying a migration, it begins a transaction. It then acquires a lock on the metadata table using SELECT * FROM metadatatable FOR UPDATE. This lock is released automatically after the migration completes when the transaction is commited or rolled back.