text:
Q: Custom Linked List - Cannot cast object class to object For this project I'm not allowed to use generic classes keep in mind. I have tried copying all my classes into another friends computer and he gets the same error.
I cannot make calls like..
int counter = ((Movie) movieList.get(movListIndex)).getShowList().size();

Where getShowList() is a method in my Movie class that returns a LinkedList.
Eclipse says:

Cannot caste from Object to Movie

Additionally
movieList.add(objMovie, counter);

where objMovie is a Movie object.
Eclipse says:

The method add(Object, int) in the type LinkedList is not applicable for the arguments (Movie, int)

-Suggestion is change add method to take in Movie.
I need to be able to keep LinkedList and Node in a way that they can take in anything that is an Object, which when I create a Movie class I cannot cast to an Object.
Linked List Class
public class LinkedList {
 Node head;
 public LinkedList() {
  head = null;
 }

 public boolean isEmpty() {
  return(head==null);
 }

 public int size() {
  int count = 0;
  Node current = head;
  while (current != null) {
   count++;
   current = current.getNext();
  }
  return count;
 }

 public Object get(int index) {
  if ((index < 0) || (index > size()))
   throw new IndexOutOfBoundsException();
  Node current = head;
  int count = 0;
  while (count > 0) {
   count ++;
   current = current.getNext();
  }
  return current.getData();
 }

 public void add (Object data, int index) {
  if ((index < 0) || (index > size())){
   throw new IndexOutOfBoundsException();
  }
  Node previous = null;
  Node current = head;
  while (index > 0) {
   index --;
   previous = current;
   current = current.getNext();
  }

  Node splice = new Node();
  splice.setData(data);
  splice.setNext(current);

  if (previous == null)
   head = splice;
  else
   previous.setNext(splice);
 }

 public Object remove (int index) {
  if ((index < 0) || (index >= size()))
   throw new IndexOutOfBoundsException();
  Node previous = null;
  Node current = head;
  while (index > 0) {
   index --;
   previous = current;
   current = current.getNext();
  }
  if (previous == null)
   head = current.getNext();
  else
   previous.setNext(current.getNext());

  return current.getData();
 }
}

Node class
public class Node {
 private Object data;
 private Node next;

 public Object getData() {
  return data;
 }
 public Node getNext() {
  return next;
 }
 public void setData(Object data) {
  this.data = data;
 }
 public void setNext(Node next) {
  this.next = next;
 }
}

If needed Movie Class
public class Movie{
 private int filmNumber; //Movie ID
 private String filmTitle; //Title of Movie
 private int filmTime; //Movie Runtime
 private String filmRating; //Movie Rating
 private LinkedList showingList = new LinkedList();

 public Movie (int filmNumber, String filmTitle, int filmTime, String filmRating) {
  this.filmNumber = filmNumber; //sets global variable to parameter being passed
  this.filmTitle = filmTitle;   //                    |
  this.filmTime = filmTime;     //                    |
  this.filmRating = filmRating; //                    V
 }

 public int getFilmNumber() {
  return filmNumber;
 }

 public String getFilmTitle() {
  return filmTitle;
 }

 public int getFilmTime(){
  return filmTime;
 }

 public String getFilmRating() {
  return filmRating;
 }

 public String getStringFilmTime() {
  String runtime = ""; //returned value
  int hours; //variable to hold 2 hour digits
  int minutes; //variable to hold minute digits

  hours = filmTime / 60; //formats original input to just hours
  minutes = filmTime % 60; //formats original input to just minutes

  if (minutes < 10) {
   runtime += ( Integer.toString(hours) + ":0" + Integer.toString(minutes));
   //Mod will only return a single digit if under 10
  }

  if (minutes > 10) {
   runtime += ( Integer.toString(hours) + ":" + Integer.toString(minutes));
   //Same statement without adding a '0'
  }

  return runtime;
 }

 public void setFilmNumber(int newFilmNumber) {
  filmNumber = newFilmNumber;
 }

 public void setFilmTitle(String newFilmTitle) {
  filmTitle = newFilmTitle;
 }

 public void setFilmTime(int newFilmTime) {
  filmTime = newFilmTime;
 }

 public void setFilmRating(String newFilmRating) {
  filmRating = newFilmRating;
 }

 //public void setShowList()

 public LinkedList getShowList() {
  return showingList;
 }
}

A: Are these three classes all you have? I'm asking because if -- for some reason -- you have a class named Object next to your other classes, I can reproduce the error messages.
It may be as simple as:
public class Object {
}

If that's the case you should never name your classes Object, String, Integer or whatever else appears in the package java.lang.


text:
Q: Nginx + SSL + Rails + Juggernaut (Node.js) + Engineyard I have two different applications on the same server. One of them is running on the 80 port (mydomain.com), another on the port 443 (sub.mydomain.com) and has wildcard certificate.
The first application is only for information purposes and don't need websockets support.
The second application should have secure websockets support (wss protocol).
I tried to set up juggernaut gem (for websockets) for my rails app with nginx server on the engineyard cloud, but i have one problem. Engineyard cloud provide only two opened ports: 80 and 443. I know that nginx do not fully support http 1.1 reverse proxing, so i can't use proxing from nginx for redirects websockets requests to the specific local port (in my case this port is 8080).
I tried use HAProxy and it's work for me when i use only unsecure websockets, but i need to support secure websockets. As i know in this case i should use something like STunnel for tunneling my https request and than use HAProxy, but when i test it - i saw that the server has to work several times slower and i still did not work to use the secure socket connection :(
Maybe I'm doing something wrong? Maybe someone will tell how to set up nginx for multiple applications (one of them should work via https) and secure websockets using only two ports (80 and 443).
p.s. Also i used a node-http-proxy, in this case i was able to set up proxy for different nginx applications but i do not get run websockets (happened only for "handshake" via nginx, not for "switching protocols")

A: I did some research on the various reverse proxies and websockets not too long ago.  The bottom line is that websockets is new, and the reverse proxy support for it is very poor right now.
The recommendation I saw and I agree with is that you should run your websockets on a different stack than the rest of your items.  That usually means putting it on a separate domain or subdomain.
You still have to deal with the complexities of getting the reverse proxies working, but it will be less complicated if you don't have to worry about breaking the other stuff.
Also, I agree that maybe you'll get better answers at serverfault or superuser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google login with mechanize on ruby I'm trying to get to google play developer console using ruby. But first I have to login. I'm trying like this:
def try_post(url, body = {}, headers = {})
  unless @agent #This just creates a new mechanize instance
    setup
  end

  puts 'Logging in'

  # Hardcoded for testing purposes
  @agent.get 'https://accounts.google.com/ServiceLogin?service=androiddeveloper&passive=1209600&continue=https://play.google.com/apps/publish/%23&followup=https://play.google.com/apps/publish/#identifier'

  form = @agent.page.forms.find {|f| f.form_node['id'] == "gaia_loginform"}

  unless form
    raise 'No login form'
  end

  form.field_with(:id => "Email").value = @config.email

  form.click_button
  form = @agent.page.forms.find {|f| f.form_node['id'] == "gaia_loginform"}

  unless form
    raise 'No login form'
  end

  form.field_with(:name => "Passwd").value = @config.password

  form.click_button

  if @agent.page.uri.host != "play.google.com"
    STDERR.puts "login failed? : uri = " + @agent.page.uri.to_s
    raise 'Google login failed'
  end

  # @agent.post(url, body)
end

However this fails spectacularly. I tried a few other ways (trying to populate Passwd-hidden, finding field by id and so on) but no luck. I think that the password does not get entered since when I try to puts @agent.page.body after the final click_button I see enter password text somewhere in HTML.
What am I doing wrong and how can I fix it?

A: I've been digging around a bit more and found out that it's not that simple and I could not login with mechanize in any way.
So I ended up with using watir which was fairly simple and straightforward. Here's an example:
browser.goto LOGIN_URL

browser.text_field(:id, 'Email').set @config.email
browser.button(:id, 'next').click

browser.text_field(:id, 'Passwd').wait_until_present
browser.text_field(:id, 'Passwd').set @config.password
browser.button(:id, 'signIn').click

# Here I wait until an element on my target page is visible and then continue
browser.link(:href, '#SOMETHING').wait_until_present

Hope it helps.


text:
Q: Testing whether a string has repeated characters I am trying to figure out the lightest method for determining whether a string has any repeated characters, in the lightest way possible. I have tried searching for similar questions, but cant find any. It also needs to be the shorted way possible, as i will be checking quite a few strings (I can handle putting this into a loop, etc.)
For example:
a = "12348546478"
#code to check multiple characters
print(result)

Results: 8 was repeated, 4 was repeated
The code will check what character was repeated and print out what was repeated. I don't need to know how many times it was repeated, just whether it was or was not repeated.

A: You can use collections.Counter :
>>> from collections import Counter
>>> [i for i,j in Counter(a).items() if j>1]
['4', '8']

Or you can use a custom function :
>>> def finder(s):
...    seen,yields=set(),set()
...    for i in s:
...      if i in seen:
...         if i not in yields:
...            yield i
...            yields.add(i)
...         else :
...            yields.add(i)
...      else:
...          seen.add(i)
...
>>> list(finder(a))
['4', '8']

Or use str.count method in a set comprehension :
>>> set(i for i in a if a.count(i)>1)
set(['8', '4'])

A benchmark on all approaches, which shows that the last 2 way (custom function and set comprehensions are much faster than Counter):
from timeit import timeit

s1="""
a = "12348546478"
[i for i,j in Counter(a).items() if j>1]

"""
s2="""
def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i in seen:
         if i not in yields:
            yield i
            yields.add(i)
         else :
            yields.add(i)
      else:
          seen.add(i)

a = "12348546478"
list(finder(a))

"""

s3="""
a = "12348546478"
set(i for i in a if a.count(i)>1)
"""

print '1st: ' ,timeit(stmt=s1, number=100000,setup="from collections import Counter")
print '2nd : ',timeit(stmt=s2, number=100000)
print '3rd : ',timeit(stmt=s2, number=100000)

result :
1st:  0.726881027222
2nd :  0.265578985214
3rd :  0.26243185997

I also tried this for long string (a = "12348546478"*10000) and still got the same result:
1st:  25.5780302721341
2nd :  11.8482989001177
3rd :  11.926538944245

Any way my suggestion is using the set comprehension which is more pythonic :
set(i for i in a if a.count(i)>1)

A: Or alternatively you could do
len(set(x)) == len(x)

This returns a boolean, True if the string has no repeating characters, False otherwise.
The set type can't have any duplicates so when the string gets turned into one, it gets broken down into characters. The difference in length shows how many repeated characters there were (But NOT the characters themselves)

A: you can also use dictionary to get the count of unique characters as the key in a dictionary is always unique.
import collections

d = collections.defaultdict(int)
for c in a:
    d[c] += 1

d will contain {'1': 1, '3': 1, '2': 1, '5': 1, '4': 3, '7': 1, '6': 1, '8': 2}
And the answer given by Kasramvd is a nice approach.

