text:
Q: post a form using ajax and returning the results to span or div I would like to submit a form using ajax and return the results to the same page using innerHTML. But it seems the input value on the form is not getting passed to the action which is a php.
Here is my html form
<form id="check" method="POST" onsubmit="return checkFunction();">

                        Type Store Number to check:
                        <input type="text" id="store" name="storenum" maxlength="4"/>

                        <input type="submit" value="Check" onclick="return checkFunction();"/>

                </form>

This is where I would like the results returned on the same page

And this is how I put together the ajax call
function checkFunction(){
        var ajaxRequest;

        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                document.getElementById("results").innerHTML = ajaxRequest.responseText;
                }
        }
        ajaxRequest.open("POST","run.php",true);
        ajaxRequest.send();
}

And this is how the php action file put together
<?php
$storeNum = $_POST['storenum'];

echo "
Store number: " . $storeNum . "
";
$pingresult = shell_exec("./ping_isp.sh $storeNum");
echo "
$pingresult
";
if (strpos($pingresult, 'ISP was unreachable') == true) {
echo '';
die();
}
echo "
";

?>

If I use directly the php on the form as action let say like below it works perfectly
<form id="check" method="POST">

                        Type Store Number to check:
                        <input type="text" id="store" name="storenum" maxlength="4"/>

                        <input type="submit" value="Check" formaction="run.php"/>

                </form>

But this will return the results on another page. I would like to get the results returned on the same page. Hope you guys can help me out on this.

A: I agreee with @chris85, this could be dangerous to do. In any event, to answer your question I've made the changes to your code that I believe you need...
function checkFunction(){
    var ajaxRequest;

    try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
    } catch (e){
            // Internet Explorer Browsers
            try{
                    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                    try{
                            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                            alert("Your browser broke!");
                            return false;
                    }
            }
    }
    ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
            document.getElementById("results").innerHTML = ajaxRequest.responseText;
            }
    }

    var storevalue = document.getElementByID("storenum").value;
    ajaxRequest.open("POST","run.php",true);
    ajaxRequest.send("storenum=" + storevalue);
}

Please forgive me if I've made any slight mistakes in coding, this is untested and it's possible I made a typo that I've missed.
EDIT: I had a little more time this morning than yesterday, so I took your code and reworked it a bit. The version below now works and should give you the result you're looking for.
function checkFunction(){
    var xmlhttpmod;
    var storevalue = document.getElementByID("store").value;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttpmod=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttpmod=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttpmod.onreadystatechange=function() {
        if (xmlhttpmod.readyState==4 && xmlhttpmod.status==200)  {
            // console.log(xmlhttpmod.responseText);
            document.getElementById("results").innerHTML = xmlhttpmod.responseText;
        }
    }

    xmlhttpmod.open("POST","test.php",true);
    xmlhttpmod.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttpmod.send("storenum="+storevalue);
}

A: try this and post your results please
 <form id="check" method="POST">

      Type Store Number to check:
      <input type="text" id="store" name="storenum" maxlength="4"/>

      <input type="button" value="Check" id="submitMyForm"/>

</form>

your php file:
<?php
if($_POST){
    $required = array('storenum');
    $error = false;
    foreach($required as $key){
        if(empty($_POST[$key])){
            $error = true;
        }
    }
    if(!$error){
        // process data or whatever you need
    }
    else{
        echo 'empty field error';
    }
}
else{
    header("Location: ../login.php");
}

and your ajax
    $('#submitMyForm').on('submit', function(){
    var thisForm = $(this),
        url = thisForm.attr('action'),
        type = thisForm.attr('method'),
        data = {};
    thisForm.find('[name]').each(function(index, value){
        var thisField = $(this),
            name = thisField.attr('name'),
            value = thisField.val();
            data[name] = value;
    });
    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response){
            $('#response').hide().html(response).fadeIn(700);
        },
        error: function(){
            $('#response').hide().html('Ocurrió un error desconocido').fadeIn(700);
        }
    });
    return false;
});


text:
Q: What are alternatives to block? I use \begin{block} ... \end{block} to describe formalization of some notions, and I want to write some examples under it. I still would like to stick to the structure of a block (one part for title and the other part for the content), but it is desirable to use another color to distinguish the example from the notion.
Could anyone tell me what I could use to embed the example?

A: It's probably a bit late to join the party. However...
...the tcolorbox package provides some beautiful and flexible block environments (PGF-based) that specifically support "split boxes" with an upper and a lower half. As of version 1.1 (2012-03-01), there is also a complete English documentation available (previous versions where German only).
\documentclass{beamer}
\usepackage{tcolorbox}

\begin{document}

\begin{frame}{A frame}

\begin{tcolorbox}[colback=blue!5,colframe=blue!75!black,title=My title]
  My cool formalization
  \tcblower
  $\displaystyle\sum\limits_{i=1}^n i = \frac{n(n+1)}{2}$
\end{tcolorbox}

\end{frame}

\end{document}

A: How about using the alertblock or the exampleblock environment?
\documentclass{beamer}

\usecolortheme{whale}
\usecolortheme{orchid}

\begin{document}

\begin{frame}{A frame}

\begin{block}{A block environment}
Some text.
\end{block}

\begin{alertblock}{An alertblock environment}
Some text.
\end{alertblock}

\begin{exampleblock}{An exampleblock environment}
Some text.
\end{exampleblock}

\end{frame}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: HttpsURLConnection + Cloudflare API FileNotFoundException I'm trying to create an app for android and I'm trying to read my stats from my CloudFlare Dashboard.
The strange thing is that if my code reaches the line ins = con != null ? con.getInputStream() : null; It will say "FileNotFoundException".
The headers are set as they should. Here is the quote from the CF API Documentation:

The dashboard view provides both totals and timeseries data for the given zone and time period across the entire CloudFlare network.
  GET /zones/:zone_identifier/analytics/dashboard
  - https://api.cloudflare.com/#zone-analytics-dashboard

Some parameters are optional, I double checked my data already and it works fine in Postman.
I tried to use http but CF doesn't allow it.
My code:
class JsonRequest extends AsyncTask<String, String, String> {
private String readStream(InputStream is) {
    try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        int i = is.read();
        while (i != -1) {
            bo.write(i);
            i = is.read();
        }
        return bo.toString();
    } catch (IOException e) {
        return "";
    }
}

