text:
Q: Intersection and Complement of multiple lists of ranges I have a problem like this: I have multiple list of intervals,now I want to get all the possible intersections and complements of it. For example, in case of 2 lists:
a = [[0, 2], [5, 10], [13, 23], [24, 25]]
b = [[1, 5], [8, 12], [15, 18], [20, 24]]

The output should be
output_a = [[0, 1], [1, 2], [5, 8], [8, 10], [13, 15], [15, 18], [18, 20], [20, 23], [24, 25]]
output_b = [[1, 2], [2, 5], [8, 10], [10, 12], [15, 18], [20, 23], [23, 24]]

and so on for n list
For visualization:
    List_a           |-----------|     |----------|
    List_b                  |------------|   |-------|
    List_c           |---------|     |------------|

       Set           |------|--|-|---|-|-|---|----|--|

  Output_a           |------|--|-|     |-|---|----|
  Output_b                  |--|-|---|-|-|   |----|--|
  Output_c           |------|--|     |-|-|---|----|

My pseudocode with Python set()
Get all (start, end) of all intervals in all list into a set()
for each list:
    for intervals in list:
        for each element in set:
            if element in intervals:
                ->store element in dict

But it seems like this is not efficient and elegant, since it requires 3 for loops
Could you please suggest a better algorithm for this case please? Thank you very much