A: You can use the function below to check a character repetition. It returns True if there is no repetition of character and returns False otherwise.
Python Code
def isThereRepitition(x):
   for char in x: #copies and iterates passing a value to char everytime
       x=x[1:] #deletes the first character in the string x
       if char in x: #checks if there is char in x string
           return False
return True

A: Simplifying @Kasravnd Second Answer,
First approach :
def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i not in seen:
         seen.add(i)

      elif i not in yields:
         yield i
         yields.add(i)

a = "12348546478"
print(list(finder(a)))

Second approach
def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i in seen and i not in yields:
          yield i
          yields.add(i)
      else:
          seen.add(i)

a = "12348546478"
print(list(finder(a)))

Third approach
def finder(s):
    yield from {i for i, v in enumerate(s) if v in s[i+1:]}

a = "12348546478"
print(list(set(a[i] for i in finder(a))))

all produce what are duplicates
['4', '8']

[Program finished]

@muddyfish is the easiest way to check if there exits a duplicate.

A: import collections

 a = "12348546478"
 countOfWords = collections.Counter(a)
 result = [i for i in countOfWords if countOfWords[i]>1]
 result

Try this

A: Updates from the future. (Jan 26, 2021)
Just out of curiosity, re-run this test with 2 changes in Python3.8 tonight and got very different resultls:

*

*change 1- from collections import Counter    # import this first

*change 2 -  make a larger number string:
a = "123485464781233299345355234234355234458"

results:
1st:  0.4764095
2nd :  0.6692353
3rd :  0.6512726000000002

A: Or with numpy's unique:
import numpy as np
chars, times = np.unique(list("12348546478"), return_counts = True)
chars[times > 1]


text:
Q: requested page give 404 in server but works perfect in localhost codeiginter i am programming a website using codeiginter i have an items in home page when click on it  it's open item details in new page
the details page work perfect in localhost but when i upload the site the page doesn't work it give me error 404
this is url to test
server url (It's URL doesn't work) :
 http://flux-electric.com/product_detials/view_product/9

localhost url (It's URL work) :
localhost/new_site/product_detials/view_product/9

A: i found the solution the mistake the first letter of Controller was small i change it to capital and it works perfect


text:
Q: Excel file getting corrupted while downloading using PowerShell/Curl I am trying to download an Excel file from Artifactory to my local machine using a PowerShell/Curl script. The Excel file is getting created, but when I open a sheet I am getting the below message and there is no data in this.

The file format and extension of 'DataSheet_DEP.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

curl.exe -k -u artifactory_TEMP:Password16 https://../artifactory/../DataSheet_DEP.xls --output  D:\ABC\Team Members\Datasheet\DataSheet_DEP.xls

Just to add Excel file is in 97-2003 workbook (.xls). I am able to download the file manually without any issue.

A: This is resolved now.. I was using wrong artifactory path. Thanks everyone who tried to help here


text:
Q: Need to subset data frame by specific times using R I have a data frame called summer.q.0 that contains time (X) and 4 temperatures (X0,  X0.33, X0.66 and,  X1). I need to subset the data frame extracting rows at specific times. Here is the head of my data frame:
                   X     X0  X0.33  X0.66     X1
1 6/28/2009 19:30:00 30.760 27.340 25.800 24.600
2 6/28/2009 19:32:24 30.740 27.352 25.804 24.599
3 6/28/2009 19:35:16 30.740 27.363 25.807 24.599
4 6/28/2009 19:38:44 30.740 27.372 25.808 24.599
5 6/28/2009 19:40:00 30.740 27.375 25.809 24.599
6 6/28/2009 19:42:24 30.703 27.379 25.810 24.599
7 6/28/2009 19:45:16 30.703 27.384 25.810 24.599
8 6/28/2009 19:48:44 30.703 27.390 25.811 24.599

In columnXthe time in minutes occur at random times. I need to extract the rows where the time in minutes in column Xis on the quarter hour (i.e. rows where minutes = 00, 30, or 45). In the data frame the values in the X column are factors. I realize that they need to be converted to a recognizable R time format for extracting the required rows but not sure of the best or easiest method. Then after converting X to the proper R date and time format, what is the easiest way to extract/subset the required rows?
For example: assuming my data frame was just the 8 rows above (the full data set has 33601 rows and is modeled temperature time-series data), I would would have a subset that would look like this and with a new time format as below:
                    X     X0  X0.33  X0.66     X1
1 2009-06-28 19:30:00 30.760 27.340 25.800 24.600
2 2009-06-28 19:45:16 30.703 27.384 25.810 24.599

In the subset, I need to subset all the rows where minutes are exactly 00, 33 and 45 (15 minute data) so that I can compare it to a measured data set that is already in 15 minute intervals and with  time in POSIXlt format. So, the subset would contain rows 1 and 7 from the original data frame of 8 rows. Ideally I would set the seconds in the subset ==00; not sure if this can be accomplished easily. Reasoning is that the modeled and measured data will not match exactly so seconds is not that important when comparing plots of both data sets. Hope this makes sense. Thanks!

A: If you provide a slightly fuller example we can help more, but this should get you started.
library(lubridate)

#this will return just the minutes from a date (I've added a random example to demonstrate this)
your_data$X <- format(mdy_hms(df$X, format="%M")
example <- format(mdy_hms("6/28/2009 19:30:00"), format="%M")

#you can then subset your data frame using something like this
subset_data <- subset(your_data,X == "0" | X=="30"| X=="45")

A: Consider the base R solution:
# CONVERT COLUMN TO DATE (POSIXlt)
df$X <- strptime(df$X, "%m/%d/%Y %H:%M:%S")

# SUBSET BY NUMERIC MINUTE
df <- (df[as.numeric(format(df$X, "%M")==0)
        | as.numeric(format(df$X, "%M")==15)
        | as.numeric(format(df$X, "%M")==30)
        | as.numeric(format(df$X, "%M")==45),])

# LESS VERBOSE SUBSET
df <- subset(df, format(df$X, "%M") %in% c('0', '15', '30', '45'))


text:
Q: vanilla javascript vs jquery I am having trouble grasping the difference between the two. I tried downloading the library and there was no code. I am trying to build a basic slider along with other basic functions I have built in jQuery. Any help, tutorials, plugins and information would be very helpful!

A: javascript is built in to the browser
and you can just link to the online versions of jquery and jqueryui to start with

and the slider is in jquery ui library - (it is a library built on top of and dependant on jquery)
so bring that in next

then the samples from jqueryui should make more sense

from
http://jqueryui.com/slider/

A: "Vanilla JS" refers to plain, unmodified JavaScript.
document.getElementById('myelement').innerHTML = "I was written with JavaScript!";

jQuery is a collection of functions and stuff that are intended to make it easier to write JavaScript (although personally I feel it makes it more like spaghetti)
$("#myelement").html("I was written with jQuery!");

Since jQuery is just a bunch of JavaScript, plain JavaScript is ALWAYS faster to run. It may be harder to write because you have to actually think about what you're doing, but it will run faster than the same thing in jQuery.
For a comparison of the two code samples above, see this JSPerf

A: jQuery is a library based on JavaScript. It provides short-hand methods of things that could be otherwise coded in JavaScript. jQuery is coded in JavaScript, and is not built-in inside the browser, so you have to embed it.
jQuery UI, on the other hand, is a UI library which allows you to codes basic UI elements in a short-hand manner.
You didn't specify which one you were utilizing.
To embed jQuery, use this for the latest jQuery version:

and this for the latest UI version:

Note that the examples above our hosted on jQuery.com.
Google also offers a hosted jQuery solution via developers.google.com.
You can also self-host jQuery on your own server (if you have any). Some people think that using Google's servers (or jQuery's) is quite faster then hosting it on your own server, but it's you to run tests and discover which one works best/faster for you.
Because jQuery is an external library (an extension of JavaScript), you have to load it, it's not built into the browser, therefore it's always slower.
Though some people think that due to the fact that jQuery is (for some), much easier to code (and the transitions like FadeIn are built-in), that it's worth the slower loading time.
Hope this helps.
Edit:  You also mentioned that you downloaded JavaScript and that there was no code inside, but JavaScript is built-in inside the browser so there's no download of it. You're probably referring to this joke.


text:
Q: Can't drop table with geography column I imported shp to postgis 2.0.1 with shp2pgsql and chose to use geography instead of geometry. However, now when I try to drop the table, the pgadmin/sql console/phpPgAdmin freezes. I can't neither truncate it or change the columns.
Any help would be appreciated :-).


text:
Q: Why won't my form display? I'm using Bootstrap 3 with a Bootswatch theme. Here is my HTML:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>

    <link href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/flatly/bootstrap.min.css" rel="stylesheet">

                <button type="button" data-toggle="collapse" data-target=".navbarcollapse" class="navbar-toggle">
                    Toggle navigation

                </button>
                LicenseApp

Dashboard

Nav 1

Nav 2

            <form class="form-horizontal" role="form">

                    Username

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

            </form>

Any ideas why I'm having so many problems? Am I missing a DIV or something?

A: Your form is placed under your navbar because your navbar is fixed at top.
With following css rules:
.navbar-fixed-top {
   top: 0;
   border-width: 0 0 1px;
}

Therefore, either push your form more down or make navbar not fixed, for example remove navbar-fixed-top from this element:

Therefore, it displays jsfiddle example
Or as @Jamesking56 noticed, changing navbar-fixed-top to navbar-static-top works

A: In Bootstrap, when using a fixed navigation header, you usually put a padding-top on the body, the same height as the header.
See here: Bootstrap docs

Body padding required
The fixed navbar will overlay your other content, unless you add padding to the top of the body. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.
body { padding-top: 70px; }
Make sure to include this after the core Bootstrap CSS.


text:
Q: How to enable vscode protocol for Visual Studio extension in Mac I just installed Visual Studio in MacOS Sierra for using Xamarin.
And to enable Emacs keybinding in Visual Studio I tried to install this extension.
https://marketplace.visualstudio.com/items?itemName=hiro-sun.vscode-emacs
But by clicking install button, it failed by unknown protocol of vscode:
The URI is vscode:extension/hiro-sun.vscode-emacs.
I think it works find if I use Windows. How can I install the extension in MacOS?

A: That extension is for "VS Code". It will not work on "Visual Studio for Mac" or for regular "Visual Studio" on windows. These are all separate products


text:
Q: Card probability problem
Possible Duplicate:
Probability problem

I found the following problem in Rosen's Discrete Mathematics and Its Applications 6th ed.:
There are three cards in a box. Both sides of one card are black, both sides of one card are red, and the third card has one black side and one red side. We pick a card at random and observe only one side.
If the side is black, what is the probability that the other side is also black?
Shouldn't the answer to the question be $1/3$, as among $3$ cards only $1$ of them has both sides black. But the book says answer is $2/3$, do I miss anything?

A: An informal way of seeing it is that there are $6$ sides, and we are observing a randomly chosen side. Of the $3$ sides that are black, $2$ belong to the double-black card.
We can alternately do a formal conditional probability calculation. Let $DB$ be the event that the card picked is a double-black, and let $OB$ be the event that we observe a black. We want $P(DB|OB)$. By the usual formula,
$$P(DB|OB)P(OB)=P(DB\cap OB).$$
We have $P(OB)=\frac{1}{2}$ and $P(DB\cap OB)=P(DB)=\frac{1}{3}$.


