text:
Q: PHP, admins usersystem I was wondering if you think this is possible:
Ok so I have a database storing usernames and I would like to echo the admins which are inside a file called admins.php IF they match the usernames inside the database so far I have got:
admins.php;
$admins = array("username","username2","username3");

and
$users="SELECT username from usrsys";
$query_users=mysql_query($users);
while loop here.

The while loop should hopefully echo the users which matches the admins.php file. I assume I should use something like (inarray()), but I am really not sure.

A: You should definitely use IN clause in your SQL to do this. Selecting everything from the table in order to determine in PHP if it contains the user names you're looking for makes no sense and is very wasteful. Can you imagine what would happen if you had a table of 1 million users and you needed to see if two of them were on that list? You would be asking your DBMS to return 1 million rows to PHP so that you can search through each of those names and then determine whether or not any of them are the ones you're looking for. You're asking your DBMS to do a lot of work (send over all the rows in the table), and you're also asking PHP to do a lot of work (store all those rows in memory and compute a match), unnecessarily.
There is a much more efficient and faster solution depending on what you want.
First, if you only need to know that all of those users exist in the table then use SELECT COUNT(username) instead and your database will return a single row with a value for how many rows were found in the table. That way you have an all or nothing approach (if that's what you're looking for). Either there were 3 rows found in the table and 3 elements in the array or there weren't. This also utilizes your table indexes (which you should have properly indexed) and means faster results.
$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT COUNT(username) FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
    echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
    exit;
}
if (false === $result = mysql_fetch_row($query_users)) {
    echo "Huston we have a problme! " . mysql_error(); // Basic error handling (DEBUG ONLY)
}
if ($result[0] == count($admins)) {
    echo "All admins found! We have {$result[0]} admins in the table... Mission complete. Returning to base, over...";
}

If you actually do want all the data then remove the COUNT from the SQL and you will simply get all the rows for those users (if any are found).
$admins = array("username","username2","username3");
// Make sure you properly escape your data before you put in your SQL
$list = array_map('mysql_real_escape_string', $admins);
// You're going to need to quote the strings as well before they work in your SQL
foreach ($list as $k => $v) $list[$k] = "'$v'";
$list = implode(',', $list);
$users = "SELECT username FROM usrsys WHERE username IN($list)";
$query_users = mysql_query($users);
if (!$query_users) {
    echo "Huston we have a problem! " . mysql_error(); // Basic error handling (DEBUG ONLY)
    exit;
}
// Loop over the result set
while ($result = mysql_fetch_assoc($query_users)) {
    echo "User name found: {$result['username']}\n";
}

However, I really urge you to reconsider using the old ext/mysql API to interface with your MySQL database in PHP since it is deprecated and has been discouraged from use for quite some time. I would really urge you to start using the new alternative APIs such as PDO or MySQLi and see the guide in the manual for help with choosing an API.
In PDO, for example this process would be quite simple with prepared statements and parameterized queries as you don't have to worry about all this escaping.
There's an example in the PDOStatement::Execute page (Example #5) that shows you just how to do use the IN clause that way with prepared statements... You can then reuse this statement in other places in your code and it offers a performance benefit as well as making it harder for you to inadvertently expose yourself to SQL injection vulnerabilities.
// Connect to your database
$pdo = new PDO("mysql:dbname=mydb;host=127.0.0.1", $username, $password);

// List of admins we want to find in the table
$admins = array("username","username2","username3");

// Create the place holders for your paratmers
$place_holders = implode(',', array_fill(0, count($admins), '?'));

// Create the prepared statement
$sth = $dbh->prepare("SELECT username FROM usrsys WHERE username IN ($place_holders)");

// Execute the statement
$sth->execute($admins);

// Iterate over the result set
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo "We found the user name: {$row['username']}!\n";
}

Your PHP code even looks so much better with PDO :)

A: If your looking for syntax to pull in only the users from your $admins array then you could use something like:
$users="SELECT username FROM usrsys WHERE username IN ('".join("','",$admins)."')";

Where the php function JOIN will print username,username2,username3. Your resulting MySQL statement will look like:
SELECT username FROM usrsys WHERE username IN ('username','username2','username3')

Alternatively, if your looking to iterate through your $query_vars array and separate your admins from non-admins then you could use something like:
<?php
while($row = mysql_fetch_assoc($query_users)){
    if(in_array($row['username'],$admins)){
        //do admin stuff here
    }else{
        //do NON-admin stuff here
    }
}?>

A: Just include admins.php file and use the next construction in your loop:
while ($row = mysql_fetch_array($users)) {
if (in_array($users[0], $admins))
    echo $users[0];
}

A: Try this:
<?php
# include admins.php file that holds the admins array
include "admins.php";

# join all values in the admins array using "," as a separator (to use them in the sql statement)
$admins = join(",", $admins);