protected String doInBackground(String... params) {
    URL myurl = null;
    try {
        myurl = new URL(params[0]);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpsURLConnection con = null;
    try {
        con = (HttpsURLConnection)myurl.openConnection();
        con.setRequestProperty("X-Auth-Email", "email");
        con.setRequestProperty("X-Auth-Key", "key");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
        con.setRequestProperty("Accept","*/*");
        con.setDoOutput(false);
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream ins = null;
    try {
        ins = con != null ? con.getInputStream() : null; // FileNotFoundException
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStreamReader isr = new InputStreamReader(ins);
    BufferedReader in = new BufferedReader(isr);
    try {
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return readStream(ins);
    }
}


text:
Q: How to check id of textbox in JavaScript? I have this great JavaScript that automatically populates the values of all textboxes on a page with a number, starting at 1 then increasing.
 function editTextBoxes() {
        var textboxs = $('input:text');

        for (i = 0; i <= textboxs.length; i++) {
            $('input:text:eq(' + i + ')').val(i + 1);
        }
    }

However, I only want to fill textboxes who's id contain txtSortOrder.
Can someone please help me fix this line: (it's just a guess)
if ($('input:text:eq(' + i + ')').ID.Contains("txtSortOrder")

A: You can pull any attribute using the attr function. For the Contains(), you can use indexOf which will return -1 if the search is not found.
So that brings us this far:
if ($('input:text:eq(' + i + ')').attr('id').indexOf("txtSortOrder") !== -1)

Now, for your iteration, you can actually use each to process the results of your query.
E.g.
function editTextBoxes() {
    $('input:text[id~=txtSortOrder]').each(function (index) {
        $(this).val(index + 1);
    });
}

Notice this extends your selector to use Attribute Contains word Selector: input:text[id~=txtSortOrder]
Which means you do not have to do the ID comparison manually

A: Code:
function editTextBoxes() {
    // it will select all textboxes which id contain txtSortOrder
    var textboxs = $('input:text').filter(function(){
        this.id.indexOf("txtSortOrder") !== -1;
    });

    for (i = 0; i <= textboxs.length; i++) {
        $('input:text:eq(' + i + ')').val(i + 1);
    }
}


text:
Q: R - ggplot, construct manual legend does not show I wanted to construct a manual legend, using ggplot in R.
Following this post: Construct a manual legend for a complicated plot, I constructed a manual legend for my plot.(reproducible example at bottom of post)
I'm not sure what I'm doing wrong, but the legends do not show. The most common answer out on the internet is appointing a color or fill inside your aesthetic, but I believe I did that (?). I'm working with two different dataframes, might that be the issue?
Any help is nice, here's the code (data below):
#plot effect of external ROI negative influence
cols <- c("Yes"="#4730ff","No"="#07BEB8")

EP_ROI <- ggplot() +
  geom_ribbon(data=external_ROI,aes(x=month,ymin=div - divsd, ymax=div + divsd,fill="No"),alpha=0.12,fill="#4730ff") +
  geom_line(data=external_ROI,aes(x=month,y=div,group=1,colour="Yes"),colour="#4730ff",size=1) +
  geom_vline(aes(xintercept=73),colour="#4730ff",linetype="dashed") +
  geom_vline(aes(xintercept=130),colour="#4730ff",linetype="dashed") +
  labs(y="return on investment (ROI)", x="time (months)") +
  geom_ribbon(data=noexternal_ROI,aes(x=month,ymin=div - divsd, ymax=div + divsd,fill="No"),alpha=0.12,fill="#07BEB8") +
  geom_line(data=noexternal_ROI,aes(x=month,y=div,group=1,colour="No"),colour="#07BEB8",size=1) +
  annotate(x=103, y=7.3,label=paste("external ROI\ninfluence period"), geom="text", color="#4730ff", size=3) +
  scale_colour_manual(name="External influence",values=cols) +
  scale_fill_manual(name="standard deviation",values=cols)

my data:
> dput(head(external_ROI))
structure(list(month = 0:5, n = c(0, 16.9, 16.9, 16.9, 16.9,
16.9), ids = c(0, 16.9, 16.9, 16.9, 16.9, 16.9), ids_sd = c(0,
7.83075094292788, 7.83075094292788, 7.83075094292788, 7.83075094292788,
7.83075094292788), prods = c(0, 0, 0, 0, 0, 0), prods_sd = c(0,
0, 0, 0, 0, 0), cons = c(0, 0, 0, 0, 0, 0), cons_sd = c(0, 0,
0, 0, 0, 0), strat = c(0, 0, 0, 0, 0, 0), strat_sd = c(0, 0,
0, 0, 0, 0), div = c(0, 0, 0, 0, 0, 0), divsd = c(0, 0, 0, 0,
0, 0), REf = c(0, 0, 0, 0, 0, 0), part = c(NaN, 0, 0.341557936787342,
0.343963785131726, 0.348913136282736, 0.354318810222323), shares = c(0,
1.48042413246047, 1.48042413246047, 1.48042413246047, 1.48042413246047,
1.48042413246047)), .Names = c("month", "n", "ids", "ids_sd",
"prods", "prods_sd", "cons", "cons_sd", "strat", "strat_sd",
"div", "divsd", "REf", "part", "shares"), row.names = c(NA, -6L
), class = c("tbl_df", "tbl", "data.frame"))

> dput(head(noexternal_ROI))
structure(list(month = 0:5, n = c(0, 16.9, 16.9, 16.9, 16.9,
16.9), ids = c(0, 16.9, 16.9, 16.9, 16.9, 16.9), ids_sd = c(0,
7.83075094292788, 7.83075094292788, 7.83075094292788, 7.83075094292788,
7.83075094292788), prods = c(0, 0, 0, 0, 0, 0), prods_sd = c(0,
0, 0, 0, 0, 0), cons = c(0, 0, 0, 0, 0, 0), cons_sd = c(0, 0,
0, 0, 0, 0), strat = c(0, 0, 0, 0, 0, 0), strat_sd = c(0, 0,
0, 0, 0, 0), div = c(0, 0, 0, 0, 0, 0), divsd = c(0, 0, 0, 0,
0, 0), REf = c(0, 0, 0, 0, 0, 0), part = c(NaN, 0, 0.347981045925851,
0.346991946002129, 0.349521295784053, 0.354625736233002), shares = c(0,
1.47284681870507, 1.47284681870507, 1.47284681870507, 1.47284681870507,
1.47284681870507)), .Names = c("month", "n", "ids", "ids_sd",
"prods", "prods_sd", "cons", "cons_sd", "strat", "strat_sd",
"div", "divsd", "REf", "part", "shares"), row.names = c(NA, -6L
), class = c("tbl_df", "tbl", "data.frame"))

A: As mentioned in the comments, the legend isn't appearing because you are also setting the color and fill outside of the aes call, which overwrites the color assignments you are wanting.
The easiest way would be to combine your data into one tidy dataframe which will then work much better with ggplot and make the code easier to read.
# create fake dataframes
external_ROI <- data.frame(month=1:168, div = c(rnorm(72, 80,5), rnorm(58, 100, 5), rnorm(38, 80, 5)), divsd = rnorm(168, 3, 1))
noexternal_ROI <- data.frame(month=1:168, div = rnorm(168, 80,5), divsd = rnorm(168, 4, 1))
# combine into one dataframe that is tidy
external_ROI$influence <- "No"
noexternal_ROI$influence <- "Yes"
combined.df <- rbind(external_ROI, noexternal_ROI)

#example
library(ggplot2)
#plot effect of external ROI negative influence
cols <- c("Yes"="#4730ff","No"="#07BEB8")

ggplot(data = combined.df) +
  geom_ribbon(aes(x = month, ymin = div - divsd, ymax = div + divsd,
                                      fill = influence), alpha = 0.12) +
  geom_line(aes(x = month, y = div, colour = influence,), size = 1) +
  geom_vline(aes(xintercept = 73), colour = "#4730ff", linetype = "dashed") +
  geom_vline(aes(xintercept = 130), colour = "#4730ff", linetype = "dashed") +
  labs(y = "return on investment (ROI)", x = "time (months)") +
  annotate(x=103, y=7.3,label=paste("external ROI\ninfluence period"), geom="text", color="#4730ff", size=3) +
  scale_colour_manual(name= "External influence", values = cols) +
  scale_fill_manual(name= "standard deviation", values = cols)

If you don't want to create extra objects in your environment, you could also use a pipe to combine them and plot in one call. F


text:
Q: inconsistent results when reading the memory of another process with winapi ReadProcessMemory So following on with my attempt at making a memory scanner in rust, I've stumbled upon some problems with the output of the reading script. It seems that sometimes the returned array of u8 is large and mostly zeroed out with some values here and there. It looks akin to the output from second episode of this tutorial series. Most frequently however it seems to find no memory at all, returning 0 from ReadProcessMemory with invalid handle error. Sometime however it does neither and keep on returning few small identical looking regions (always the same).
Below is my script narrowed down to be very basic:
use std::ffi::OsStr;
use std::iter::once;
use std::os::windows::ffi::OsStrExt;
use std::mem::size_of;
use winapi::ctypes::c_void;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::HANDLE;
use winapi::um::memoryapi::{ReadProcessMemory, VirtualQueryEx};
use winapi::um::processthreadsapi::OpenProcess;
use winapi::um::winnt::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, PAGE_WRITECOPY, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ, PROCESS_VM_WRITE, PROCESS_ALL_ACCESS};
use winapi::um::winuser::{FindWindowW, GetWindowThreadProcessId};
use winapi::_core::ptr::null_mut;
use winapi::shared::windef::HWND;
use winapi::um::errhandlingapi::GetLastError;

pub const RW_FLAGS: DWORD = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE;
pub const ACCESS_PERMS: DWORD = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE;

// a static function to get wide string from &str
pub fn win32_string(value: &str) -> Vec<u16> {
    OsStr::new(value).encode_wide().chain(once(0)).collect()
}

pub unsafe fn read_from_pid(pid: u32) {
    let handle: HANDLE = OpenProcess(ACCESS_PERMS,
                                     0, pid);
    // OpenProcess -> HANDLE -> *mut c_void ( a mutable pointer to anything )
    println!("hProc: {:?}",handle);

    let mut current: *const _ = 0_usize as *const _;
    // is a pointer sized int we treat as pointer, not a pointer to pointer sized int we treat as pointer to c_void!

    let mut meminfo = MEMORY_BASIC_INFORMATION::default();
    // memory basic information ( mutable to be populated from structs )

    let mut bytes_read: usize = 0;
    // was read per read

    let mut buff: Vec<u8> = Vec::new();
    // temporary vector for displaying the contents

    while VirtualQueryEx(handle, current,
                         &mut meminfo, size_of::<MEMORY_BASIC_INFORMATION>()) != 0 {

        if meminfo.State & MEM_COMMIT != 0 && meminfo.Protect & RW_FLAGS != 0 {
            // if memory was written to by an app and has the permissions to access it then

            let outcome_of_read = ReadProcessMemory(handle,
                                                    meminfo.BaseAddress,
                                                    buff.as_mut_ptr() as *mut c_void,
                                                    meminfo.RegionSize,
                                                    &mut bytes_read);

            if outcome_of_read == 0 {
                // if zero then nothing was read -> reached the end of process memory
                println!("no mem");
                println!("has error: {:?}",GetLastError());
                break;
            } else {
                // if not zero then set len to bytes read
                // cuz u8 = 1 byte = unsigned c_char
                buff.set_len(bytes_read);
                println!("have buff: {:?}", buff);
            }
        }

        current = (current as usize + meminfo.RegionSize) as *mut _;
        // keep on adding size of chunks read
    }
}

fn main() {
    unsafe {

        let winname: Vec<u16> = win32_string("Test App");
        // wide string

        let hwnd: HWND = FindWindowW(null_mut(),winname.as_ptr());
        // getting window handle

        println!("HWND: {:?}",hwnd);

        if !hwnd.is_null() {
            // if valid window handle

            let mut pid: DWORD = DWORD::default();
            GetWindowThreadProcessId(hwnd,&mut pid);
            // get pid for window handle

            println!("pid: {:?}",pid);
            read_from_pid(pid);

        }

    }
}

and further down is my test app (written with druid crate):

use druid::widget::{Align, Flex, Label, TextBox, Button};
use druid::{AppLauncher, Data, Env, Lens, LocalizedString, Widget, WindowDesc, WidgetExt};

const WINDOW_TITLE: LocalizedString<AppState> = LocalizedString::new("Test App");

#[derive(Clone, Data, Lens)]
struct AppState {
    num: u64,
}

fn main() {
    let main_window = WindowDesc::new(build_root_widget)
        .title(WINDOW_TITLE)
        .window_size((400.0, 400.0));

    let initial_state = AppState {
        num: 255_u64,
    };

    AppLauncher::with_window(main_window)
        .launch(initial_state)
        .expect("Failed to launch application");
}

fn build_root_widget() -> impl Widget<AppState> {

    let button = Button::dynamic(|data: &AppState,_env| -> String {format!("has number {:?}",data.num)})
        .on_click(|_ctx, data: &mut AppState, _env| {
        data.num += 1;
    });

    let layout = Flex::column().with_child(button);
    Align::centered(layout)
}

My suspicion that i need to close the hProc handle somehow, but since there is no CloseProcess function from what i can see I'm not sure if that's the cause of the problem. Despite that I tried to call CLoseHandle on my hProc after the read to no avail sadly.
I've also ensured it acquires the correct pid by comparing it to the entry from Task Manager.
update:
According to the comment from Inspectable I looked into the question of permissions (and currently looking into the nature of virtual memory). I've tried to copy this example function in my rust code like so:
pub unsafe fn set_perms(hToken: HANDLE, privilege: Vec<u16>, enable: bool) -> bool {
    let mut luid: LUID = LUID::default();
    let mut outcome: bool = false;

    if LookupPrivilegeValueW(null_mut(), privilege.as_ptr(), &mut luid).is_positive() {
        let mut tp: TOKEN_PRIVILEGES = TOKEN_PRIVILEGES::default();

        tp.PrivilegeCount += 1;
        tp.Privileges[0].Luid = luid;
        tp.Privileges[0].Attributes = if enable {SE_PRIVILEGE_ENABLED} else {0};

        if AdjustTokenPrivileges(hToken, FALSE,
                                 &mut tp, 0,
                                 null_mut(), null_mut()).is_positive() {
            outcome = (GetLastError() == 0);
        }
    }

    outcome
}

pub unsafe fn get_debug_for_current_proc() -> bool {
    let mut hProc: HANDLE = GetCurrentProcess();
    let mut hToken: HANDLE = null_mut();
    let mut priv_name: Vec<u16> = win32_string(SE_DEBUG_NAME);

    OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES, &mut hToken);
    let ret = set_perms(hToken, priv_name, true);
    CloseHandle(hProc);
    CloseHandle(hToken);
    ret
}

It seem to work, however the problem persists.


text:
Q: Search bar to search through TextViews I have made an application that has several insurance companies in a RelativeLayout within a ScrollView. Each Insurance company is within a LinerarLayout. Is it possible to have a search bar that would search through the TextViews and return only the TextView that has been searched for.
My Code is as fallows
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/bg"
        tools:context="saveourcar.soc.Insurance">
        <ScrollView
            android:id="@+id/ScrollView01"
            android:layout_width="580dp"
            android:layout_height="fill_parent" >

        <RelativeLayout
            android:id="@+id/RelativeLayout01"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="580dp"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        android:clickable="true"
        android:fontFamily="sans-serif-condensed"
        android:textSize="27dp"
        android:text="@string/chooseinsurance"/>
        <LinearLayout
            android:id="@+id/list_item9"
            android:layout_width="match_parent"
            android:layout_height="62dp"
            android:layout_below="@+id/list_item"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:background="#26BFDA" >

            <ImageView
                android:layout_width="33dp"
                android:layout_height="match_parent"
                android:layout_marginRight="15dp"
                android:src="@drawable/onetwothree" />

            <TextView
                android:id="@+id/TextView08"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="21sp"
                android:textColor="#ffffff"
                android:text="@string/oneTwoThree"/>
            <ImageView
                android:layout_width="51dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:onClick="onClick123Arrow"
                android:src="@drawable/nextarrow" />

            <!-- Put line under text -->

        </LinearLayout>
        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="#c0c0c0" />

        <LinearLayout
            android:id="@+id/list_item10"
            android:layout_width="match_parent"
            android:layout_height="62dp"
            android:layout_below="@+id/list_item"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:background="#26BFDA" >

            <ImageView
                android:layout_width="33dp"
                android:layout_height="match_parent"
                android:layout_marginRight="15dp"
                android:src="@drawable/acorn" />

            <TextView
                android:id="@+id/TextView10"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="21sp"
                android:textColor="#ffffff"
                android:text="@string/acorn"/>
            <ImageView
                android:layout_width="51dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:onClick="onClickAcornArrow"
                android:src="@drawable/nextarrow" />

        </LinearLayout>
        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="#c0c0c0" />

        <LinearLayout
            android:id="@+id/list_item11"
            android:layout_width="match_parent"
            android:layout_height="62dp"
            android:layout_below="@+id/list_item"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:background="#26BFDA" >

            <ImageView
                android:layout_width="33dp"
                android:layout_height="match_parent"
                android:layout_marginRight="15dp"
                android:src="@drawable/admiral" />

            <TextView
                android:id="@+id/TextView11"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:textSize="21sp"
                android:textColor="#ffffff"
                android:text="@string/admiral"/>
            <ImageView
                android:layout_width="51dp"
                android:layout_height="20dp"
                android:layout_alignParentRight="true"
                android:onClick="onClickAdmiralArrow"
                android:src="@drawable/nextarrow" />

        </LinearLayout>
        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="#c0c0c0" />

</RelativeLayout>
        </ScrollView>
    </RelativeLayout>

Each insurance company is directly beneath the other split by a View. This is only a snippet of my code. This picture is what my Insurance activity currently looks like.

A: I'm not sure what you want to accomplish but I think there is a simpler solution to you problem.
Library that might help you a lot

A: Try something like this
Add a edittext at the top of your activity as a searchbar and
EditText searchedittext = (EditText) findViewById(R.id.search_layoutEditText);

        String edittxt = searchedittext.getText().toString();
        if(edittxt.isEmpty()){

                //display a dialog or toast saying no results found
               }else{
                          //write the condition to display the textviews matching the searched insurance company

      ◆                 }

and as ankitagarwal said it would be easy using a list view


text:
Q: How to compute the vertices for a 3D polyline extrusion? I have a polyline composed of multiple line segments. The line is very complex and squiggles all over the place in 3D, so for simplicity's sake let's say it looks something like this

I want to render it in 3D. Currently, I do a very simple process where I just generate a cylinder for each segment:

This is decent, but looks bad where the line changes direction. It is also wasteful - each of the direction changes requires twices as many vertices as is strictly necessary. I would be much happier with an approach that generated shapes like this:

At first I didn't think it would be too hard, but the more I've worked on it the more I've found it to be surprisingly nontrivial. I'm working in C#, and if this were in 2D I would just use Clipper, but I can't find any libraries or resources for how to solve this problem in 3D. It's okay if the solution isn't always perfect or sometimes leads to self-intersections or things of that nature. Anyone have any guidance?

A: So in a mathematical sense, the intersection of two cylinders is an ellipse. If I give you where the semi-major axis point on the ellipse is and the semi-minor axis you could calculate any number (like numsides) nodes on the ellipse.
Take the node connecting two segments located at a point p and define the two vectors of the ellipse as follows. a is the semi-major axis and b is the semi-minor axis

Each joining line segment has unit directions vectors e_1 and e_2 and the cylinder has radius R.
Then the intersection ellipse would be defined from the vectors a and b:

Then find a point c around the ellipse use the following parameterization with t = 0..1

Here is some C# code that calculates numsides points around the ellipse
// Vectors p, a, b defined
for(int i=0; i<numsides; i++)
{
    double t = (1.0*i)/numsides
    Vector c = p + a*Math.Cos(2*Math.PI*t) + b*Math.Sin(2*Math.PI*t)
    // use/store c as needed for the mesh generation
}

A: I found this site which had an elegant solution. Starting with some points around the first line segment making up your polyline, you compute the intersection of the line parallel to the current segment that passes through each point and the plane formed by the intersection of the two current line segments.


text:
Q: Efficiently multiply OpenCL vector components? I have a float8 vector type that I multiply the components of the vector using vector component addressing as follows ( note the variable v below isn't a constant in reality);
float8 v = (float8) (1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f);
float result = v.s0 * v.s1 * v.s2 * v.s3 * v.s4 * v.s5 * v.s6 * v.s7;

However this prevents my kernel from being vectorised when being compiled with Intel Code builder.
Device build started
Device build done
Kernel <test> was not vectorized

To over come this I started to create copies of the vector, masking the required components and multiplying them all together before trying to call the dot function however this all seemed rather inefficient and convoluted.
My question is therefore how can I multiply the components of my vector in a efficient vectorised manor?

A: My comment was wrong as it is not a dot product you need in the result. It is simply a multiplication of 8 numbers. Parallel work data should be parallel, not in same container. If you want to multiply s0 s1 s2 ... s7 then you put them in consecutive vector variables
variable-1:  s0 p0 r0 q0 .... z0
variable-2:  s1 p1 r1 q1 .... z1

variable-8:  s7 p7 ....       z7

you can multiply those at SIMD speed and have 8 multiplications at a time using float8 type and continue as many times as you need, not just 8.
At each multiplication, you have responsibility to check for errors and overflows. But when hardware does 8 multiplications in a single instruction, which order do you want? You want them multiplied in increasing index order(serial,slow) or something like a pairwise multiplication on tree elements(less multiplications,faster,but give different results)? Order of operations may be important sometimes.
If it is a gpu, simply multiply items and instruction level parallelism + hyperthread engine of gpu achieves efficiency. If it is cpu, you should first check if your cpu supports vertical multiplication instructions(I doubt such thing exists), if not then you need to multiply on array elements not vector elements. This should be easier to vectorise as it is a continuous data on main memory since a cpu does not give explicit control on local memory.


text:
Q: Difference between symbol and variable name in emacs lisp I'm wondering what the difference is between
(add-to-list 'flymake-allowed-file-name-masks
         '("\\.py\\'" flymake-pylint-init))

and
(add-to-list flymake-allowed-file-name-masks
         '("\\.py\\'" flymake-pylint-init))

What is the clear meaning of the apostrophe here?

A: The apostrophe is a quote, which tells the interpreter to not parse the following expression (the symbol name).  Thus, 'add-to-list gets the symbol which contains the list value that is intended to be evaluated.
To learn more about symbols, read the Symbol documentation (specifically, Symbol Components symbols have names, values, function definitions and property lists).
Without reading the documentation, this is how I explain it: Emacs lisp's evaluation strategy is to pass by value (as opposed to by name or reference or something else).  If the quote were not there, flymake-allowed-file-name-masks would be evaluated to a value, and add-to-list would have to work directly on the list.  This would work, with the following exceptions.  If the list were empty, there would be no way to change what the original variable pointed to.  For the same reason, you would not be able to add elements to the front of the list.
To make those two cases work, you actually need the variable name so that you can modify what it points to.
It'd probably be useful to read the following: Introduction to Evaluation, Modifying List Variables, and Modifying Existing List Structures.
If you're familiar with box diagrams, perhaps this will help.
Imagine that some-var points to a list:
somevar
  |
  |
  v
 --- ---      --- ---      --- ---
|   |   |--> |   |   |--> |   |   |--> nil
 --- ---      --- ---      --- ---
  |            |            |
  |            |            |
   --> rose     --> violet   --> buttercup

And you wanted to put something on the front of that list.
If all you have to work with is the value of the pointer in somevar, then the best you can do is put a new element on the front of the list, but you cannot actually modify what somevar points to (because you don't have somevar, you have it's value).  Like so:
             somevar
               |
               |
               v
 --- ---      --- ---      --- ---      --- ---
|   |   |--> |   |   |--> |   |   |--> |   |   |--> nil
 --- ---      --- ---      --- ---      --- ---
  |            |            |            |
  |            |            |            |
   --> tulip     --> rose     --> violet   --> buttercup

So, to write your own 'add-to-list function, you need the variable name.
Of course, if you wrote 'add-to-list as a macro, you wouldn't have that restriction.


text:
Q: How to prevent a SVG marker (arrow head) to inherit path's stroke width? I have arrows with different edge thickness however I want the arrowhead (svg marker) to have the same size, i.e., to not be resized according to the path's stroke width. What can I do?
svg.append("svg:defs").selectAll("marker")
    .data(["suit", "licensing", "resolved"])
  .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
    .style("stroke-width", 1)
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var path = svg.append("svg:g").selectAll("path")
    .data(force.links())
  .enter().append("svg:path")
    .attr("class", function(d) { return "aglink " + "suit"; })
    .attr("marker-end", function(d) { return "url(#" + "suit" + ")"; })
    .style("stroke-width", function(d) { if (d.total != 0) {

        var min = 2;
        var max = 16;
        var val = Math.round((max-min)*(d.count/d.total))+min;

        return val ;
        } });

A: See http://www.w3.org/TR/SVG11/painting.html#MarkerUnitsAttribute.
What you seem to want is markerUnits="userSpaceOnUse".


text:
Q: Filter firestore stream based on value in field I have a collection of arrays and in that a field of todos which is an array of maps. I want to fetch all the todos from all the arrays, filter them according to a given value in the todos map which is dataAndTimeEnabled.
class ArrayController extends GetxController {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  late CollectionReference collectionReference;

  RxList<Array> arrays = RxList<Array>([]);
  List<Todo> scheduledTodos = [];

  @override
  void onInit() {
    super.onInit();
    String uid = Get.find<AuthController>().user!.uid;
    collectionReference =
        _firestore.collection("users").doc(uid).collection("arrays");
    arrays.bindStream(getArrays());
    arrays.forEach((element) {
      element.todos!
          .where((element) => element.dateAndTimeEnabled == true)
          .toList()
          .forEach((element) {
        scheduledTodos.add(element);
      });
    });
  }

  Stream<List<Array>> getArrays() {
    return collectionReference
        .snapshots()
        .map((query) => query.docs.map((item) => Array.fromMap(item)).toList());
  }
}

This is what I have tried but am receiving an empty list

A: Although I wasn't able to filter the todos in the map of arrays, I figure out another way. I made another collection allTodos and stored all the todos from all the arrays in that and Set a custom id as the doc id for each todo in that way whenever a todo was updated or deleted in any list it would also be updated in the allTodos collection.
This is the code:
class ArrayController extends GetxController {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  late CollectionReference collectionReference;
  late CollectionReference allTodosCollectionReference;

  late Query doneQuery;
  late Query scheduledQuery;
  late Query todayQuery;

  RxList<Array> arrays = RxList<Array>([]);
  RxList<FilterTodo> allTodos = RxList<FilterTodo>([]);
  RxList<FilterTodo> doneTodos = RxList<FilterTodo>([]);
  RxList<FilterTodo> scheduledTodos = RxList<FilterTodo>([]);
  RxList<FilterTodo> todayTodos = RxList<FilterTodo>([]);

  @override
  void onInit() {
    super.onInit();
    String uid = Get.find<AuthController>().user!.uid;
    collectionReference =
        _firestore.collection("users").doc(uid).collection("arrays");
    allTodosCollectionReference =
        _firestore.collection("users").doc(uid).collection("allTodos");
    doneQuery = allTodosCollectionReference.where("done", isEqualTo: true);
    scheduledQuery = allTodosCollectionReference.where("dateAndTimeEnabled",
        isEqualTo: true);
    todayQuery = allTodosCollectionReference.where("date",
        isEqualTo: DateFormat("MM/dd/yyyy").format(DateTime.now()));
    arrays.bindStream(getArrays());
    allTodos.bindStream(getAllTodos());
    doneTodos.bindStream(getAllDoneTodos());
    scheduledTodos.bindStream(getAllScheduledTodos());
    todayTodos.bindStream(getAllTodayTodos());
  }

  Stream<List<Array>> getArrays() {
    return collectionReference
        .snapshots()
        .map((query) => query.docs.map((item) => Array.fromMap(item)).toList());
  }

  Stream<List<FilterTodo>> getAllTodos() {
    return allTodosCollectionReference.snapshots().map(
        (query) => query.docs.map((item) => FilterTodo.fromMap(item)).toList());
  }

  Stream<List<FilterTodo>> getAllDoneTodos() {
    return doneQuery.snapshots().map(
        (query) => query.docs.map((item) => FilterTodo.fromMap(item)).toList());
  }

  Stream<List<FilterTodo>> getAllScheduledTodos() {
    return scheduledQuery.snapshots().map(
        (query) => query.docs.map((item) => FilterTodo.fromMap(item)).toList());
  }

  Stream<List<FilterTodo>> getAllTodayTodos() {
    return todayQuery.snapshots().map(
        (query) => query.docs.map((item) => FilterTodo.fromMap(item)).toList());
  }
}


text:
Q: Does event loops polls for event completion or kernel/os notifies back? When Node.js starts, it initializes the event loop, processes the provided input script  which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.
There are seven phases and each phase has its own event queue which is based on FIFO.
So application makes a request event, event demultiplexer gathers those requests and pushes to respective event queues.
For example, If my code makes two reqeusts one is setTimeOut() and another is some API Call, demultiplexer will push the first one in timer queue and other in poll queue.
But events are there, and loop watches over those queues and events, on completion in pushes the registered callback to the callstack where it is processed.
My question is,
1). Who handles events in event queue to OS?
2). Does event loop polls for event completion in each event queue or does OS notifies back?
3). Where and who decides whether to call native asyncrhonous API or handle over to a thread pool?
I am very verge of understanding this, I have been strugling a lot to grasp the concepts. There are a lot of false information about node.js event loop and how it handles asynchronous calls using one thread.
Please answer this questions if possible. Below are the references where I could get some better insight from.
https://github.com/nodejs/nodejs.org/blob/master/locale/en/docs/guides/event-loop-timers-and-nexttick.md
https://dev.to/lunaticmonk/understanding-the-node-js-event-loop-phases-and-how-it-executes-the-javascript-code-1j9
how does reactor pattern work in Node.js?
https://www.youtube.com/watch?v=PNa9OMajw9w&t=3s

A:
Who handles events in event queue to OS?

How OS events work depends upon the specific type of event.  Disk I/O works one way and Networking works a different way.  So, you can't ask about OS events generically - you need to ask about a specific type of event.

Does event loop polls for event completion in each event queue or does OS notifies back?

It depends.  Timers for example are built into the event loop and the head of the timer list is checked to see if it's time has come in each timer through the event loop.  File I/O is handled by a thread pool and when a disk operation completes, the thread inserts a completion event into the appropriate queue directly so the event loop will just find it there the next time through the event loop.

Where and who decides whether to call native asynchronous API or handle over to a thread pool?

This was up to the designers of nodejs and libuv and varies for each type of operation.  The design is baked into nodejs and you can't yourself change it.  Nodejs generally uses libuv for cross platform OS access so, in most cases, it's up to the libuv design for how it handles different types of OS calls.  In general, if all the OSes that nodejs runs on offer a non-blocking, asynchronous mechanism, then libuv and nodejs will use it (like for networking).  If they don't (or it's problematic to make them all work similarly), then libuv will build their own abstraction (as with file I/O and a thread pool).

You do not need to know the details of how this works to program asynchronously in nodejs.  You make a call and get a callback (or resolved promise) when its done, regardless of how it works internally.  For example, nodejs offers some asynchronous crypto APIs.  They happen to be implemented using a thread pool, but you don't need to know that in order to use them.


text:
Q: How to make variables auto-complete in Notepad++? How do I make variables auto-complete in Notepad++? Many editors have it.

I'm working on a program scan file. For every string that begins with a $ character, as soon as I type $, it would show me a drop down list of all variables I have used so far.
This is very useful where there are long_descriptive_variables in code, and I think it is a better way of programming than doing it like $a, $b, $c, but without autocompletion there is more room for error when typing these variables.

A: You can use word completion with Ctrl-Enter to autocomplete any word in your document, including your functions, definitions, vars, et cetera.

A: Notepad++ (v5.5) cannot auto-complete variables or functions you have declared, just language function names and possibly their arguments.

A: According to this link:

This feature is disabled by default, but a quick trip to the Preferences will get you using the new auto-complete feature in no time at all. Go to Settings -> Preferences, and switch to the Backup/Auto-competion tab. At the bottom of that screen you'll see where you can enable auto-completion, and you can optionally turn on the "show function parameters" feature as well. What's that do? Here's an example of me using a PHP function, and you'll notice that it gives me a friendly reminder of the parameters the function takes:

Keep in mind this is only supported in Notepad++ 5.0 or later...

A: Notepad++ do auto complete through following steps:
Settings > Preferences > Backup/Auto-Completion

Under the section "Auto-Completion", you can change the settings.
Enable auto-completion on each input > Word Completion

Through this, we get variables autocompleted.


text:
Q: react-router connected to redux : works with links but only the URL change when dispatching push I'm trying to programmatically push an URL to navigate with react-router, redux, and connected-react-router
When clicking on a <Link /> button, it's working great, the URL is changing and the route too.
But when using a dispatch(push(url)), the URL only change and the content is not updated
I've made a minimal example here.
Any help would be really grateful,
Thanks

A: A lot of anti-pattern code, poor application structured, and mixing of packages is holding your application back.
I rewrote it entirely, here's what I've done:

*

*Reconfigured your application folder's structure to be standard.

*Don't mix Router (BrowserRouter) with ConnectedRouter.

*Don't place all of your components within the App.js file.

*Since the Header is always mounted, you don't need redux, instead you can just use withRouter (it exposes route props to the component).

*Your rootReducer is missing a reducer, so I added a dummyReducer that just returns state.

*Stick to Link or this.props.history when navigating. For this example, there's no need to use both. Also, you don't need to use ConnectedRouter's push function, because the history is passed as a prop when using withRouter.

Side note: If you want the Header to be a "router" where all route changes pass through here, then you'll need to create an action and a reducer that passes a string and stores it to the redux's store. The Header is then connected to the redux store and updates the route when this string has changed.
Working example: https://codesandbox.io/s/526p7kjqq4
components/Header.js
import React, { PureComponent, Fragment } from "react";
import { withRouter } from "react-router-dom";

class Header extends PureComponent {
  goTo = route => {
    this.props.history.push(route);
  };

  render = () => (
    <Fragment>

          <button onClick={() => this.goTo("/")}> Announcements </button>

          <button onClick={() => this.goTo("/shopping")}> Shopping </button>

        <button onClick={() => this.goTo("/shopping")}>
          Click here to go shopping ! (if you can...)
        </button>

    </Fragment>
  );
}

export default withRouter(Header);

routes/index.js
import React from "react";
import { Switch, Route } from "react-router-dom";
import Announcements from "../components/annoucements";
import Shopping from "../components/shopping";

export default () => (

    <Switch>
      <Route exact path="/" component={Announcements} />
      <Route path="/shopping" component={Shopping} />
    </Switch>

);

components/App.js
import React, { Fragment } from "react";
import Routes from "../routes";
import Header from "./Header";

export default () => (
  <Fragment>

    <Routes />
  </Fragment>
);

Here is what you're trying to accomplish: https://codesandbox.io/s/8nmp95y8r2
However, I DO NOT recommend this as it's a bit unnecessary, when history is either already passed as a prop from the Route or can be exposed when using withRouter. According to the Redux docs, it's not recommended either. And instead to either use Link or pass the history prop to the redux action creator instead of programmatic navigation through redux state.
containers/Header.js
import React, { PureComponent, Fragment } from "react";
import { connect } from "react-redux";
import { push } from "connected-react-router";

class Header extends PureComponent {
  goTo = route => this.props.push(route); // this is equivalent to this.props.dispatch(push(route)) -- I'm just appending dispatch to the push function in the connect function below

  render = () => (
    <Fragment>

          <button onClick={() => this.goTo("/")}> Announcements </button>

          <button onClick={() => this.goTo("/shopping")}> Shopping </button>

        <button onClick={() => this.goTo("/shopping")}>
          Click here to go shopping ! (if you can...)
        </button>

    </Fragment>
  );
}

export default connect(
  null,
  { push }
)(Header);

A: After reading the complete thread react-router-redux's push() not rendering new route, I came across this solution  you need to use Router with passing down history as prop down to your app and don't use create from multiple files just import it from a common file.
Here is the working codesandbox: push rendering the new route


text:
Q: Unable to add netflix-hystrix dependency without a version number to POM.XML When I try to add the dependency of netflix-hystrix in my pom.xml without a version number for the framework to download the latest version, the system is unable to recognize the dependency. I get the following message
Cannot resolve org.springframework.cloud:spring-cloud-starter-netflix-hystrix:unknown
However when I add a version number <version>2.2.10.RELEASE</version> the system recognizes the dependency. Any idea why this happens? as it now ties the version in the dependency and will not upgrade automatically to the new version when released.


text:
Q: Laravel 5.6 Changing Breadcrumb Language i am having problem to switch the wording language on Breadcrumbs in Laravel 5.6
the code of my breadcrumbs inside my layouts file are
{{ Breadcrumbs::render('home') }}
the rendered function are located at \routes\breadcrumbs.php
below
Breadcrumbs::register('home', function ($breadcrumbs) {
    $breadcrumbs->push('Home', route('home'));
});

where do i put the keywords to change the breadcrumbs based on language currently active as i usually just put
@lang('home.home') or {{ __('home.home') }}
to change the wording language, but breadcrumbs.php aren't .blade file, so cant use the shown type for reading value

A: example:Laravel 7
Breadcrumbs::for('home', function ($trail) {

$home = e(__('home.dashboard'));  //'app/lang/home.php'

$trail->push( $home , route('home'));
});


text:
Q: Why is viewDidLoad run before didSelectItemAtIndexPath? I am using UICollectionViewDataSource & UICollectionViewDelegate in my personal ViewController subclass file. I can now click on the cell in CollectionView and navigate to the child ViewController I want, but the target's viewDidLoad method is always run before the didSelectItemAtIndexPath, so I can't get the selected cell's info before the view comes out, for example to get the label name of the selected cell.
Below is the codes I did for now, line 2 is always comes before line 1, but I need to get line 1 first, any ideas?
in UICollectionView's ViewController with datasource and delegate:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("1")  //line 1
}

in target's ViewController:
override func viewDidLoad() {
    super.viewDidLoad()

    println("2")  //line 2
}

P.S: push segue is using from main to target.

A: Use didHighlightItemAtIndexPath instead of didSelectItemAtIndexPath solved my problem.

A: Use prepareForSender:segue: instead of collectionView:didSelectItemAtIndexPath:. The sender is the cell that was tapped. If you need its index path, you can get it from the collection view using indexPathForCell: (passing the sender as the argument).


text:
Q: How can I quickly dump a query result set into JSON? import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)