text:
Q: Save data in SQLite with Category I have to save data in specific category. And I am putting these category names as SQLite Column.
And SQLite column are looking like below. Where the COL2 is the category.
COL1                 COL2                COL3

13-11-2018           Monitor             4
13-11-2018           Monitor             2
13-11-2018           Mouse               6
14-11-2018           Keyboard            5
14-11-2018           Monitor             3

Now What I want is to show unique category name to a list view. Like:
Monitor
Mouse
Keyboard

A: use distinct keyword before column name while select data.
SELECT DISTINCT COL2 FROM TableName

A: you need to filter duplicate entry using a query if you want to show COL2 in listView or Recyclerview
SELECT DISTINCT
 COL2
FROM
 table;

for more help visit this link


text:
Q: Yii2: How to mass extract Yii::t() messages for localization? I have lots of Yii::t() commands in my application. Now I need to extract them somehow but I don't want to do this manually. How can I extract all those commands easily? Do I have to do it with regular expressions?
I have read the documentation but it doesn't state anything about this.

A: Yii2 provides already somthing to help you with this topic. You can use the console with two yii commands:

*

*message/config: With the first command you create a configuration file

*message/extract: and with the second you extract the Yii:t() messages based on the configuration file

By default (part of the configuration file) all messages will be saved into a @app/messages directory that you have to have created before. These files will contain the required php arrays with empty string values for the translations. The files will be named by category that are used in the Yii::t('category', 'message') commands and are placed into sub directories for the specified language codes.
All is documented in the yii command. Type ./yii help message into your console. The config file itself also includes documentation.
Hint: don't forget to exclude the vendor directory in the configuration, otherwise the Yii framework messages gets also extracted.
Btw: these commands don't need the i18n configuration that is typically stored in the web.php or console.php files. Though, for using the localized messages you have to define it of course.
Some information is now available here in the guide.


text:
Q: Doubt based on composition of functions I have a question regarding composition of functions, which goes as follows:
Let two functions are defined as
$$g(x)=\begin{cases}
x^2,  &-1\leq x<2 \\
x+2,  & 2\leq x\leq 3\\
\end{cases}$$
and
$$f(x) = \begin{cases}
x+1,  & x \leq 1 \\
2x+1, & 1<x\leq 2\\
\end{cases}$$
The question is to find $gof$
The answer is stated to be :-
$gof = \begin{cases}
(x+1)^2,  &-2\leq x \leq 1\\
\end{cases}$
Clearly, they only use the 1st definition for $g(x)$ and the first definition for $f(x)$
$1$st question:
But, I noted something else, that is, if $x =1, \implies f(x) = 2$ using 1st definition $\implies g(x) = 4 $ using the 2nd definition of $g(x)$. Coincidentally, here for $x= 1$ the value of $g(f(x))$ is the same for both the cases, that is, $4$. But there may be cases where this isnt the case right? Can we just condense it into a single definition if the value are equal for some values of the function?
$2$nd question:
I tried to approach this question as follows, first by writing ,
$$g(f(x)) = \begin{cases}
(f(x))^2,  &-1\leq x<2 \\
f(x)+2,  & 2\leq x\leq 3\\
\end{cases}$$
And then I began checking for which values of $x$, $f(x)$ can be in these ranges, but that was quite a lengthy method as I first assumed a range of $x$, then took that corresponding result of $f(x)$  and plugged it into domain of $g(x)$ to check if the values of $x$ I get from here overlap and give me a real interval. But is this the correct method to do this?
If not, how do I approach these questions, I feel like I'm stuck, and methods/in dephth help would be nice.


text:
Q: Pagination issue I'm working with a custom post type / custom taxonomy combo and I can't seem to get pagination to work properly.  I'm wanting to add an infinite scroll to the page, however I can't even get pagination to even show up in order to get the infinite scroll piece working.
Below is my loop:
<?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

        $args = array(
            'post_type' => 'shows', // it's default, you can skip it
            'posts_per_page' => '3',
            'order_by' => 'date', // it's also default
    'paged' => $paged,
    'tax_query' => array(
                array(
                        'taxonomy' => 'show',
                        'field' => 'slug',
                        'terms' => array(
                            'anger-management'
                        )
                )
            )
            );
            $query = new WP_Query( $args );
    ?>
        <?php if (have_posts()) : while( $query->have_posts() ) : $query->the_post(); ?>

            <div class="archive-item" style="background: url(<?php echo get('archive_image'); ?>) center center no-repeat;"><a href="<?php the_permalink(); ?>">

<?php the_title(); ?>

<?php echo get('location'); ?>  -  <?php echo get('date'); ?>

    <?php endwhile; ?>

    <?php endif; ?>

    <?php wp_reset_query(); ?>

Obviously, I've put in a pagination script after the endwhile, however it still does not work;  I've even tried a plugin just to see if it'd work, and it didn't.
I'm using the HTML5blank theme to build from, so here's the pagination script that comes built in:
function html5wp_pagination()
{
    global $wp_query;
    $big = 999999999;
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages
    ));
}

I'm not sure if I need to write a new one or not; to be honest, I'd prefer just to have basic "next posts" or "previous posts" links, but regardless, I just can't get the pagination to work AT ALL.
Any help would be much appreciated.
I guess I'm starting to wonder if I need to set some parameters for this type of loop that helps set up the pagination?  But I can't seem to figure that out if that's the case.

A: Your function html5wp_pagination() is using global $wp_query;
But you're using $query = new WP_Query( $args );
Try changing that to $wp_query = new WP_Query( $args );
And adjust the while line so that it uses $wp_query.

A: You can do what @shanebp said, but you can even do a little more and follow @Chip Bennett's "guide" on how to fix pagination for custom loops


text:
Q: Placing squares randomly in a Room I have pondered this problem for several years now and think it to be impossible but I have to ask to ensure.
A rectangular room that has an arbitrary WIDTH, and HEIGHT. The goal is to place squares in the room randomly without any overlaps and without any of them being outside the room. Placement is not aligned to any grid. In addition each square placed should be uniformly randomly positioned in any valid place.
Think of: In the real world taking a handful of scrabble pieces and throwing them in a cardboard box.
A bad way I found to do this:
for( i=0; i < total_squares; i++){
    rx = random(WIDTH); ry = random(HEIGHT);
    if(no_collision(rx,ry)){
        place_square(rx, ry);
    }
    else{
     i--; //alternative_way i=0; unplace_all_squares();
    }
}

This works if the room is sufficiently large, but I wanted it to work in a room that could barely fit each square. Then the loop could get stuck since there is no place valid place. An alternative is setting i to zero in the else and removing all the squares placed. That will work but could take nearly infinite time.
Another way is to have the square slide off overlaps but that biases the placement to close to other squares.
So I came to the conclusion I can't help the bias because of how collision biases the square to a position in the room and my vapid solution would have bias in it if it ever completed. But I am not sure.
I was using game maker for this but pseduo-code or any language would be fine.


text:
Q: How to direct to another web page when "Buy Now" button is clicked in ecommerce frontend? How to direct to another web page when "Buy Now" button is clicked in ecommerce frontend magento? I am doing mobile apps and accessing my website webpages by using android webview. What I want to know is "Is there a way to direct to another custom webpage when Buy Now button is clicked with the condition if the url contains www.example.com?"
For example
if(buynow button is clicked)
{
   if(url == "www.aa.com")
   {
      go to my custom page
   }
   else
   {
      original page
   }
}

A: create a module and trigger a event when controller_action_predispatch_checkout_cart_add event call.
Create module:app/code/community/Amit/Custommodule/etc/config.xml
<?xml version="1.0" ?>
<config>
    <modules>
        <Amit_Custommodule>
            <version>1.0.0</version>
        </Amit_Custommodule>
    </modules>
    <global>
        <models>
            <custommodule>
                <class>Amit_Custommodule_Model</class>
                </custommodule>
            </models>
        <events>
        <controller_action_predispatch_checkout_cart_add>
            <observers>
                <myredirect>
                <class>custommodule/observer</class>
                <method>myredirect</method>
                </myredirect>
            </observers>
        </controller_action_predispatch_checkout_cart_add>
        </events>
    </global>
</config>

2)Observer.php (app/code/community/Amit/Custommodule/Model)
code is

public function myredirect($observer){
        if(strpos($_SERVER['HTTP_REFERER'],"www.aa.com")==true):
        Mage::app()->getResponse()->setRedirect($_SERVER['HTTP_REFERER'])->sendResponse();
        exit;
        endif;
    }
    }

3)create module control file Module name as  Amit_Custommodule.xml at app/etc/modules/Amit_Custommodule.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Amit_Custommodule>
            <codePool>community</codePool>
            <active>true</active>
        </Amit_Custommodule>
    </modules>
</config>


text:
Q: AWS Cognito Sync with Authorised Users I have implemented AWS Cognito successfully as below for Unauthorised users. With Unauthorised users, once the IdentityId is successfully returned I can then use Cognito Sync to create and manipulate Datasets successfully. I have been unable to use Cognito Sync with an Authorised user. Please can someone tell me how I obtain the IdentityId for a Authorised user, which then allows me to listRecords (which requires the IdentityId). IdentityId is always being returned as undefined.
AWS.config.credentials = new CognitoIdentityCredentials({
    IdentityPoolId: REACT_APP_AWS_CONFIG_IDENTITY_POOL_ID,
});

const userPool = new CognitoUserPool({
    UserPoolId: REACT_APP_AWS_CONFIG_USER_POOL_ID,
    ClientId: REACT_APP_AWS_CONFIG_CLIENT_ID,
});

let cognitosync = new AWS.CognitoSync();

AWS.config.credentials.get(()=>{
    IdentityId = AWS.config.credentials.identityId;
    listRecords();
});

function listRecords(){
    cognitosync.listRecords({
        DatasetName     : DATA_SET_NAME,
        IdentityId      : IdentityId,
        IdentityPoolId  : REACT_APP_AWS_CONFIG_IDENTITY_POOL_ID
    }, function(error, data) {
        //...
    });
 }

thanks in advance

A: I suspect you just need to add a Logins map to your AWS.config.credentials object for authenticated users.
What you put in the Logins map depends on how the user authenticated, but essentially you need a single entry, with the identity provider (IDP) as the key, and the id token you received from that IDP as the value.

For example, if your user authenticated with Google, you might have:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx',
    Logins: {
       'accounts.google.com': googleUser.tokenId
    }
});

where googleUser is the object returned by Google.

If your user authenticated with a Cognito User Pool, you might have:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx',
    Logins: {
        'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxxxx':
        session.getIdToken().getJwtToken()

    }
});

Where session is passed to a callback you provide to CognitoUser.getSession().  Additional code context for this use case in this Gist.

A: I've discovered what my problem was. To get the JWT for the Login key/value I was using :
result.getAccessToken().getJwtToken()
when it should have been:
result.getIdToken().getJwtToken()
all is working now