A: (Note: I did not fully understand the question and how you compose output_a and output_b. In this "solution", I'll provide the building bricks using a library I developed, I hope it helps, but remember, the output of this "solution" does not match exactly what you provided!)
I'm the maintainer of portion, a Python library providing data structure and operations for intervals (and interval sets). The library notably supports automatic simplification of intervals, which leads to a different output than the one proposed.
Let's import the library, and define your lists:
>>> import portion as P
>>> a = [[0, 2], [5, 10], [13, 23], [24, 25]]
>>> b = [[1, 5], [8, 12], [15, 18], [20, 24]]

Now we convert these lists to (disjunctions of) intervals:
>>> a = P.Interval(*[P.closed(x, y) for x, y in a])
>>> b = P.Interval(*[P.closed(x, y) for x, y in b])
>>> a
[0,2] | [5,10] | [13,23] | [24,25]
>>> b
[1,5] | [8,12] | [15,18] | [20,24]

Let's compute the intersection and its complement:
>>> intersection = a & b
>>> complement = ~intersection
>>> intersection
[1,2] | [5] | [8,10] | [15,18] | [20,23] | [24]
>>> complement
(-inf,1) | (2,5) | (5,8) | (10,15) | (18,20) | (23,24) | (24,+inf)

Since you do not care about infinities, let's restrict the complement to the range of a and b. To do so, we take the enclosure of a | b (the enclosure being the smallest atomic interval containing the given interval):
>>> (a | b).enclosure
[0,25]
>>> complement = complement & (a | b).enclosure
>>> complement
[0,1) | (2,5) | (5,8) | (10,15) | (18,20) | (23,24) | (24,25]

Based on intersection and complement, you have all possible "breakpoints" (and their "origin").

A: It seems that your example output does not match your picture: According to your picture, the element [24,25] should not be in output_b since b stops at 24. Also, according to the picture, [5,8] should not be in output_b since b does not intersect this interval.
Here is a code that generates the lists according to your picture. The code also has three nested loop but for each list, it goes through the list and the set only once, so the two innermost loops only have linear complexity, not quadratic. The idea is to sort the union of breakpoints and then scan the two lists simultaneously. It assumes that the intervals in the original list do not overlap and are in increasing order.
a = [[0, 2], [5, 10], [13, 23], [24, 25]]
b = [[1, 5], [8, 12], [15, 18], [20, 24]]

lists = [a, b]

# collect all endpoints first into a set and the into a sorted sequence
breaks = set()
for l in lists:
    for i in l:
        breaks.update(i)
breaks = sorted(breaks)

for l in lists:
    output = []
    b = 0
    # For each interval
    for start, end in l:
        # Advance b until it falls into this interval:
        while breaks[b] <= start: b += 1
        # Now collect all sub-intervals from
        while b < len(breaks) and breaks[b] <= end:
            output.append([start, breaks[b]])
            start = breaks[b]
            b += 1
    print(output)

The output is
[[0, 1], [1, 2], [5, 8], [8, 10], [13, 15], [15, 18], [18, 20], [20, 23], [24, 25]]
[[1, 2], [2, 5], [8, 10], [10, 12], [15, 18], [20, 23], [23, 24]]


text:
Q: How to draw Complicated shapes in html5 canvas? I have a brain image like the one I attached below which I want to draw on canvas.
I see that it can be drawn by using many beizercurves or quadraticCurves.
My requirement is to draw the shape only by using html canvas or css, without svg, and without images.
Is there any easier way to draw them on canvas?
Are there any formulas like the formulas used to create sine waves,  that I can use to draw these curves.
Thanks in advance!!

A: In general you would use a bezier curve to draw shapes like this.
To create a bezier curve with html5 canvas use the bezierCurveTo() function.
But it will still be very tedious to draw this kind of shape.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Positioning multiple backgrounds in css3 I've got following setup
background-image: url(image1.png) , url(image2.png);

Idea is that image1.png repeats everywhere whereas image2.png should only start 200px from pages top and only repeat-x. I know you can position background like:
background-position: top left, left bot etc...

But how do I position it 200px from top of the page? and make it repeat-x?

A: You'll want to use the shorthand for background:
{background: url(image1.png) repeat, url(image2.png) 0 200px repeat-x;}

http://www.css3.info/preview/multiple-backgrounds/


text:
Q: Are main principles different in OpenGL ES 1.1 and 2.0? As many others I've been in a crazy search for a good OpenGL ES 2.0 tutorial. But I seem to have tasted any available but I'm still not confident. I know that 1.1 has a fixed pipeline whereas 2.0 leaves everything upon the programmer's taste. So I thought I might learn lights, textures and stuff from 1.1 tutorials and then after learning those concepts I can do all the stuff that's not provided as ready functions manually using shaders. DO you think I'm on a right way or should I stop?

A: Your question is a little more subjective, so my answer will necessarily contain personal opinions, but I believe that it is no longer useful to start learning OpenGL ES with 1.1 and that people should start with 2.0. On iOS, the number of active devices in the field that can't handle 2.0 is estimated to be somewhere less than 5% (based on sales, the highest this number could possibly be is 16%). I can't speak to Android statistics, because I've had a harder time pinning down numbers there due to the diversity of available hardware, but that also appears to be very much in 2.0's favor.
When it comes to the technical side of things, I don't think there is much to be gained by learning 1.1 first, because you'll end up tossing a lot of that out the window when moving to 2.0. There isn't much of a point in learning the specific API calls to set up lights and material properties in 1.1 when you'll have to create your own shader programs to do this in 2.0. You don't really gain any insight into how these lights, etc. work in the fixed function pipeline of 1.1, because that just acts like a black box. When it came time for me to move to 2.0, I found that I didn't really understand what had been calculated for me in 1.1, so I didn't gain much from experience with the older API.
The things that are the same between the two can be learned just as well from starting with 2.0.
One large advantage that 1.1 has over 2.0 is the availability of sample code and tutorial material. However, that's getting better over time as people migrate to the new API, and I describe some of the best material I've found on the topic (with an emphasis on iOS) in this answer. As I indicate there, I taught classes on both 1.1 and 2.0 that can be found for free on iTunes U. The course notes for that link to several simple 2.0 examples I assembled to demonstrate how to replicate 1.1 capabilities. I also talk about how to transition some 1.1 code to 2.0 in this answer (the PowerVR reference I link to there is particularly good for showing how 1.1 effects can be generated in 2.0 shaders).
Personally, I feel much more at home with OpenGL ES 2.0 than I ever did with 1.1, in large part because I feel the 2.0 API is much simpler. I don't have to remember all of the commands to set up my scene in just the right way, and what I can and cannot do with the API. I just write simple GLSL code to do what I want.


text:
Q: Send custom object and a string to other activity I need send a custom object and a string to other activity. custom object(User) implemented Parcelable interface.
I do like this:
Intent intent = new Intent("action") ;
Bundle data = new Bundle() ;
data.putString("EDIT", "EDIT");
data.putParcelable("DATA", user ) ; //user is custom object
intent.putExtra("BUNDLE", data) ;
startActivity(intent) ;

In other activity, I receive the intent, but the EDIT map data is null, only Pacelable data in  Intent, EDIT string missed.
Intent intent  = getIntent() ;
String edit = bundle.getString("EDIT") ;  // edit = null should be EDIT
Bundle bundle =intent.getBundleExtra("BUNDLE") ;

Anyone else developers know this issue, can you give me suggestions? thanks.

A: Dude use it this way
 Intent intent = new Intent(getBaseContext(), NextActivity.class);
 Foo foo = new Foo();
 intent.putExtra("foo ", foo);
 intent.putExtra("string", "hi");
 startActivity(intent);

To GET
 Foo foo = (Foo) getIntent().getParcelableExtra("foo");
 String mString =  getIntent().getStringExtra("string");


text:
Q: After I put a redirect code, the login form isn't working I've set a redirect from my index.php to form.php which there's a login form inside. But the login form isn't working, after I logged in it stayed at form.php
I put this code for the redirect in index.php :
<?php
    header('Location: form.php');
    exit();
?>

I expect the login form to be working after I put the redirect code in index.php

A: Sounds like once the login is made, you are getting redirected back to the login page, try this.
//index.php
// Change user_id to whatever session you are setting
if ( !isset($_SESSION['user_id']) ) {
  exit(header('Location: form.php'));
}

If you want to block access to the login page once logged in, do the same but check if the session is set.
//form.php
if ( isset($_SESSION['user_id']) ) {
  exit(header('Location: index.php'));
} else {
  // login code
}


text:
Q: INDEXING IN mysql when using multiple columns In my project I am using DataTables plugin to display data in table from database.
Every column has filter so user can filter data based on input on each column.
I am confused how to setup indexes, do ever column need index?
Is it good practice to index every column in table?
My table have 6 columns.


text:
Q: Why does wsgiref.simple_server report content-type of request as 'text/plain' while none was sent? Output from client.py is text/plain although no content-type header was sent to the server.
Why?
# ---------------------------------------------- server.py
from wsgiref.simple_server import make_server

def simple_app(environ, start_response):
    print environ.get('CONTENT_TYPE')
    start_response('200 OK', [])
    return []

make_server('localhost', 88, simple_app).serve_forever()

# ---------------------------------------------- client.py
import subprocess
import urllib2

p = subprocess.Popen(['python', '-u', 'server.py'])
req = urllib2.Request('http://localhost:88', headers={})
assert not req.has_header('content-type')
urllib2.urlopen(req).read()
p.terminate()

A: The type text/plain is the default for MIME, in section 5.2 Content Type Defaults.
The WSGI simple_server uses BaseHTTPRequestHandler which in turn uses a mimetools.Message class to parse the headers sent by the client -- here is where it sets the default:
# mimetools.py

class Message(rfc822.Message):

    def parsetype(self):
        str = self.typeheader
        if str is None:
            str = 'text/plain'


text:
Q: How can Windows performance counter data be saved directly to SQL Server tables? I would like to log data from a given set of Windows performance counters directly to tables SQL Server.  Does Windows provide a way to do this without writing a custom application to do so?
If so, are there any serious issues with doing so?

A: Yes, it is possible. Here's a resume based on this article.
Select the counters you want to analyze
Export all counters on local machine to a local folder.
typeperf -q  > counters.txt

Edit the file exported and leave only the counters you want to sample. I left the two below:
\Processor(*)\% Processor Time
\Memory\Pages/sec

Collect Data
Here you will collect the data you want to analyze using logman.
Create a collection.
logman create counter MyCollection -s %computername% -cf counters.txt

Start Logging
logman MyCollection start

Once you have collected a representative sample, stop coolection.
logman MyCollection stop

By default on Vista and Windows 2008 servers, your performance monitor counters will be stored in %systemdrive%\PerfLogs\Admin
and will be named after your collection name (in our case they will be called MyCollection.blg
So, you need to go to this folder.
cd %systemdrive%\PerfLogs\Admin

Load to SQL Server
Create a ODBC datasource. Warning: SQL Server Native Client cannot be used with perfmon. Perfmon is a Windows tool that can only be used with DSNs that use the MDAC SQLODBC driver included with Windows.
I created an ODBC datasource named relogDSN. ServerName is the name of the server which I collected the data on. This name will be written to the SQL Server table DisplayToID that is created and I can query on it when I want to look at my counters.
relog MyCollection_000001.blg -f SQL -o SQL:relogDSN!ServerName

Analyzing Data
Your counters will be saved to the tables CounterDetails, CounterData and DisplayToID, here's a SQL query as an example.
SELECT MachineName,
   CONVERT(DATETIME, CONVERT(VARCHAR(16), CounterDateTime)) as [Date],
   AVG(CounterValue) as Average,
   MIN(CounterValue) as Minimum,
   MAX(CounterValue) as Maximum
FROM CounterDetails
   JOIN CounterData ON CounterData.CounterID = CounterDetails.CounterID
   JOIN DisplayToID ON DisplayToID.GUID = CounterData.GUID
GROUP BY MachineName,
   CONVERT(DATETIME, CONVERT(VARCHAR(16), CounterDateTime))

A: there is no built-in way in Windows to write the PerfCounters to a SQL Database. You must code a tool which does this.


text:
Q: $\int_a^bf(x) dx=\int_a^bf^\prime(x) dx$ I am facing problem in the following exercise. I don't know how to tackle this problem. Can anyone please help me?

The only thing I can say $$ \int_a^bf(x) dx=\int_a^bf^\prime(x) dx \implies \int_a^bf(x) dx=f(b)-f(a).  $$

A: There is only one function that fits this case (the questions implies D is true, so I'll run with it) which is that $f(x)=e^x$.  Therefore we must determine if the image of $f(x)$ (which is $\mathbb{R}^+$) is compact.  This leads in to a topological argument and that was a class that didn't go so well for me.


text:
Q: A fair die is rolled twice. Let X1 and X2 denote the outcomes, and define random variable X to be the minimum of X1 and X2. What is Var(X)? This question asks 4 parts.  I can get them all except for the VAR.  And I think I tried literally every combo and don't have it right.  Here is where I'm at:
Q1: How many possible values are there for X?
A1: 6 (pretty easy, min can always be 1-6)
Q2: What is the probability that X=1
A2: 11/36 (This is the probability that at least one of the two rolls is a 1.)
Q3: What is E(X)?
Expected Probability is the Summation of the P(i) * i
for each number, find the combination of rolls that allow for your "i" to be the min.  for example.  A 5's possibilities are (5,5) - (5,6) and (6,5) - therefore 3 of 36 roll combinations would be valid for a 5 being lowest.

*

*1 * 11/36 = 11/36

*2 * 9/36 = 1/2

*3 * 7/36 = 7/12

*4 * 5/36 = 5/9

*5 * 3/26 = 5/12

*6 * 1/36 = 1/6

A3: (summation) = 91/36
So far so good :)
Q4: Var(X)
VAR = E(X-mu)^2
I've tried to compute this with the above E(X) in so man ways I'm spinning. Obviously, I'm close but I just can't get this.  Can someone point me in the right direction to calculate the Var(X)?

A: For variance you know the formula. So find the $X-\mu_X$ for each X where $\mu_X $ is the mean or E(X) = 91/36. You can have columns like this:
$X. |. f(X-\mu_X).   $
where f is the frequency of each X (eg.instead of adding 1 eleven times , you can multiply by 11)
So now find $E(X-\mu_X)^2$. Which is average. So simply add the entries in last column,square the number, and divide by $\sum f$ which is 36. You will get the answer


text:
Q: Jquery occasionally returns zero height and width on image I am observing an unusual behavior. I have a floating dialogue box in which I am placing an image. I want to get the image size using jquery and resize its div container to the appropriate size. It works fairly well, but the function occasionally returns zeros as the image sizes.
$('#dialogueContainer').html('

');

var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();

console.log(imageHeight + 'x' + imageWidth); //<-- This occasionally returns "0x0"

I suspect that the image may not be ready in the DOM when jquery attempts to measure its height and width. Any thoughts?

A: You can bind a load event handler to the element before adding it to the DOM, to get the width/height once it's available. You can also explicitely set the width/height of the image using CSS or inline attributes.
//create an img element, passing attribute values as we do, then bind an event handler to the `load` event for the image
var $img = $('', { src : '/photos/' + file, id : 'lightImage' }).on('load', function () {

    //now that the image has loaded we can be sure the height/width values we receive are accurate
    var imageHeight = $(this).height(),
        imageWidth  = $(this).width();

    console.log(imageHeight + 'x' + imageWidth);
});

//now change the HTML of the container, emptying the container, then appending a div element with the `dialogue` class which also has a child img element (our image from above)
$('#dialogueContainer').html($('
', { class : 'dialogue' }).html($img));

I like to bind the load event handler to the element before adding it to the DOM or changing it's source, this way you know the load event is in place when the image actually loads (which can happen quickly from cache).
Note that .on() is new in jQuery 1.7 and in this case replaces .bind() (of earlier versions).
Update
I would like to stress the fact that if you know the dimensions of your image you should explicitly declare them (this is best practice for faster browser rendering):

A: You're right, the image is not loaded.
Worst, in IE, sometimes the size reported is something like 40x60 (the small icon you see when the image is not loaded yet).
jQuery reports that the load event can be used with images:
http://api.jquery.com/load-event/
I tried a long time ago to solve this problem, cross browser, and I ended up polling the image sizes to trigger a custom "load" event.
Thanks

A: I had this problem trying to get the height of a
 containing paragraphs and it wasn't because the content hadn't loaded - I tried alerting the height of it on a click so I could be sure it was there 1st and was still getting 0 returned. It turned out to be a css issue I added a clear class to it using the clear hack:
.clear { display:inline-block; }
.clear:after, .container:after {content:"."; display:block; height:0; clear:both; visibility:hidden;}
* html .clear { height:1%; }
.clear { display:block; }

And that fixed it right up.

A: I believe you are right. Try logging the image's width and height once the image has loaded:
var $img = $('');

$img.load(function(){
  var imageHeight = $('#lightImage').height();
  var imageWidth = $('#lightImage').width();

  console.log(imageHeight + 'x' + imageWidth);
});

$img.attr('src', '/photos/' + file);

Notice I've set src after binding the event handler to the image. Otherwise, I had unpredictable results, depending on the browser.

A: Is the image ever hidden, either with display: none or visibility: hidden? Invisible elements return a width and height of 0.

A: You are getting 0 becuase image is not loaded yet , you can use settimeout like:
setTimeout(function () {
 // your code goes here
var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();
},2000);


text:
Q: Spring Boot http call to remote web service I have to call remote REST endpoint from my web application build with Spring Boot 2.0.5
I can use HttpURLConnection, though as Spring have RestTemplate I checked what is it and I found it will be deprecated soon:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
Also this page mentions the new class to call over HTTP. It is possible to use it in both synchronous and asynchronous ways:

WebClient offers a modern alternative to the RestTemplate with
  efficient support for both sync and async, as well as streaming
  scenarios

Problem is I not see in javadoc for WebClient any note about synchronous way it works:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html
One more issue with WebClient - to get it works I need to have WebFlux in class path https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-webclient.html
But this will brake my Spring Security configuration as it build in synchronous way. As I understand once I have WebFlux Spring Security will use asynchronous configuration.
How can I make http calls to remote endpoint with Spring, or should I avoid and use HttpURLConnection class (or Apache's library)?
Update
WebFlux seems not cause any problems with Spring Security buit in synchronous way.
Also please note my application is not reactive - it is multi threaded (Sorry if I was not clear on this before). I have transactions so reactive approach seems not fit to my case.

A: You can use Spring org.springframework.web.client.AsyncRestTemplate for async Rest call. Below is one of the Utility I have used for Sync and Async call. Below are the Rest utility and CallBack for Async.
/**
 *
 */
package com.debopam.services.policyenquiryservice.rest.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

/**
 * @author dpoddar
 *
 */
public class RestUtil {

    private String url;
    private HttpMethod httpMethod;
    private MultiValueMap<String, String> headers;
    private Map<String, Object> params;
    private Class<?> responseType;
    private List<Object> uriVariables;

    private HttpEntity<Object> httpEntity;

    //AsyncRestTemplate asyncRestTemplate = (AsyncRestTemplate) ContextProvider.getBean("customAsyncRestTemplate");

    /**
     * @param url
     * @param httpMethod
     * @param headers
     * @param params
     * @param responseType
     * @param uriVariables
     */
    public RestUtil(String url, HttpMethod httpMethod, MultiValueMap<String, String> headers,
            Map<String, Object> params, Class<?> responseType, List<Object> uriVariables) {
        super();
        this.url = url;
        this.httpMethod = httpMethod;
        this.headers = headers;
        this.params = params;
        this.responseType = responseType;
        this.uriVariables = uriVariables;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Foo callServicesync(RestTemplate restTemplate) {

        //DO a sync Call
        HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
        Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);

    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void callServiceAsync(AsyncRestTemplate asyncRestTemplate,ResponseCallBack responseCallBack) {

        if(asyncRestTemplate.getMessageConverters().isEmpty()){
            asyncRestTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        }

        ListenableFuture restCall = null;
        if(null != uriVariables){
            restCall = asyncRestTemplate.exchange(this.url, this.httpMethod, this.httpEntity, responseType,uriVariables);
        }else{
            restCall = asyncRestTemplate.exchange(this.url, this.httpMethod, this.httpEntity, responseType);
        }

        restCall.addCallback(responseCallBack);

    }

    public static class RestUtilBuilder {
        private String url;
        private HttpMethod httpMethod;
        private MultiValueMap<String, String> headers;
        private Map<String, Object> params;
        private Class<?> responseType;
        private List<Object> uriVariables;

        public RestUtilBuilder url(String url) {
            this.url = url;
            return this;
        }

        public RestUtilBuilder httpMethod(HttpMethod httpMethod) {
            this.httpMethod = httpMethod;
            return this;
        }

        public RestUtilBuilder headers(MultiValueMap<String, String> headers) {
            this.headers = headers;
            return this;
        }

        public RestUtilBuilder addHeader(String key,String value) {
            if(null == this.headers){
                this.headers = new LinkedMultiValueMap<>();
            }
            this.headers.add(key, value);
            return this;
        }

        public RestUtilBuilder params(Map<String, Object> params) {
            this.params = params;
            return this;
        }

        public RestUtilBuilder addparam(String key,Object value) {
            if(null == this.params){
                this.params = new HashMap<>();
            }
            this.params.put(key, value);
            return this;
        }

        public RestUtilBuilder responseType(Class<?> responseType) {
            this.responseType = responseType;
            return this;
        }

        public RestUtilBuilder uriVariables(List<Object> uriVariables) {
            this.uriVariables = uriVariables;
            return this;
        }

        public RestUtil build() {
            RestUtil util = new RestUtil(url, httpMethod, headers, params, responseType, uriVariables);
            util.httpEntity = new HttpEntity<Object>(util.params, util.headers);
            return util;
        }
    }

    public static RestUtilBuilder restUtil() {
        return new RestUtilBuilder();
    }

}

package com.debopam.services.policyenquiryservice.rest.util;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
Response Call back for Async Call
*/
public abstract class ResponseCallBack<T> implements ListenableFutureCallback<ResponseEntity<T>>{

    private static final Logger logger = LoggerFactory.getLogger(ResponseCallBack.class.getName());

    Map<String,Object> inputs;

    public ResponseCallBack(Map<String,Object> inputs){
        this.inputs = inputs;
    }

    @Override
    public void onSuccess(ResponseEntity<T> stringResponseEntity) {
        onCallSuccess(this.inputs,stringResponseEntity);
    }

    @Override
    public void onFailure(Throwable ex) {
        logger.error(ex.getMessage(),ex);
        onCallFailure(this.inputs, ex);
    }

    //Do your stuff
    public abstract void onCallSuccess(Map<String,Object> inputs,ResponseEntity<T> stringResponseEntity);
    public abstract void onCallFailure(Map<String,Object> inputs,Throwable ex);
}

//Example
private void createRestUtilForAsync()
    {

    RestUtil restUtil = RestUtil.restUtil().url(url).addHeader("Accept", "application/json").addHeader("Content-Type", "application/json").addparam("xxx", 10).addparam("yyyy", "").addparam("zzz", "dsadsa").httpMethod(HttpMethod.POST).responseType(Policy.class).build();
    //create inputs
    ResponseCallBack<Policy> responseCallBack = new ResponseContractValuesCallBack(inputs);

    //asyncRestTemplate is autowired in the class
    restUtil.callServiceAsync(this.asyncRestTemplate, responseCallBack);
}

private void createRestUtilForSync()
    {

    RestUtil restUtil = RestUtil.restUtil().url(url).addHeader("Accept", "application/json").addHeader("Content-Type", "application/json").addparam("xxx", 10).addparam("yyyy", "").addparam("zzz", "dsadsa").httpMethod(HttpMethod.POST).responseType(Policy.class).build();

    //asyncRestTemplate is autowired in the class
    Foo foo = restUtil.callServiceAsync(this.restTemplate);
}

A: You can use technologies provided by Spring Cloud. For example for requesting other web-services the best way is using Feign Client. For the exceptions handling Hystrix.


text:
Q: validations with ClientSideValidations gem I am trying to validate my form with the gem ClientSideValidations, and works with presence true but I am trying to validate also with uniqueness but doesn't work until the form is sumited and just show the message once. I added the //= require rails.validations in aplicatios.js and installed the gem
this is my form:
   <%= form_for(@category, validate: true) do |f| %>
  <% if @category.errors.any? %>

<%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:

      <% @category.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name  %>

    <%= f.label :color %>

    <%= f.color_field :color %>

    <%= f.submit %>

<% end %>

and my model:
class Category < ActiveRecord::Base
    has_many :has_categories
    has_many :articles, through: :has_categories
    validates :name, presence: true, uniqueness: true

end

A: Quoting from the original github doc:  Wrapper objects and remote validations
Which makes sense. I haven't used this before but IMO you can't just validate uniqueness on the client side alone, it needs to be done using AJAX to compare the data you're passing with that of the respective model at your backend. One of the way you can achieve this by setting remote: true in your form which will turn into an AJAX request.
Update- After struggling for a bit, I finally came across this issue here. It states that uniqueness is disabled by default to prevent Brute force attack. Hence you need to implement this validation yourself using AJAX.
You may also look at this, if it makes any sense to you. I couldn't get it working either.


text:
Q: How to make a non-overriding method stub in Python multi-inheritance? Imagine that you have 2 mixin classes, that each define abstract methods and implementations. Together they implement every method, but depending on the inheritance order, the empty stubs will overwrite the implementation from the other class. There's at least two ways to overcome this in most situations but I don't really like either.

*

*One could remove the abstract methods and just rely on duck typing, but then there is no clear interface definition and type hinting.

*One could try to break down the classes into smaller ones to get a straight line of dependency and force a specific inheritance order, but that's not always practical.

Is there a way to, for example, mark a method virtual, which prevents it from actually being added to the class, or at least prevents it from overriding an existing method of the same name?
Is there another solution I didn't think of?
Simple example:
class MixinA:
    def high_level(self):
        self.mid_level()

    def low_level(self):
        ...

    def mid_level(self):
        raise NotImplementedError

class MixinB:
    def mid_level(self):
        self.low_level()

    def low_level(self):
        raise NotImplementedError

class ChildA(MixinA, MixinB):
    pass

class ChildB(MixinB, MixinA):
    pass

for cls in (ChildA, ChildB):
    try:
        cls().high_level()
        print("success")
    except NotImplementedError:
        print("error")

A: OK, this is what an ABC-based implementation might look like.
You just have to mix and match the Mixins to achieve what you want.  The Mixins only implement what they are actually providing.
mypy will flag errors during type-checking
abc will also throw errors about missing methods at runtime
from abc import ABC, abstractmethod

class AbstractLevel(ABC):

    @abstractmethod
    def high_level(self):
        ...

    @abstractmethod
    def low_level(self):
        ...

    @abstractmethod
    def mid_level(self):
        ...

class MixinHighMid:

    def high_level(self):
        self.mid_level()

class MixinMid:

    def mid_level(self):
        print(f"    MixinMid.mid_level")

class ConcreteLow(MixinHighMid, MixinMid, AbstractLevel):
    def low_level(self):
        print(f"    {self}.low_level")

class BadConcreteLow(MixinHighMid,AbstractLevel):

    def low_level(self):
        print(f"{self}.low_level")

for cls in (ConcreteLow, BadConcreteLow):

    good = ConcreteLow()   #happy mypy
    try:
        bad = BadConcreteLow() #sad mypy
    except (TypeError,) as e:
        pass

    try:
        print(cls.__name__)
        inst = cls()  #sad mypy because knows BadConcreteLow will blow up
        print(f"  calling high_level")
        inst.high_level()
    except (TypeError,) as e:
        print(f"error on {cls.__name__}: {e}")

runtime output:
ConcreteLow
  calling high_level
    MixinMid.mid_level
BadConcreteLow
error on BadConcreteLow: Can't instantiate abstract class BadConcreteLow with abstract method mid_level

and mypy output:
test_418_mixindecl.py:41: error: Cannot instantiate abstract class "BadConcreteLow" with abstract attribute "mid_level"
test_418_mixindecl.py:49: error: Cannot instantiate abstract class "AbstractLevel" with abstract attributes "high_level", "low_level" and "mid_level"
Found 2 errors in 1 file (checked 1 source file)

To amuse myself, I also added the following Mixin to mangle method signatures:
class BadMixinMid:

    def mid_level(self, v : int):
        print(f"    MixinMid.mid_level")

class BadConcreteMid(MixinHighMid,BadMixinMid,AbstractLevel):

    def low_level(self):
        print(f"{self}.low_level")

mypy caught that on type-checking while the runtime only blew up on the method call itself.
test_418_mixindecl.py:41: error: Definition of "mid_level" in base class "BadMixinMid" is incompatible with definition in base class "AbstractLevel"

A: I found a solution that satisfies my requirements, that is:

*

*it describes an interface which the inheriting class needs to implement

*does not override existing functions with abstract functions

*is typing compatible

Basically, I just defined the abstract functions in a separate protocol and marked the self var as that protocol.
from typing import Protocol

class InterfaceForA(Protocol):
    def mid_level(self): ...

class MixinA:
    def high_level(self: InterfaceForA):
        self.mid_level()

    def low_level(self):
        print("success")

class InterfaceForB(Protocol):
    def low_level(self): ...

class MixinB:
    def mid_level(self: InterfaceForB):
        self.low_level()

class ChildA(MixinA, MixinB):
    pass

class ChildB(MixinB, MixinA):
    pass

for cls in ChildA, ChildB:
    try:
        cls().high_level()
    except:
        print("error")

With this code, I get success printed twice. In addition, the type hints let me know if the method implementations in the mixin are incompatible with the requirements defined in the protocols.


text:
Q: Installing Vim: What is the difference betwen "--with-local-dir" and "includedir" My main goal is that I want to understand how parameters works in ./configure. So, I decided to install ncurses and vim in $HOME/local/, so, as to not affect my system.
while configuring vim, I looked into --with-local-dir and includedir. I want to know what is the difference between them.
When I looked into vim-git-INSTALL-script, it said:
Unix: LOCAL HEADERS AND LIBRARIES NOT IN /usr/local

Sometimes it is necessary to search different path than /usr/local for locally
installed headers (/usr/local/include) and libraries (/usr/local/lib).
To search /stranger/include and /stranger/lib for locally installed
headers and libraries, use:
    ./configure --with-local-dir=/stranger

I thought that was the purpose of includedir. I would appreciate if someone can tell me where I went wrong. Thank you!

A: Conventionally (and per documentation), includedir is used for the directory where the current program would install header files.  That's not the same as the places where the configure script might have to tell the compiler to find the header files needed to compile the program.


text:
Q: Expect Script to Send Different String Outputs I have something like this.
expect
 "hi"    { send "You said hi\n" }
 "hello" { send "Hello yourself\n" }
 "hi"    { send "2nd time you said hi\n" }

The scenario is I will get a initial response 'hi', then 'hello', then 'hi' again. The second time I get a response of 'hi', I want to send a different string.
Thanks.

A: You should use a list and iterate...
set responses {{You said hi} {2nd time you said hi}}
set idx 0
while {$idx < [llength $responses]} {
    expect {
     "hi"    { send [lindex $responses $idx]\n; incr idx }
     "hello" { send "Hello yourself\n" }
    }
}


text:
Q: Oracle stored procedure using temp tables The main idea: I want create 3 tables (as temp tables) with some selects, take 1 and 2 and compare.
Result insert to 3 table.
My procedure looks like:
create or replace PROCEDURE CHECK_PARAMS
AS
TYPE row IS RECORD (id NUMBER,
                    count_id NUMBER );
TYPE my_table_type IS TABLE OF row;

first my_table_type;
second my_table_type;
third my_table_type;
BEGIN
  SELECT id, count_id bulk collect -- GOOD SELECT
  INTO first
  FROM
    (SELECT test1.A_ID id,
            COUNT(test1.A_ID) count_id
     FROM MY_OTHER_TABLE1 test1,
          MY_OTHER_TABLE2 test2
     WHERE test1.A_ID = test2.A_ID
     GROUP BY test1.A_ID);

  SELECT id, count_id bulk collect -- GOOD SELECT
  INTO first
  FROM
    (SELECT test1.A_ID id,
            COUNT(test1.A_ID) count_id
     FROM MY_OTHER_TABLE3 test1,
          MY_OTHER_TABLE4 test2
     WHERE test1.A_ID = test2.A_ID
     GROUP BY test1.A_ID);

  SELECT id, count_id bulk collect -- ORACLE CAN'T FIND MY TEMP TABLES
  INTO third
  FROM frist, second; -- **HERE I GOT ERROR: ORA-00942 table or view does not exist**

What's wrong?

A: You have to define the types outside of the procedure
create TYPE t_row as object  (id NUMBER,
                    count_id NUMBER );

create TYPE my_table_type IS TABLE OF t_row;

and than you have to use table
SELECT id, count_id bulk collect -- ORACLE CAN'T FIND MY TEMP TABLES
  INTO third
  FROM table(first), table(second);


text:
Q: Example of a Sufficient MUD-Style and working Text Parser for Python I am in the middle of programming a MUD like game, more for the experience and practice. I am trying to find an algorithm that will effectively prase text commands. If you have played MUD type games before you know what I am talking about. If not and example would be if I typed in the command: 'search' it would execute the 'search' whether you type in s, se, sea, sear, searc, search, etc...
Now I do have a algorithm already established, but the more I think about it the more problems see to arise. In code it goeslike this:
 def text_parser(string, command):
    string_list = []
    command_list = []

    for x in string:
        string_list.append(x)

    for x in command:
        command_list.append(x)

    if len(string_list) == 0:     # checks to see if user have entered anything
        return False

    if ((string_list > command_list) - (string_list < command_list)) is 1:    # returns false if string has more items than command
        return False

    else:
        if string_list[:len(string_list)] == command_list[:len(string_list)]:
            return True
        else:
            return False

And you can call this function by:
if text_parser('hel', 'hello') is True:
    print('This returns True')

if text_parser('hel', 'Foo') is True:
    print('This returns False')

Now this code works perfectly.. exactly what I need for it to do. If I type in 'se' and its other end-members for the command' search' it will always be true... but now comes my biggest problem.. Say i have two commands:
'quit' and 'quaff' and the user only inputs 'qu'
According to my algorithm it will execute both the 'quit' and the 'quaff', because my code is set up as:
if (text parser check):
    blah
if (text parser check):
    blach
etc....   # The only way out of this is to do nested if's and elif's.. which will look messy..

Which is not what I want to do at all. As you can see many more problems can arise the more commands you set up with the game.
What will be a good algorithm set up for text parsing? Or do I just need to change a few things in my already existing code to address the bugs that can pop up with this set up...? Thanks

A: I think your approach can be simplified by having a list of all available commands. And then define a function that will parse your input string and look for a command match like this:
all_commands = ['search', 'quit', 'quaff']

def find_command(string, allowed_commands=None):
    if allowed_commands is None:
        # if there is no restrictions, look for all commands
        allowed_commands = all_commands

    matching_commands = []

    for command in commands:
        if command.startswith(string):
            matching_commands.append(command)

    if len(matching_commands) == 1:
        # found a match
        return matching_commands[0]

    # found either no match or more than one
    return None

Now, the function find_command will find matches for the input string and it will either match all commands (all_commands) or a given subset (allowed_commands), in case you only want to allow certain commands in that situation.
For example:
print find_command('se') # returns search
print find_command('search') # returns search
print find_command('qu') # returns None
print find_command('quaf') # returns quaff
print find_command('qu', ['search', 'quit']) # returns quit

A: Did you try pyparsing? It looks good for such tasks. Check examples: http://pyparsing.wikispaces.com/Examples

A: You might want to consider the cmd module, which lets you define commands as methods on a class. It then provides a prompt where you can type the commands and see the results. The parsing is fairly rudimentary, but probably sufficient for you to get started.
cmd was featured on Python Module of the Week a while ago, and it has a very nice tutorial. Here's just a very brief taste:
import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    def do_greet(self, person):
        """greet [person]
        Greet the named person"""
        if person:
            print "hi,", person
        else:
            print 'hi'

    def do_EOF(self, line):
        return True

    def postloop(self):
        print

if __name__ == '__main__':
    HelloWorld().cmdloop()

When you run the above code you'll get a prompt where you can type commands. For example:
(Cmd) greet
hi
(Cmd) greet bob
hi, bob
(Cmd)

The module provides the command loop, and it also supports autocompletion, live help, a customizable prompt, and several other features.

A: Perhaps, put your commands in a list, and do
def parse(userInput):
    returnList = []
    for cmd in commandList:
        if userInput in cmd:
          cmdList.append(cmd)
    return returnList

Then you have matching commands in your returned list.


text:
Q: Upload .TXT file to SharePoint from custom ASPX/HTML webpage using JavaScript I have a custom ASPX/HTML webpage hosted within a SharePoint site and need to upload a generated txt to a specific folder within the SharePoint site using JavaScript.
Processes:
User clicks button on webpage -> JavaScript generated text file -> JavaScript uploads text file to SharePoint site folder
I'm not sure about SharePoint approach to file upload as there's no custom backend to work with. Would this be the correct process to use?
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-javascript-library-code-in-sharepoint#create-a-file-in-a-document-library

A: Here is a sample code for your reference, you can create a SharePoint site page and use Script Editor Web Part to embed it:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript">

function uploadDocument() {
    if (!window.FileReader) {
        alert("This browser does not support the HTML5 File APIs");
        return;
    }

    var element = document.getElementById("uploadInput");
    var file = element.files[0];
    var parts = element.value.split("\\");
    var fileName = parts[parts.length - 1];

    var reader = new FileReader();
    reader.onload = function (e) {
        addItem(e.target.result, fileName);
    }
    reader.onerror = function (e) {
        alert(e.target.error);
    }
    reader.readAsArrayBuffer(file);

    function addItem(buffer, fileName) {
        var call = uploadDocument(buffer, fileName);
        call.done(function (data, textStatus, jqXHR) {
            console.log(data);
            alert("File Upload Successfully");
        });
        call.fail(function (jqXHR, textStatus, errorThrown) {
            failHandler(jqXHR, textStatus, errorThrown);
        });
    }

    function uploadDocument(buffer, fileName) {
        var url = String.format(
            "{0}/_api/Web/Lists/getByTitle('Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)",
            _spPageContextInfo.webAbsoluteUrl, fileName);
        var call = jQuery.ajax({
            url: url,
            type: "POST",
            data: buffer,
            processData: false,
            headers: {
                Accept: "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
                }
        });

        return call;
    }

    function failHandler(jqXHR, textStatus, errorThrown) {
        var response = JSON.parse(jqXHR.responseText);
        var message = response ? response.error.message.value : textStatus;
        alert("Call failed. Error: " + message);
    }
}
</script>

<input type="file" id="uploadInput"/>
<input type="button" id="Upload" value="Upload" onclick="uploadDocument()"/>


text:
Q: What is the problem with overdifferencing a long memory time series? Suppose I have a long memory time series and instead of using fractional differentiation I take a first difference.
What kind of problems am I going to run into? Is there any advantage to doing the fractional differentiation?

A: First differences remove all the long term memory whilst fractional differences preserve some of it. If, therefore, the long term memory is important for your intended application fractional differencing is the way to go. Chapter 5 of the book Advances in Financial Machine Learning discusses this in some detail.
For example, assume you want to predict a long term ( financial?) trend using a machine learning algorithm and you feed it first differences as training data, it will be extremely difficult for the algorithm to learn the trend as it isn't present in the data it's presented with; the algorithm is much more likely to learn to predict just one step ahead, and thereby "failing."
The above book suggests that this "over-differencing" is one reason why ML on (financial) time series is so often problematic. The book also, tentatively, suggests that this may be the reason why the Efficient Market Hypothesis holds such sway among financial academia, in that removing the "historical memory" from the data logically leads to the conclusion that future prices cannot be predicted from past prices. Any evidence that contradicts this belief is called an anomaly, e.g. momentum. However, fractionally differenced financial data show that trends and momentum do persist, whilst at the same time being stationary.


text:
Q: Override e.force:createRecord default behaviour on save I am using $A.get('e.force:createRecord') on click of my lightning component's button. I saw the default behaviour is after save it redirects to that object's detail page.
Is there is any way out to override this behaviour?

A: you can use "panelOnDestroyCallback" function to redirect to a custom Url.
Please refer to the sample code:
 var eve = $A.get("e.force:createRecord");

    eve.setParams({
        "entityApiName": "Contact",
         "panelOnDestroyCallback": function(event) {
             window.location.href = "https://www.google.com";
    }
    });
    eve.fire();

}

A: Not to my knowledge, asuming that you are having users fill in some kind of form, you should be better of using
lightning:recordEditForm
and use its available events, such as:

onsuccess Action  The action triggered when the form is saved.

some of the advantages of this component are that it handles FLS, CRUD and is quite easy to use:
<lightning:recordEditForm objectApiName="sObjectName">

</lightning:recordEditForm>

and add your custom logic to do whatever it is you need done.
Otherwise, you can always Call a Server-Side Action
controller.js
"saveSomething" : function(cmp) {

    var action = cmp.get("c.saveSobject");
    action.setParams({ field: cmp.get("v.fieldName") });

    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            // custom action here
        }
        else if (state === "INCOMPLETE") {
            // do something
        }
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " +
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });
    $A.enqueueAction(action);
}

A: In the Spring 19 above mentioned answers are not working and I tried something like below and it worked for me.
var eve = $A.get("e.force:createRecord");
eve.setParams({
    "entityApiName": "Contact",
    "navigationLocation" : "LOOKUP",
    "panelOnDestroyCallback": function(event) {
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": "/lightning/o/Contact/home"
        });
        urlEvent.fire();
    }
});
eve.fire();

It works fine after adding the "navigationLocation" : "LOOKUP",


text:
Q: What is the best practice when type checking option hash values in a ruby C extension? I'm developing a C extension for ruby, one of the functions from the C library I'm accessing  receives an options struct which seems to be naturally translate to an options hash in ruby-world.
The struct is being initialized with known default values when the hash on the ruby side does not define a value for a given option. On the C side I have some along these lines:
VALUE tmp;

tmp = rb_hash_aref(r_hash, rb_str_new2("opt1"));

if(TYPE(tmp) == T_STRING){
  strcpy (c_learn_param->opt1, StringValuePtr(tmp));
}else{
  strcpy (c_learn_param->opt1, "default value 1");
}

Now my problem is when an option has a defined value but the ruby type does not make sense in C.
Should I raise type error even for an optional value? that seems overkill, should I fall back to a default? the problem with falling back to a default is a user passing {"opt1" => 123 } will see the same behaviour as if he had not defined opt1 which seems like a bad idea, should I fall back and print a ruby warning? (do people even read them?).

A: You should probably accept at least a Symbol or a String as they are, in practice, used nearly interchangeably (hence ActiveSupport::HashWithIndifferentAccess).
Depending on your specific situation, it might make sense to call to_s on your tmp and let anything in that can be converted to a String that way. However, if it only makes sense to accept a String or Symbol then raising a TypeError is a perfectly sensible thing to do.
Being as flexible as possible with your inputs but strict with your outputs is usually a good idea and makes for friendly libraries.
If people don't read warnings then it is their own fault when things go wrong and you're well within your rights to smirk and say "I told you so".


text:
Q: Is there a way to set a common image path for LESS files? I am using the LESS styling language.
Consider the following CSS:
.side-bg
{
    background:url(../img/layout/side-bg.jpg) top no-repeat;
}

Right now all of my images are in the folder ../img/ I wanted to be able to set a variable as the image path and use it like so:
@image-path: ../img;

.side-bg
{
    background:url(@image-path/layout/side-bg.jpg) top no-repeat;
}

This does not work however. Its not a huge deal, I could always use find and replace if the image folder ever changed. I am just starting to learn LESS and was wondering if something like this is possible.

A: Try using string interpolation for things like this. Look for "variable interpolation" in docs.
@base-url: "http://assets.fnord.com";
background-image: url("@{base-url}/images/bg.png");

A: I was searching for the same question and found this page. Thought I would post my solution as someone else might find it useful...
@iconpath: '/myicons/';

.icon (@icon) {
    background: no-repeat url('@{iconpath}@{icon}');
}

.icon-foo { .icon('foo.png'); }
.icon-bar { .icon('bar.png'); }
.icon-spuds { .icon('spuds.png'); }

which compiles to (used http://winless.org/online-less-compiler)
.icon-foo {
  background: no-repeat url('/myicons/foo.png');
}
.icon-bar {
  background: no-repeat url('/myicons/bar.png');
}
.icon-spuds {
  background: no-repeat url('/myicons/spuds.png');
}

A: Anton Strogonoff's answer is good but be aware of the Issue @294:
Using the above which comes straight from the docs, I get url://pathtolessfile/variable I set.  Even though I'm trying to set an absolute URL instead of a relative one. For example this works
@base-url: "../../images/";
@background-image : url ("@{base-url}/bg.png");

But this does not work
$base-url: "http://localhost/ns/assets/images/";
@background-image : url ("@{base-url}/bg.png";

In the latter example, my final source path becomes
http://localhost/ns/assets/css/libs/http://localhost/ns/assets/images/bg.png

A: Here is an updated and clean way to handle image paths with LESS:
Start with your variable:
@imagePath: ~"../images/bg/";

Then use it like this:
.main-bg {
   background: url('@{imagePath}my-background-image.png') repeat scroll left top;
}

Make sure the @imagePath variable points to the images folder from wherever you have your compiled CSS, NOT from where you have your LESS files. Also, you have to escape the address in the variable as in the example above to ensure that it does not get rewritten by less.js.

A: The solution:
.side-bg
{
    background : ~"url( '@{image-path}/layout/side-bg.jpg' )" top no-repeat;
}

A: Relative urls can be handled by the command line compiler, supposedly. There's probably some similar option you can set in the file watcher.
https://github.com/cloudhead/less.js/wiki/Command-Line-Usage
EDIT: There totally is. Just look: http://lesscss.org/usage/#command-line-usage-options
relativeUrls: true


text:
Q: I'm looking for a definitive ordered list of transcendental numbers For example, I know that e, pi, sin (1), Louville's constant etc are just four of the many transcendental numbers, but definitively are any of these the "first", "second" and so on transcendental numbers?
I'm looking for the first 10 transcendental numbers from such a list.
From a puzzle I am trying to solve, I know this much:
- the 16th digit of the "2nd" transcendental number is 4
- the 11th digit of the "9th" transcendental number is 1, 2 or 3
- the 23rd digit of the "8th" transcendental number is 0 or 5
- the 12th digit of the "4th" transcendental number is 0 or 9
Thanks!
Adrian.

A: There are uncountable many transcendental numbers, so putting them in a list is technically impossible (as a list is defined to be a bijection with $\omega$). However, you can put it in bijection with the ordinal that equals the cardinality of the continuum. There is no canonical way to do this (the natural ordering doesn't work because it's dense and has no endpoints), and any specific example requires the axiom of choice.
I would assume that the puzzle you're doing wants you to fix some ordering and that the problem works for any bijection with the ordinal that equals the cardinality of the continuum.


text:
Q: VBA Regex: from last used row, in a column,get count of a matched pattern between another pattern I'm new to VBA using regex. On a worksheet, I have a column with cells that have several specific names and between these names are several qualifiers. I need help to put together a VBA/macro code using regex to loop through the column and get the counts of the qualifiers between names and put the count value to the cell on the right of the name. The names all start with uppercase letters while the qualifiers start with  a lower case letter. So i'm using ^[A-Z]* to match the names and ^[a-z]* for the qualifiers. Each value is in separate cells and the occurrences are random. So far I can only get total count of all qualifiers.  I appreciate the help.

A: Like instead of RegEx
Adjust the values in the constants section.
Option Explicit

'START ****************************************************************** START'
' Title:        Count Owners                                                   '
' Purpose:      Counts the number of cells containing a string starting with   '
'               a lower-case character below a cell containing a string        '
'               starting with an upper-case character and writes the result    '
'               to the same row of the string starting with the upper-case     '
'               character, in another (specified) column.                      '
'******************************************************************************'
Sub CountOwners()

    Const wsName As String = "Sheet1"   ' Worksheet Name
    Const rowHeader As Long = 3         ' Header Row
    Const colOwner As Long = 2          ' Owner Column Number
    Const colCount As Long = 3          ' Count Column Number

    Dim rng As Range                    ' Owner Column, Owner Column Range,
                                        ' Count Column Range
    Dim vntOwner As Variant             ' Owner Array
    Dim vntCount As Variant             ' Count Array
    Dim LneRinC As Long                 ' Last Non-Empty Row in Owner Column
    Dim UB As Long                      ' Arrays Last Element Count
    Dim lngOwner As Long                ' Current Owner Element (Row)
    Dim lngCount As Long                ' (Current) Owner Count(er)
    Dim i As Long                       ' First Arrays Element Counter
    Dim j As Long                       ' Second Arrays Element Counter
    Dim strChar As String * 1           ' Current Char

    ' IN WORKSHEET

    ' Define Owner Column.
    Set rng = ThisWorkbook.Worksheets(wsName).Columns(colOwner)
    ' Using the Find method, try to define Owner Column Range.
    Set rng = rng.Find("*", , xlFormulas, , , xlPrevious)
    ' Check if no data in Owner Column.
    If rng Is Nothing Then GoTo NoData
    ' Calculate Last Non-Empty Row in Owner Column.
    LneRinC = rng.Row
    ' Check if no Owners in Owner Column Range.
    If LneRinC <= rowHeader Then GoTo NoOwners
    ' Define Owner Column Range.
    Set rng = rng.Parent.Cells(rowHeader + 1, colOwner).Resize(LneRinC - rowHeader)
    ' Write values of Owner Column Range to Owner Array.
    vntOwner = rng

    ' IN ARRAYS

    ' Define Arrays Last Element Count
    UB = UBound(vntOwner)
    ' Resize Count Array (vntCount) to the size of Owner Array (vntOwner).
    ReDim vntCount(1 To UB, 1 To 1)
    ' Loop through elements of Owner Array.
    For i = 1 To UB
        ' Write first characterg of current element in Owner Array
        ' to Current Char.
        strChar = Left$(vntOwner(i, 1), 1)
        ' Check if current char is an uppercase character.
        If strChar Like "[A-Z]" Then
            ' Assign the value of the current row of Owner Array
            ' to Current Owner Element (Row).
            lngOwner = i
            ' Reset Current Owner Element.
            lngCount = 0
            ' Loop through the rest of the elements in Owner Array.
            For j = i + 1 To UB
                ' Write first character of current element in Owner Array
                ' to Current Char.
                strChar = Left$(vntOwner(j, 1), 1)
                ' Check if Current Char is an uppercase letter.
                If strChar Like "[A-Z]" Then
                    ' Reset First Arrays Element Counter.
                    i = j - 1
                    Exit For
                Else
                    ' Check if Current Char is a lowercase letter.
                    If strChar Like "[a-z]" Then
                        ' Increase (Current) Owner Counter.
                        lngCount = lngCount + 1
                    End If
                End If
            Next
            ' Write value of (Current) Owner Counter to Count Array.
            vntCount(lngOwner, 1) = lngCount
        End If
    Next

    ' IN WORKSHEET

    ' Define Count Column Range.
    Set rng = rng.Offset(, colCount - colOwner)
    ' Write values of Count Array to Count Column Range.
    rng = vntCount

ProgramError:

Exit Sub

NoData:
    MsgBox "There is no data in Owner column (" & colOwner & ")."
    GoTo ProgramError

NoOwners:
    MsgBox "There are no Owners in Owner column (" & colOwner & ")."
    GoTo ProgramError

End Sub
'******************************************************************************'
' Remarks:    Values not starting with alpha characters are not counted.       '
'             Owner Column Range doesn't have to start with an Owner.          '
'             Owner Column Range can end with an Owner; the count will be 0.   '
'END ********************************************************************** END'


text:
Q: Keydown Event to save locally using javascript I am making a basic online editing interface for coursework. I would like to save the content of my #textarea div every time there's a keydown event. The code works partially but I can't edit the text without the cursor going to the top of the div.

document.addEventListener('keydown', saveLocally);

const saveLocally = function() {
  let areaText = document.getElementById("textArea");
  console.log(areaText);
  let text = document.getElementById("textArea").innerHTML;
  console.log(text);
  let localData;

  localStorage.setItem('siteData', text);
  localData = localStorage.getItem('siteData');

  console.log(localData);
  console.log(localStorage.getItem('siteData'));

  areaText.innerHTML = localData;
}

A: The issue is because you immediately update the innerText of the element after someone types. This affects the cursor as the node contents are changed. You don't need to do this anyway, so the line can be removed.
You instead need to perform the logic which retrieves the value from localStorage when the page loads. Also note that you should use the keyup event instead of keydown, otherwise you'll not save the last key which was pressed. Try this:

let areaText = document.getElementById("textArea");

const saveLocally = function() {
  let text = areaText.innerHTML;
  localStorage.setItem('siteData', text);
}

const retrieveSavedText = function() {
  var text = localStorage.getItem('siteData');
  areaText.innerHTML = text;
}

document.addEventListener('keyup', saveLocally);
retrieveSavedText();

Working example


text:
Q: How to add multiline text to an image using Python, while having each word or character drawn using a different color? I am using the following code to generate images of multiline words. How can I make it draw each word or character in a different color?
from PIL import Image, ImageDraw, ImageFont
import random
import textwrap
from better_profanity import profanity
import time

width = 2000
height = 2000
number_of_words = 2400
number_of_characters = 300
font = ImageFont.truetype(r'cour.ttf', 48)

how_many = int(input("How many? "))

while how_many > 0:

    def list_of_words():
        words = []
        for i in range(number_of_words):
            words.append(random.choice(open("pwd2.txt").read().split()))
        return(" ".join(words))

    wrapper = textwrap.TextWrapper(width=number_of_characters)
    value = str(list_of_words())
    wrapped = wrapper.fill(text=value)

    censored = profanity.censor(wrapped, "")

    r = random.randint(40,200)
    g = random.randint(40,200)
    b = random.randint(40,200)
    rgb = (r,g,b)

    date_string = time.strftime("%Y-%m-%d-%H_%M_%S")

    img = Image.new('RGB', (width, height), color='black')
    imgDraw = ImageDraw.Draw(img)
    imgDraw.multiline_text((-12, -5), censored, font = font, fill=rgb)
    img.save('output/background-' + str(how_many) + '_' + date_string + '.png')

    how_many -=1

The text is coming from a file named pwd2.txt, which is a list of the world's most commonly used passwords. Note that I use "better_profanity" to remove cursewords, because people apparently like to use them in their passwords. Here's the text file: https://raw.githubusercontent.com/nonfunjible/word-backgrounds/main/pwd2.txt
The code above asks you how many images to generate, then pulls random words and draws them to an image in a random color. Example output of 2 images:

*

*https://i.stack.imgur.com/frPuU.png

*https://i.stack.imgur.com/xVsRi.png
Each image is generated with a text color randomly selected. But how would I make each word (preferred) or character (acceptable) a different color?
So far I tried what appeared to be related solution here: https://stackoverflow.com/a/19213360/
In it, in my understanding the text is pasted as a series of images of each letter. I adapted it to my project as follows.
from PIL import Image, ImageDraw, ImageFont
import random
import textwrap
from better_profanity import profanity
import time

width = 2000
height = 2000
number_of_words = 2400
number_of_characters = 300
font = ImageFont.truetype(r'cour.ttf', 48)
make_color = lambda : (random.randint(50, 255), random.randint(50, 255), random.randint(50,255))

how_many = int(input("How many? "))

while how_many > 0:

    def list_of_words():
        words = []
        for i in range(number_of_words):
            words.append(random.choice(open("pwd.txt").read().split()))
        return(" ".join(words))

    wrapper = textwrap.TextWrapper(width=number_of_characters)
    value = str(list_of_words())
    wrapped = wrapper.fill(text=value)

    censored = profanity.censor(wrapped, "")

    img = Image.new("RGB", (width, height), (0,0,0)) # scrap image
    draw = ImageDraw.Draw(img)
    img2 = Image.new("RGB", (width, height), (0,0,0)) # final image

    fill = " o "
    x = 0
    w_fill, y = draw.textsize(fill)
    x_draw, x_paste = 0, 0
    for c in censored:
        w_full = draw.textsize(fill+c)[0]
        w = w_full - w_fill     # the width of the character on its own
        draw.text((x_draw,0), fill+c, make_color())
        iletter = img.crop((x_draw+w_fill, 0, x_draw+w_full, y))
        img2.paste(iletter, (x_paste, 0))
        x_draw += w_full
        x_paste += w

    date_string = time.strftime("%Y-%m-%d-%H_%M_%S")
    img2.save('output/background-' + str(how_many) + '_' + date_string + '.png')

    how_many -=1

However, probably due to my lack of understanding how it works, I'm unable to have it wrap text as in my first code snippet above, or even change the font. Here is example output of 2 images:

*

*https://i.stack.imgur.com/xyBTo.png

*https://i.stack.imgur.com/3neNY.png
I'm wondering if that related solution may not be the best way to accomplish what I'm trying to do. Is there another approach entirely to draw multiline text on an image using Python in a way that enables you to print each word or character in a different color?
(As another possible avenue to explore, I've noticed this wordcloud generator seems to print words in different colors, but I don't understand how it works: https://www.geeksforgeeks.org/generating-word-cloud-python/)


text:
Q: AS3 - Event.ENTER_FRAME - error 1119 I'm trying to develop a simple game in Adobe Animate and AS3.
I have a class GameCore where I want to add an ENTER_FRAME event listener.
package as3 {

import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.*;
import as3.movieclips.RocketShip;

public class GameCore {

    var rocket:RocketShip;
    var stage:Stage;
    var timeline:MovieClip;
    var i:int;

    public function GameCore( stage:Stage ) {
        // constructor code
        this.rocket = new RocketShip();
        this.stage = stage;
        this.timeline = this.stage as MovieClip;
        this.i = 0;
        this.stage.addEventListener(Event.ENTER_FRAME, gameLoop);
    }

    public function goToMainScreen():void {
        this.timeline.goToAndStop("MainScreen");
    }

    public function goToGameScreen():void {
        this.timeline.goToAndStop("GameScreen");
    }

    public function startGameLoop():void {

    }

    public function gameLoop(event:Event){
        trace(this.i);
        this.i += 1;
    }

}

}

When I try to execute the code on a timeline frame like so:
  import as3.GameCore;
  var game:GameCore = new GameCore(stage);

It throws an error saying:
 Can´t access probably undefined property ENTER_FRAME referenced with static type Class

i did this before, but i don't touch as3 for a couple of years, can you tell me whats going wrong here?
Thanks in advance and happy programming!

A: You can extends your class with:
public class GameCore extennds EventDispatcher

and use this code
this.addEventListerner(Event.EnterFrame,gameloop)

maybe it works

A: Ok so this might be a long shot but I don't think you have to have the (stage) in there.  You can set game.x and game.y, and a few other variables, and then stage.addchild(game).  if you want multiple objects of that type it is sometimes helpful to make an array, but there are other semantic stuff you have to do to make that work.
I know this is an old post but hopefully, it helps someone.


text:
Q: Initializer for conditional binding must have Optional type, not"()" I couldn't solve an "if let" issue in my code. Based on the error it says that I must use an optional type?
@IBAction func operate(sender: UIButton) {

    if userIsInTheMiddleOfTypingANumber{
        enter()
    }
    if let operation = sender.currentTitle {
        if let result = calcModel.performOperation(operation){
            displayValue = result
        }else {
            displayValue = 0
        }
    }
}

A: I suspect that your problem is in this line:
if let result = calcModel.performOperation(operation)

Your performOperation function's return type is (), or void, which means it doesn't return anything. Chances are, to get the error in the title, your performOperation function on calcModel has the following signature:
func performOperation(operation: String) {

Note the lack of an arrow and type. If you're going to return a result, the signature should be something like this:
func performOperation(operation: String) -> Int {

You would only need the if let, if you decided to return Int?.


text:
Q: Can we start a sentence with "Like this,"? Is the following sentence well constructed? Like this, doing things that you do not like help you learn important skills. It looks wrong to me, but I have yet to find a rule or guide that could give a reason for this.
Thank you for any and all help!

A: I'm not sure there is a rule, other than the rule of statistics, since I don't recall seeing that before.
There is a ready alternative:

In this way, doing things that you do not like helps you learn important skills.

The underlying problem, though, seems to have to do with the fact that some phrases seem inappropriate at the beginning of a sentence.  Consider 'as well':

We are moving out.  We are selling the furniture as well.

Compare:

We are moving out.  As well, we are selling the furniture.

This is odd/unacceptable in most varieties of English.  However, it is common and accepted in Canadian English.  I remember using it in essays all the time, until, during grad school in the US, I read about it and realized that no one there did the same.
http://www.englishforums.com/English/CanadianUsage/ndcdj/post.htm


text:
Q: How do I install python 3.7.4 and pip to the path in windows 10? Python and pip wont work when added to the path
I've tried adding it to user variables and system variables and multiple different directories including the default location which is the option I chose when installing.

A: Never mind. Turns out I had to uninstall py launcher and then go to installation setting for python and check add to path.


text:
Q: Missing posts in a query I've got this loop where I need to grab a custom post type, get a taxonom, then for each term in taxonomy I need to output all posts. They are all output in a gallery, where taxonomy term is the title, posts are the items in the gallery (for that I use http://bit.ly/1jCf2Wj). I have something like this:
<?php

        global $post;
        $post_type = 'people';
        $taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) );
        $tax = $taxonomies[0];
        $terms = get_terms( $tax );

        //make the query
        $people_args = array( 'post_type' => $post_type);
        $loop = new WP_Query( $people_args ); //look for people posts
        $termsLength = count($terms);// count terms in the taxonomy, returns correct number

        //for each people post
        while ( $loop->have_posts() ) : $loop->the_post();

        //for each term in the taxonomy
        for ($x = 0; $x <= $termsLength-1; $x++) {
          //this is all posts looped by terms length - 1

          //if the post has got the name (department name) in $tax (departments group)
          if( has_term( $terms[$x]->name, $tax ) ) {

            echo '
'. $terms[$x]->name .'
';

            // echo '
'.$wp_query->post_count.'
';
            $name = $terms[$x]->name; // dept name
            $title = get_the_title($post->ID); // the post title
            $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail_size' ); // the post thumb
            $url = $thumb['0']; // url to thumb
            echo '
';
            echo '';
            echo ''.$title.''. get_post_meta($post->ID, 'position', true).'';
            echo '';
            echo '
 ';

          }
        }

        endwhile;
        rewind_posts(); wp_reset_query();

        ?>

What happens is I get the the results of the query, but not all posts are there. If I publish more posts than x, then one of taxonomy terms (departments) are not showing up. Another taxonomy term shows only one post.
Where am I making a mistake?

A: Turns out setting explicity posts per page did if for me.


text:
Q: How do I pick iBus keyboard layouts on NixOS All additions to list of keyboard layouts made with ibus-setup have no effect, and after launching ibus-setup there is no trace of them.
Having iBus enabled in configuration.nix means having no other layout but English, regardless of services.xserver.layout. And I want layouts like Polish, French Canadian QWERTY, Russian Phonetic. I also want to enable uniemoji and some pinyin IME, although i think i already discovered some engines attribute that enables me to add them.
I may use nixos-unstable and am happy with continuing to.

A: I have no experience with ibus, but looking at https://nixos.org/nixos/options.html#ibus I'd suggest i18n.inputMethod.ibus.engines – there are examples in docs.


text:
Q: Append string to form input I got this form:
<form class="navbar-form navbar-right" role="search" action="https://www.google.com/search" target="_blank">

<input id="search" type="text" name="q" class="form-control" placeholder="Search">

<button type="submit" class="btn btn-default">Search</button>
</form>

When a user hits the search button I want to add a string to the input.
For example, when a user types in "Foo" and submits the form, I want for the final URL to be https://www.google.com/search?q=FooSTRING instead of https://www.google.com/search?q=Foo.
How would I go about achieving this?

A: Add an event handler to the form submit that appends the string to the input before it's POSTed.  From another StackOverflow article:
window.onload = function() {
    document.getElementById('theForm').onsubmit = function() {
        var txt = document.getElementById('txtSearch');
        txt.value = "updated " + txt.value;
    };
};

You'd obviously have to modify the id selects to match your HTML for this to work.
If you want to do it in JQuery:
$('#theForm').submit(function() {
    var txt = $('#txtSearch');
    txt.val("updated " + txt.val());
});

A: You can make onclick event when pressing the button that changes input value, therefore changing final URL. Here is the code:
<!DOCTYPE html>

    <form class="navbar-form navbar-right" role="search"    action="https://www.google.com/search" target="_blank">

        <input id="search" type="text" name="q" class="form-control"     placeholder="Search">

      <button onclick="addString()" type="submit" class="btn btn- default">Search</button>
    </form>


text:
Q: set non-ORM object fields while querying Assume I have a class Interaction. My program processes interactions, in a way that each interaction updates a score table. Interaction is declared as an exact mapping of the database table, but I also want it to have a reference to the relevant instance of ScoreTable. ScoreTable is a class that holds the scores, and controls the business logic to update scores:
class Interaction(Base):
    __tablename__ = 'interactions'
    #Mirror the table's structure
    anomaly_id = Column(Integer, ForeignKey('anomalies.id'), primary_key=True)
    user_id = Column(Integer, primary_key=True) # ForeignKey('users.id'),
    feedback_score = Column(Integer)

    #scoreUpdater is another (non-ORM) object I want this instance to be aware of
    myScoreUpdater=  ...

All instances of Interaction fetched by a query() will share the same ScoreUpdater.So when I run the query() to get all my instances of Interactions, can I somehow tell the query() to set the scoreUpdater to a certain value, in the same process? Else, can I give query() a half-built template instance if Interaction to clone and populate the ORM data into?
I read that I could modify the standard constructor to perform certain tasks, but don't know how to pass extra arguments (such as the instance of ScoreUpdater) to the constructor via the query()
I guess the other way is to run the query first and let it populate the ORM-related fields, and then in a second step, iterate over the query results to set the non-OM fields (i.e. the right instance of scoreUpdater)?
I'm new to SQLalchemy ... and converting from java to python. So if you think my approach is fundamentally wrong, let me know!

A: The relevant documentation on constructing objects says:

The SQLAlchemy ORM does not call __init__ when recreating objects from database rows. The ORM's process is somewhat akin to the Python standard library's pickle module, invoking the low level __new__ method and then quietly restoring attributes directly on the instance rather than calling __init__.
If you need to do some setup on database-loaded instances before they're ready to use, there is an event hook known as InstanceEvents.load() which can achieve this; it is also available via a class-specific decorator called orm.reconstructor(). When using orm.reconstructor(), the mapper will invoke the decorated method with no arguments every time it loads or reconstructs an instance of the class. This is useful for recreating transient properties that are normally assigned in __init__

So if I've understood you correctly, you could define a reconstructor for Interaction that populates the non-ORM fields:
from sqlalchemy.orm import reconstructor

class Interaction(Base):

    __tablename__ = 'interactions'

    # Mirror the table's structure
    anomaly_id = Column(Integer, ForeignKey('anomalies.id'), primary_key=True)
    user_id = Column(Integer, primary_key=True) # ForeignKey('users.id'),
    feedback_score = Column(Integer)

    # myScoreUpdater is another (non-ORM) object I want this instance to be aware of
    @reconstructor
    def init_on_load(self):
        # Do what you must to populate score updater
        self.myScoreUpdater =  ...

Note that you'll probably want to share the logic between the reconstructor and __init__, so either just decorate __init__ as the reconstructor, if it can be called without arguments, or move initialization of score updater to a method.
Finally, if your ScoperUpdater does not actually need to know what instance it is bound to, you could just have it as a class attribute shared between all instances – like static attributes in Java.


text:
Q: Android : How to make a widget take full screen in java I want to make a RelativeLayout that takes full screen in JAVA CODE.
Inside this RelativeLayout I want to have 2 ImaveView, one that is in the top-left side with 50 heigth and 50 weight and the other that is in the top-left side as well and that "match_parent".
For now I have that :
relativeLayout = new RelativeLayout(this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
    relativeLayout.setLayoutParams(lp);

    im = new ImageView(this);
    im.setLayoutParams(new LayoutParams(50,50));

    im2 = new ImageView(this);
    im2.setScaleType(ImageView.ScaleType.FIT_XY);
    im2.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

    relativeLayout.addView(im2);
    relativeLayout.addView(im);

But the first image doesn't display and the second only take full weigth.
Here's an image of what I want :

A: Can you check this code ?
 RelativeLayout relativeLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        relativeLayout.setLayoutParams(lp);

        ImageView im = new ImageView(this);
        im.setLayoutParams(new RelativeLayout.LayoutParams(50, 50));
        im.setImageResource(R.color.accent);
        ImageView im2 = new ImageView(this);
        im2.setScaleType(ImageView.ScaleType.FIT_XY);
        im2.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        im2.setImageResource(R.color.orderProcessing);
        relativeLayout.addView(im2);
        relativeLayout.addView(im);
        setContentView(relativeLayout);


text:
Q: Is there a limit to the key length for localStorage? Is there any limit (up to the amount of local storage available) for the key when using localStorage?
i.e. can I do something like:
localStorage.setItem("pretend that this is a 1MB string", "whatever");

A: Yes, the limit is 5MB per domain.
Your string can be as long as you want. The total usage must, however, be under 5 MB.
http://dev.w3.org/html5/webstorage/
http://www.stackoverflow.com/questions/2747285/html5-localstorage-restrictions-and-limits


text:
Q: Understanding the use of convolution in neural networks. I'm reading about Convolutional Neural Networks (CNNs) in Deep Learning by Ian Goodfellow.
CNNs are different from traditional neural networks in that they use convolution in place of general matrix multiplication in at least one of their layers. The convolution is introduced as follows:

Suppose that we are tracking the location of a spaceshift with a laser sensor. Our laser provides a single output $x(t)$, the position of the spaceship at time $t$. Both $x$ and $t$ are real-valued, that is, we can get a different reading from the laser sensor at any instant in time.
  Now suppose our laser is somewhat noisy. To obtain a less noisy estimate of the spaceship's position, we would like to average several measurements. Of course, more recent measurements are more relevant, so we will want this to be a weighted average that gives more weight to recent measurements. We can do this with a weighting function $w(a)$, where $a$ is the age of a measurement. If we apply such a weighted average operation at every moment, we obtain a new function $s$ providing a smoothed estimate of the position of the spaceship: $$\displaystyle s(t) = \int x(a)w(t - a)da$$
  This operation is called convolution
$\ldots$
In convolutional network terminology, the first argument (in this example, the function $x$) to the convolution is often referred to as the input, and the second argument (in this example, the function $w$) as the kernel. The output is sometimes referred to as the feature map.
$\ldots$
In machine learning applications, the input is usually a multidimensional array of data, and the kernel is usually a multidimensional array of parameters that are adapted by the learning algorithm. We will refer to those multidimensional arrays as tensors. Because each element of the input and kernel must be explicitly stored separately, we usually assume that these functions are zero everywhere but in the finite set of points for which we store the values. This means that in practice, we can implement the infinite summation as a summation over a finite number of array elements.
  Finally, we often use convolutions over more than one axis at the time. For example, if we use a two-dimensional image $I$ as our input, we probably also want to use a two-dimensional kernel $K$:
  $$S(i,j) = (I*K)(i,j) = \sum_m\sum_nI(m,n)K(i-m,j-n)$$

(I assume that $S(i,j)$ means the feature map at point $(i,j)$).
The author then gives an example of $2$-D convolution with the following image:

I don't understand how this image illustrates what the author explains earlier. If we consider the input an image, then $a$ would resemble $I(0,0)$ right? Using the given definition of the feature map I find that $S(0,0) = \sum_m\sum_nI(m,n)K(0-m,0-n) = I(0,0)K(0,0) = aw$. Since e would resemble $I(1,0)$ I find that $$S(1,0) = \sum_m\sum_nI(m,n)K(1-m,0-n) = I(0,0)K(1,0) + I(1,0)K(0,0) = ay + ew$$ However, according to the image the output would be $aw + bx + ey + fz$.
Question: Why does the output equal $aw + bx + ey + fz$?
Edit: If the displayed outputs (feature maps) are only the outputs corresponding to the internal points on the grid, then I think I understand the figure. I would mean that the highlighted output corresponds to $S(1,1)$ and that the outputs $S(0,0), S(1,0), \ldots$ are simply not shown here right?
Thanks in advance!

A: Unfortunately, it is common practice in machine learning to compute correlations rather than convolutions (but calling them convolutions). They are different: for instance, see [1], [2], [3], [4], [5]. In the 2D case:
\begin{align}
\text{Corr: }\; C(u,v) &= (f\star g)(u,v)=\iint_{\mathbb{R}^2} f(u,v) g(u+x,v+y) \;dx dy\\
\text{Conv: }\; H(u,v) &= (f\ast g)(u,v)=\iint_{\mathbb{R}^2} f(u,v) g(u-x,v-y) \;dx dy
\end{align}
So notice that one can compute a convolution by mirroring the filter kernel (i.e., flipping vertically and horizontally) and then computing a correlation. So the answer to your question is just to do that double flipping first.
This renaming of correlations vs convolutions has seemingly caused widespread confusion. E.g., see these posts:
[1],
[2],
[3],
[4],
[5],
[6]. So why has it happened? Basically because (1) correlation and convolution have equal representational power (i.e., the capacity of a model using one is equal to that of a model using the other), (2) the kernels are learned so whether it is mirrored or not makes no difference, and (3) because convolution has such nice properties (e.g., Convolution Theorem for Fourier transforms) and is classically/historically more important in computer vision, practitioners prefer to think in terms of convolutions.


text:
Q: How to upgrade an existing kubeflow pipeline? In the pipeline UI I use the upload pipeline button to upload new pipelines.
Since the pipeline name is unique, the only way to update is to delete the old pipeline and then to upload a new one.
Is there a better way, maybe to manage a version for a single pipeline name?

A: Currently I'm using Kubeflow on prem with this config and there is no easy way to update a uploaded pipeline. However, I have tried just deploying Kubeflow Pipelines only by following this doc and the UI is more updated and it supports pipeline versioning (sorry but I can't get the screenshot since I already uninstall it). So probably this feature is half-way complete.
Just FYI, I also check the road map of Kubeflow, the pipeline versioning suppose to be ready in 2019 Q4 and will be in Kubeflow v1.0 release.

A: I assume you're running an older version of Kubeflow. The current latest version (v1.0 and beyond) supports Pipeline versioning. No, there's no native pipeline versioning in older Kubeflow versions (at least v0.7 or above). So you either have to manually remove the old pipeline and add the new one each time.
However, I typically bypass having to do this by not uploading the pipelines manually at all. There's a kfp-server-api library that you can check.
You create a kfp.Client object (link), giving it the host address, namespace and other authenticating info, and then use the upload_pipeline() call to give a suitable name to your pipeline. Or you can automate the delete + add new pipeline (with same name) workflow.
I find this pretty useful!


text:
Q: ProjectEuler#3: Why is it telling me that this division breaks even when it doesn't? For smaller numbers, my code seems to find the highest prime number ok. However, for this particular larger number it thinks 600851475143 is divisible by 7 (It is not a factor, which I verified using wolfram).
My algorithm to solve the problem is as follows:
1) Let p=value for which we want to find the immediately smaller prime number.
2) Check if p is prime using isComposite(p)
3) If p is composite, decrement p and try again
4) Stop when found a prime number
isComposite(p) works as follows:
1) Let i=2
2) Given some number 'limit', check to see if i divides 'limit'
3) If it does, then return i (Originally, it was 1 but I wanted to check what it think divides 'limit')
4) If i does not divide limit, increment i and repeat starting from 2, stopping when i>= sqrt(limit). This is because factors of a number, if they exist, occur in pairs in which one value is less than sqrt(number).
Here is the call tree:
printf("P3:%lu\n",p3v2(600851475143)); //Print the highest prime