This doesn't work!!

A: How about http://docs.djangoproject.com/en/dev/topics/serialization/
?
from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all())

# it's pretty useful and quick.
data = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))

A: results is a python object. simplejson.dumps only works on python dict's/list's.
You need to convert your results object to a dict first. Either you do it manually like this:
l = []

for result in results:
    d = {
        'attr1': result.attr1,
        'attr2': result.attr2,
        ...
    }
    l.append(d)

theresult_json = simplejson.dumps(l)

or dynamically with a the objects __dict__ method, removing non JSON serializable attributes from it afterwards:
l = []

for result in results:
    d = result.__dict__
    # remove attributes from dict which are not JSON-serializable with del d[key]
    l.append(d)

theresult_json = simplejson.dumps(l)

A: Depending on what you're trying to do, you may also want to check out Piston.  It has special Emitter classes for dumping your objects into a JSON format, XML format, etc... if you are building AJAX or API endpoints, the piston framework is incredibly useful.


text:
Q: $slice operator of mongoDB not working in PHP I have got this mongoDB query:
db.b_activity.find(
    {token_id:"71e32267108b163ccdd3f59ba06c66674b295499"},
    {activity_log:{$slice: -1}}
).pretty();

It gets all the desired results in the mongoDB terminal, but when I write the same query in PHP, it fetches the complete array every time.
MY PHP query:
$get_current_activity = $this->mongo_b_employee->b_activity->findOne(
    array('token_id'=>$token_id),
    array("activity_log" => array('$slice' => -1))
);