text:
Q: Ruby on Rails link with post request I need a way to create a link in Rails 3 that will send a post request with several parameters and not cause a reload. I was using a form:
= form_for Vote.new, :remote => true do |f|
  .actions
    = f.submit 'Vote'
  = hidden_field_tag('question', q.id)
  = hidden_field_tag('seat', @seat.id)

but it slowed my render time down quite a bit and I don't want a submit button. Is there any other way to submit a form like that without using a button?
I tried =link_to and such but couldn't seem to get the parameters working correctly.

A: I would use a link with params like this:
= link_to "Post", new_vote_path(vote: {question_id: question.id, seat_id: seat.id}, remote: true, method: :post, rel: "nofollow"

I've used this without remote: true but I see no reason why it shouldn't work with jquery rails. If it doesn't work, I would assume the jquery $.ajax object isn't setting the type from the method.  You might be able to override this or create your own binding to the click event.
Just for reference - link_to api:
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

A: You can either use javascript to make a link do a form post when clicked (messy, but similar to how scaffolding does deletes) or use css to style a button to look like a link.


text:
Q: how to create a task that uses a text file in IntelliJ eduTools I am trying to create a task that needs to read from a file in IntelliJ EduTools.
I tried creating a directory at the root of the course and marked it as a resources, I tried putting the actual file in the src component of the Task. I tried a number of locations for the resource file.
Here's what I got. Once I created a resource file at the top level of the project, the task was able to work. However, the tests were not able to find the file. (I then tried creating a test resource directory in many locations without success).
Where should I place resource files for Tasks and Tests to run in IntelliJ Edu Tools?

A: You should put the files for tasks into the task directory and files for tests into the tests directory. Path to file should be defined like this:
./filename.extension - for task files
./tests/filename.extension - for test files


text:
Q: How to await on the closing event of the fd assigned to loop.add_reader? Let's consider this example code:
myfd = ... # my fd, can be a socket for example

def reader():
    data = myfd.recv(100)
    print("Received:", data.decode())

asyncio.get_event_loop().loop.add_reader(myfd, reader)

asyncio.get_event_loop().run_forever()

My issue is the asyncio.get_event_loop().run_forever() part. I would like to await on the closing event of myfd instead.

A: This is a possible solution:
myfd = ... # my fd, can be a socket for example

conn_closed = asyncio.Event() # <-- This is the solution

def reader():
    try:
      data = myfd.recv(100)
      print("Received:", data.decode())
    except EOFError: # connection closed
      conn_closed.set()
    except Exception as e:
      print(f"Unexpected Exception: {e}")
      conn_closed.set()

asyncio.get_event_loop().loop.add_reader(myfd, reader)

await conn_closed.wait()


text:
Q: Running KMeans clustering several times with the same random seed I have a problem with understanding the scikit-learn specification of the KMeans clustering function. The function:
sklearn.cluster.k_means(X, n_clusters, *, sample_weight=None, init='k-means++', n_init=10, max_iter=300, verbose=False, tol=0.0001, random_state=None, copy_x=True, algorithm='lloyd', return_n_iter=False).
The specification says that:

*

*init{'k-means++', 'random'}, callable or array-like of shape (n_clusters, n_features), default='k-means++'
Method for initialization:
'k-means++' : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details.

*n_init int, default=10
Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.

*random_state int, RandomState instance or None, default=None
Determines random number generation for centroid initialization. Use an int to make the randomness deterministic.
The question:
If I run the algorithm with init = k-means++, n_init = 10 and random_state = int (0, 1, 42 etc.) will it mean that: (1) the algorithm will be run 10 times with the same initial cluster centers; (2) the inital cluster centers will be different for each run (but still determined by the random number generator associated with the specified random state) or (3) for each of the 10 runs the inital cluster centers will be different because they will be determined by different seeds? I am little confused because to me it seems like the n_init is contradictory to setting a random_state.


text:
Q: Not able to delete string item with colon in python list So I'm having the following problem while coding in python: I have a few string items in a list like so:
['X','Y','Z','A', 'B:C', 'D']

I want to delete everything past 'Z'. I use the following code to attempt this:
for item in lines:
   if ((item == "A")):
      lines.remove(item)

   if (item == "B:C"):
      lines.remove(item)

   if (item == "D"):
      lines.remove(item)

A and D get removed perfectly. However, B:C is not removed and stays in the list...
Mind you, A, D, B:C etc represent strings, not characters (e.g. A could be Transaction failed! and B:C can represent WRITE failure: cannot be done!)
How can this be solved?

A: Modifying a list while iterating over it is usually a bad thing.  Some of the elements get skipped when you remove the current element.  You may be able to fix it by iterating over reversed(lines), but it is better to create a new list that doesn't have the elements that you want to drop:
to_remove = {'A', 'B:C', 'D'}
new_lines = [line for line in lines if line not in to_remove]

Or, if you want to modify in-place:
to_remove = {'A', 'B:C', 'D'}
lines[:] = [line for line in lines if line not in to_remove]

A: You may use the .index() method to find the index of a specific element inside a list.
Then after finding the z_index, you may create another list by slicing the first one.
Here's an example:
l1 = ['X','Y','Z','A', 'B:C', 'D']

#finding index of element 'Z'
z_index = l1.index('Z')

#slicing list from 0 until z_index
l2 = l1[:z_index]

print l2

Output:
['X', 'Y']

A: Generally, it is not a good idea to delete elements from a list you are iterating. In your case, you may consider creating a new list with the result you want:
l = ['X','Y','Z','A', 'B:C', 'D']
clean_l = [i for i in l if i not in ('A', 'B:C', 'D')]

Which is a good option if you know which elements you want to delete. However, if you know that you don't want anything after 'Z' regardless of their value, then just slice the list:
clean_l = l[:l.index('Z') + 1]

A: Firstly you would want to find the position of 'Z' by using the index() method.
x = ['X','Y','Z','A', 'B:C', 'D']
position = x.index('Z')

Then to delete everything after z i would do this:
del x[postion+1:]

You have to add one to the position otherwise it will delete 'Z' also


text:
Q: Drawing a plane with vertex buffer object I'm trying to draw a square plane of 10 x 10 using the VBO on OpenGL. So I have a function getPlaneCoords that calculate the vertices and the indexes however the program just ends up crashing when I run it.
fragment shader:
#version 330 core

out vec4 color;

void main()
{
    color = vec4(0.5, 0.2, 0.3, 1.0);
}

vertex shader:
#version 330 core
layout (location = 0) in vec3 position;

out vec3 FragPos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view *  model * vec4(position, 1.0f);
    FragPos = vec3(model * vec4(position, 1.0f));
}

Main.cpp:
constexpr GLuint dimensions{ 10 };
int numberOfPoints{ 0 };
int numberOfIndexes{ 0 };

float vertices[dimensions * dimensions * 3];
unsigned int indices[(dimensions - 1) * (dimensions - 1) * 6];

void getPlaneCoords()
{
    int half = dimensions / 2;
    for (int i{ 0 }; i < dimensions; ++i)
    {
        for (int j{ 0 }; j < dimensions; ++j)
        {
            float x = j - half;
            float y = 0;
            float z = i - half;

            vertices[numberOfPoints++] = x;
            vertices[numberOfPoints++] = y;
            vertices[numberOfPoints++] = z;

        }
    }

    for (int row{ 0 }; row < dimensions - 1; ++row)
    {
        for (int col{ 0 }; col < dimensions - 1; ++col)
        {
            indices[numberOfIndexes++] = dimensions * row + col;
            indices[numberOfIndexes++] = dimensions * row + col + dimensions;
            indices[numberOfIndexes++] = dimensions * row + col + dimensions + 1;

            indices[numberOfIndexes++] = dimensions * row + col;
            indices[numberOfIndexes++] = dimensions * row + col + dimensions + 1;
            indices[numberOfIndexes++] = dimensions * row + col + 1;
        }
    }
}