Here is the p3v2() function:
unsigned long p3v2(unsigned long limit)
{
    unsigned long i = limit;

    while(i>1)
    {
        printf("Checking %lu\n", i);
        if(!(isComposite(i) != 0))
        {
            printf("%lu is prime!\n", isComposite(i));
            return i;
        }
        else
        {
            printf("%lu is composite!\n", isComposite(i));
            i--;
        }
    }
    return -1;
}

And isComposite()
unsigned long isComposite(unsigned int limit)
    {
        unsigned long i = 2;
        unsigned long searchUpperBound = (unsigned long)sqrt(limit); //Only need to search up to sqrt(limit) to see if there is a factor
        while(i<=searchUpperBound)                                   //See if numbers up through searchUpperBound divides limit
        {
            if(limit%i==0) //If factor found
                return i;
            else
                i++;
        }
        return 0;
    }

A: unsigned long is probably 32-bit on your machine. 600851475143 (hex 0x8BE589EAC7) doesn't fit in an unsigned long, it's actually 0xE589EAC7 (decimal 3851020999, which is dividable by 7)  that is used in calculation.
The solution is to use unsigned long long instead.

A: I'm going to assume that unsigned longs are 64-bit on your machine and unsigned ints are 32-bit.  Otherwise your printfs would probably be printing weird numbers already.  If this is all true, the culprit is this line:
unsigned long isComposite(unsigned int limit)