Any suggestions where I am doing something wrong?
PS: I am just trying to access the last array element.

A: The signature for MongoDB\Collection::findOne() is slightly different from the "shell". It requires the "projection" key in the $options as the second argument:
$get_current_activity=$this->mongo_b_employee->b_activity->findOne(
    array('token_id'=>$token_id),
    array(
      "projection" => array( "activity_log" => array('$slice' => -1) )
    )
)


text:
Q: PostgreSQL / NodeJS: Query Result Empty I have a query which returns 0 rows but executing the same query using pgadmin or dbeaver returns a result set with rows.
Ive noticed this because i have a postgresql function which should return rows but didnt. After that i started debugging.
Other queries are not affected.
I tried it using knexjs (knex.raw()) and pg (client.query()).
Off cause, i checked the connection a dozen times using different queries and reading the connection string.
This is really strange.
The whole point here is, why does this work in dbeaver and not in my code. Is this a drivers thing?
Queries
select id from (
    select id, started_at from queue
    where finished_at is null and started_at is not null order by id
) d
where date_part('minute',age(now(), started_at)) >= 5

I played around a lot and found that the following queries do work.
select id from queue
where date_part('minute',age(now(), started_at)) >= 5;

and
select id from (
    select id, started_at from queue
    where finished_at is null and started_at is not null order by id
) d;