int main()
{
 glViewport(0, 0, WIDTH, HEIGHT);

    // OpenGL options
    glEnable(GL_DEPTH_TEST);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    getPlaneCoords();

    // Build and compile our shader program
    Shader lightingShader("lighting.vs", "lighting.frag");

    GLuint squareVAO, VBO, EBO;
    glGenVertexArrays(1, &squareVAO);
    glBindVertexArray(squareVAO);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, numberOfPoints * sizeof(vertices), vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, numberOfIndexes * sizeof(GLuint), indices, GL_STATIC_DRAW);

    GLint PosAttrib{ glGetAttribLocation(lightingShader.Program, "position") };
    glVertexAttribPointer(PosAttrib, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // Note that we skip over the normal vectors
    glEnableVertexAttribArray(PosAttrib);

    glBindVertexArray(0);

    glm::mat4 projection = glm::perspective(camera.GetZoom(), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 1000.0f);

    while(window.running)
    {
     glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        lightingShader.Use();

        glm::mat4 view;
        view = camera.GetViewMatrix();

        // Get the uniform locations
        GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model");
        GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view");
        GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection");

        // Pass the matrices to the shader
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

        glBindVertexArray(squareVAO);
        glm::mat4 model = glm::mat4();
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        glDrawElements(GL_TRIANGLES, numberOfIndexes, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        window.display();
    }

// Missing important display code but that is related to SFML. The code shared is primarily the OpenGL methods
}

It's meant to be a 10 x 10 plane with the color rgba ratio (0.5, 0.2, 0.3, 1.0);
I'm not sure as to where I went wrong?


text:
Q: FTDI VDIP1L File Creation "Bad Command" I'm using an FTDI VDIP1L with my Arduino Uno to log data to USB (Sandisk Cruzer 8 GB). The Arduino is programmed with Software Serial as available at http://www.arduino.cc/en/Reference/SoftwareSerial so I'm able to echo serial from the Arduino serial port monitor to/from the VDIP. The light on the USB stick is working (so it's alive) as are some of the Vinculum commands, e.g. DIR, IDDE, DSN, DVL, but anything related to actual files on the disk doesn't seem to work (make that OPW; I haven't tried reading or writing since I'm using a blank flash drive and they don't apply yet).
The Uno is powered with the external adapter, and also connected to PC by the USB cable. Arduino--VDIP1L connections are as follows: (Arduino--VDIP1L):
5V--5V; GND--GND; 11(SW TX)--AD1(RX); 10(SW RX)--AD0(TX); GND--AD3(CTS);
The VDIP1L has the latest version of the VDAP firmware, "MAIN 03.69VDAPF
RPRG 1.00R" as returned by the FWV command.
Syntax used:
OPW DATAFILE.TXT
I've tried sending it all at once and in parts. When I try it in parts the OPW generates no complaint (or response for that matter) by then I get "Bad Command" when I send the file name or part thereof.
Anyone know why the file commands won't work?
Cheers,

A: Still not able to get this working with the Arduino Serial monitor, but I have noticed a couple of things about said monitor. There is a drop-down menu that allows you to select between "no line ending", "carriage return", "newline", and "carriage return+newline". The monitor will append a carriage return and/or a line feed to your text entry depending on your selection.
Now I don't know why that wasn't enough to get the commands to the VDIP. Perhaps the serial monitor adds a carriage return (when this option is selected) after each block of text, in which case my command would have been "OPW " 'carriage return' "datafile.txt" 'carriage return', while the VDIP wants "OPW datafile.txt" 'carriage return'.
I tried this syntax with Putty in place of the Arduino serial monitor and got it working, along with writing to the file, so the question is pretty much closed as far as I'm concerned.
Cheers,


text:
Q: Computing Many Slow I/O Operations In working on a custom stock screener, I often need to run mathematica code like this:
{#, FinancialData[#, "DividendYield"]} & /@ Take[FinancialData["NYSE:*"], 30]

In this example, I've limited the result set to 30, but ideally I'd like to get the dividend yield for a much larger set.
This is a specific example of a more general problem I have with mathematica, which is that sometimes I need to run a large number of distinct network IO calls and this blocks further computations.
Is there some workaround for writing calls like this that won't block further computations? I am a fairly competent programmer and therefore can implement a system in my Mathematica code to compute results one at a time, but I am trying to avoid reinventing the wheel. I feel this must be a very common problem for Mathematica users who use the built in data sources/Wolfram|Alpha integration.

A: Parallel Kernels for separate Notebooks
Perhaps you simply want to run two kernels in parallel.  You can do this by:

*

*Open Evaluation > Kernel Configuration Options... and set up more than one kernel.

*Assign a different kernel to each of two Notebooks using Evaluation > Notebook's Kernel
From there you can run your slow code in one Notebook and do your interactive programming in the other.

"Dialogs" on a single Kernel

I guess the main point of my question is, if I'm launching an external command, even if I am waiting for feedback from it, it shouldn't take up a kernel's resources ... also not to mention that I'm being a complete jerk launching two kernels when we only have 2 on our network seat.

Perhaps your best option in that case is to run calculations in a kernel dialog while the background task is momentarily paused.  On my system the shortcut key for Evaluation > Evaluate in Subsession is F7.
As an example try:
Do[Pause[1], {i, 50}];

And while it is running put the cursor in a separate cell containing:
Print[i]

And press F7.
Every time you select that cell and press F7 you should get the current value of i from the evaluating Do loop.

A: As Szabolcs mentions, the simplest way to do this is to start a new kernel and push this bulk of data acquisition to that kernel and let it run in the background. There are good examples in the documentation in tutorial/ConcurrencyManagingParallelProcesses.
For your specific case, here's an example following the above:
LaunchKernels[1];
j = ParallelSubmit[{#, FinancialData[#, "DividendYield"]} & /@
   Take[FinancialData["NYSE:*"], 30]];

Parallel`Developer`QueueRun[]
Out[3]= True

You can continue working as usual in your main kernel.


text:
Q: Compile boost-python tutorial with VS-2015 CTP 5 and Python 3.5a on Windows 10 TP I'm trying to get the boost-python extension module tutorial working on a modern C++14 compiler in Windows 10. I've downloaded the latest versions of boost 1.57 and python 3.5a source using vc-14 (VS 2015 CTP 5).
I compiled python from source using VS 2015 CTP 5 and these instructions: 1.1.3.3. Windows.
I've run the command
.\bootstrap.bat && .\b2 stage toolset=msvc --with-python

from the boost project folder c:\boost
This is the user-config.jam file in my home directory:
using msvc : 14.0 : C:\\Program\ Files\ (x86)\\Microsoft\ Visual\ Studio\ 14.0\\VC\\bin\\cl.exe ;

using python
        : 3.5                                        # Version
        : C:\\python35a3\\PCBuild\\win32\\python.exe # Python Path
        : C:\\python35a3\\include                    # include path
        : C:\\python35a3\\libs                       # lib path
        : <define>BOOST_ALL_NO_LIB=1
        ;

Running bjam in the tutorial directory results in an incompatibility when creating the pdb file:
    c:\boost\libs\python\example\tutorial>bjam --debug-configuration
        notice: found boost-build.jam at C:/boost/libs/python/example/tutorial/boost-build.jam
        notice: loading Boost.Build from C:/boost/tools/build/src
    ....
        notice: Loading user-config configuration file 'user-config.jam' from 'C:/Users/marcel'.
        notice: [msvc-cfg] msvc-14.0 detected, command: 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe'
        notice: [msvc-cfg] msvc-12.0 detected, command: 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\cl.exe'
        notice: will use 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe' 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe' for msvc, condition <toolset>msvc-14.0
        notice: [msvc-cfg] condition: '<toolset>msvc-14.0/<architecture>/<address-model>', setup: 'call "C:\Users\marcel\AppData\Local\Temp\b2_msvc_14.0_vcvarsall_x86.cmd" >nul
        '
        notice: [msvc-cfg] condition: '<toolset>msvc-14.0/<architecture>/<address-model>32', setup: 'call "C:\Users\marcel\AppData\Local\Temp\b2_msvc_14.0_vcvarsall_x86.cmd" >nul
        '
        notice: [msvc-cfg] condition: '<toolset>msvc-14.0/<architecture>x86/<address-model>', setup: 'call "C:\Users\marcel\AppData\Local\Temp\b2_msvc_14.0_vcvarsall_x86.cmd" >nul
        '
        notice: [msvc-cfg] condition: '<toolset>msvc-14.0/<architecture>x86/<address-model>32', setup: 'call "C:\Users\marcel\AppData\Local\Temp\b2_msvc_14.0_vcvarsall_x86.cmd" >nul
        '
        notice: [python-cfg] Configuring python...
        notice: [python-cfg]   user-specified version: "3.5"
        notice: [python-cfg]   user-specified cmd-or-prefix: "C:\python35a3\PCBuild\amd64\python_d.exe"
        notice: [python-cfg]   user-specified includes: "C:\python35a3\include"
        notice: [python-cfg]   user-specified libraries: "C:\python35a3\libs"
        notice: [python-cfg]   user-specified condition: "<define>BOOST_ALL_NO_LIB=1"
        notice: [python-cfg] Checking interpreter command "C:\python35a3\PCBuild\amd64\python_d.exe"...
        notice: [python-cfg] running command 'DIR /-C /A:S "C:\Python35a3\PCbuild\amd64\python_d.exe" 2>&1'
        notice: [python-cfg] running command 'C:\python35a3\PCBuild\amd64\python_d.exe -c "from sys import *; print('version=%d.%d\nplatform=%s\nprefix=%s\nexec_prefix=%s\nexecutable=%s' % (version_info[0],version_info[1],platform,prefix,exec_prefix,executable))" 2>&1'
        notice: [python-cfg] ...requested configuration matched!
        notice: [python-cfg] Details of this Python configuration:
        notice: [python-cfg]   interpreter command: "C:\python35a3\PCBuild\amd64\python_d.exe"
        notice: [python-cfg]   include path: "C:\python35a3\include"
        notice: [python-cfg]   library path: "C:\python35a3\libs"
        notice: [python-cfg]   DLL search path: "C:\python35a3"
        notice: Searching '../../../..' for project-config configuration file 'project-config.jam'.
        notice: Loading project-config configuration file 'project-config.jam' from '../../../..'.
    ....
        ...patience...
        ...patience...
        ...found 1893 targets...
        ...updating 6 targets...
        msvc.link.dll bin\msvc-14.0\debug\threading-multi\hello_ext.dll
           Creating library bin\msvc-14.0\debug\threading-multi\hello_ext.pdb and object bin\msvc-14.0\debug\threading-multi\hello_ext.exp
        LINK : fatal error LNK1207: incompatible PDB format in 'c:\boost\libs\python\example\tutorial\bin\msvc-14.0\debug\threading-multi\hello_ext.pdb'; delete and rebuild

    ....

    ...removing bin\hello.test\msvc-14.0\debug\threading-multi\hello.py
    ...skipped <pbin\hello.test\msvc-14.0\debug\threading-multi>hello for lack of <pbin\hello.test\msvc-14.0\debug\threading-multi>hello.py...
    ...failed updating 3 targets...
    ...skipped 3 targets...

The command producing the error output is:
call "C:\Users\marcel\AppData\Local\Temp\b2_msvc_14.0_vcvarsall_x86.cmd" >nul

link /NOLOGO /INCREMENTAL:NO /DLL /NOENTRY /DEBUG /MACHINE:X86 /MANIFEST /subsystem:console /out:"bin\msvc-14.0\debug\threading-multi\hello_ext.dll" /IMPLIB:"bin\msvc-14.0\debug\threading-multi\hello_ext.pdb" /LIBPATH:"C:\python35a3\libs"   @"bin\msvc-14.0\debug\threading-multi\hello_ext.dll.rsp"

Creating library bin\msvc-14.0\debug\threading-multi\hello_ext.pdb and object bin\msvc-14.0\debug\threading-multi\hello_ext.exp
LINK : fatal error LNK1207: incompatible PDB format in 'c:\boost\libs\python\example\tutorial\bin\msvc-14.0\debug\threading-multi\hello_ext.pdb'; delete and rebuild

The link command seems to be consistent with the way python and boost are compiled (32 bit on the same compiler version).
Is there an way to diagnose where this error originated?
UPDATE: Compiling with VC9 (VS2010) and a prebuilt python 3.4 installation. I still get the same error:
link /NOLOGO /INCREMENTAL:NO /DLL /NOENTRY /DEBUG /MACHINE:X86 /MANIFEST /subsystem:console /out:"bin\msvc-10.0\debug\threading-multi\hello_ext.pyd" /IMPLIB:"bin\msvc-10.0\debug\threading-multi\hello_ext.pdb" /LIBPATH:"C:\python34\libs"   @"bin\msvc-10.0\debug\threading-multi\hello_ext.pyd.rsp"

Creating library bin\msvc-10.0\debug\threading-multi\hello_ext.pdb and object bin\msvc-10.0\debug\threading-multi\hello_ext.exp

LINK : fatal error LNK1207: incompatible PDB format in 'c:\boost\libs\python\example\tutorial\bin\msvc-10.0\debug\threading-multi\hello_ext.pdb'; delete and rebuild

Running the python interpreter to confirm the correct compiler version:
c:\Python34\python.exe
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Apparently this error has nothing to do with the "bleeding edge-ness" of the environment the build is running on. Rather its a direct result of a boost-build configuration issue.
UPDATE 2: Trying the same test with pre-built Python 2.7 and VS 2008 results in the same error.
UPDATE 3 SOLVED This builds correctly on boost v1.55 when the following steps are taken:

*

*Download and build python 3.5 a3 and build boost 1.55 with VC14 by
modifying the user-config.jam file in the home directory and running
"bjam stage --use-python"

*Move the resultant files in stage\lib from
libboost* to boost* run bjam from the tutorial directory

*Change the errant link command by adding the following LIBPATH switch:
/LIBPATH:c:\boost_1_55_0\stage\lib

The problem of linking to python 3.5 alpha3 with VC14 is isolated to boost v1.57 builds.

A: The problem seems to have been introduced with 1.56. I've managed to get Boost.Build working again by editing the file:
D:\boost\boost_1_59_0\tools\build\src\tools\msvc.jam

I made two changes:

*

*Change this (lines #1351-1355):
     generators.register [ new msvc-linking-generator msvc.link.dll :
         OBJ SEARCHED_LIB STATIC_LIB IMPORT_LIB : SHARED_LIB IMPORT_LIB :
         <toolset>msvc <suppress-import-lib>false ] ;
     generators.register [ new msvc-linking-generator msvc.link.dll :
         OBJ SEARCHED_LIB STATIC_LIB IMPORT_LIB : SHARED_LIB :
         <toolset>msvc <suppress-import-lib>true ] ;

to:
    generators.register [ new msvc-linking-generator msvc.link.dll :
        OBJ SEARCHED_LIB STATIC_LIB IMPORT_LIB : SHARED_LIB IMPORT_LIB :
        <toolset>msvc ] ;

*Remove this line (#1472):
    toolset.flags msvc.link.dll LINKFLAGS <suppress-import-lib>true : /NOENTRY ;

I've tested this on Win7 with VS2012 and Python 2.7.

A: Yes, I think Boost.Build 1.59 (and possibly 1.57 and 1.58) is broken on Windows. I gave up using Boost.Build and built it myself.


text:
Q: Bootstrap: anchors and body top margin/padding I'm using Bootstrap with a global navbar fixed to the top of the page body.

                MyBrand

Page 1

Page 2

Page 3

I added a 40px margin on top of the body in order the top of page content underlying not to be overlayed by the navbar.
body {
    background-color: #f5f5f5;
    position: relative;
    margin-top: 40px;
}

Up to there, everything works fine. I also make usage of internal anchors in order to ease the navigation inside the page, using the same mechanisms Twitter used with the affix component on the Bootstrap documentation, making the user able to jump to different sections within the page (see http://twitter.github.com/bootstrap/getting-started.html)
Section 1
Section 2
Section 3

[...]

    [...]
    [...]
    [...]
</section

    [...]
    [...]
    [...]
</section

    [...]
    [...]
    [...]

My problem is when the user clicks, the browser sticks the target to the very top of the screen, the content disappears under the navbar. I noticed Twitter used a trick, the targeted
 tags include a "padding-top: 30px;", the closest
 include a "margin-top: 10px;" CSS directive in order the text to be displayed exactly 40px below the top of the screen.
I cannot allow me to "lose" 40px between each section, my display have to remain compact. My question is: is there a way in order internal anchors not to stick to the very top of the screen view but to remain away from of the top of the screen an arbitrary length?

A: To get it to scroll to the correct position and to have the selected menu item be correct when scrolling the page, you need to set padding-top: 40px; on the anchor, and set margin-bottom: -40px; on the previous sibling of the anchor.
You can achieve this with a JS snippet that will find the elements from the nav menu and apply the styling changes.
$("header .nav a[href!=#]").each(function(){
    $($(this).attr("href")).css("padding-top", "40px").prev().css("margin-bottom", "-40px");
});

A: If your application can apply javascript then the following javascript works well too:
function maybeScrollToHash() {
    if (window.location.hash && $(window.location.hash).length) {
        var newTop = $(window.location.hash).offset().top - $('.navbar-fixed-top').height() + parseInt($('body').css('padding-top'),10);
        $(window).scrollTop(newTop);
    }
}

$(window).bind('hashchange', function() {
maybeScrollToHash();
});

maybeScrollToHash();

It is a slight modification of the answer found here: https://github.com/twbs/bootstrap/issues/193
The only difference is that the code above works on the navbar-fixed-top class.

A: Finally, I figured out how to easily solve this issue:
body {
    background-color: #f5f5f5;
    position: relative;
    margin-top: 40px;
}

section {
    padding-top:40px;
    margin-top:-40px;
}

This means a 40px margin is added on top of the body, a 40px padding is added on top of  the sections, a negative 40px margin is also added in order to move up their respective expected locations, introducing an invisible margin taken into account when the browser draws the display to a section after an anchor is clicked.
Hope this help.


text:
Q: c# I want to calculate a number in base 3 I work for a university and we have session numbers that go like this:
YYYYs

Where YYYY is four digit year (e.g. 2017, 2020 etc.) and s is a semester which can be 1, 2, 3 (1 stands for spring, 2 is summer and 3 is winter). Some examples:
20171 spring semester in year 2017
20172 summer    -/-           2017
20173 winter    -/-           2017
20181 spring    -/-           2018

I want to implement semester + and - arithmetics (+ 1 means next semester, - 1 means previous one), e.g.
20171 + 1 == 20172 (adding 1 semester)           i.e. 2017 spring + 1 = 2017 summer
20171 - 1 == 20163 (subtracting 1 semester)      i.e. 2017 spring - 1 = 2016 winter
20171 + 3 == 20181 (adding 3 semesters - a year) i.e. 2017 spring + 3 = 2018 spring
20173 + 8 == 20202 (adding 8 semesters)          i.e. 2017 winter + 8 = 2020 summer

Any idea ???

A: You are looking for modular arithmetics, e.g.
private static int AddSemester(int value, int shift) {
  int semester = (value % 10 - 1 + shift);

  int deltaYear = semester >= 0
    ? semester / 3
    : semester / 3 + (semester % 3 == 0 ? 0 : -1);

  int deltaSemester = semester - deltaYear * 3;

  return (value / 10 + deltaYear) * 10 + deltaSemester + 1;
}

Tests:
var tests = Enumerable
  .Range(-9, 19)
  .Select(shift => $"20173 + {shift,2} == {AddSemester(20173, shift)}");

Console.WriteLine(tests);

Outcome:
20173 + -9 == 20143
20173 + -8 == 20151
20173 + -7 == 20152
20173 + -6 == 20153
20173 + -5 == 20161
20173 + -4 == 20162
20173 + -3 == 20163
20173 + -2 == 20171
20173 + -1 == 20172
20173 +  0 == 20173
20173 +  1 == 20181
20173 +  2 == 20182
20173 +  3 == 20183
20173 +  4 == 20191
20173 +  5 == 20192
20173 +  6 == 20193
20173 +  7 == 20201
20173 +  8 == 20202 <- Test from the question
20173 +  9 == 20203


text:
Q: Send push notifications to APNS (AdHoc deployment) I'm trying to send push notification from my Java backend to my mobile app. For that, I'm using notnoop java-apns library.
I managed to set everything up and everything works perfectly on Development (Development certificate and provisioning profile).
I want to release the app soon but first I wanted to setup everything so that I'm ready once it's live. So I created an 'App Store and Ad Hoc' certificate, and also an 'Ad Hoc' provisioning profile.
Then I'm trying to use that P12 file which should be the same as the one I will be using once the app is live.
But unfortunately I'm getting the following exception:
java.net.SocketException: Connection closed by remote host
    at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1510)
    at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
    at java.io.OutputStream.write(OutputStream.java:75)
    at com.notnoop.apns.internal.ApnsConnectionImpl.sendMessage(ApnsConnectionImpl.java:328)
    at com.notnoop.apns.internal.ApnsConnectionImpl.sendMessage(ApnsConnectionImpl.java:312)
    at com.notnoop.apns.internal.ApnsServiceImpl.push(ApnsServiceImpl.java:46)
    at com.notnoop.apns.internal.AbstractApnsService.push(AbstractApnsService.java:56)
    at com.notnoop.apns.internal.ApnsServiceImpl.push(ApnsServiceImpl.java:36)
    at com.notnoop.apns.internal.AbstractApnsService.push(AbstractApnsService.java:45)
    .....

Anyone know what might be happening? How is it possible to work fine on Development but not AdHoc (and I'm guessing production as well, since they're using the same Push Notification certificate)?

A: I found the answer immediately after posting the question!
Basically, in development mode I had the following code to initialize the service:
this.service = APNS.newService().withCert(p12Stream, passphrase).withSandboxDestination().build();

But, when using a production certificate, you can no longer using the sandbox destination but instead you need to use the following:
this.service = APNS.newService().withCert(p12Stream, passphrase).withProductionDestination().build();


text:
Q: How are function attributes transparently viewed by a method I recently wrote a number of functions that needed a marker attribute:
def fn1(): pass
fn1.mark = True

The actual marking was done by a decorator, but that it neither here nor there. My worry was that when I marked methods in a class in the same way, the marker would not be visible when the method was bound:
class A:
    def meth1(): pass
    meth1.mark = True

But in fact the attribute was visible just fine:
>>> fn1.mark
True
>>> A.meth1.mark
True
>>> A().meth1.mark
True

However, the attribute can not be assigned to or deleted in the bound method, as it can be in the function:
>>> A().meth1.mark = False
AttributeError: 'method' object has no attribute 'mark'

>>> del A().meth1.mark
AttributeError: 'method' object has no attribute 'mark'

How are the attributes of a method made visible when it is bound?

A: Method objects implement __getattribute__ to delegate attribute access for unknown attributes to the underlying function object. They don't delegate __setattr__, though, which is why the assignment failed. If you want to see the code, it's method_getattro in Objects/classobject.c.


text: Q: How is back pressure handled when NGINX receives more requests than available PHP-FPM processes? Suppose I'm using NGINX and PHP-FPM. If I have 20 PHP-FPM processes and I receive 100 simultaneous web requests,  what manages the queue for the remaining 80 requests?


text:
Q: Understanding of Camera API Although Camera API is deprecated, it's simpler to get started than Camera2. But the document seems not to be that easy to understand(with my reading ability). I've searched a lot trying to figure it out. But there're still bunch of questions.

1.What is camera's orientation? Is there any definition that I miss? There're 4 dimensions(left, top, right, bottom) of camera. When we say orientation, which one is used and what is the relative object?
2.Why it's different between camera's orientation and device's?
3.Could you please tell me how to understand the algorithm given in the document of Camera.setDisplayOrientation() and Camera.parameters.setRotation()? There're sample code given by document for these two methods. These two algorithm both use sum and difference of orientation/rotation. I may use it directly in my project. But what does that mean exactly?
Besides, taking back-facing camera as example, the former uses (info.orientation - degrees + 360) % 360, while the latter uses (info.orientation + orientation) % 360. Confusing:/

Thanks if you can answer any of these questions above or just share some of your thoughts and experiences.

A: 1. it is the how the camera is orientated in your device
2. Device orientation is the current orientation/rotation of your device (landscape/portrait )
3. Camera.setDisplayOrientation()
affects the preview
Camera.parameters.setRotation()
affects the result pictures (jpeg etc.)

Documentation:
Camera.setDisplayOrientation()

Set the clockwise rotation of preview display in degrees. This affects
  the preview frames and the picture displayed after snapshot. This
  method is useful for portrait mode applications. Note that preview
  display of front-facing cameras is flipped horizontally before the
  rotation, that is, the image is reflected along the central vertical
  axis of the camera sensor. So the users can see themselves as looking
  into a mirror.

Camera.parameters.setRotation()

Sets the clockwise rotation angle in degrees relative to the orientation of the camera. This affects the pictures returned from JPEG Camera.PictureCallback. The camera driver may set orientation in the EXIF header without rotating the picture. Or the driver may rotate the picture and the EXIF thumbnail. If the Jpeg picture is rotated, the orientation in the EXIF header will be missing or 1 (row #0 is top and column #0 is left side).


text:
Q: PySpark: Fastest way of counting values in multiple columns I need to count a value in several columns and I want all those individual count for each column in a list.
Is there a faster/better way of doing this? Because my solution takes quite some time.
dataframe.cache()
list = [dataframe.filter(col(str(i)) == "value").count() for i in range(150)]

A: You can do a conditional count aggregation:
import pyspark.sql.functions as F

df2 = df.agg(*[
    F.count(F.when(F.col(str(i)) == "value", 1)).alias(i)
    for i in range(150)
])

result = df2.toPandas().transpose()[0].tolist()

A: You can try the following approach/design

*

*write a map function for each row of the data frame like this:

VALUE = 'value'

def row_mapper(df_row):
    return [each == VALUE for each in df_row]

*write a reduce function for data frame that takes 2 two rows as input:

def reduce_rows(df_row1, df_row2):
    return [x + y for x, y in zip(df_row1, df_row2)]

Note: these are simple python function to help you understand not some udf functions you can directly apply on PySpark.


text:
Q: Start Spring maven project with Angular 2+ I am learning stuff which I wrote in title. I need som good point where to start. Old I found is old sheets for it, so I decide ask to help here. Can you tell me how to start project with these technologies? Do exist some artifact for Spring 5 and Angular least in version 4? Pure spring project I should generate from start.spring.io but it's for spring boot, and I read boot is not good for beginners, and still without angular. Can you give me some hints? Thanks.
I will be also glad for some git repository with these technologies for inspiration.

A: You must to notice to the these notes:

*

*If you want to use AngularJs you can add your angular javascripts to the every html files and use it.

*]f you want to use Angular 2+, it is difference than AngularJs because Angular 2+ is written with Typescript and then Transpile to javascript, Angular 2+ has one html file(index.html) and your javascripts after transpile add to this file.

*If you want to use both of Spring and Angular 2+, you can use Angular project instead of Client Project and Spring Project instead of Backend Project, and how to these projects communicate each other it's very easy By Spring API.

*And the Bad Project is mixing Spring and Angular Project, in these situation you must to try hard to join Angular and Spring.


text: Q: Fast Cholesky Factrorization for Tree Laplacians Suppose $T_1$ and $T_2$ represent two Laplacian matrices of two spanning trees of $n$ vertices. Since the Cholesky factorization needs $O(n)$ time for each $T_i\ (i=1,2)$ due to the tree structure, the question is: Is there any way to factorize, e.g., using Cholesky factorization, the matrix $T:=T_1-T_2$ in $\widetilde{O}(n)$ time? What is the upper bound of time to factorize the matrix $T$?


text:
Q: ADAL java support for authentication via user credentials AzureAD supports the OAuth Resource Owner Password Credential Grant.
The ADAL SDK has recently added support for it (https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/2.8.10804.1442-rc)
Here the link for UserCredentials on ADAL .net library :
https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/blob/master/src/ADAL.NET/UserCredential.cs
do we support Authentication via user credentials in the adal4j (adal java) library ??

A: This is Brandon from the ADAL team. We do plan on adding support for  OAuth Resource Owner Password Credential Grant but it isn't there yet.
I've added this to our repo for tracking: https://github.com/AzureAD/azure-activedirectory-library-for-java/issues/4

A: It is very very recent update to the ADAL library for .NET only. Note that this is not yet available even for the Windows Phone and Windows Store apps (which are also .NET).
And, from the official GitHub Repository, the most recent work on ADAL4J is from 4 months. So, no not yet available for Java clients.


text:
Q: disabling flip screen windows 7 How do I disable the keyboard shortcut ctrl+alt+down arrow in windows 7 so that the screen is not rotated 180° when I use this shortcut?

A: I think it's Intel video driver feature, so try go to Intel Control Panel (right mouse click on Desktop) and look for "Enable Hot Keys" option.


text:
Q: How do I add multi-checkboxes to Woocommerce checkout page and allow the selections to conditionally email recipients? I would appreciate any assistance with the following...
On my WooCommerce checkout page, I need to allow my customers to select multiple distributors and then have the new order emails sent out to myself and only the distributors they selected.
I can't for the life of me figure out how to set it up using multi-checkboxes, which would allow them to select more than one (i.e. they select Distributor 1 and 3, and only the three of us receive the new order email).
I was able to figure it out using a dropdown menu (thanks to reading through a variety of posts within this community), however, this option only allows for one selection. Any help would be greatly appreciated! :)
Current code I was able to piece together:
// // Add custom checkout field
add_action( 'woocommerce_after_order_notes', 'sj_custom_checkout_field' );
function sj_custom_checkout_field( $checkout ) {
    echo '

' . __('Distributor') . '
';

    woocommerce_form_field( 'my_field_name', array(
        'type'      => 'select',
        'class'     => array('wps-drop'),
        'required'  => true, // Missing
        'options'   => array(
            ''          => __( 'Select Your Preferred Distributor', 'wps' ),
            'Distributor 1'   => __( 'Distributor 1', 'wps' ),
            'Distributor 2'      => __( 'Distributor 2', 'wps' ),
            'Distributor 3'    => __( 'Distributor 3', 'wps' ),
            'Distributor 4'    => __( 'Distributor 4', 'wps' ),
            'Distributor 5'    => __( 'Distributor 5', 'wps' )

        )
    ), $checkout->get_value( 'my_field_name' ) );
    echo '
';
}

// Process the checkout
add_action('woocommerce_checkout_process', 'sj_custom_checkout_field_process');
function sj_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( empty( $_POST['my_field_name'] ) )
        wc_add_notice( __( 'Please select your preferred distributor.' ), 'error' );
}

// Save the custom checkout field in the order meta
add_action( 'woocommerce_checkout_update_order_meta', 'sj_custom_field_checkout_update_order_meta', 10, 1 );
function sj_custom_field_checkout_update_order_meta( $order_id ) {

    if ( ! empty( $_POST['my_field_name'] ) )
        update_post_meta( $order_id, 'my_field_name', $_POST['my_field_name'] );
}

add_filter( 'woocommerce_email_recipient_new_order',  'new_order_conditional_email_recipient', 10, 2 );
function new_order_conditional_email_recipient( $recipient, $order ) {
    if( is_admin() ) return $recipient;

    // Get the order ID (Woocommerce retro compatibility)
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    // Get the custom field value (with the right $order_id)
    $my_field_name = get_post_meta( $order_id, 'my_field_name', true );

    if ($my_field_name == "Distributor 1")
        $recipient .= ',1@email.com';
    elseif ($my_field_name == "Distributor 2")
        $recipient .= ',2@email.com';
    elseif ($my_field_name == "Distributor 3")
        $recipient .= ',3@email.com';
    elseif ($my_field_name == "Distributor 4")
        $recipient .= ',4@email.com';
     elseif ($my_field_name == "Distributor 5")
        $recipient .= ',5@email.com';

    return $recipient;
}


text:
Q: Why does the matplotlib histogram bar disappear with increasing bins range? import matplotlib.pyplot as plt
ones = [1 for _ in range(500)]

plt.hist(ones, bins=range(50), orientation='horizontal', density=True)

yields the following plot:

A higher bins range still makes the bar visible:
plt.hist(ones, bins=range(900), orientation='horizontal', density=True)

However, increasing the bins range even further lets the plot disappear:
plt.hist(ones, bins=range(999), orientation='horizontal', density=True)

Obviously the bin width becomes thinner with an increasing bins range.
How can I nevertheless make the plot visible for bins=range(999)?

A: Try setting ylim
import matplotlib.pyplot as plt
ones = [1 for _ in range(500)]

plt.hist(ones, bins=range(1000), orientation='horizontal')
plt.ylim(-3,3)


text:
Q: How to remove item in list in list with list comprehension I have a large list like this:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]

I'm trying to remove all numbers within the lists of this list. So I made a list of numbers as strings from 1 to 100:
def integers(a, b):
         return list(range(a, b+1))

numb = integers(1,100)

numbs = []
for i in range(len(numb)):
    numbs.append(str(numb[i])) # strings

numbs = ['1','2',....'100']

How can I iterate through lists in mylist and remove the numbers in numbs? Can I use list comprehension in this case?

A: If number is always in the end in sublist
mylist = [ x[:-1] for x in mylist ]

A: mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick.
However, this isn't quite what you've asked. Nothing was actually removed from mylist, we've just built an entirely new list and reassigned it to mylist. Same logical result, though.

A: If numbers are always at the end and only once, you can remove the last item like:
my_new_list = [x[:-1] for x in mylist]

If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]

I would also recommend to generate the list of interger as follow :
integer_list = list(map(str, range(1, 100)))

I hope it helps :)

A: Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]

A: If you have the following list:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]