Here, you should make limit an unsigned long:
unsigned long isComposite(unsigned long limit)

However, I would suggest you remove all your unsigned longs and replace them with uint64_t:
#include <stdint.h>

uint64_t isComposite(uint64_t limit)


text:
Q: Using "would" in questions to ask about past habits I know the difference between used to and would. I've seen many examples of used to in questions, but I'm not sure if I've seen any for would. Are these questions correct to ask about someone's past habits, assuming the person who is being asked from is 60 years old.

Would you smoke when you were younger?
As a teenager, where would you hang out with your friends?

Is it possible to use would in this sense in questions?

A: The problem with "would" is that it has lots of senses, such as forming conditional phrases or "future in the past". This makes your first example of a "garden path sentence".  Your interpretation of "would" has to change:

Would you smoke...  {I think this is a conditional, I'm expecting an "if" clause like "if it was healthy"}
Would you smoke when {hmm, the if clause is a when clause, perhaps "when no children are around"...}
Would you smoke when you were younger {what?? I'm lost. I was younger, so that would can't have been a conditional clause. I've been led "up the garden path" meaning I've been tricked I have to go back re-interpret "would" as meaning "habit". Now I can understand, but it is confusing.}

Garden path sentences are not good English.
The second sentence is not a garden path sentence. The initial "as a teenager" sets a past time context. So there is no way that the "would" could be conditional, and the interpretation is straightforward.  So the second sentence is an example of good English.


text:
Q: Understanding UIView Height When Constraints Are Set with AutoLayout/UIScrollView I hope this  helps, but I am trying to wrap my head around a concept.  I have a UIScrollView, added to a self.view in my ViewController, with its top, leading, trailing, and bottom edges pinned to that of the self.view.  This is viewA.
I have a second UIView, viewB, with several subviews.  Each of those subviews are added to viewB with AutoLayout, and for brevity, each of those subviews have a height constraint set to a value.
I want to add viewB to viewA, with viewA able to scroll vertically.  Since viewB is undoubtedly taller than viewA, it should scroll.
I am adding viewB like so;
viewB.topAnchor.constraint(equalTo: viewA.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: viewA.leadingAnchor).isActive = true
viewB.trailingAnchor.cosntraint(equalTo: viewA.trailingAnchor).isActive = true

This is where I am stuck.  If I set a bottom anchor (viewB.bottomAnchor.constraint(equalTo: viewA.bottomAnchor).isActive = true), my UIScrollView does not scroll, and viewB is visibly cut off.
If I set a random height for viewB (using viewB.heightAnchor.constraint(equalToConstant: 2000.0).isActive = true), the UIScrollView does scroll, though this constant is far too tall.
I am confused how to get the appropriate height for viewB.  Since viewB does have an actual height (with hard-coded subviews), I see no reason that AutoLayout shouldn't be able to calculate that height of viewB, even with no bottom anchor set, but can't figure out the right code.

A: 1- You need to hook viewB leading , trailing , top and bottom to viewA , plus width of viewB is set = width of main vc's view
2- all constraints inside viewB should be hooked properly from top to bottom
3- instead of repeatedly using .isActive = true consider wrapping all constraints inside NSLayoutConstraint.activate([<#ConstraintsHere#>])
4- May be for your current approach a UITableView is more suitable

A: If the height constraint is complete, you don't have to consider viewA's contentSize.
You don't need to use ViewB, subviews add to viewA, subview1's top equalTo viewA's top, set subview1 height, subview1's bottom equalTo subview2's top or offset some Height. And so on. Until the last subview, subview4's bottom equal to viewA' bottom. You can get a suitable content size without setting the height of the content.