Update
not working
const test = await this.knexInstance.raw(`
    select id from (
        select id, started_at from queue
        where finished_at is null and started_at is not null order by id
    ) d
    where date_part('minute',age(now(), started_at)) >= 5
`);
console.log(test.rows); // => []
console.log(test.rows.length); // => 0

working
const test = await this.knexInstance.raw(`
    select id from queue
    where date_part('minute',age(now(), started_at)) >= 5;
`);
console.log(test.rows); // => Array(48083) [Object, Object, Object, Object, Object, Object, Object, Object, …]
console.log(test.rows.length); // => 48083

A: Why directly using raw?
const test = await this.knexInstance.select('queue')
             .columns(['id'])
             .whereRaw('date_part('minute',age(now(), started_at)) >= 5');

I'm have less idea about PostgreSQL but it should work.

A: Okay, I tried to reproduce this, but got result as expected. I'm using knex@0.14.4.
const knex = require('knex')(config)

async function main () {
    await knex.raw('create table queue ( id bigserial primary key, started_at timestamp with time zone not null default current_timestamp, finished_at timestamp with time zone);')
    await knex('queue').insert({ started_at: knex.raw('now() - \'10 minutes\'::interval'), finished_at: null })
    await knex('queue').insert({ started_at: knex.raw('now() - \'11 minutes\'::interval'), finished_at: null })
    await knex('queue').insert({ started_at: knex.raw('now() - \'12 minutes\'::interval'), finished_at: null })
    await knex('queue').insert({ started_at: knex.raw('now() - \'13 minutes\'::interval'), finished_at: null })

    await knex('queue').insert({ started_at: knex.raw('now() - \'4 minutes\'::interval'), finished_at: null })
    const test = await knex.raw(`
    select id from (
        select id, started_at from queue
        where finished_at is null and started_at is not null order by id
    ) d
    where date_part('minute',age(now(), started_at)) >= 5
`);
    console.log(test.rows) // Array(4)
    console.log(test.rows.length) // => 4
    await knex.raw('drop table queue;')
    await knex.destroy()
}

main()