# execute the query
$result = mysql_query("
    SELECT username
    FROM usrsys
    WHERE username IN ($admins)
");

if ($result) {
    while ($row = mysql_fetch_array($result)) {
        echo $row["username"] . "<br>";
    }
}
?>


text:
Q: How does really work rendering in browser (event loop) I've created simple demos, let's get started...
Should to say what we have to use chrome and firefox for comparison
Demo 1:

block.addEventListener("click", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "";
    block.style.transition = "transform 1s ease-in-out";
    block.style.transform = "translateX(100px)";
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

In both browsers, we'll not see any changes
Demo 2:

block.addEventListener("click", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "";
    requestAnimationFrame(() => {
      block.style.transition = "transform 1s ease-in-out";
      block.style.transform = "translateX(100px)";
    });
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

In chrome we'll see animation, in firefox we'll see another thing. Need to mention that firefox conforms actions from video of Jake Archibald in the Loop. But not in case with chrome. Seems that firefox conforms to spec, but not chrome
Demo 2 (alternate):

block.addEventListener("mouseover", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "";
    requestAnimationFrame(() => {
      block.style.transition = "transform 1s ease-in-out";
      block.style.transform = "translateX(100px)";
    });
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

Now we see that chrome works correctly, but firefox does same thing as chrome was doing on Demo 2. They has changed by theirs places
I've also tested events: mouseenter, mouseout, mouseover, mouseleave, mouseup, mousedown. The most interesting thing that the last two ones work same in chrome and firefox and they are both incorrect, I think.
In conclusion: It seems what these two UAs differently treats events. But how do they do?
Demo 3:

block.addEventListener("click", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "";
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        block.style.transition = "transform 1s ease-in-out";
        block.style.transform = "translateX(100px)";
      });
    });
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

Here we see that firefox works as well as chrome, how this expects, by the Archibald's words. But do you remember demo 2, both versions, why their behaviour is so different?

A: TL;DR; if you want your code to work the same everywhere force a reflow yourself after you set the values you want as initial ones.

block.addEventListener("click", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "";
    requestAnimationFrame(() => {
      // if you want your transition to start from 0
      block.style.transform = "translateX(0px)";
      // force reflow
      document.body.offsetWidth;
      block.style.transition = "transform 1s ease-in-out";
      block.style.transform = "translateX(100px)";
    });
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

What you are stumbling upon here is called the reflow. I already wrote about it in other answers, but basically this reflow is the calculations of all the boxes in the page needed to determine how to paint every elements.
This reflow (a.k.a layout or recalc) can be an expensive operation, so browsers will wait as much as they can before doing this.
However when this happens is not part of the event loop's specifications. The only constraint is that when the ResizeObserver's notifications are to be fired this recalc has been done.
Though implementations can very well do it before if they wish (Safari for instance will do it as soon as it has a small idle time), or we can even force it by accessing some properties that do require an updated layout.
So, before this layout has been recalculated, the CSSOM won't even see the new values you passed to the element style, and it will treat it just like if you did change these values synchronously, i.e it will ignore all the previous values.
Given both Firefox and Chrome do wait until the last moment (before firing the ResizeObserver's notifications) to trigger the reflow, we can indeed expect that in these browsers your transition would start from the initial position (translate(0)) and that the intermediate values would get ignored. But once again, this is not true for Safari.
So what happens here in Chrome? I'm currently on my phone and can't make extensive tests, but I can already see that the culprit is the line setting the transition, setting it first will "fix" the issue.

block.addEventListener("click", () => {
    block.style.transform = "translateX(500px)";
    block.style.transition = "transform 1s ease-in-out";
    requestAnimationFrame(() => {
      block.style.transform = "translateX(100px)";
    });
});
.main {
  width: 100px;
  height: 100px;
  background: orange;
  }

Since I have to make a guess I'd say setting the transition probably makes the element switch its rendering path (e.g from CPU rendered to GPU rendered) and that they will force a reflow doing so. But this is still just a guess without proper testings. The best would be to open an issue to https://crbug.com since this is probably not the intended behavior.
As to why you have different behavior from different events it's probably because these events are firing at different moments, for instance at least mousemove will get throttled to painting frames, I'd have to double check for mousedown and mouseup though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cannot see HOSTNAME field in /etc/sysconfig/network file in RedHat Linux I am trying to set up HOSTNAME to a machine , but I am unable to find the HOSTNAME field in the /etc/sysconfig/network file
all I can see is this below
# Generated by anaconda
NETWORKING=yes
NTPSERVERARGS=iburst

Can anyone let me know how can I change the HOSTNAME in this scenario ?

A: There is a utility available in RHEL to permanently set the hostname:
sudo hostnamectl set-hostname newhostname

Alternatively on RHEL 7 you can simply edit (or create if needed) the file /etc/hostname and add the desired hostname as the only content in the file.
I believe the method you are using is only applicable to RHEL 6 and earlier. If that applies to you, then simply add a hostname field in the format below to that file and reboot:
HOSTNAME=newhostname


text:
Q: Create multiple dataframes based on unique values in a column Hi I am trying to subset the data to state specific data frames and subsequently convert them to XTS objects.
Here is the code I am using.
library(tidyverse)

us <- read_csv(url("https://covidtracking.com/api/v1/states/daily.csv")) # pulling detailed state level data from covidtracking project website
us <- select(us, date, state, cases = positive, hosp = hospitalizedCumulative, icu = inIcuCumulative, death) # selecting columns of interest
head(us)

AK <- filter(us, state == "AK")
AK <- xts(AK[,c(-1,-2)], order.by = strptime(AK$date, format = "%Y%m%d")) %>% na.fill(0)

Instead of doing this process manually for all 50 states one by one, is there an easier way to do this automatically by doing something like this?
state <- unique(us$state)

x <- function(x) {
  x <- filter(us, state == x)
  x <- xts(x[,c(-1,-2)], order.by = strptime(x$date, format = "%Y%m%d")) %>% na.fill(0)
}

Running the function gives me nothing or an error.

A: Consider by (object-oriented wrapper to tapply) which subsets a data frame by one or more factors in a column and (unlike split) passes subsets into a defined method. The return of by is a list of whatever method outputs equal to the number of unique levels of factor(s).
build_xts <- function(x) {
  xts(x[,c(-1,-2)], order.by = strptime(x$date, format = "%Y%m%d")) %>% na.fill(0)
}

xts_list <- by(us, us$state, build_xts)

xts_list$AK
...
xts_list$WY

A: You can try this:
#List
List <- split(us,us$state)
#Process
process <- function(x)
{
  x[is.na(x)]<-0
  y <- xts::xts(x[,c(-1,-2)], order.by = strptime(x$date, format = "%Y%m%d"))
  return(y)
}

List2 <- lapply(List,process)

A: This approach creates a column of xts objects created from each state's data. It's kind of like group_by and summarize but the output is a list of objects instead of an atomic vector. I chose to use tidyverse verbs for subsetting, but you could use [[ as well.
You could also look into tibbletime/tsibble to stay in the tidyverse. Also check out the purrr package for more information on the map family of functions.
library(tidyverse)
library(lubridate)
library(xts)

# pulling detailed state level data from covidtracking project website
us <- read_csv(url("https://covidtracking.com/api/v1/states/daily.csv")) %>%
    select(date,
           state,
           cases = positive,
           hosp = hospitalizedCumulative,
           icu = inIcuCumulative,
           death)

# Create a function that will take a tibble and return an XTS object
build_xts <- function(df) {
    out <- xts(select(df, -c(1:2)),
               order.by = pull(df, "date"))
    return(out)
}

us %>%
    mutate(date = strptime(date, format = "%Y%m%d")) %>%
    # Create a list-column with the relevant data per state
    nest(data = c(date, cases, hosp, icu, death)) %>%

    # Apply the "build_xts" function to each one
    mutate(time_obj = map(
        .x = data,
        .f = build_xts))

#> # A tibble: 56 x 3
#>    state data               time_obj
#>    <chr> <list>             <list>
#>  1 AK    <tibble [124 x 5]> <xts [124 x 3]>
#>  2 AL    <tibble [123 x 5]> <xts [123 x 3]>
#>  3 AR    <tibble [124 x 5]> <xts [124 x 3]>
#>  4 AS    <tibble [114 x 5]> <xts [114 x 3]>
#>  5 AZ    <tibble [126 x 5]> <xts [126 x 3]>
#>  6 CA    <tibble [126 x 5]> <xts [126 x 3]>
#>  7 CO    <tibble [125 x 5]> <xts [125 x 3]>
#>  8 CT    <tibble [123 x 5]> <xts [123 x 3]>
#>  9 DC    <tibble [125 x 5]> <xts [125 x 3]>
#> 10 DE    <tibble [124 x 5]> <xts [124 x 3]>
#> # ... with 46 more rows

Created on 2020-07-08 by the reprex package (v0.3.0)


text:
Q: Show button after the text but not outside the cell I have the following code:

    Can be long, can be short
    <button>Test</button>

td{
  white-space: no-wrap;
  width:175px;
  position: relative
}
button{
  position:absolute;
  right: 15px;
  bottom: 5px;
}

What I get is

I want to show name in one line (even if it is outside the cell), but button should be always in cell (on the same line).
If name is short then it should be right after the name, if not then stick to the right of cell.
I used absolute positioning, but in this case button always sticks to the right of the cell. Not what I need for short names.
So, picture for long name is what I need, but for short name I want yellow button to show near name, not stick to the right side.
Working jsfiddle: https://jsfiddle.net/8kchkucv/
Is it possible to do this with CSS?

A: Andrew what you are asking is not possible with having only one css for both the buttons, either you can have something like this jsfiddle
https://jsfiddle.net/rohts76/8kchkucv/1
.but
{
  cursor: pointer;
  padding: 2px 5px;
  margin: 5px 0px 0px 5px;
  border-radius: 5px;
  font-family: 'Pacifico', cursive;
  font-size: 10px;
  color: #FFF;
  text-decoration: none;
  background-color: #F2CF66;
  border-bottom: 1px solid #D1B358;
  text-shadow: 0px -2px #D1B358;
  position:absolute;
  //right: 15px;
  bottom: 5px;
}
.cell{
  white-space: nowrap;
  width:175px;
  position:relative;
}
.cell div{
    margin: 0;
    padding: .35em;
    float: left;
    width: 100%;
    height: 100%;
}
tr{
    background-color: #8db4e3;
    background-size: 100% 100%;
}

This code will give you correct thing..


text:
Q: How to get single Flex Object by its property value like search() can for Flex Collection According to https://learn.getgrav.org/17/advanced/flex/using/object#712b8c68bf0 we can get a single Flex Object from a Flex Collection by the key of the object:
{% set contact = grav.get('flex').object('gizwsvkyo5xtms2s', 'contacts') %}

However, I think in most cases we don't know the key and would like to get an object by the value of its property for example by a string in the title.
As to Flex Collection, we have the method search() if we want to get modified collection by a string in property value and of course we can use this to get collection with one item.
But is there the same method to get a single Flex Object?
I see there is the method search() for the Flex Object too. But as I can understand, it's just to determine whether a property contains a string or not only AFTER we have already got the object by its key.
Or if I'm wrong and we can get a single Flex Object by this search() method, then how to do that in Twig template? Can you post an example?
So I need something like
{% set contact = grav.get('flex').object('contacts').search('Michael', ['first_name'], {'contains': true}) %}

A: I don't believe there is a function that returns an object by a given property:value.
Instead, you can use collection.filterBy({ 'first_name': 'michael' }). https://learn.getgrav.org/17/advanced/flex/using/collection#filterby
If you're certain that michael is going to be a value unique to that object and you just want to render it without looping through a collection, you can use Twig's |first filter to access the first (only) object in the collection.
{% set contacts = grav.get('flex').collection('contacts') %}
{% set collection = contacts.filterBy({ 'first_name': 'michael'}) %}

{{ collection|first.first_name }}


text:
Q: Have div and span based on the number of elements My intention is to create class="dot" based on the number of elements in the array called count, then use the following for loop:
for(var i = 0; i < count.length; i++)
So what I want to get is a single  where the currentSlide argument is automatically updated based on the for loop, therefore having i in place of 1,2,3 etc.
Is it possible to do this? Can you help me? I'm new to html and javascript.

A: This should work by using template literal.

var slideIndex = 1;
//showSlides(slideIndex);

function currentSlide(n) {
  showSlides(slideIndex = n);
}

var count = ['img1', 'img2', 'img3', 'img4']
for (var i = 0; i < count.length; i++) {
  document.querySelector('div').innerHTML += `

 `
}
console.log(document.body.innerHTML)

OR:

var slideIndex = 1;
//showSlides(slideIndex);

function currentSlide(n) {
  showSlides(slideIndex = n);
}

var count = ['img1', 'img2', 'img3', 'img4']
for (var i = 0; i < count.length; i++) {
document.body.innerHTML += `

 `
}
console.log(document.querySelectorAll('span'))


text:
Q: SAM S70 Microcontroller - Need to use 2 functions on one pin I need to connect a SAM S70 (ARM® Cortex®-M7 based microcontroller) to both a camera and an eMCC FLASH.  The problem is that the PA27 pin has both MCDA3 and ISI_D7 as PIO Peripheral functions.  How do I handle this?  Do I have to switch the function of the pin each time, meaning I can only use one device at a time?  Is there something else I can do?

A: You cannot assign the functions to another pin.  Other packages in the same processor family have the same issue.  I found some ST processors that might have worked, but none are available (Jan 2022).  Two possiblilties for using the S70 processor with the camera and eMMC interface are actually switching the functions of the pin (which means that both cannot be used at the same time) or using the one data wire configuration in the MMC interface.


text:
Q: Size of interline in pt? I need to write a document with a font of 12pt and 18pt of interline (EXACTLY). I used the \linespread{X}\selectfont command line to increase the interline size... but I do not know how much I must put for X to have 18pt. Do you know how to properly define X to get 18pt for each interline ?
Thanks !

A: TeX uses three primitive registers which control the interline spaces. First of them is \baselineskip. If the two followed lines are not overlapped in sense of \lineskiplimit register then \baselineskip is used as the distance of two following baselines. The "overlapping in sense of \lineskiplimit register" (it is set to 0pt by default but it should be positive or [more usual] negative) means: the distance between biggest descender in the first line and the biggest ascender in the second line (when the rule with \baselineskip is tried) is greater or equal to \lineskiplimit. If such condition is not true then \baselineskip is not used for these two lines at all, but the \lineskip is inserted between such lines (default 1pt by plain TeX).
Examples: if you set \lineskiplimit to sufficient negative value then all lines have \baselineskip distance independent of they are overlapped or not.
If you set \lineskiplimit and \baselineskip to 0pt then \lineskip is inserted between all lines and the baseline grid is typically lost.
Note, that \baselineskip nad \lineskip are "skip" registers (they may include stretchability and/or shrinkability) but \lineskiplimit is "dimen" register.

A: When metal type was used, characters were cut on pieces of metal having all the same size, independent of ascenders and descenders

Source: http://designwithfontforge.com/en-US/The_EM_Square.html
(Note that the picture has been mirrored in order to ease reading.)
Lines could be spaced by inserting strips of metal (mostly made of lead, so "leading").
TeX uses a different model for this, because it just aligns characters by their reference point, so its model is different: it tries to keep a fixed distance between baselines (the amount of the current \baselineskip).
What 18pt leading means is rather ambiguous. As you see, in the picture there is no leading, but the characters don't touch: "yp" is just above "th", but there's some space between them. This is because the height of the piece carrying a character is greater than the sum of maximum height and maximum depth among all characters (the same length as a strut).
So you could refer to 18pt between the deepest possible descender on a line and the highest possible ascender on the next line; or you could measure the 18pt from the depth and height of a strut. This will give quite different results.
The suggested leading package can solve the issue, because it allows specifying the baseline distance in points, rather than computing a factor for \linespread. However, a simplistic
\leading{18pt}

will not do:
\documentclass[12pt]{article}
\usepackage{leading}

\leading{18pt}

\begin{document}

\noindent
\llap{\smash{%
  \vrule height0pt depth \fontchardp\font`y \hskip 1pt
  \vrule height0pt depth \dimexpr\fontchardp\font`y + 18pt\relax
}}by\\
by

\end{document}

The image makes clear that 18pt is the baselineskip.
\documentclass[12pt]{article}
\usepackage{leading}

\AtBeginDocument{%
  \settoheight{\dimen0}{%
    ABCDEFGHIJKLMNOPQRSTUVWXYZ%
    abcdefghijklmnopqrstuvwxyz%
  }%
  \settodepth{\dimen2}{%
    ABCDEFGHIJKLMNOPQRSTUVWXYZ%
    abcdefghijklmnopqrstuvwxyz%
  }%
  \leading{\dimexpr18pt+\dimen0+\dimen2}%
}

\begin{document}

\noindent
\llap{\smash{%
  \vrule height0pt depth \fontchardp\font`y \hskip 1pt
  \vrule height0pt depth \dimexpr\fontchardp\font`y + 18pt\relax
}}by\\
by

\end{document}

Now there are exactly 18pt from the bottom of the y to the top of the b.
If you use accented uppercase characters, you might have to fix the alphabet used for measuring the maximum height and depth.


text:
Q: Using modern list view formatting to alternate row colors I have been looking into using view formatting to alternate the colors of rows in order to recreate what came out of the box in the classic views.
However it seems like I can't access the row ID as a criteria nor can I use Mod as an operator.
I kinda found a work around using a calculated column to do the MOD, but it is not an elegant solution.
Is there really no easy way to alternate the row colors?

A: All Items, Format current view,  put the following in the JSON box.
{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
  "additionalRowClass": "=if(@rowIndex % 2 == 0,'ms-bgColor-themeLighter ms-bgColor-themeLight--hover','')"
}


text:
Q: Displaying data from YouTube JSON Im looking to display:
"subscriberCount": "42", from thsi json document.
$.getJSON( "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCgTe4gCl_pH-RNkgdcndl8g&key=AIzaSyARe-kxioXcvyS-WE3mx6Bo2fAijyG4OWo", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "
" + val + "
" );
  });

  $( "
", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

How do i get this to access subscriberCount a level down in the document?
Edit:
the JSON data looks like this:
{
 "kind": "youtube#channelListResponse",
 "etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/E7mYHJ0kZvDNIuPF1HnDg4A27lc\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/UFziElXqGi6jIN-zE5VbkSt4QvM\"",
   "id": "UCgTe4gCl_pH-RNkgdcndl8g",
   "statistics": {
    "viewCount": "18242",
    "commentCount": "1",
    "subscriberCount": "42",
    "hiddenSubscriberCount": false,
    "videoCount": "104"
   }
  }
 ]
}


text:
Q: Proxy configuration change There used to be an option in proxy configuration that was:
Use this proxy server for all protocols

However, in 12.04, I can't find it. Is there anyway to reproduce its behavior in a handy way? I can't seem to find it.
I tried to install gnome-network-properties to get the old applet back but sadly it's part of gnome-control-center and I have that installed already.
Any hint on how to proceed will be appreciated.

A:
Is there anyway to reproduce its behavior in a handy way?

Well, the handiest way is good old copy-and-paste! (see screenshot below)  Usually an HTTP/HTTPS proxy will not also do FTP/SOCKS, while a SOCKS proxy will handle everything. But if the "Apply to all protocols" setting worked for you before, no reason why it shouldn't now.


text:
Q: server-side data push for web services I´m  a web programmer and I'm experienced in regular synchronous and asynchronous web services. So the normal way to get data from a web server is to request it (pull it) or to establish a permanent connection.
Now I'm asking myself if there is any possibility to run this the other way round so that the server pushes new data to the client without a previous request of the client by using native technologies like HTML5 and Javascript.
Summarized: I'm searching for a way to realise a server side push system what works with any modern web browser (IE, FF, Chrome, Safari,...) by using regular technologies like HTML5 and Javascript without any plugins or additional software.
The client should just listen for new data as long as the web site is opened and the only connection from the server should happen if new data gets pushed. It must work even through NAT or Firewalls.
Well main reason is to save server load and data transfer with many connected clients. Please also mind that not each push will be a broadcast, single client push must also be available.
Is this somehow possible or still no way to handle it without extra software?
Thank you

A: Though it's not implemented in all browsers yet, you can try using the standard Web Push API.
You can read more on it in the articles Using the Push API & Push Notifications on the Open Web.
The Push API is a W3C standard to let you enable users of your Web app to get push notifications at any time—even in the background; i.e., even when your Web app isn't running in the foreground on the user's device (or even when the browser's not currently running on the user's device).
It uses Service Workers to handle messages sent using common push services, and to allow your Web app to react to the push notifications it receives.
It exposes a new push event to scripts. Here's a simple code example from the Push Notifications on the Open Web article that shows how to use that push event to show an actual notification.
self.addEventListener('push', function(event) {
  console.log('Received a push message', event);

  var title = 'Yay a message.';
  var body = 'We have received a push message.';
  var icon = '/images/icon-192x192.png';
  var tag = 'simple-push-demo-notification-tag';

  event.waitUntil(
    self.registration.showNotification(title, {
      body: body,
      icon: icon,
      tag: tag
    })
  );
});

Update 2016-02-12
The Microsoft Edge team recently moved the status of Web Push support in Edge to Roadmap Priority: High — We intend to begin development soon. Since Chrome and Firefox have already shipped support for it, that means
once Edge lands that support, you'll be able to send standard push notifications to Edge, Chrome, and Firefox users of your Web apps.

A: There is WebSockets technology, it allows continuous full-duplex connection stream between a client and a server. More detailed here https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications.
WebSocket is standardized  protocol and each server supports it.


text:
Q: Improving sound quality of a video from "abysmal" to understandable I have a series of videos (in WMV format) which are recordings of presentations.
Unfortunately, the audio is awful.
Is there any method that I can use to improve the audio quality at least so the words can be understood?  I'm not expecting crystal clarity, obviously, just understandable.
Any potential solution would preferably work on Windows.

A: You might be able to do some tuning with Audacity, but this is garbled pretty bad. Might take a lot of work to get something workable. Audacity is FOSS, so it should be within your price range.

A: I don't have mig hopes for you to restore the sound even to make it understandable.
It sound like it's either recorded at way too high level, so that it distorts from being cut at the max level, or recorded at too low level through a device that filters out near-silence so that it's cut at the min level.
In either of those cases you have lost a lot of the data. Also, it sounds like it has been compressed quite a bit, which removes even more data.
You could try to adjust the level up or down depending on what the problem is, and applying a band-pass filter to single out the voice frequencies from some of the noise. Then you will see if there is enough left to be made understandable.
This should be available in most programs that can edit sound. I used GoldWave many years ago, but I don't know if it's still around...


text:
Q: Match when paragraph contains sentences from indexes with Elasticsearch I use elasticsearch to create a program allowing to find all the places in a text where the bible is quoted as well as the place where is the verse mentioned
I indexed all the verses of the bible in elasticsearch, each verse is a document
When I do a search by partially typing a verse, I find the right result (even by making mistakes)
How to browse the text to find all the occurrences where a verse (even partial) is cited and thus attribute the source of the verse to them? and tolerating faults (with the fuzziness parameter or using synonyms I think)
Example of my index :
{"index":{"_index":"test","_type":"","_id":1}}
{"fields":{"year":3560,"book":"1","chapter":1,"section":1,"text":"others words consectetur adipiscing and others words"},"id":"test1","type":"add"}
{"index":{"_index":"test","_type":"","_id":2}}
{"fields":{"year":3560,"book":"2","chapter":3,"section":2,"text":"others words a sagittis nisl quam and others words"},"id":"test2","type":"add"}
{"index":{"_index":"test","_type":"","_id":3}}
{"fields":{"year":3560,"book":"3","chapter":1,"section":5,"text":"others words Aliquam ultrices auctor pharetra and others words"},"id":"test3","type":"add"}
{"index":{"_index":"test","_type":"","_id":4}}
{"fields":{"year":3560,"book":"4","chapter":2,"section":4,"text":"others words Proin ut vestibulum and others words"},"id":"test4","type":"add"}
{"index":{"_index":"test","_type":"","_id":5}}
{"fields":{"year":3560,"book":"5","chapter":1,"section":5,"text":"others words Aenean pretium tincidunt aliquet and others words"},"id":"test5","type":"add"}
{"index":{"_index":"test","_type":"","_id":6}}
{"fields":{"year":3560,"book":"6","chapter":2,"section":1,"text":"others words In vitae sagittis and others words"},"id":"test6","type":"add"}
{"index":{"_index":"test","_type":"","_id":7}}
{"fields":{"year":3560,"book":"7","chapter":7,"section":7,"text":"others words ligula laoreet pharetra and others words"},"id":"test7","type":"add"}
{"index":{"_index":"test","_type":"","_id":8}}
{"fields":{"year":3560,"book":"8","chapter":1,"section":4,"text":"others words luctus eros a pretium and others words"},"id":"test8","type":"add"}
{"index":{"_index":"test","_type":"","_id":9}}
{"fields":{"year":3560,"book":"9","chapter":1,"section":7,"text":"others words ullamcorper eu id quam and others words"},"id":"test9","type":"add"}
{"index":{"_index":"test","_type":"","_id":10}}
{"fields":{"year":3560,"book":"10","chapter":5,"section":4,"text":"others words Nullam ac enim ac lacus hendrerit and others words"},"id":"test10","type":"add"}

I need to find all the occurrences in the paragraph which are in the index, in order to recover their sources :

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla rhoncus, nulla vitae porta euismod, purus nisl faucibus nunc, a sagittis nisl quam id arcu. Sed sit amet arcu sed dui auctor bibendum. Proin ut vestibulum sem, id rutrum felis. Phasellus sagittis justo sit amet justo consequat, id scelerisque eros cursus. Quisque dapibus finibus euismod. Proin dui urna, auctor ut gravida quis, fringilla quis velit. Donec sed pulvinar leo. Sed pulvinar pharetra arcu nec egestas. Mauris non dapibus diam. Pellentesque quis pellentesque libero.
  Aliquam ultrices auctor pharetra. Cras ullamcorper, odio sit amet aliquam convallis, magna nibh gravida nunc, sit amet volutpat elit purus eget lectus. Pellentesque eu est a risus euismod consequat. Duis id erat porttitor, sodales justo non, aliquet ex. Etiam tincidunt neque ut nisi commodo auctor. Sed congue urna ac tellus scelerisque hendrerit. Mauris lobortis sed dui ut varius.
  Proin ac luctus felis. In vitae sagittis erat, nec luctus sapien. Aenean pretium tincidunt aliquet. Morbi at enim vel ligula laoreet pharetra. Sed dignissim luctus eros a pretium. Vestibulum molestie molestie nisi, vitae scelerisque nibh bibendum nec. Donec laoreet sapien sed vehicula dictum. Nullam ac enim ac lacus hendrerit tempor et vitae neque. Quisque at leo pretium, efficitur augue vitae, congue eros. Maecenas volutpat ante nec scelerisque vestibulum.
  Donec tristique orci erat, nec imperdiet nulla commodo ut. Nam non odio vel quam cursus ullamcorper eu id quam. Duis volutpat, nisl eu interdum mattis, augue ipsum mollis leo, eget efficitur orci augue eget leo. Integer feugiat facilisis dolor ut vehicula. Maecenas quis feugiat massa. Curabitur feugiat odio eget ligula tincidunt sodales. Donec feugiat dapibus lectus, non maximus dui rhoncus vitae. Phasellus eget massa faucibus, tristique nibh sed, aliquet metus.

I do not know if I have been clear enough but do not hesitate to ask me if you need more precision
I think this problem is handled by the Aho-Corasick algorithm but I don't know how to integrate it into elasticsearch
Thank you!

A: If I am able to understand your question correctly then all you are looking for is to be able to

"some partial verses" : query

and get the source documents from elasticsearch as response with the results showing the searched verse in them (which is what highlighting is)
Here is the simplest of the query to achieve the same
GET <index_name>/_search
{
 "query": {
   "match": {
     "message": "partial verse"
   }
 } ,
    "highlight" : {
        "fields" : {
            "message": {}
        }
    }
}

In response you will get something like this
"hits" : [
      {
        "_index" : "testSample",
        "_type" : "_doc",
        "_id" : "TkdvGXAB5bHyIJQ-QRow",
        "_score" : 0.2876821,
        "_source" : {
          "bookName" : "bible",
          "message" : "this is a good book"
        },
        "highlight" : {
          "message" : [
            "this is a good book"
          ]
        }
      }
    ]

The response is self explanatory , where you get the heighlted results in a different section.


text:
Q: Meaning of word 'synonym' in the given context What is the meaning of Synonym in this context?

Nowadays modern mobile users are very exigent – they want great,
  unique Material design, in-app maps, fast and precise geolocation,
  social (let's use synonym – Facebook  ) sign-in and so on…

I didn't look up a dictionary because I already know what "synonym" means, but I can't fit that meaning to this context. I was expecting "let's use app– Facebook".
Why does the author use the word "synonym"? What do they want to imply?

A:
Users want social sign-in

Is almost synonymous to

Users want Facebook sign-in

Because Facebook is the predominant social network.
Thus the author says:

Users are very demanding nowadays. When a user selects a new app for his smartphone, he wants this app to have a social network sign-in feature. Oh, well, let's just use a synonym. He wants it to have a Facebook sign-in feature.


text:
Q: How can a 'scripts' directory be hooked into wp_head();? So I'm trying to get my head round <?php wp_head(); ?>.
I understand that it loads in the stuff needed for plugins etc., but I'm using a theme that seems to be using it to load in scripts for theme elements as well.
There's a folder within my theme called 'scripts' that appears to have all of the javascript needed for the theme. In the outputted code is all of the javascript files etc.
So my question is: How do I hook in a javascript file (or anything for that matter) into <?php wp_head(); ?>?

A: You use wp_enqueue_script for Javascript files in your theme functions.php files. I suggest wrapping up all the requests in a function and hook it like so
add_action( 'wp_enqueue_scripts', 'script_enqueuer' );


text:
Q: Can a CNN be trained to match two different pictures of the same painted rock? I am trying to design a convolutional neural network that will match two images together. The images will be of painted rocks. One person will paint the rock, take a picture of it and hide it. Another person will find the rock and take a picture of it. I want to CNN to be able to search s database of images and match the photes to indentify the right rock.
I understand how to train a CNN to classify a photo by giving it many examples and then asking it to match a new picture to the category. I am having trouble figuring out a way to train the CNN to match two images together out of one database. The photos will be slightly different because two people are taking a picture of the same rock at different times.
I can reduce the size of the image search on the database by using GPS locations most times but not always. Meaning the person that hides the rock will hopefully record the location and the person finding will also record the location where they found it.  This way the CNN has to only compare let's say six rocks from around that location to the rock the person found. The rock images will have profiles associated with them to allow for communication between the finder and the hider.
Does anyone have any ideas of how I can set this up?


text:
Q: How to define an interface using another interface In Go, how to define an interface using another interface?
Here is an example:
package main

import (
    "fmt"
)

// Interfaces
type Message interface {
    Read() string
}

type MessageReader interface {
    ReceiveMessages([]Message)
}

// Structs
type SQSMessage struct {
    Content string
}

type SQSMessageReader struct {
    Name string
}

// Implements
func (reader *SQSMessageReader) ReceiveMessages([]SQSMessage) {
}

func (msg *SQSMessage) Read() string {
    return msg.Content
}

// A function needs a reader interface
func FuncNeedsReader(MessageReader) {
    fmt.Println("get reader")
}

func main() {
    var reader SQSMessageReader
    FuncNeedsReader(reader)
}

I got error:
./prog.go:40:17: cannot use reader (type SQSMessageReader) as type MessageReader in argument to FuncNeedsReader:
    SQSMessageReader does not implement MessageReader (wrong type for ReceiveMessages method)
        have ReceiveMessages([]SQSMessage)
        want ReceiveMessages([]Message)

Do anyone know if this design is conflicting with Go's design?
I know we have "accept interfaces, return structs"
So I also tried https://play.golang.org/p/qdGaKRYAqw7, but still fail with similar error.

A: I see two problems here.
First:
You have defined your MessageReader interface as:
type MessageReader interface {
    ReceiveMessages([]Message)
}

But you have defined your ReceiveMessages method on SQSMessageReader like this:
func (reader *SQSMessageReader) ReceiveMessages([]SQSMessage) {
}

Because it takes an []SQSMessage parameter rather than []Message, it does not implement the MessageReader interface. You would need to write:
func (reader *SQSMessageReader) ReceiveMessages([]Message) {
}

Second:
You have written:
func main() {
    var reader SQSMessageReader
    FuncNeedsReader(reader)
}

But ReceiveMessages has a pointer receiver (func (reader *SQSMessageReader) ReceiveMessages...), so you would need:
func main() {
    var reader SQSMessageReader
    FuncNeedsReader(&reader)
}

With these two changes, your code builds without errors.


text:
Q: WSO2 -> Active Directory -> user - role mapping I use WSO2 5.0.0 as IdP and the user store is an Active Directory (AD). User and Roles are listed in WSO2 Management console and I'am also being able to login in WSO2 with User/PW stored in AD.
Therefore everything works fine.
The only problem I have is that if I request roles of users (e.g. over RemoteUserStoreManagement- WebService with method getUserClaimValues) than I get the WSO2 roles and not the Active Directory Roles assigned to the users in the AD. Also only the WSO2- Roles are mapped to users in WSO2.
Actually I have only basic knowledge in AD (I haven't adjust the current connection between WSO2 and AD) - therefore I have no idea where I should have a look at in order to resolve this problem.
Has anybody a hint concerning this issue (user-mgt.xml or WSO2 console or ...)
Thanks a lot for help!

A: So,  you need to retrieve the roles of the user? According what you have mentioned, Please do following to resolve this issue.

*

*Please add following attributes under user store manager configuration in user-mgt.xml file, if there are not with the configuration.

<Property name="BackLinksEnabled">true</Property>
<Property name="MemberOfAttribute">memberOf</Property>
Please restart the server and verify.

*Please enable the debug logs in the user kernel and verify where is the issue has been generated.

To enable logs,
Locate log4j.properties file which can be found at /repository/conf directory.
Add following entry in to the file
log4j.logger.org.wso2.carbon.identity.sso.saml=DEBUG
Restart the server and try to invoke the server. You would see LDAP related logs where it would help to identify the issue.


text:
Q: What is the regular expression to match the string after id= in python I am trying to match the string after id= from the below selenium exception so that I can use it in a ui pop up to tell the user which is the attribute causing error.

selenium.common.exceptions.NoSuchElementException: Message: Unable to
  locate element: [id="dragg"]

In this case I am expecting the regex to return dragg
I am not able to create a good regex pattern to match this.
Can anyone help?

A: I am assuming you want all the chars between double quotes,
import re

myStr = """selenium.common.exceptions...... [id="dragg"]"""

print(re.search(r'id=\"([^\"\']*)\"', myStr).group(1))
# dragg


text:
Q: Using a union for multiple interpretations of IP address? At work we have the following construct to enable interpreting an IP address as either an array of 4 bytes, or as a 32-bit integer:
union IPv4
{
    std::uint32_t ip;
    std::uint8_t  data[4];
};

This works fine, but I'm a little worried after reading chapter 97 "Don't use unions to reinterpret representation" of the book C++ coding standards. The example in the book is more insidious though and I'm not sure if it applies to my code.
Are there any potential issues with my code?

A: According to the standard, reading a member of a union other than the last one written is undefined behavior.  Unions were designed to save space, no for data type conversion.  That said, what you are doing will probably work on all mainstream platforms and compilers.

A: No problem, as the represantation is the same you just access ist differently.


text:
Q: blurring a web page background i have seen many websites like msn.com or sulekha.com(although sulekha.com is not in silverlight)  which is said to be in silverlight. and its home page gives blurr effect. But when we right click on the page it does show html. so can any body help me on this?
i don't want to do anything in ??javascript??

A: I think you are referring to the effect whereby the background is "dimmed" or "darkened" while presenting something in the foreground, like a picture or a dialog box. Clicking on the example images on the lightbox page should provide an example of what I mean.
This is done with plain JavaScript and a handy div. First you need a div with some CSS properties so that it can cover the entire page:
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 50;

The last line puts it above everything else. You also need to make it dark but see-through, and initially invisible:
background-color: #000;
opacity: 0.75;
filter: alpha(opacity=75); /* IE */
display: none;

You can now use some JavaScript to make it visible:
document.getElementById("your_div_id").style.display = "";

Edit: I just saw that you don't want to do anything in JavaScript. I don't understand why you're willing to use  Silverlight but not JavaScript, but what do I know?

A: If you are indeed referring to a lightbox/modal dialog, it's doable with CSS only but pretty much a hack.

A: I think you do mean a blurred background (as opposed to just darkened, in which case you can use the CSS3 commands:
.background {
    -webkit-filter: blur(10px);
    filter: blur(10px);

This will only work in Chrome, Safari 6+, and Opera 15+.


text:
Q: SAS: adding a column with if how to create a column with if construction? for example create JOB column with values from column NAME with job names
if name="actor" then job = 1 , elseif name="analyst" then job = 2 ...etc

A: Well, you almost have it.  It's really simple:
data new;
set old;
if name = 'actor' then job=1;
else if name = 'analysts' then job = 2;
run;

Seems like you could of figured this out by yourself


text:
Q: Get Groupname after using groupby.size() I am using a Billboard-Charts dataset which looks like this:

I want to write a function that receives an arbitrary number of artists as parameters. From these artists, i want to determine the one whose songs have been in the charts the longest. I already managed to write the function i wanted but there is one thing i can't figure out:
How can i get the name of the song which was in the Charts the longest? I just can't figure how to access the groupname after using the .size() function.
def determine_most_popular_performer(*performers):
    results = []
    for performer in performers:
        results.append((performer, max(df.loc[df["performer"]==performer].groupby("song").size())))
        return max(results)

print(determine_most_popular_performer("Queen", "Prince", "Michael Jackson"))
>> ('Queen', 44)

As an output i would want ('Queen', 'Bohemian Rapsody', 44)

A: You can access the max row with .idxmax().
You should then be able to select that row and access the values in that row with the following changes. Note that I used .reset_index() to set the groupby index as a column.
def determine_most_popular_performer(*performers):
    results = []
    for performer in performers:
        df2 = df.loc[df["performer"]==performer].groupby("song").size().reset_index(name="value")
        max_id = df2["value"].idxmax()
        results.append((performer, df2.loc[max_id]["song"], df2.loc[max_id]["value"]))
        return max(results)


text:
Q: Find if 2 vectors are equal in python Ok so here is my class:
class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
    elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
    self.D = labels
    self.f = function

I need help creating a function that takes in two vectors, lets say:
u = Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
v = Vec({'A','B','C'},{'A':1})

the function equal:
equal(u,v)

should return:
false

So far I've tried this:
v = Vec({'x','y','z'},{'y':1,'x':2})
u = Vec({'x','y','z'},{'y':1,'x':0})

def equal(u,v):
    "Returns true iff u is equal to v"
    assert u.D == v.D
    for d in v.f:
        for i in u.f:
            if v.f[d] == u.f[i]:
                return True
            else:
                return False
print (equal(u,v))

I get true which is incorrect because it's only looking at the last value: 'y':1, how can I check for both?

A: The method that you are trying to implement has already been done for you. You can use the set equality and the dictionary equality operator. I ask you not to make a function called equal and instead use __eq__ which allows the use of == on class instances.
Here's what you can do
def __eq__(self, anotherInst):
    return self.D == anotherInst.D and self.f == anotherInst.f

Read about the __eq__ method in the Python Docs
Test Run after applying the changes -
>>> u = Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
>>> v = Vec({'A','B','C'},{'A':1})
>>> u == v
False

A: You can compare the fields:
def equal(self, u, v):
    return u.D == v.D and u.f == v.f

A: I think just implement a function such as equal is not the best choice. You can implement the __eq__ so you can use == to identify the similarity.
def __eq__(self, v):
    return self.D == v.D and self.f == v.f


text:
Q: How to replace a  with  and saving all attributes

        <button class="ajax left" data-href="" rel="prev"></button>
        <button class="active">1</button><button class="ajax" data-href="/legenda/carrega_destaques/todos/2">2</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/3">3</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/4">4</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/5">5</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/6">6</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/7">7</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/8">8</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/9">9</button>
        <button class="ajax right" data-href="/legenda/carrega_destaques/todos/2" rel="next"></button>

I came to this code with some research:
$("button").on('load',function(){
    var buttonclass = $(this).attr('class');
    var buttonrel = $(this).attr('rel');
    var buttondatahref = $(this).attr('data-href');
    var buttonText = $(this).html();
    $(this).replaceWith("" + buttonText + "");
            }
});

Im get some error like last button with class "java right" or "java left" save only "java" word and some undefined attribute.
And this will become a userscript to greasemonkey in someway.
If someone can help or know a simply way to do this will be great.

A: I found this solution:
function addEventListener(){
    var replacementTag = 'a';
// Replace all a tags with the type of replacementTag
$('div.pagination>button').each(function() {
    var outer = this.outerHTML;

    // Replace opening tag
    var regex = new RegExp('<' + this.tagName, 'i');
    var newTag = outer.replace(regex, '<' + replacementTag);

    // Replace closing tag
    regex = new RegExp('</' + this.tagName, 'i');
    newTag = newTag.replace(regex, '</' + replacementTag);

    $(this).replaceWith(newTag);

});
}


text:
Q: qsort() from stdlib.h is not sorting a spezified structure containing zip-codes and corrresponding city I'm using this gloabal crisis to study C beside my studies and i am following a german book (Rheinwerk Computing: C von A bis Z, ANSI-C99) and finally reached searching functions. As a practice I wanted to implement a sorting function to provide the functionallity of a binaray search.
My problem is, that whenever i add a new zip-structure they won't get sorteted. I was looking through different qestions here already and found out how to build a comparsion function for structures and how to handle structs with qsort. But it seems like that the answers didn't help or i am probably to dump to see it.
Technical enviorment:
I use vim and gcc (FLAGS: -Wpedantic -Wstrict-aliasing -Wshadow -Wcast-align -Wextra -Wfloat-equal) on a 32-Bit debian subsystem for windows. Since gcc is not complaining about anything while compiling the code, i wonder what i made wrong.
My code:
struct zipc
{
   char place[255];
   unsigned int zip;
};

struct zipc zipcodes[100];

static int N; //Counting how many adresses are already typed in

// create new zip with city, init function creates one with N=0 and dummy values

void insertbs(unsigned int p, char *o)
{
    zipcodes[++N].zip = p;
    strcpy(zipcodes[N].place, o);
}

int cmp_uinteger(const void *value1, const void *value2)
{
   const struct zipc *p1 = value1;
   const struct zipc *p2 = value2;

   if(p1->zip > p2->zip)
        return 1;
   if(p2->zip > p1->zip)
        return (-1);
   else
        return 0;
}

//usage of qsort later in main

qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);

The cmp_uinteger function is inspired by annother question here and seems to be pretty nice but the sort always fails, but not in a way that the program fails. The program is running but if one inserts zip codes in abitrary order, binary search fails, that's why i thinks it's about qsort() but i although can be somewhere else. I think i don't really get the point for the comparsion function maybe somebody can explain that too.
It feels strange to post my first question here because stack overflow become my second home during the C tutorial :D
Best greets,
Maleware

A: qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);

Third argument of qsort() "Size in bytes of each element in the array".
In your case it should be sizeof(struct zipc) instead of sizeof(unsigned int).

A: With a dummy value at zipcodes[0], sort from zipcodes + 1 and use the size of an array element - easier to code right, review and maintain than attempting to code the size of a type (which was the wrong type in OP's code)
// qsort(zipcodes, N-1, sizeof(unsigned int), cmp_uinteger);
qsort(zipcodes + 1, N-1, sizeof zipcodes[0], cmp_uinteger);


text:
Q: Can VBScript add properties to objects like JScript? I am playing with Windows Script Host VBScript and I am curious if VBScript is capable of adding/removing properties like JScript can.
For example:
var global = this;

var test = function() {
    if ('greeting' in global) {
        WScript.echo (
            'global has property named greeting with value: ' +
            global.greeting +
            '.'
        );
    } else {
        WScript.echo('global has no property named greeting.');
    }
};

test();
global.greeting = 'Hello, World!';
test();
delete global.greeting;
test();

This code determines the global scope (JScript has no initial access to global scope such as window in browsers or global in Node.js, so I have to find it myself).
The test() function checks if the global object has a key named "greeting", and reports its current state as output.
The code does an initial test to show that global object has no greeting key, then sets the greeting property, then does a second test to show that the greeting key has been added to the global object. After this, the greeting property is deleted and a third test is run to show that the key is no longer a part of the global object.
Is this possible to replicate in VBScript?
I know VBScript has Scripting.Dictionary object that can be used to store such information, but I am curious if there is a way to hook existing objects with new properties and delete such properties in VBScript, or if VBScript has no parallel to JScript's {} construct other than Scripting.Dictionary or Classes (whose properties are immutable).

A: Your specific example could be emulated with something like this:
Set global = CreateObject("Scripting.Dictionary")

Sub test
    If global.Exists("greeting") Then
        WScript.Echo "global has property named greeting with value: " & _
            global("greeting") & "."
    Else
        WScript.Echo "global has no property named greeting."
    End If
End Sub

test
global("greeting") = "Hello, World!"
test
global.Remove("greeting")
test

but in general patching objects, or even regular inheritance, is not supported in VBScript. The best you could do to extend a class is wrap it in a class of your own:
Class MyClass
    Private nested_

    Public Sub Class_Initialize
        Set nested_ = CreateObject("Some.Other.Class")
    End Sub

    Public Function Foo(val)          'wrapped method
        Foo = nested_.Foo(val)
    End Sub

    Public Function Bar(val)          'patched method
        x = nested_.Bar(val)
        Bar = x * 42
    End Sub
End Class


text:
Q: Good usage of managed entities / proxies with ORM I'm currently thinking about how i handle my domain objects along with hibernate considering the following :

*

*My model object are directly annotated with JPA annotation, no entity layer.

*On some database heavy operation, i don't mind tuning my code so i take full advantages of the proxies, even if we can consider it as a leak of abstraction/implementation masking. Of course i prefer when i can do otherwise.

*Because i don't have entity layer, i don't have a DAO layer, the entity manager is considerered itself as a DAO layer (related : I found JPA, or alike, don't encourage DAO pattern)

However i was thinking about improve what i'm doing know in order to reduce a bit the complexity, or at least, relocate that complexity in a place it fits better, like entity's related service. And maybe more abstract the fact that i'm using an ORM.
Here is a generic CRUD Service from which all my business service inherits. This code is to show you how things are done currently (annotation, logs remove for clarity) :
public void create(T entity) {
    this.entityManager.persist(entity);
}
@Transactional(value = TxType.REQUIRED, rollbackOn=NumeroVersionException.class)
public void update(T entity) throws NumeroVersionException{
    try{
        this.entityManager.merge(entity);
    }catch(OptimisticLockException ole){
        throw new NumeroVersionException("for entity "+entity, ole);
    }
}

public T read(int id) {
    return this.entityManager.find(entityClass, id);
}
public void delete(int id) {
    T entity = this.entityManager.getReference(entityClass, id);
    this.entityManager.remove(entity);
    // edit : removed null test thanks to @JBNizet
}

The problem with this kind of implementation, is that if i want to create an object, then use the advantages of the proxies i basically have to create it then refetch it. Of course the query may not hits the database but hits only hibernat's cache (not sure about it though). But that means i still have to not forget to refetch the proxy.
This mean i leak the fact that i'm using an ORM and proxies behind the scenes.
So i was thinking to change my interface to something like :
public T read(int id);
public T update(T t)throws NumeroVersionException;
public T create(T object);
public void delete(int id);
List<T> list();

Meaning once i pass an object to this layer, i will have to use the returned value.
And implements update specifically like :
public T update(T t){
    if(!(t instanceof [Proxy class goes there])){
        //+ check if it is a detached proxy
        entityManager.merge(t);
    }
}

Since merge hits the database every time called, for some operation involving just some 10ish entities this can be annoying i wouldn't call it in an update method with a proxy.
Of course I expect to have some edge cases where i'll need the entityManager to flush things and so on. But i think this would reduce significatively the current complexity of my code and isolate better the concerns.
What i'm trying in short is to relocate the ORM code within the service so i can hide the fact that i'm using an ORM and proxies and use the interface like i was using any other implementation without loosing the benefits of using an ORM.
The question is so :

*

*Is that new design a good idea towards this idea ?

*Did i miss anything about how to handle this properly ?

Note : Even though i'm talking about performance, my concern is also about isolation of concerns, maintenability, and easier usability for developers that aren't familiars with ORMs and Java which i work with.

A: Thanks to @JBNizet i'm seeing some thing more clearly :

*

*I should use the value returned by merge() method.

*A managed entity is not always a proxy.

*I don't have to abstract the fact that i use managed entities, this will lead to complex and unefficient code

*I choosed JPA i won't switch for it which is true unless rewriting the full model to stand for something based on non relationnal database.

So i'll just change my update method from the original code and i'll keep the rest.


text:
Q: Error in binding SqlDataSource data to GridView I am getting this error:

Databinding methods such as Eval(), XPath(), and Bind() can only be
  used in the context of a databound control.

I am trying to bind SqlDataSource's results to a GridView.
This is the code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataSourceID="grid_getbranch" Height="111px" Width="91px">
    <Columns>
        <asp:TemplateField HeaderText="branch" SortExpression="branch">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("branch") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("branch") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="name" SortExpression="name">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="grid_getbranch" runat="server"
    ConnectionString="<%$ ConnectionStrings:svpolyConnectionString %>"
    SelectCommand="SELECT branch.branch, course.name FROM branch INNER JOIN course ON branch.c_id = course.id WHERE (branch.c_id = @c_id)">
    <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList2" Name="c_id"
            PropertyName="SelectedValue" />
    </SelectParameters>
</asp:SqlDataSource>

A: Can you try changing your SelectCommand query to:
SELECT branch.branch AS branch, course.name AS name FROM branch INNER JOIN course ON branch.c_id = course.id WHERE (branch.c_id = @c_id)

I'm not sure it's causing your error, but it's the first thing I would try.

A: Remove Binding to the Label field.
Also refer to this question How to 'bind' Text property of a label in markup


text:
Q: Google OAuth / OpenID - use branded login page I'm building a stacked identity provider (using SimpleSAMLphp).  I have successfully integrated with several OpenID and OAuth providers.  This includes Google using OpenID and now upgraded to OAuth 2.0.
The issue I'm having is that I also have a domain in Google Apps.  I'd like to integrate with Google again, but have the login page show my themed / branded login page.  This domain is not utilizing SSO, just a standard Google based login page.
I can't seem to find any options to control which page is shown ... i.e. I can only get the generic Google page to show.
Am I missing something or is this left out by design?


text:
Q: Find whole line that contains word with php regular expressions I want to search for a word "session" in a text. But I would like to retrieve the whole line in which this word appears. So far I have come up with this.
$pattern="[^\\n]*session[^\\n]*";
preg_match_all($pattern,$content, $matches, PREG_OFFSET_CAPTURE);

But I get an error "Unknown modifier '*'". Any ideas how to make such an regular expression?

A: Your regular expression is missing delimiters, hence your error:
$pattern = "/[^\\n]*session[^\\n]*/";
// or, with single quotes, you don't need to escape \n
$pattern = '/[^\n]*session[^\n]*/';

If I interpret your intentions correctly, you're trying to match zero-or-more not newlines, followed by "session", followed by zero-or-more not newlines.
A simpler (potentially more correct) pattern would be this:
$pattern = '/^.*\bsession\b.*$/m';

That is, from the start of a line (^) match 0 or more of any character (.*), a word-boundary (\b), the word "session", another word boundary, another series of characters, and the end of the line ($), matching over multiple lines (m modifier).
You've sort of reinvented the anchors (^ and $) with [^\n] which is somewhat non-obvious, but missed the word boundaries, which is probably not desired as you're matching any word that contains the word "session". That is, yours would match a line containing "sessions" or "possessions" or "obsessions" or "abcsessionxyz", where mine wouldn't; if this isn't desired, you can remove the \b's yielding /^.*session.*$/m and our patterns will be more or less equivalent.
Here's a proof-of-concept, finding the entire middle line which contains the word:
<?php

$lines ="This is a test
of skipping the word obsessions but
finding the word session in a
bunch of lines of text";

$pattern = "/^.*\bsession\b.*$/m";

$matches = array();
preg_match($pattern, $lines, $matches);

var_dump($matches);

Output:
array(1) {
  [0]=>
  string(29) "finding the word session in a"
}

Your pattern would have found the line "of skipping the word obsessions but".


text:
Q: Elasticsearch-dsl nested filtering I'm using elasticsearch-dsl library and my Documents are like these:
class Market(InnerDoc):
    market_no = Integer()

class Event(Document):
    event_id = Integer()
    markets = Nested(Market)

I want to get all Events and within these Events I want to filter some markets. How can I achive this by using elasticsearch-dsl?
Example data:
events = [
    {'event_id': 1, 'markets': [{'market_no': 1}, {'market_no': 2}, {'market_no': 3}]},
    {'event_id': 2, 'markets': [{'market_no': 1}]},
    {'event_id': 3, 'markets': [{'market_no': 1}, {'market_no': 11}]}
]

I want all events and within these, filtering markets that market_no lower or equal to 2.
results = [
    {'event_id': 1, 'markets': [{'market_no': 1}, {'market_no': 2}]},
    {'event_id': 2, 'markets': [{'market_no': 1}]},
    {'event_id': 3, 'markets': [{'market_no': 1}]}
]

Thanks.

A: In order to get events which has at least one market with market_no <= 2:
Event.search().query(
    Nested(path='markets', query=Range(markets__market_no={'lte':2}))
)

If you want to get all events despite of markets.market_no values (if no markets with market_no <=2 => results in empty markets list for event)
It'll be more complicated but still possible (only query in this example):
from elasticsearch_dsl.query import Nested, Range, Bool, MatchAll

Bool(should=[MatchAll(), Nested(path='markets', query=Range(markets__market_no={'lte':2}), inner_hits={"size": 100})])

You'll have to set inner hits limit by yourself and extract market matches from separate field in the response (it won't be in the _source but under hits.hits.inner_hits.markets)


text:
Q: Where JasperStudio stores .jrxml files? I am migrating from Jasper 5.5.x to 6.4.0, using Jaspersoft Studio (no more iReport), but I noticed that after modifying a few reports, JRXML files are not modified (at least not in the folder where .jrxml and .jasper are, from where I opened it). they are in the "workspace".
How can I make Studio to save the jrxml in the same place that .jaspers?

A: Usually they are saved in the same folder but I don't have experience in migrating from iReport.
You can change the directory where Jasersoft Studio saves the files by right-clicking on your project in the Project Explorer and selecting Properties.
On the left side you select Resources->Linked Resources. Under Path Variables you can set the PROJECT_LOC variable.
Hope this helps


text:
Q: Kafka Streams application issues with version 0.10.2.0 I had an existing Kafka Streams application which was working fine with 0.10.1.1. Updated to the new 0.10.2.0 Kafka Streams library along with the new broker as well (although the new library is backward compatible with 0.10.1.1). Quick background

*

*I have a REST API built on top of the interactive query metadata based API

*It searches the local store and also queries remote store (using the StreamsMetadata obtained by KafkaStreams.allMetadataForStore method)

*Use the application.server config param in order for this to work

Application is working fine with a single application instance. As soon as I start another instance and query the store via the REST, I experience the following issues
If I execute the search on the node which started first, the local store search failed with this exception
SEVERE: Error - the state store, my-store, may have migrated to another instance.
org.apache.kafka.streams.errors.InvalidStateStoreException: the state store, in-memory-avg-store, may have migrated to another instance.
        at org.apache.kafka.streams.state.internals.StreamThreadStateStoreProvider.stores(StreamThreadStateStoreProvider.java:49)
        at org.apache.kafka.streams.state.internals.QueryableStoreProvider.getStore(QueryableStoreProvider.java:55)
        at org.apache.kafka.streams.KafkaStreams.store(KafkaStreams.java:699)
        **at mycode.getLocalMetrics(myclass.java:121)**
        **at mycode.remote(myclass.java:98)**
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)

If I execute the search on the new node, the local store search was fine, but I see a nullpointer in the .forEach(new Consumer() line
ks.allMetadataForStore(storeName)
                    .stream()
                    .filter(sm -> !(sm.host().equals(thisInstance.host()) && sm.port() == thisInstance.port())) //only query remote node stores
                    .forEach(new Consumer<StreamsMetadata>() {
                        @Override
                        public void accept(StreamsMetadata t) {
                            //some logic
                        }

                    });

What could I be missing ??

A: Maybe you need to add a little 'sleep-time' for the creatation of StreamsMetadata.When i comment out the Thread.sleep(1000L);,i have the same error.
    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();

    Thread.sleep(1000L);//If commented out,error occur
    System.out.println(streams.allMetadataForStore("statestore").size());

A: If you start multiple instances, store might migrate from one instance to another. If you collect the metadata about store location before a store migrates, you metadata is not correct anymore. Thus, you need to refresh your metadata (ie, collect it again).
The exception org.apache.kafka.streams.errors.InvalidStateStoreException: the state store, in-memory-avg-store, may have migrated to another instance indicates that your meta data is stall.
So you can catch this exception  and retry to recover from it.

A: Based on Matthias J. Sax comments, one can load stream store inside stream statelistener like below
streams.setStateListener((newState, oldState) -> {
   if (newState == State.RUNNING && oldState.REBALNCING) {
      System.out.println(streams.allMetadataForStore("statestore").size());
   }});


text:
Q: How to spell the word 'trie'? In computer science, there is a word trie. It is  pronounced either /tri:/ or /trai/. However, according to the common spelling rule, "When two vowels go walking, the first one does the talking", the pronunciation is not reasonable. I want to know how to spell this word correctly.

A: A trie is spelled thusly and sounds like the word try or tree, but actually comes from the word retrieval.
Because the source word's trie sounds like tree, this can be one valid pronunciation. On another, it is obvious that on its own, trie can look like it should be pronounced try, especially when it is intended to sound audibly different from tree when in verbal discussion.

A: It is spelled "trie."
Since it is a new word, people can pronounce it however they want to. Do you not think the first option is 'reasonable,' since the term trie comes from retrieve?
Do you not think the second option is reasonable in an attempt to make it sound different from the word tree?
Welcome to English. We don't have either standardized or reasonable spelling/pronunciation. This ain't Mandarin.
Edit: in other words, few native English speakers are going to pay attention to that 'common spelling rule,' simply because such spelling 'rules' are only descriptions of certain patterns. Outside of that, since the sound system of English does not correspond to the orthography, native speakers have a variety of possible spellings and/or pronunciations for any new word that may come along. And the choices we make may not seem reasonable to a non-native speaker...


text:
Q: Packaging multiple models from Azure ML experiment So I have started to create a MLOps pipeline that is training multiple models within multiple pipeline steps.
The picture below is the graphical representation of the coded pipeline steps within the Azure ML Studio.

These steps run fine and both the end steps produce the models I want (Train Data - Non EOW TFIDF and Train Data - EOW TFIDF)...
However this is where I get stuck with registering and packaging the model parts for deployment. These models get produced and stored within the individual pipeline step (see below for the model output of Train Data - Non EOW TFIDF)

but I don't know how I would register the model outputs from both pipeline steps together as the docs I have read for registering a model seem to only reference the ability to register one model from one path.
https://learn.microsoft.com/en-us/python/api/azureml-core/azureml.core.model.model?view=azure-ml-py#register-workspace--model-path--model-name--tags-none--properties-none--description-none--datasets-none--model-framework-none--model-framework-version-none--child-paths-none--sample-input-dataset-none--sample-output-dataset-none--resource-configuration-none-
Basically, is it possible to produce multiple model outputs from multiple pipeline steps and register them together as one??
Thanks in advance for the help!

A: Here is sample for Multi-model Register and deploy. https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/deployment/deploy-multi-model/multi-model-register-and-deploy.ipynb


text:
Q: TSQL Loop through two queries to insert into another table For Example, say I have two tables
Product(id, name)
Company(id, name)

I want to loop through every product and every company in order to build a related table(already built so I would use an insert here).
CompanyProduct(companyId, productId)

I have never done a loop with TSQL. I know easily how to do this with LINQ, but TSQL should be faster for the amount of records I want to do this with.An
Seeing as I am looking at having to build upwards of 80,000 - 150,000 new records every time this is used what is the most efficient way I could go about this? Thanks for your help

A: If you simply want a combination of every Product and Company, you are looking for a CROSS JOIN, like this:
INSERT INTO CompanyProduct
SELECT P.id, C.id FROM Product as P CROSS JOIN Company AS C;

This will be very fast.
Hope that helps,
Ash


text:
Q: "Illegal assignment from List to List" I have a scheduled class that runs over my Incident records each day to check if any have been resolved for 30,31,32 days.
If it finds any, it should update the status to closed.
An Incident record looks up to the Status object.
The status on Incident is a lookup field called BMCServiceDesk__FKStatus__c
I've been told I need to get the BMCServiceDesk__FKStatus__crecord named "Closed" which has an Id of a4Bw0000000CcCNEA0 somewhere near the start of my code. I need some help on how to do this as I've tried creating a new list for BMCServiceDesk__Status__c object, but it says that i have "Illegal assignment from List to List"
global class Set_Status_Closed_Scheduled  Implements Schedulable // If an Incident has in a static Resolved state for 30 days, change it to Closed
{
global void execute (SchedulableContext sc)
{
    changeStatusToClosed();
}
public void changeStatusToClosed()
{
    // Get Status ID for the 'Closed' status.

    List<BMCServiceDesk__Status__c> ClosedStatus = new List <BMCServiceDesk__Status__c>();

    ClosedStatus = [SELECT Id FROM BMCServiceDesk__Status__c WHERE Name = 'Closed'];

    List<BMCServiceDesk__Incident__c> listIncident = new List <BMCServiceDesk__Incident__c>();

    List<BMCServiceDesk__Incident__c> updateListIncident = new list <BMCServiceDesk__Incident__c>();

    // Below query fetches records from 30 to 32 days. As per our discussion the incident should be closed
    //only after 30 days. So modify below filter logic.
    listIncident = [SELECT Id FROM BMCServiceDesk__Incident__c
                    WHERE (BMCServiceDesk__Status_ID__c = 'Resolved'
                           OR BMCServiceDesk__TemplateName__c = 'Incident Resolved')
                    AND BMCServiceDesk__FKRequestDefinition__c = ''
                    AND (BMCServiceDesk__StatusChangeDate__c = LAST_N_DAYS:30
                         OR BMCServiceDesk__StatusChangeDate__c = LAST_N_DAYS:31
                         OR BMCServiceDesk__StatusChangeDate__c = LAST_N_DAYS:32) LIMIT 100];
    for(BMCServiceDesk__Incident__c up: listIncident)
    {

        up.BMCServiceDesk__FKStatus__c = 'a4Bw0000000CcCNEA0';

        updateListIncident.add(up);
    }

    update updateListIncident;
}

}

A: Your new operator is constructing a List<BMCServiceDesk_Category__c> and assigning it to a List<BMCServiceDesk_Status__c>, which is causing your error.  That whole line is completely unnecessary though, you can remove it.  I've updated your code to remove the unnecessary initializations, and also adjusted the query to use "greater than or equal" and "less than or equal" to dates in order to make it more maintainable.
public void changeStatusToClosed()
{
    // Get Status ID for the 'Closed' status.

    List<BMCServiceDesk__Status__c> ClosedStatus = [SELECT Id FROM BMCServiceDesk__Status__c WHERE Name = 'Closed'];

    //You can also use ID ClosedStatus = [select ID...].ID if there is only one

    List<BMCServiceDesk__Incident__c> listIncident = [SELECT Id FROM BMCServiceDesk__Incident__c
                    WHERE (BMCServiceDesk__Status_ID__c = 'Resolved'
                           OR BMCServiceDesk__TemplateName__c = 'Incident Resolved')
                    AND BMCServiceDesk__FKRequestDefinition__c = ''
                    AND (BMCServiceDesk__StatusChangeDate__c >= LAST_N_DAYS:30
                         AND BMCServiceDesk__StatusChangeDate__c <= LAST_N_DAYS:32) LIMIT 100];
    for(BMCServiceDesk__Incident__c up: listIncident)
    {

        up.BMCServiceDesk__FKStatus__c = ClosedStatus[0].ID;//'a4Bw0000000CcCNEA0';
    }

    update listIncident;
}


text:
Q: Подскажите пожалуйста почему при ресайзе не меняется ширина первого и последнего slider_item? Подскажите пожалуйста пишу плагин, по задумке при ресайзе страницы ширина элементов и отступ слева должны пересчитываться, но  почему-то не меняется ширина первого и последнего slider_item которые вставлены в html через jQuery. Как это исправить ?

$( document ).ready(function() {

$('.slider-box').simpleSlider();

});

(function($){

$.fn.simpleSlider = function() {

 return this.each(function(){

  resized=false;
  var thisEl =$(this);
  slider = thisEl.children('div','ul','img'),
  slideWidth = thisEl.width(),
  slider_item = slider.children(),
  slideCount = slider_item.length,
  next = $(document).find('.nextBtn'),
  prev = $(document).find('.prevBtn');
    sliderInterval = 3300,
    animateTime = 1000,
    course = 1,
    margin = - slideWidth;

  slider_item.css('width',slideWidth);
  slider_item.last().clone().prependTo(slider);   // Копия последнего слайда помещается в начало.
  slider_item.eq(1).clone().appendTo(slider);   // Копия первого слайда помещается в конец.
  slider.css('margin-left', -slideWidth);

  function nextSlide(){                                 //
    interval = window.setInterval(animate, sliderInterval);
  }

$(window).resize(function() {
  slideWidth = thisEl.width();
    slider_item.css('width',slideWidth);
  resized=true;
 }).resize()

  function animate(){
   if (resized) {
    var widthslider=slider_item.width(); //старая ширина слайдеов
    var numslider=parseInt(-margin/widthslider); //номер текущего слайдера
    slider_item.css('width',slideWidth); //меняем ширину слайдеров
    margin = -slideWidth * numslider; //считаем смещение слайдеров слева
    slider.css('margin-left', margin); //меняем смещение слайдов слева
    resized=false;
  }
    if (margin==-slideCount*slideWidth-slideWidth){
      slider.css({'marginLeft':-slideWidth});
      margin=-slideWidth*2;
    }else if(margin==0 && course==-1){
      slider.css({'marginLeft':-slideWidth*slideCount});
      margin=-slideWidth*slideCount+slideWidth;
    }else{
    margin = margin - slideWidth*(course);
    }
    slider.animate({'marginLeft':margin},animateTime);
  }

  function sliderStop(){
    window.clearInterval(interval);
  }

  nextSlide();

})

};

})(jQuery)
.slider-box{
  max-width:1000px;
  overflow:hidden;
  position: relative;
}
.slider{
  position:relative;
  width: 10000px;
}
.slider_item {
 float: left;
}

.slider_item img{
  width: 100%;
  height: auto;
}

A: После создания копий слайдов нужно переопределить slider_item = slider.children();
PS. Я так и не понял зачем нужно добавлять последний слайд в начало. Он в анимации не участвует. Хватает копии первого слайда в конце.

$( document ).ready(function() {

$('.slider-box').simpleSlider();

});

(function($){

$.fn.simpleSlider = function() {

 return this.each(function(){

  resized=false;
  var thisEl =$(this);
  slider = thisEl.children('div','ul','img'),
  slideWidth = thisEl.width(),
  slider_item = slider.children(),
  slideCount = slider_item.length,
  next = $(document).find('.nextBtn'),
  prev = $(document).find('.prevBtn');
    sliderInterval = 3300,
    animateTime = 1000,
    course = 1,
    margin = - slideWidth;

  slider_item.css('width',slideWidth);
  slider_item.last().clone().prependTo(slider);   // Копия последнего слайда помещается в начало.
  slider_item.eq(1).clone().appendTo(slider);   // Копия первого слайда помещается в конец.
  slider.css('margin-left', -slideWidth);
  slider_item = slider.children();

  function nextSlide(){                                 //
    interval = window.setInterval(animate, sliderInterval);
  }

$(window).resize(function() {
  slideWidth = thisEl.width();
    slider_item.css('width',slideWidth);
  resized=true;
 }).resize()

  function animate(){
   if (resized) {
    var widthslider=slider_item.width(); //старая ширина слайдеов
    var numslider=parseInt(-margin/widthslider); //номер текущего слайдера
    slider_item.css('width',slideWidth); //меняем ширину слайдеров
    margin = -slideWidth * numslider; //считаем смещение слайдеров слева
    slider.css('margin-left', margin); //меняем смещение слайдов слева
    resized=false;
  }
    if (margin==-slideCount*slideWidth-slideWidth){
      slider.css({'marginLeft':-slideWidth});
      margin=-slideWidth*2;
    }else if(margin==0 && course==-1){
      slider.css({'marginLeft':-slideWidth*slideCount});
      margin=-slideWidth*slideCount+slideWidth;
    }else{
    margin = margin - slideWidth*(course);
    }
    slider.animate({'marginLeft':margin},animateTime);
  }

  function sliderStop(){
    window.clearInterval(interval);
  }

  nextSlide();

})

};

})(jQuery)
.slider-box{
  max-width:1000px;
  overflow:hidden;
  position: relative;
}
.slider{
  position:relative;
  width: 10000px;
}
.slider_item {
 float: left;
}

.slider_item img{
  width: 100%;
  height: auto;
}


text:
Q: Put a kind of border in the center of an image HTML and CSS I need to put this image, and also make this risk at the center of it. Is there any kind of border that make this?
HTML:

A: You can do it with a pseudo element.
This solution is flexible (works with every image/line height).
jsFiddle
HTML

CSS
img {
  width: 80px;
  height: 80px;
  background: blue;
  display: block;
  margin: 0 auto;
  z-index: 2;
  position: relative;
}

.middle-border {
    position: relative;
    background: yellow;
    text-align: center;
}

.middle-border::before {
    content: "";
    display: block;
    height: 5px;
    background: red;
    width: 100%;
    position: absolute;
    z-index: 1;
    top: 50%;
    transform: translateY(-50%);
}

Result


text:
Q: A recursive function to check if element is in SORTED list I am not really into recursive function and I am asking  to change my function in recursive and more optimal func. I know that in this task i should take advantage of the fact that this list is sorted, but I dont know how, maybe some bubble sort? This is my code, pretty simple but not even recursive and it doesn't take into account whether the list is sorted or not.
list1 = [1, 2, 3, 4, 5, 6]

def is_in_List(x):
    if x in list1:
        return True
    else:
        return False

x = 3

if is_in_List(x):
    print(f"{x} is in list")
else:
    print(f"{x} is not in list")

A: what you could do, is use devide and conquer, which means :
The algo goes like this :
You have a sorted list of n total elements. Checkin array if the element at n/2 is the one you're looking for
If it isn't, being a sorted list, you know that all the elements from n/2 -> n are bigger, and all the elements from 0 -> n/2 are smaller.  Check if the number at n/2 is less or more than the one you're searching for. If it's less, you run the same function again, but now, you give it only a subset of the list, meaning, if it's smaller you give 0 -> n/2, if it's bigger, you give n/2 -> n. Of course you'll need some stoping condtitions but hey, this is the algo.
That's the theory, here's the code.
Not the best implementation of it, just from the top of my mind.
my_list = [1,2,3,4,5,6,7,8,9];

def binary_search(a_list, search_term):

    #get the middle position of the array and convert it to int
    middle_pos = int((len(a_list)-1)/2)

    #check if the array has only one element, and if so it it is not equal to what we're searching for, than nothing is in the aray

    if len(a_list) == 1 and search_term != a_list[middle_pos] :
        #means there are no more elements to search through
        return False

    #get the middle term of the list
    middle_term = a_list[middle_pos]

    #check if they are equal, if so, the number is in the array
    if search_term == middle_term:
        return True

    #if the middle is less than search, it means we need to search in the list from middle to top
    if middle_term < search_term :
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[middle_pos:len(a_list)], search_term)

    else :
        #on else, it means its less, we need to search from 0 to middle
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[0:middle_pos], search_term)

print(binary_search(my_list, 1)


text: Q: PDE fouriertransform Im supposed to find the solution of ODE (10) with $\lim_{y \to \infty} u(x,y) = 0$. I have done the same as the soultionsheet and got the general solution (11). But the next step confuses me, howcome we knpw thath the D(w) = 0 when we use the foruiertransform? Can somebody please explain the theory behind the calculation?


text:
Q: Bootstrap Modal not Working on Click I'm trying to get the button to open up a modal on click of the button with label "Select Quantity and Sizes*:"  but for some reason I can't get this working, I'll appreciate a heads up, Please note that I included additional jQuery for the updateSizes() function found in the modal in the footer.php file already.
I believe your expertise will help me solve this, i'm kinda stuck here, I copied the modal on getbootstrap . com,
The modal on my page is found just below the comment:
    <-- Modal for Select Quantity and Sizes -->
PS: this is just a personal test project to sharpen up my skills, so security is undermined though a very important aspect.
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/eCommerce/core/init.php';
include 'includes/head.php';
include 'includes/navigation.php';

if (isset($_GET['add'])) {

    $brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
    /* making query and putting in alphabetical order */
    $parentQuery = $db->query("SELECT * FROM categories WHERE parent=0 ORDER BY Category");

    ?>

Add a New Product

    <form action="products.php?add=1" method="POST" enctype="multipart/form-data">

            Title*:
            <input type="text" class="form-control" name="title" id="title" value="<?= ((isset($_POST['title'])) ? sanitize($_POST['title']) : ''); ?>">

            Brand*:
            <select class="form-control" id="brand" name="brand">
                <option value=""<?= ((isset($_POST['brand']) && $_POST['brand'] == '') ? ' selected' : ''); ?>></option>
                <?php while ($brand = mysqli_fetch_assoc($brandQuery)): ?>
                    <option value="<?= $brand['id'] ?>"<?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id']) ? ' selected' : ''); ?>><?= $brand['brand']; ?></option>
                <?php endwhile; ?>
            </select>

            Main Category*:
            <select class="form-control" id="parent" name="parent">
                <option value=""<?= ((isset($_POST['parent']) && $_POST['parent'] == '') ? ' selected' : ''); ?>></option>
                <?php while ($parent = mysqli_fetch_assoc($parentQuery)): ?>
                    <option value="<?= $parent['id'] ?>"<?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id']) ? ' selected' : ''); ?>><?= $parent['category']; ?></option>
                <?php endwhile; ?>
            </select>

            Child Category*:
            <select class="form-control" id="child" name="child">
            </select>

            Price*:
            <input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price'])) ? $_POST['price'] : ''); ?>">

            List Price*:
            <input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price'])) ? $_POST['list_price'] : ''); ?>">

            Select Quantity and Sizes*:
            <button  type="button" class="btn btn-success form-control" onclick="jQuery('#sizesModal').modal('toggle');return true;">Quantity $ Sizes</button>

            Sizes and Quantity Preview*:
            <input type="text" id="sizes" name="sizes" class="form-control" value="<?= ((isset($_POST['sizes'])) ? $_POST['sizes'] : ''); ?>" readonly>

            Product Photo:
            <input type="file" name="photo" id="photo" class="form-control">

            Product Description:
            <textarea id="description" name="description" class="form-control" rows="6"><?= ((isset($_POST['description'])) ? sanitize($_POST['description']) : ''); ?></textarea>

            <input type="submit" value="Add Product" class="form-control btn btn-success pull-right">

    </form>

                    <button class="close" type="button" onclick="closeModal()" aria-label="Close">
                        ×
                    </button>

Select quantity & Sizes

                            ...

                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="updateSizes();jQuery('#sizesModal').modal('toggle');return false;">Save changes</button>

        Product
        Price
        Category
        Featured
        Sold

        <?php
        while ($product = mysqli_fetch_assoc($product_results)):
            /* setting category of child element */
            $childID = $product['categories'];
            $category_sql = "SELECT * FROM categories WHERE id = '$childID' ";
            $category_result = $db->query($category_sql);
            $category_child = mysqli_fetch_assoc($category_result);
            $parentID = $category_child['parent'];
            $parent_sql = "SELECT * FROM categories WHERE id ='$parentID' ";
            $parent_results = $db->query($parent_sql);
            $parent_fetch = mysqli_fetch_assoc($parent_results);
            $category = $parent_fetch['category'] . '-' . $category_child['category'];

            ?>

                    <a href="products.php?edit=<?= $product['id']; ?>" class="btn btn-xs btn-default">
                    <a href="products.php?delete=<?= $product['id']; ?>" class="btn btn-xs btn-default">

                <?= $product['title']; ?>
                <?= money($product['price']); ?>
                <?= $category; ?>

                <a href="products.php?featured=<?= (($product['feature'] == 0) ? '1' : '0'); ?> &id=<?= $product['id']; ?>" class="btn btn-xs btn-default"> <span class="glyphicon glyphicon-<?= (($product['feature'] == 1) ? 'minus' : 'plus'); ?>">&nbsp <?= (($product['feature'] == 1) ? 'Featured Product' : ''); ?>

                0

    <?php endwhile; ?>

<?php } include 'includes/footer.php'; ?>

A: Use bootstrap's data-toggle attribute instead on onclick attribute.
<button  type="button" class="btn btn-success form-control"
onclick="jQuery('#sizesModal').modal('toggle');return true;">
    Quantity $ Sizes
</button>

<button  type="button" class="btn btn-success form-control"
data-toggle="modal" data-target="#sizesModal">
    Quantity $ Sizes
</button>

Check out this link for detail explanation
Bootstrap Modal