Using list comprehension to remove element in numbs
[[l for l in ls if l not in numbs] for ls in mylist]

This is a more general way to remove digit elements in a list
[[l for l in ls if not l.isdigit()] for ls in mylist]


text:
Q: terminating a running boost thread I currently have a boost thread as such
class foo
{
  private:
  boost::shared_ptr<boost::thread> t;
  public:
  foo()
  {
    t = boost::make_shared<boost::thread>(&foo::SomeMethod,this);
  }
  void SomeMethod()
  {
    while(true)
    {
       .... //Does some work
    boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); //sleep for 5 seconds
    }
  }

  void stopThread()
  {
    //Elegant and instant way of stopping thread t
  }
}

I have read from this post that you have to define interruption points however I am not sure if I understand how that would fit in my scenario. I am looking for a safe elegant way that will ensure that thread t is terminated

A: You can't ever safely terminate a thread, you just need to tell it from the outside that it should stop. If you interrupt a thread, you don't know where you interrupted it and you could leave the system in an unknown state.
Instead of looping forever, you can check a variable (make sure it's thread safe though!) inside the thread's loop to see if the thread should exit. What I do in work threads is I have them wait on a condition variable, and then when there's work they wake up and do work, but when they're awake they also check the "shutdown" flag to see if they should exit.
A snippet of my code:
//-----------------------------------------------------------------------------
void Manager::ThreadMain() {
    unique_lock<mutex> lock( m_work_mutex, std::defer_lock );
    while( true ) {
        lock.lock();
        while( m_work_queue.empty() && !m_shutdown ) {
            m_work_signal.wait( lock );
        }

        if( !m_work_queue.empty() ) {

            // (process work...)
            continue;
        }

        // quit if no work left and shutdown flag set.
        if( m_shutdown ) return;
    }
}

You could maybe get away with something like:
std::atomic<bool> stop_thread = false;

void SomeMethod()
{
  while( !stop_thread )
  {
    .... //Does some work
    boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); //sleep for 5 seconds
  }
}