All I can recommend is to try to run this example locally and watch the results. And try to upgrade knex to the latest version (if it's not).


text:
Q: Difference between FreeBSD 8.0 CD and DVD What is the difference between the Installation Media for FreeBSD 8.0. One is a CD and the other is the DVD...any place where I can find what packages are not present in the CD media that are in the DVD media.

A: The subsequent install disks for FreeBSD contain 'as many third party packages as would fit on the disk'.
The DVD appears to be the first CD + those packages, bundled together.
It's odd that the 8.0 FreeBSD release doesn't include any additional CD images. The previous releases do.
There's some mention here: http://www.freebsd.org/releases/8.0R/announce.html
From the page:

dvd1
This contains everything necessary to install the base FreeBSD operating system, a collection of pre-built packages, and the documentation. It also supports booting into a "livefs" based rescue mode. This should be all you need if you can burn and use DVD-sized media.
disc1
This contains the base FreeBSD operating system and the documentation packages for CDROM-sized media. There are no other packages.

Looking back to the release candidate for 8.0, I found the following info:
"ISO images for all supported architectures are available on the FTP
sites, and a "memory stick" image is available for amd64/i386
architectures.  For amd64/i386 architectures the cdrom and memstick
images include the documentation packages this time but no other
packages.  The DVD image includes a rough pass at what packages will be
available on the official release media but is subject to change between
now and release."
http://lists.freebsd.org/pipermail/freebsd-stable/2009-September/052024.html
Since 8.0 was only recently released, it is possible the additional disks will be released soon.
The disks appear to be available already for PowerPC and ia64 builds.

A: @Billamama: No, X is not part of disc1 for 8.0-RELEASE.  I just loopback-mounted the ISO image and the packages/All directory contains the documentation ports and various translations of the docs:
bn-freebsd-doc-20090913.tbz
da-freebsd-doc-20090913.tbz
de-freebsd-doc-20090913.tbz
el-freebsd-doc-20090913.tbz
en-freebsd-doc-20090913.tbz
es-freebsd-doc-20090913.tbz
fr-freebsd-doc-20090913.tbz
hu-freebsd-doc-20090913.tbz
it-freebsd-doc-20090913.tbz
ja-freebsd-doc-20090913.tbz
mn-freebsd-doc-20090913.tbz
nl-freebsd-doc-20090913.tbz
pl-freebsd-doc-20090913.tbz
pt-freebsd-doc-20090913.tbz
ru-freebsd-doc-20090913.tbz
sr-freebsd-doc-20090913.tbz
tr-freebsd-doc-20090913.tbz
zh_cn-freebsd-doc-20090913.tbz
zh_tw-freebsd-doc-20090913.tbz

So if you want to install Xorg during the install process, you will have to download either the DVD version or more CD-ROM images from the "disc*[2-N]*" set.


text:
Q: Printing rotated text from web page I run a web application that generates some reports for users. For one of those reports, I need to print the text rotated 90 degree. I've tried many ways but have not found a way to print it properly. I can display text on that pop-up 90 degree rotated with the css class below but when it's sent to printer as usual the text is rotated to normal form and printed. I understand the reason printer is not printing as it's displayed on the browser but is there any way I can do that? Scripting language for this site is PHP.
UPDATE: I can print text rotated that's on a static page but can't print text rotated when it's on a pop up. Actually now I need help to print a page with CSS styling intact
Edit: It will be even helpful enough if I can print it via Firefox only as the client uses Mozilla Firefox.
.rotate{
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    width:400;
    height:400;
}

This is how the pop-up shows the text and how I want to print the text
Much appreciated!

A: You can use PHP to generate an image of the rotated text and then print it.
The cool thing about images is that it doesn't depend upon the browser at all. There are some solutions (already mentioned in this thread) that work, but are tested only on few latest browsers. This solution doesn't care about the browser as long as the browser can print images, only it bothers about a server that can support PHP5.
here's how your PHP file (image_gen.php) should look:
<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);

// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, $_GET['text'], $textcolor);
header('Content-type: image/png');
// Save the image
imagepng($im);
imagedestroy($im);
?>

See this link...
This file takes in the text to print vertically as a get parameter like so:

http://example.com/example.html?text=This+Is+The+Text+To+Be+Printed+Vertically

and it returns an image of that text printed vertically. So you can do this in your main HTML file that you want to print:

PLEASE NOTE: the values specified in the example code are just sample values, text and colours, change them according to your purpose...
so that is how you insert that image into your HTML file. Now when you print that image you must get the image printed as it is, i.e. with vertical text...
Here, i took a print out and captured a photo of it to show to you that it actually works, i know that the text is not clearly visible, but you can make out that it is vertical.

hope that helps...

A: Hmm... This works for me... Tested on:

*

*Firefox 23 (Win7, OSX)

*Chrome 28 (Win7, OSX)

*Safari 6 (OSX)

Admittedly I didn't actually print it, but redirected the print output to PDF (OS-level feature; nothing to do with Firefox).
Make sure that your rules defining the rotation do not have some media query attached disabling them in media="print".
I used the following example document, which comes as a handy data-URI:
data:text/html,%3Cp%20style=%22%20-webkit-transform:%20rotate%28-90deg%29;%20transform:%20rotate%28-90deg%29;%20border:%201px%20solid%20red;%20padding:%201ex;%20width:%20100px;%20%22%3Etest%20rotate%3C/p%3E

A: This should work.
The following has been tested in Chrome:

(Notice I put backslashes to escape enters.)
If you'd rather just have an invisible print frame (the user clicks a button and a print dialog appears), use an iframe. Just note that Opera (probably until they switch to WebKit stuff) doesn't like this.

A: If your text is rotated when displaying on your screen, but not when printing it, then it could be that your CSS is being applied only to the screen and not to the print media.
Make sure to set the media attribute value to all in your <link> tag:
<link rel="stylesheet" type="text/css" href="style.css" media="all">

And avoid using screen if you want your CSS file to target more than just computer screens:
<link rel="stylesheet" type="text/css" href="style.css" media="screen">

You could also have two dedicated CSS files, one for computer screens, and one for printing, allowing you more control:
<link rel="stylesheet" type="text/css" href="style.css" media="screen">
<link rel="stylesheet" type="text/css" href="style-print.css" media="print">

More info about the media attribute: http://www.w3schools.com/tags/att_link_media.asp
Cheers!


text:
Q: How to print table like(see image) that in mysql? My table format
mysql> desc attendance;
+--------+------------+------+-----+---------+----------------+
| Field  | Type       | Null | Key | Default | Extra          |
+--------+------------+------+-----+---------+----------------+
| aid    | bigint(20) | NO   | PRI | NULL    | auto_increment |
| sid    | int(10)    | YES  | MUL | NULL    |                |
| cid    | bigint(20) | YES  | MUL | NULL    |                |
| ttid   | bigint(20) | YES  | MUL | NULL    |                |
| did    | int(3)     | YES  | MUL | NULL    |                |
| date   | date       | YES  |     | NULL    |                |
| hour   | varchar(3) | YES  |     | NULL    |                |
| stuid  | bigint(20) | YES  | MUL | NULL    |                |
| status | varchar(8) | YES  |     | NULL    |                |
+--------+------------+------+-----+---------+----------------+
9 rows in set (0.47 sec)

mysql>

My table result is
mysql> select * from attendance;
+-----+------+------+------+------+------------+------+-------+---------+
| aid | sid  | cid  | ttid | did  | date       | hour | stuid | status  |
+-----+------+------+------+------+------------+------+-------+---------+
|   1 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    16 | present |
|   2 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    17 | absent  |
|   3 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    18 | present |
|   4 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    19 | absent  |
|   5 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    20 | present |
|   6 |    2 |   13 |    4 |    3 | 2020-03-25 | p1   |    15 | absent  |
|   7 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    16 | present |
|   8 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    17 | absent  |
|   9 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    18 | present |
|  10 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    19 | absent  |
|  11 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    20 | present |
|  12 |    2 |   13 |    2 |    2 | 2020-03-17 | p6   |    15 | absent  |
|  13 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    16 | present |
|  14 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    17 | present |
|  15 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    18 | present |
|  16 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    19 | present |
|  17 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    20 | present |
|  18 |    2 |   13 |    4 |    3 | 2020-03-25 | p2   |    15 | present |
|  19 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    16 | absent  |
|  20 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    17 | absent  |
|  21 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    18 | present |
|  22 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    19 | present |
|  23 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    20 | present |
|  24 |    2 |   13 |    4 |    3 | 2020-03-25 | p8   |    15 | absent  |
+-----+------+------+------+------+------------+------+-------+---------+
24 rows in set (0.00 sec)

I need predefined table result will be like this.
Please refer attached image. Only print present or absent under p1 , p2, upto p8.
Those result must be student id, cid, ttid,did, date based result.
Can anyone do this?

A: You want to create a pivot table result from your query. I would recommend use a case statement in your query to get the desire result.
Check pivot table in mysql
Check similar issue on stackoverflow


text:
Q: Publish in Web Store From google drive, I would like users to be able to open files using my new app maker app. In app scripts, you can click register in the chrome web store. Is this possible with app maker? It would also be awesome for users to be able to simply click the icon from the apps section of their gmail, etc. Thank you in advance!

A: It's ambiguous as to what you're looking to achieve from your question.
You might either be looking for how to use the Drive Picker widget
Or you might be looking to release an App Maker app in the Chrome Web Store, which is not at all possible.


text:
Q: OpenStack Swift TempAuth authentication prod usage Almost in every OpenStack Swift documentation is mentioned that TempAuth is a solution just for test non-prod environment (however it's fully functional).
The key reason to don't use this approach in prod that user-creds are stored in plain configuration file that decrease overall security for Object storage.
On the other hand if App is using Object Storage internally (so it's only stores files in the internal infrastructure) and authentication and authorization is provided by App itself it seems such approach might be suitable for production usage.
Could you please share any other drawbacks of TempAuth usage on prod environment taking into account that object storage is internal (or add additional arguments that it's ok :) )?

A: I think the problem with tempauth is that,it is built in module in the Swift, and cant be used as an external authentication module in distributed swift storage systems. but keystone can.


text:
Q: Show that $\det\left[\begin{smallmatrix}1&\cos a&\cos b\\ \cos a&1&\cos(a+b) \\ \cos b&\cos(a+b)&1 \end{smallmatrix}\right]=0$ I am unable to show - without expanding, by using determinant properties - that
$$\det\begin{bmatrix}  1                       &\cos a               &\cos b\\
\cos a                     &1                &\cos(a+b) \\
\cos b                  &\cos(a+b)           &1
\end{bmatrix}=0$$
I am using trigonometric identities to solve this but I don't understand what would be the next step.

A: Here we go: directly
$$\begin{align}\begin{vmatrix}  1                       &\cos a               &\cos b\\
\cos a                     &1                &\cos(a+b) \\
\cos b                  &\cos(a+b)           &1
\end{vmatrix}&=\\&=
[1+2\cos a\cos b\cos(a+b)]-[\cos^2b+\cos^2a+\cos^2(a+b)]\\&=
1+\cos(a+b)\cdot [2\cos a\cos b-\cos (a+b)]-\cos^2a-\cos^2b\\&=
1+\cos(a+b)\cos(a-b)-\cos^2a-\cos^2b\\&=
1+\frac12[\cos(2a)+\cos(2b)]-\cos^2a-\cos^2b\\&=
1+\frac12[2\cos^2a-1+2\cos^2b-1]-\cos^2a-\cos^2b\\&=0\end{align}$$
Another method: triangulation
$$\begin{vmatrix}  1                       &\cos a               &\cos b\\
\cos a                     &1                &\cos(a+b) \\
\cos b                  &\cos(a+b)           &1
\end{vmatrix}\stackrel{(-\cos a)R_1+R_2\to R_2; \\(-\cos b)R_1+R_3\to R_3}{=}\\
\begin{vmatrix}  1                       &\cos a               &\cos b\\
0                     &1-\cos^2a                &\cos(a+b)-\cos a\cos b \\
0                  &\cos(a+b)-\cos a\cos b           &1-\cos^2b
\end{vmatrix}=\\
\begin{vmatrix}  1                       &\cos a               &\cos b\\
0                     &\sin^2a                &-\sin a\sin b \\
0                  &-\sin a\sin b           &\sin^2b
\end{vmatrix}\stackrel{\frac{\sin b}{\sin a}\cdot R_2+R_3\to R_3}{=}\\
\begin{vmatrix}  1                       &\cos a               &\cos b\\
0                     &\sin^2a                &-\sin a\sin b \\
0                  &0           &0
\end{vmatrix}=0.$$

A: This determinant is clearly zero.
The matrix
is the Gram matrix of the three unit vectors $(1,0)$, $(\cos a,\sin a)$
and $(\cos b,-\sin b)$ in the plane. Your matrix equals $AA^T$ where
$$A=\pmatrix{1&0\\\cos a&\sin a\\\cos b&-\sin b}$$
and so it is singular.

A: To flesh out my comment from earlier,$$\Delta:=\left|\begin{array}{ccc}
1 & \cos a & \cos b\\
\cos a & 1 & \cos\left(a+b\right)\\
\cos b & \cos\left(a+b\right) & 1
\end{array}\right|=\left|\begin{array}{ccc}
1 & \cos a & \cos b\\
\cos a & 1 & \cos\left(a+b\right)\\
0 & -\sin a\sin b & \sin^{2}b
\end{array}\right|=\left|\begin{array}{ccc}
1 & \cos a & 0\\
\cos a & 1 & -\sin a\sin b\\
0 & -\sin a\sin b & \sin^{2}b
\end{array}\right|.$$We may as well also simplify the second row/column:
$$\Delta=\left|\begin{array}{ccc}
1 & 0 & 0\\
\cos a & \sin^{2}a & -\sin a\sin b\\
0 & -\sin a\sin b & \sin^{2}b
\end{array}\right|=\left|\begin{array}{ccc}
1 & 0 & 0\\
0 & \sin^{2}a & -\sin a\sin b\\
0 & -\sin a\sin b & \sin^{2}b
\end{array}\right|.$$Well, now we just have an easy $2\times 2$ determinant.

A: Multiply the given matrix by
$$\begin{bmatrix}\sin (a+b)\\-\sin b \\ -\sin a             \end{bmatrix}$$
When you carry out the matrix multiplication, the identities for the sine of a sum and sine of a difference render all components of the product vector $=0$.
This of course fails when $a$ and $b$ are multiples of $\pi$, die to the proposed eigenvector being zero; but then the matrix trivially has all rows proportional to each other.  The breakdown of this eigenvector argument correlates with the null space becoming two-dimensional so that the zero-eigenvalue eigenvector is nonunique.


text:
Q: change border color of multiple divs with button I'm totally new to this and working on a script that will change body background color and some html div's border color on button click.
I got where I can change the body background color to a random color with button click but now I'm stuck on how to do the same to all div borders with a separate button and all the divs have different class names and I would like to change them all at same time to same random color.
Any ideas that will help me or if you could point me in the right direction I would really appreciate it.

var button2 = document.getElementById("button2");
var allchar = "0123456789ABCDEF";

button2.addEventListener("click", myFun);

function myFun() {
  var randcol = "";
  for (var i = 0; i < 6; i++) {
    randcol += allchar[Math.floor(Math.random() * 16)];
  }
  document.body.style.backgroundColor = "#" + randcol;
}
.hud-menu-1 {
  border-style: solid;
  border-radius: 4px;
  border-color: red;
}

.hud-menu-2 {
  border-style: solid;
  border-radius: 4px;
  border-color: red;
}

.hud-menu-3 {
  border-style: solid;
  border-radius: 4px;
  border-color: red;
}

.hud-menu-4 {
  border-style: solid;
  border-radius: 4px;
  border-color: red;
}

.hud-menu-5 {
  border-style: solid;
  border-radius: 4px;
  border-color: red;
}

  Text Here

  Text Here

  Text Here

  Text Here

  Text Here

<button id="button1">click me to change border color</button>
<button id="button2">click me to change background color</button>

A: Use code as below:
        document.getElementsByClassName("hud-menu-"+i)[0].style.borderColor = "#" + randcol;

Here:

    var button2 = document.getElementById("button2");
    var allchar = "0123456789ABCDEF";

    button2.addEventListener("click", myFun);

    function myFun() {
      var randcol = "";
      for (var i = 0; i < 6; i++) {
        randcol += allchar[Math.floor(Math.random() * 16)];
      }
      document.body.style.backgroundColor = "#" + randcol;
    }
function changeBorder(){
      var randcol = "";
      for (var i = 0; i < 6; i++) {
        randcol += allchar[Math.floor(Math.random() * 16)];
      }
      for (var i = 1; i < 6; i++) {
        document.getElementsByClassName("hud-menu-"+i)[0].style.borderColor = "#" + randcol;
      }
}
.hud-menu-1 {
      border-style: solid;
      border-radius: 4px;
      border-color: red;
    }

    .hud-menu-2 {
      border-style: solid;
      border-radius: 4px;
      border-color: red;
    }

    .hud-menu-3 {
      border-style: solid;
      border-radius: 4px;
      border-color: red;
    }

    .hud-menu-4 {
      border-style: solid;
      border-radius: 4px;
      border-color: red;
    }

    .hud-menu-5 {
      border-style: solid;
      border-radius: 4px;
      border-color: red;
    }

      Text Here

      Text Here

      Text Here

      Text Here

      Text Here

    <button id="button1" onclick="changeBorder()">click me to change border color</button>
    <button id="button2">click me to change background color</button>

A: You could add a separate function and attach a click event to the button1 then inside the function get all the divs using querySelectorAll and loop through them changing the border like :
var divs = document.querySelectorAll('div[class^=hud-menu]');
for (var i = 0; i < divs.length; i++) {
    divs[i].style.borderColor = "#" + randcol
}

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");

var allchar = "0123456789ABCDEF";

button1.addEventListener("click", changeBorderColor);
button2.addEventListener("click", myFun);

function changeBorderColor() {
  var randcol = "";
  for (var i = 0; i < 6; i++) {
    randcol += allchar[Math.floor(Math.random() * 16)];
  }

  var divs = document.querySelectorAll('div[class^=hud-menu]');
  for (var i = 0; i < divs.length; i++) {
    divs[i].style.borderColor = "#" + randcol
  }
}

function myFun() {
  var randcol = "";
  for (var i = 0; i < 6; i++) {
    randcol += allchar[Math.floor(Math.random() * 16)];
  }
  document.body.style.backgroundColor = "#" + randcol;
}
.hud-menu-1,
.hud-menu-2,
.hud-menu-3,
.hud-menu-4,
.hud-menu-5 {
  border: 4px solid red;
}

  Text Here

  Text Here

  Text Here

  Text Here

  Text Here

<button id="button1">click me to change border color</button>
<button id="button2">click me to change background color</button>

A: Use getElementsByTagName() if you really want to change all div elements. For more complex sites you may want to use getElementsByClassName() instead, as @לבנימלכה pointed out.
Notice that you don't need to bind your function with js. You can add it to the button directly.

function setDivBorderColor() {
    var divs = document.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        divs[i].style.borderColor = 'red'; // Use random color here
    }
}
* {
  margin: 0.2em;
  padding: 0.2em;
}

div {
  border: solid 2px black;
}

Test

Test

Test

<button onClick="setDivBorderColor()">Change Color</button>


text:
Q: p5.js - achieving smooth animation with draw function I am making a Monopoly style game written in javascript (Using the p5.js library). I am trying to create an animation of a card, using rect, sliding on top of a 2d object with a fixed width and height. Here are my 3 functions that show my thought process:
card_property.js:
function PropertyCard(posX, posY, width, height, property){
  this.width = width;
  this.height = height;
  this.posX = posX;
  this.posY = posY;
  this.property = property;

  this.display = function(){
    rect(this.posX, this.posY, this.width, this.height);
  };
  this.update = function(){
      // not sure if I need to use this
  };
}

This is a snippet of my draw function (p5.js function which is invoked continuously unless conditional logic is used or a p5.js noLoop function is called) inside of my game.js:
var propCards = []
...
function draw(){
  ...
  for (var j = propCards.length - 1; j >= 0; j--){
    frameRate(10)
    console.log(propCards)
    while (propCards[j].posX > 90){
      propCards[j].display();
      propCards[j].posX -= 5;
    }
  }
}

Lastly, this function creates an instance of the property card that I'm trying to animate:
function addCard(property){
  propCard = new PropertyCard(680, 760, 20, 40, property);
  propCards.push(propCard);
}

When I try to create the animation, I end up rendering a static image that shows the cards overlapping each other across descending x values. How can I get the card to slide over my created rectangle and stop at a certain point? The picture below shows what I am seeing:

A: "Draw" displays what you program into it at the end of the function.
So what your doing is drawing multiple rectangles in the same frame.
What you have to do is make something that calculates where to put the rectangle each iteration of draw.
eg:
animationframe = 0

// draw function
// when you want the animation do: animationframe = distancetogo / 5
if (animationframe>0){
  for (var j = propCards.length - 1; j >= 0; j--){
    propCards[j].posX -= 5;
    propCards[j].display();
  }
}


text:
Q: openSUSE installation on root partition encrypted with adiantum cipher I'm trying to install openSUSE Tumbleweed on my Raspberry Pi 4, using SD card encryption.
That would normally be a trivial task but using regular AES cipher for RPi4 is not recommended as explained here. And adiantum is not choosable by Yast during installation.
So I prepared my SD card partitions before openSUSE installation.
The key command I use for encryption of the root partition is :
cryptsetup --cipher xchacha20,aes-adiantum-plain64 --hash sha256 --iter-time 5000 –-key-size 256 luksFormat /dev/mmcblk0p3 (in my case, mmcblk0p1 is /boot/efi, mmcblk0p2 is swap)
With that setup, during installation, Yast warns about the incompatibility between LUKS2 and the bootloader. I know that Grub should support LUKS2, but is it about U-boot that is also present as a bootloader on RPi4 ?
That warning message appeared despite the absence of --type luks2 argument when I encrypted the partition.
Later after packets installation, Yast fails to configure Grub, but eventually finishes installation until the end.
This is error message that popped-up :
Error
The execution of the command "[["/usr/bin/grub2-editenv", "list"]]" failed.
Output code : 1
Error output : /usr/bin/grub2-editenv : error : can't set cipher of cryptodisk 'CRYPT-LUKS2-42742da5c57747e9905eeb26b0075db3-cr-auto-2' to 'xchacha20,aes' with mode 'adiantum-plain54'.
You have a memory leak (not released memory pool): [0xaaaaec497beo0] dtree Internal error: Unreleased memory pool(s) found.

The main question is what should I do to perform a successful installation, but in order to avoid a dozens of hours wasted in empirical tests, there are some bonus questions that might be answered along the way:
— What is this LUKS2 incompatibily Yast is talking about ?
— How to be sure that LUKS1 is used for encryption as asked by the installer ?
— Is Yast really capable to detect LUKS1 ?
— Since the installation finished to the end, do I only need to add a couple of Grub entries to complete what is missing to boot, or is it better to reinstall the whole thing with corrected parameters ?
— Is the use of adiantum cipher a lost cause to begin with ?


text:
Q: Segue removes tabBarItem.badgeValue I have a custom TabBarControllerand on one of the Tab Bar Items I have a round red counter. The first Tab Tab Item presents a summary View Controller. The second Tab Bar Item presents a menu embedded in a Navigation Controller The Tab Bar Counterworks fine across the board, except when I segue back from the summary View Controller. Then the counter disappears. I have tried to load the counter in the customTabBarController:
import UIKit

class CustomTabBarController: UITabBarController {

    override func viewDidAppear(_ animated: Bool) {
        if tabBarCounter != 0
        {
            let vc = self.tabBarController?.viewControllers?.last
            vc?.tabBarItem.badgeValue = "\(tabBarCounter)"
            vc?.tabBarItem.badgeColor = UIColor.red
        }
    }
}

Screendump of storyboard. (The bottom ViewController is the one I´m having trouble with. Segue highlited)


text:
Q: Create a loop for a set of similar statements in python I have a 2D matrix called A0
A0 = [[0 for x in range(3)] for y in range(3)]

I have a function called newProb which takes this as an argument and returns another 2D matrix in the following way:-
A1 = newProb(A0)

So, I want to put this code into a loop.
A1 = newProb(A0)
A2 = newProb(A1)
A3 = newProb(A2)
A4 = newProb(A3)

Any help will be appreciated. Thanks!
P.S. I have to make 100 calls to that function in the above way

A: Rather than trying to create local variables in your loop, you'd be better off storing the results in a list. Your list's index will line up nicely with your naming convention.
A = []

A.append([[0 for x in range(3)] for y in range(3)])

A[1] = newProb(A[0])
A[2] = newProb(A[1])
# ...

You can then easily put this into a loop with a range.
# start the range off by 1
for i in range(1, 10):
    A[i] = newProb(A[i - 1])

This could also be written as
for i in range(10):
    A.append(newProb(A[i]))

A: Use a dict:
A = {}
A[0] = [[0 for x in range(3)] for y in range(3)]
for i in range(1, 101):
    A[i] = newProb(A[i-1])

A: You can store your values in a list generated like so:
A = [A0]
for i in range(99):
    A.append(newProb(A[i]))

A: Combining the answers from @jez and @Soviut:
A = []
A.append([[0 for x in range(3)] for y in range(3)])

for i in range(100):
    A.append(newProb(A[-1])

A[-1] is the last element in the list.

A: If you just need the 'final' value, after the 100st loop:
value = [[0 for x in range(3)] for y in range(3)]
for i in range(100):
    value = newProb(value)

A: Round out the answers with a while loop
A = [A0]
while len(A) < 100:
    A.append(newProb(A[-1]))


text:
Q: AWS snapshots created without policy in my AWS snapshots, I see, that there are snapshots created without policy, and I don't know, hot to disable them.
In my "Lifecycle Manager" I see only one policy, and it creates snapshot every day, and keep them for 2 weeks.
Those snapshots have description added "Created for policy: policy-0fd537dfc2b885c39 schedule: Daily".
And kept only for 2 weeks, then deleted automatically.
But there are also some snapshots without description, which aren't deleted and kept forever. Their creation date is about 11:45PM (East Europe time).
Snapshot list, with unknown snapshots in red border.

The only policy defined:

Are they created by some automatic volume backup, or how?
I didn't have any cron jobs on the server.
What can I do to disable them? Where to find their configuration?
I appreciate any help :)
Kind regards,
Wojtek

A: You can use AWS CloudTrail to look for the API events that created the Snapshots. A user identity (eg IAM Role or IAM User) will be associated with those events.
That should help you figure out how/what is creating those snapshots each night at 12:45am.


text:
Q: How this animation work? Here is example: https://beta.virusbay.io/
As you can see, on the background there are many moving points. Is it some kind of animation in file or this work with JS? How to do smth like this on your own site?

A: This uses particle.js - https://vincentgarreau.com/particles.js/ An Open source library.


text:
Q: Can I use or import an Eclipse formatter in NetBeans? We have been using Eclipse for a long time. We have formatter for each of our projects. Now, some of us are moving to NetBeans. Is it possible to migrate / sync / import our Eclipse formatter to NetBeans? I tried importing an Eclipse project into NetBeans. It does not import the formatter we used.

A: The answer is YES. You can use eclipse code formatter in Netbeans, and enjoy using Netbeans. You need to download eclipse code formatter plugin from below location suitable to your Netbeans version, import your existing eclipse code formatter and ready to go
http://plugins.netbeans.org/plugin/50877/eclipse-code-formatter-for-java

A: AFAIK There is no way to import the Eclipse formatting preferences into NetBeans.
But if you use Maven you can use the Maven2 Java Formatter Plugin which uses the Eclipse JDT features to format source files and integrates nicely with Maven projects. For a usage of current version 0.3.1 see here.
This is a simple pom.xml using the formatter. Just put in any Java source file and run mvn java-formatter:format, your source should be formatted using the given Eclipse configuration file (where you have to provide the path to your own one).
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>de.mackaz</groupId>
    <artifactId>maven.java.formatter.plugin.example</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>com.googlecode.maven-java-formatter-plugin</groupId>
                <artifactId>maven-java-formatter-plugin</artifactId>
                <version>0.3.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>format</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                <configFile>./example-eclipse-code-format-config.xml</configFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

EDIT:
A different approach is to invoke the Eclipse Code Formatter from commandline, (but takes a bit longer and is not nicely integrated into the Maven lifecycle), as described here.
You can format a sourcefile with it like this:
/opt/eclipse/eclipse -application org.eclipse.jdt.core.JavaCodeFormatter -verbose -nosplash -config example-eclipse-code-format-config.xml src/main/java/de/mackaz/FormatMe.java

(Also take a look at this page where the author put that into a little script)
It should be easy to integrate one of those approaches into NetBeans. Either wrap those inside an Ant file and add that to your NetBeans commands, or write a little NetBeans plugin to add the action e.g. to the contextmenu (which is pretty easy, especially compared to writing Eclipse Plugins).

A: I like NetBeans very much, but have the same problem with formatting.
I've found this maven plugin http://mvneclipsefmt.sourceforge.net/usage.html
Seems it can run eclipse formatter as maven goal. But I didn't try it yet.

A: There is a post on JBoss community which seems to address formating issues, it might be of some help; http://community.jboss.org/wiki/ImportFormattingRules

A: You can use "Eclipse Code Formatter for Java" NetBeans plugin it works with NetBeans 7.3 and .7.4 (but with a little problem!).

A: It would appear that, as of Netbeans 7.3.1, a very clever fellow developed a Netbeans plugin that accepts Eclipse Formatter XML files. I have not tested this yet TBH, but I will be doing so in the very near future (as I am the only one at the office that prefers Netbeans over Eclipse, and I think my co-workers are conspiring to kill me due to git merge conflicts).
https://blogs.oracle.com/geertjan/entry/eclipse_formatter_for_netbeans_ide

A: It should be easy to use Eclipse's formatter as a plugin in Netbeas, like it was done for IntelliJ

A: The following link may be of assistance http://netbeans.dzone.com/articles/importexport-code-formatting it talks about sharing sharing settings.