void stopThread()
{
  stop_thread = true;

  // join thread (wait for it to stop.)
  t->join();
}

And let me tell you, sometimes it isn't easy to make something safely exit. A few weeks ago I had a big struggle with threaded console input. I ended up having to handle raw windows console events and translating them into keystrokes myself, just so I could simultaneously intercept my custom shutdown event.

A: Use boost::thread interrupt()
#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>

class Foo
{
private:
    boost::shared_ptr<boost::thread> t;
public:
    Foo()
    {
        t = boost::make_shared<boost::thread>(&Foo::SomeMethod, this);
    }
    void SomeMethod()
    {
        std::cout << "thread starts" << std::endl;
        while(true) {
            std::cout << "." << std::endl;
            boost::this_thread::sleep(boost::posix_time::seconds(1));
        }
    }
    void stopThread()
    {
        t->interrupt();
        t->join();
        std::cout << "thread stopped" << std::endl;
    }
};

int main()
{
    Foo foo;
    boost::this_thread::sleep(boost::posix_time::seconds(5));
    foo.stopThread();
    return 0;
}

Execute it
# g++ f.cpp -lboost_thread && ./a.out
thread starts
.
.
.
.
.
thread stopped


text:
Q: How to Extract Payment response? I'm integrating payment gateway of PayTM to my using android and PHP I got this type of response. How can I extract the code using PHP and store it to the Mysql database?
The Response Code is:-
[
    {
    STATUS=TXN_SUCCESS,
    CHECKSUMHASH=hMgfJKzp6a2W91+wVQ71qd58nfvyEsLPgNrnvnYSRYpXDf9YB6+vdtYyejB2w1ZUt1MG8TiASW/jWBRnDO84MM3OlM/+1e5T2tmQ3JasAIw=,
    BANKNAME=Bank,
    ORDERID=789ERJSO5HAG,
    TXNAMOUNT=73.00,
    TXNDATE=2019-10-27 16:16:39.0,
    MID=NGtbUJ50332856675382,
    TXNID=20191027111212800110168691700967146,
    RESPCODE=01,
    PAYMENTMODE=DC,
    BANKTXNID=778001546502320,
    CURRENCY=INR,
    GATEWAYNAME=HDFC,
    RESPMSG=Txn Success
    }
]

A: Unless I am missing something that is not a particularly useful format for the data response. However this would convert it into a json string which you could store in a database, or make into data that would store into specific columns
$s = '[
    {
    STATUS=TXN_SUCCESS,
    CHECKSUMHASH=hMgfJKzp6a2W91+wVQ71qd58nfvyEsLPgNrnvnYSRYpXDf9YB6+vdtYyejB2w1ZUt1MG8TiASW/jWBRnDO84MM3OlM/+1e5T2tmQ3JasAIw=,
    BANKNAME=Bank,
    ORDERID=789ERJSO5HAG,
    TXNAMOUNT=73.00,
    TXNDATE=2019-10-27 16:16:39.0,
    MID=NGtbUJ50332856675382,
    TXNID=20191027111212800110168691700967146,
    RESPCODE=01,
    PAYMENTMODE=DC,
    BANKTXNID=778001546502320,
    CURRENCY=INR,
    GATEWAYNAME=HDFC,
    RESPMSG=Txn Success
    }
]';

function makeIntoJsonString($string)
{
    $t = str_replace(['[', '{', ']', '}', ' ', "\n"], '', $string);
    $json_string = [];
    foreach ( explode(',', $t) as $pair ) {
        $bits = explode('=', $pair,2);
        $json_string[$bits[0]] = $bits[1];
    }
    return json_encode($json_string);
    // or you could just return the array if you dont want a JSON String
    // return $json_string;
}

$json = makeIntoJsonString($s);
echo $json;

RESULT
{
    "STATUS":"TXN_SUCCESS",
    "CHECKSUMHASH":"hMgfJKzp6a2W91+wVQ71qd58nfvyEsLPgNrnvnYSRYpXDf9YB6+vdtYyejB2w1ZUt1MG8TiASW\/jWBRnDO84MM3OlM\/+1e5T2tmQ3JasAIw=",
    "BANKNAME":"Bank",
    "ORDERID":"789ERJSO5HAG",
    "TXNAMOUNT":"73.00",
    "TXNDATE":"2019-10-2716:16:39.0",
    "MID":"NGtbUJ50332856675382",
    "TXNID":"20191027111212800110168691700967146",
    "RESPCODE":"01",
    "PAYMENTMODE":"DC",
    "BANKTXNID":"778001546502320",
    "CURRENCY":"INR",
    "GATEWAYNAME":"HDFC",
    "RESPMSG":"TxnSuccess"
}


text:
Q: RewriteOptions / UseRewriter behaves inconsistently after upgrading from .net 5 to .net 6 I updated an app from .net 5 to .net 6.
This same code:
        app.UseHttpsRedirection();

        var redirectOptions = new RewriteOptions()
            .AddRedirect(@"^(?i)\bassets/collagebuilder\b/((.*)\.(gif|jpg|jpeg|png|bmp))", $"{surveyConfig.CollageBuilderAssetsRedirectUrl}/$1")
            .AddRewrite("st/(.*)", "/$1", true);

        app.UseRewriter(redirectOptions);

shows the expected images in the UI for the .net 5 version, but in .net 6

Error: AccountRequiresHttps.
This
surveyConfig.CollageBuilderAssetsRedirectUrl is
configured as "https://*****/collagebuilder" (I masked the root part of the URL).
To make matters more confusing, I have at least 2 examples where the images do show up, redirect is practically identical, and the url similarly would require https.

A: I found a solution that might help someone else who crosses this bridge.
First I created an XML file, IISUrlRewrite.xml and saved it.  This part was easy for me since this is almost exactly the same that was in the project back when it was in the .net framework version's web.config:
<rewrite>
<rules>
    <rule name="images redirection">
        <match url="^assets/([0-9]+)/((.*)\.(gif|jpg|jpeg|png|bmp|mp4|mp3|ogg|wav|tiff))$" ignoreCase="true" />
        <action type="Redirect" url="https://****/assets/design/{R:1}/{R:2}" />
    </rule>
    <rule name="capture question redirection">
        <match url="^answers/([0-9]+)/([a-zA-Z0-9]+)/((.*)\.(gif|jpg|jpeg|png|bmp|mp4|mp3|ogg|wav|tiff))$" ignoreCase="true"/>
        <action type="Redirect" url="https://****/answers/design/{R:1}/{R:2}/{R:3}" />
    </rule>
    <rule name="collagebuilder redirection">
        <match url="^assets/collagebuilder/((.*)\.(gif|jpg|jpeg|png|bmp))$" ignoreCase="true" />
        <action type="Redirect" url="https://****/collagebuilder/{R:1}" />
    </rule>
    <rule name="survey theme redirection">
        <match url="^themes/((.*)\.css)$" ignoreCase="true" />
        <action type="Redirect" url="https://****/themes/{R:1}" />
    </rule>
    <rule name="st folder redirection">
        <match url="st/(.*)" ignoreCase="true"/>
        <action type="Rewrite" url="/{R:1}" />
    </rule>
</rules>

Next, modified my Startup / Program (whatever you want) code:
app.UseHttpsRedirection();

        using (StreamReader iisUrlRewriteStreamReader =
        File.OpenText("IISUrlRewrite.xml"))
        {
            var options = new RewriteOptions()
                .AddIISUrlRewrite(iisUrlRewriteStreamReader);
            app.UseRewriter(options);
        }

        //var redirectOptions = new RewriteOptions()
        //    .AddRedirect(@"^/assets/([0-9]+)/((.*)\.(gif|jpg|jpeg|png|bmp|mp4|mp3|ogg|wav|tiff))", $"{surveyConfig.AssetsRedirectUrl}/$1/$2")
        //    .AddRedirect(@"^/answers/([0-9]+)/([a-zA-Z0-9]+)/((.*)\.(gif|jpg|jpeg|png|bmp|mp4|mp3|ogg|wav|tiff))", $"{surveyConfig.AnswerAssetsRedirectUrl}/$1/$2/$3")
        //    .AddRedirect(@"^/assets/collagebuilder/((.*)\.(gif|jpg|jpeg|png|bmp))", $"{surveyConfig.CollageBuilderAssetsRedirectUrl}/$1")
        //    .AddRedirect(@"^/themes/((.*)\.css)", $"{surveyConfig.ThemeAssetsRedirectUrl}/$1")
        //    .AddRewrite("st/(.*)", "/$1", true);

        //app.UseRewriter(redirectOptions);

I'm not sure why the original approach wasn't working for me (reliably), but this seems to do the trick.  It's explained in more detail here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-6.0


text:
Q: VIM [new file] message appears when file already exists I'm trying to view the following node logs on my server:

However, when I run vim 2020-10-11T00_31_14_122Z-debug.log - It's creating a new file rather than acknowledging the existing one:

Am I missing something blatantly trivial?

A: Please be sure you are running the code from the correct folder or the path leads you to the file you want, once the path is correct you might use auto-complete which will give you the file easier and faster.


text:
Q: iOS In House Distribution with iOS Enterprise program and external developer if external developer is developing the app for one client that is going to distribute the app in house, how should the developer export the app, so that the client can than distribute it in house.
Does developer need private key of In House Distribution certificate of the client? Are there other solutions to export the app for the client without getting the private key of In House Dist. certificate?
Solution
I came out with following solution:

*

*get admin rights for iOS Enterprise program

*create new certificate (or get the private key from team agent) (thanks to Z.pyyyy)

*configure XCode to allow "don't sign code" like described here

*in project and targets build settings use "don't sign code" for signing and automatic for provisioning profiles (it will take the provisioning profile for your team)

*select right team

*archive your project

*use export for enterprise distribution (this creates ipa file)

*distribute the ipa file

A: Actually, as an external developer, you don't need any of those certificate or signing identity stuff.
You can generate an unsigned ipa iOS application, send the unsigned ipa file to your client so that they can resign the application as they like.
You can refer to the following links:
Generating an unsigned IPA iOS application
and
How to Re-sign an iOS App from External Developers


text:
Q: Adding a relay to stop motorcycle engine I have a Honda CG125 - kickstart CDI motor cycle and I am adding a security system in it which has a relay to cut off the engine remotely.
The ignition coil has two cables coming to it, one green and other black/light green.
one of the cable is coming from CDI and the other is ground.
I am planning to install relay to one of these wires. I connected the Voltmeter to find out the voltage, when I kick the starter the voltage seems to go very high like 10,000 V etc.
Is this OK to install relay to one of these cable to stop engine - the relay 12 V / 40 A ?

A: A CDI usually has two inputs. The first receives several pulses of some 100V to charge a capacitor, the second is a trigger signal of just a few volts to discharge the CDI via the primary side of the ignition coil.
So, if you want to place your relay here, you should switch the trigger. Remember that the charging and trigger pulses come from a generator like setup, if you open these circuits, you may get high voltage spikes. So, you may ground the trigger signal via an appropriate resistor.
However, the motor is stopped by the key, so why don't you switch the wire from the key?

A: It's probably easier to interrupt the input power to the CDI than it is to interrupt (or short to ground) the high voltage output.