text:
Q: Can we create an object of a class (super or sub class) which cannot invoke any methods from the class? This question was asked to one of my friend in an interview.

Assume that there is a class called
A which is a super class and a sub class called B . Class A has a method called blah() which is also overridden in the subclass B . So create a  object in such a way that object created cannot invoke any of the methods from both class(can use both upcasting and downcasting).Is this possible in java or not. If possible construct the object.

So I tried this but I'm getting only ClassCast Exception at runtime.
So the above mentioned question is possible or not.
Thanks in advance.

A: This is not possible in java,
static class A{
    public void printF(){

        System.out.println("a");
    }
}
static class B extends A{
    @Override
    public void printF(){

        System.out.println("b");
    }
}
public static void main(String args[]){
    A obj1 = new A();
    obj1.printF();
    B obj2 = new B();
    obj2.printF();

    A obj3 = new B();
    obj3.printF();

    // this will throw error
    B obj4 = (A)new B();
    B obj5 = new A();
}

So we can expect the outputs as below,

*

*obj1.printF() will print a because it is created using the class A

*obj2.printF() will print b because it is created using the class B and class A is the superclass of class B because class B is inheriting the class A and class B is overriding the method in class A

*obj3.printF() will print b because it is created using class B and due to class B is overriding class A printF() method.And this is using upcasting in java
(upcasting - Upcasting is the typecasting of a child object to a parent)

*B obj4 = (A)new B() or B obj5 = new A(); is not possible in java this is trying to downcast an object implicitly,and this will throw the ClassCastException
(ClassCastException -Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.)
The approach in java for downcasting is to use instanceOf() method. It is downcasting explicitly.
A obj3 = new B();
if(obj3 instanceof B){
  B obj5 = (B)obj3;
  obj5.printF();
}

(Downcasting-downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.)


text:
Q: What is the method for solving this class of problem? $\frac{dx}{dt} = y$
$\frac{dy}{dt} = -\partial y - \mu x - x^2$
Find the fixed points and discuss stability.
I'd at least like to know what I should be googling, any help is appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scraping Aliexpress with Python - Login required I am trying to ceate a web scraper in Python that goes through all products of Aliexpress supplier.
My problem is that when I am going it without logging it I am eventually redirected to login web page. I added login section to my code but it does not help. I will appreciate all suggestions.
My code:
import requests
from bs4 import BeautifulSoup
import re
import sys
from lxml import html

def go_through_paginator(link):
    source_code = requests.get(link, data=payload,  headers = dict(referer = link))
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    print(soup)
    for page in soup.findAll ('div', {'class' : 'ui-pagination-navi util-left'}):
        for next_page in page.findAll ('a', {'class' : 'ui-pagination-next'}):
            next_page_link="https:" + next_page.get('href')
            print (next_page_link)
            gather_all_products (next_page_link)

def gather_all_products (url):
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for item in soup.findAll ('a', {'class' : 'pic-rind'}):
        product_link=item.get('href')
    go_through_paginator(url)

payload = {
    "loginId": "EMAIL",
    "password": "LOGIN",
}

LOGIN_URL='https://login.aliexpress.com/buyer.htm?spm=2114.12010608.1000002.4.EihgQ5&return=https%3A%2F%2Fwww.aliexpress.com%2Fstore%2F1816376%3Fspm%3D2114.10010108.0.0.fs2frD&random=CAB39130D12E432D4F5D75ED04DC0A84'

session_requests = requests.session()
source_code = session_requests.get(LOGIN_URL)
source_code = session_requests.post(LOGIN_URL, data = payload)

URL='https://www.aliexpress.com/store/1816376?spm=2114.10010108.0.0.fs2frD'

source_code = requests.get(URL, data=payload,  headers = dict(referer = URL))
plain_text = source_code.text
soup = BeautifulSoup(plain_text)

for L1 in soup.findAll ('li', {'id' : 'product-nav'}):
    for L1_link in L1.findAll('a', {'class' : 'nav-link'}):
        link = "https:" + L1_link.get('href')
        gather_all_products(link)

And this the aliexpress login URL:
https://login.aliexpress.com/buyer.htm?spm=2114.12010608.1000002.4.EihgQ5&return=https%3A%2F%2Fwww.aliexpress.com%2Fstore%2F1816376%3Fspm%3D2114.10010108.0.0.fs2frD&random=CAB39130D12E432D4F5D75ED04DC0A84

A: Try to set the cookies value from xman_t and intl_common_forever from response cookies.
I was try it directly to grab all products information. Before I set xman_t and intl_common_forever Aliexpress just allow me to grab 7 products. After I set xman_t and intl_common_forever I successfully grab 50 products.
Hopefully this help you to scrapes their product.

A: Your problem is a bit too complex for Stackoverflow but let's take a look at few tips that can make huge difference.
What is happening here is that Aliexpress is suspecting you of being a robot and requests you to login to proceed.
To avoid that you need to fortify your scraper a bit. Let's take a look at common tips for AliExpress.
First, you need to sanitize your urls and remove tracking parameters:
URL='https://www.aliexpress.com/store/1816376?spm=2114.10010108.0.0.fs2frD'
#                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# we don't need this parameter, it just helps AliExpress to identify us

Then, we should fortify our requests Session with browser-like headers:
BASE_HEADERS = {
    # lets use headers of Chrome 96 on Windows operating system to blend in:
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "accept-language": "en-US;en;q=0.9",
    "accept-encoding": "gzip, deflate, br",
}
session = requests.session(headers=BASE_HEADERS)

These two tips will decrease login requests significantly!
Though that's just the tip of an iceberg - for more see blog tutorial I wrote How to Scrape AliExpress


text:
Q: How to replace a string with a date using awk in unix? I have the following piece of code:
v=`date "+%Y%m%d"`
awk -F, '{$2=$v;}1' OFS=, test.txt > test2.txt

where test.txt is my input file and test2.txt the output file.
The lines in test1.txt respect the following format: Unix,10,A
When I execute the above script, it doubles the first and last word from test.txt

A: If the intention is to replace the second field with the value in $v, you will need to pass in the value to Awk somehow.  As a separate process, Awk has no knowledge about the shell's internal variables.
awk -F, -v v="$v" '{$2=v}1' OFS=, test.txt > test2.txt

Notice also that the Awk variable's name is just v.  To Awk, $v means the input field whose number is in the variable v.

A: Like this
awk -F, '{$2=v;}1' OFS=, v=`date "+%Y%m%d"` file
Unix,20140109,A

You should not read variable inside awk
Assign them first, ten use them.
v=`date "+%Y%m%d"`
awk -F, '{$2=var;}1' OFS=, var="$v" file

A: I would recommend the non legacy syntax here:
v=$(date "+%Y%m%d")

then you can use any of these awk invocations:
awk -F, -v v="$v" '{$2=v}1' OFS=, test.txt > test2.txt
awk -F, '{$2=v}1' OFS=, v="$v" test.txt > test2.txt
awk -F, '{$2="'$v'"}1' OFS=, test.txt > test2.txt

Alternatively, if you don't need the v variable later in the shell, you can run the date command from inside awk with either:
awk -F, 'BEGIN{"date \"+%Y%m%d\""|getline v}{$2=v}1' OFS=, test.txt > test2.txt

or
awk -F, 'BEGIN{v="'$(date "+%Y%m%d")'"}{$2=v}1' OFS=, test.txt > test2.txt

or the inefficient
awk -F, '{$2="'$(date "+%Y%m%d")'"}1' OFS=, test.txt > test2.txt


text:
Q: Populating Combo Box While populating the Combo box, i am getting the error

"Run time error 424 Object required".

Below is my code and i am trying to populate the list of countries(range name as countries) in the combo box.
Sub Country()
    Dim Count As Range
    Dim ws As Worksheet

    Set ws = Worksheets("sheet2")

    For Each Count In ws.Range("countries")
        With ComboBox1
            .AddItem Count.Value
        End With
    Next Count
End Sub

Please help me in resolving my errors.
Thanks in advance

A: Also, from what your code looks like it is doing, why not use the .ListFillRange property to do this rather than a loop.
Dynamically set ListFillRange in Excel ComboBox using VBA
Also where is the code? You are just referencing ComboBox1, try referencing it on the sheet that it resides on. Like
With Sheets(1).OLEObjects("ComboBox1").Object.AddItem

or
Sheets(1).ComboBox1.List = Sheets("countries").Range("A2:A10").Value

A: Try changing your variable name from Count to something like nCount


text: Q: How will you find area of quadrilateral.? If we are given four points in coordinate geometry. After finding the length joining these four points  like as AB, Bc, CA, AD. If a Quadrilateral is formed by these sides and length of these sides are unequal then,how will u find the area of quadrilateral?


text:
Q: Accessing Query Variables inside inside dataIdFromObject in InMemoryCache? I want to access the query variables to set the key in local cache, since my query doesn't have id and identical by query variable, how to access the query variables ?
const cache = new InMemoryCache({
  dataIdFromObject: (object, variables) => {
    console.log(object, variables);
    switch (object.__typename) {
      default:
        return defaultDataIdFromObject(object); // fall back to default handling
    }
  },
});

In the above code variables is undefined

A: Well it feels like. You need to do it on the backend.
query someQuery(justAnArg: Int) {
  someQuery {
    _justAnArg: $justAnArg
  }
}

This should do it.


text:
Q: I cannot view iAds in my application in viewcontroller.m
#import "ViewController.h"
#import "MyScene.h"

@import AVFoundation;

@interface ViewController ()
@property (nonatomic) AVAudioPlayer * backgroundMusicPlayer;
@end

@implementation ViewController

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    NSError *error;
    NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"loop" withExtension:@"wav"];
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    self.backgroundMusicPlayer.numberOfLoops = 1;
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];

    // Configure the view.
    SKView * skView = (SKView *)self.view;
    if (!skView.scene) {
      skView.showsFPS = YES;
      skView.showsNodeCount = NO;

      // Create and configure the scene.
      SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
      scene.scaleMode = SKSceneScaleModeAspectFill;

      // Present the scene.
      [skView presentScene:scene];

        self.canDisplayBannerAds = YES;

    }
}
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskAll;
    }

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}
@end

in viewcontroller.m
#import <UIKit/UIKit.h>
#import <SpriteKit/SpriteKit.h>
#import <iAd/iAd.h>

@interface ViewController : UIViewController <ADBannerViewDelegate>

@end

in appDelegate.h
#import <UIKit/UIKit.h>
#import <iAd/iAd.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, ADBannerViewDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

I cannot get my iAds to view at all.
I feel i have missed something but i cannot work it out.
My app/game functions perfectly but I cannot get it to show iAds.
the files I am using are
appDelegate.h
appDelegate.m
main storyboard
viewController.h
viewController.m
myScene.h
myScene.m
main.m
GAME-prefix.pch
gameOverScene.h
gameOverScene.m

A: It looks like your not actually implementing the iAd banner methods anywhere... You could use them like this:
-(void)bannerViewDidLoadAd:(ADBannerView *)banner {
    //user has internet connection, show the iAd

    CGRect bannerFrame = banner.frame;
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    UIViewController *ViewController;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1]; //animate the ad in
    [banner setAlpha:1]; //show the banner add
    [UIView commitAnimations];
}

- (void)bannerView:(ADBannerView *) banner didFailToReceiveAdWithError:error{
//banner view could not be loaded
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1]; //animate the ad out
[banner setAlpha:0]; //do not show the ad
[UIView commitAnimations];
}

You could put that in your Root ViewController file, then just drag an ADBannerView onto your view in your storyboard. Then right-click the ADBannerView, and under Outlets, connect delegate to your File's Owner, or the little yellow circle at the bottom of your view:

After that, ads should show correctly when there is internet connection.


text:
Q: Cannot parse ?next= value from http://login/?next=/my_page/ using request.GET.get('next','') I have a custom login url/view/template. I use the @login_required decorator for a page (let
's call it my_page) that requires login. Attempting to access
my_site.com/my_page

correctly calls
my_site.com/login/?next=/my_page/

BUT my view is unable to parse out the value of ?next=/my_page/my and instead always redirects to my default which is /qa/ in my view:
def login_with_email(request):
    error = ''
    if request.method == 'POST':
        if not request.POST.get('email', ''):
            error = 'Please enter your email and password'
        if not request.POST.get('password', ''):
            error = 'Please enter your email and password'
        if not error:
            email = request.POST['email']
            password = request.POST['password']

            try:
                user = User.objects.get(email=email)
                user = authenticate(username=user.username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request, user)

                        # ***
                        next_page = request.GET.get('next', '/qa/')
                        response = HttpResponseRedirect(next_page)
                        # ***

                        response.set_cookie('login_email', email, max_age=14*24*60*60)
                        return response
            except User.DoesNotExist:
                error = 'Invalid email and password combination'

Urls.py:
url(r'^login/$', views.login_with_email),

A: Per my comment below, I realized I had to grab the value of next from the url before my POST processing (thanks to @Anentropic for flashing on the lightbulb). So now I grab the value of next, pass it to my template where I store it in a hidden field, and finally access it when required for the redirect using request.POST.get:
Revised view:
def login_with_email(request):
    error = ''
    next = request.GET.get('next', '/qa/profile/private/')
    if request.method == 'POST':
    ...
                if user.is_active:
                    login(request, user)
                    next = request.POST.get('next', '/qa/profile/private/')
                    ...
    return render(request, 'qa/login_with_email.html', {'error': error, 'login_email': login_email, 'next': next,})

And in my template:
<form method="post" action="." autocomplete="on">{% csrf_token %}

<input type="hidden" name="next" value="{{ next }}"/>

    ...

Note: This answer was originally posted by the poser of the question. I just moved it here.


text:
Q: UIButtons in a UIView I have a UIScrollview with an IBOutlet mapped to ganttScroller. This UIScrollView has a UIView in it. I made the UIView in IB and its width is 100.
I then start to add buttons to that UIView (mapped via an IBOutlet scrollContent)
float test = [scrollContent frame].size.width;
for (int i=0; i<15; i++) {
        UIButton *showButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        showButton.frame = CGRectMake(55.0 * i,
                                        50.0,
                                        50.0,
                                        20.0);
        [showButton setTitle:NSLocalizedString(@"test", @"") forStates:UIControlStateNormal];
        [scrollContent addSubview:showButton];
    }
    test = [scrollContent frame].size.width;
    [scrollContent sizeToFit];
    test =[scrollContent frame].size.width;

At the beginning I check the size of my scrollContent and it is indeed 100 (checked 'test' in the debugger), after adding the buttons it is again 100, and after sizeToFit it is still 100 (I would expect a lot larger since all those buttons were added... The buttons are shown correctly!
I need the correct size for my gantScroller (UIScrollView)
What is wrong ?

A: I don't think -[UIView sizeToFit] actually takes in to account its subviews.  You'll need to simply calculate the correct width and assign that to the view's frame.  You'll then also need to set the scroll view's contentSize property so that it scrolls correctly.
Probably the reason you see all the buttons despite the container being too small is that UIViews do not clip their subviews by default.


text:
Q: Alphabets of Turing Machine I'm not completely sure about equivalence of two definitions of Turing machine.

*

*The first one states that Turing machine has a finite alphabet $\Sigma$, set of states and some rules.

*Turing machine in the second definition has two alphabets - input one $\Sigma_1$ and working one $\Sigma_2$ and set of states and rules.
I think it doesn't matter which definition you use, but I didn't find any proof or at least some mention about it anywhere.
The biggest "problem" I have is when you prove that multi-tape Turing machine is equivalent to one-tape Turing machine because in the proof you extend the alphabet (for example here). When you use the second definition you extend just the working alphabet and everything is ok. When you have the first definition you have to extend the "input" alphabet so the modified one-tape Turing machine accept more languages than the original multi-tape one and they are not equivalent...
Do you know where this problem (equivalence of the two definitions) is discussed? Or can you explain me that it does not matter?

A: We'll first proof that a Turing Machine with a finite alphabet of size $n$ can be reduced to a Turing Machine with a finite alphabet of size 2 (with more stats, of course)
Give each of the symbols a binary code of length $\lceil \log_2 n \rceil$ and split each cell to $\lceil \log_2 n \rceil$ subcells, which will be the cells of the new Turing Machine.
For each state, we need $2^{\log_2 n}$ states to read the symbol. Then we decide what symbol to write per state. This takes $n \log_2 n$ states. Then moving to another state takes another takes $2 \log_2 n$ states.
The exact number doesn't matter, what matters is that we can reduce it.
More detail on this you can read here.
Note that a Turing machine with alphabet $\Sigma_1 \cup \Sigma_2$ is at least as strong as the second Turing machine in your question. But this Turing machine is equivalent to the Turing machine with alphabet size 2, which is in turn equivalent to the Turing machine with alphabet $\Sigma$.
I hope this answers your question.


text:
Q: lstlistings: symbols in lstset morekeywords For some reason morekeywords doesn't consider =>, <= and check-sat as keywords in the example below. Is there a workaround or a more adequate way to do this?
\documentclass[a4paper,12pt]{article}
\usepackage{listings}

\lstset
{
    numbers             =left,
    numberstyle         =\color{gray},
    keywordstyle        =\bfseries,
    morekeywords        ={
        forall, exists,
        assert, check-sat,
        =>, <=,
        and, or
    },
    breaklines          =true,
    frame               =tlrb
}

\begin{document}
\begin{lstlisting}
(assert(
    forall ((x Int) (y Int) (z Int) (t Int))
        (=>
            (and
                (<= 0 (+ y z))
                (<= (+ y z) 1))
            (=>
                (= 1 (+ x t y z))
                (=>
                    (distinct 0 (+ y z))
                    (= 0 (+ x t)))))
))

(check-sat)
\end{lstlisting}
\end{document}

A: Adding \usepackage{listingsutf8} and
\usepackage{lmodern} and adding the symbols as letters with alsoletters seems to work
\documentclass[a4paper,12pt]{article}
\usepackage{listings}
\usepackage{listingsutf8}
\usepackage{lmodern}

\lstset
{
    numbers             =left,
    numberstyle         =\color{gray},
    alsoletter          ={<=, =>, +, -, =},
    morekeywords        ={
        forall,exists,
        assert,check-sat,distinct,
        =>, <=, =, +,
        and,or},
    keywordstyle        =\bfseries\boldmath,
    breaklines          =true,
    frame               =tlrb
}

\begin{document}
\begin{lstlisting}
(assert(
    forall ((x Int) (y Int) (z Int) (t Int))
        (=>
            (and
                (<= 0 (+ y z))
                (<= (+ y z) 1))
            (=>
                (= 1 (+ x t y z))
                (=>
                    (distinct 0 (+ y z))
                    (= 0 (+ x t)))))
))

(check-sat)
\end{lstlisting}
\end{document}


text:
Q: Insert in teradata table very slow I'm trying to insert 1,5 billion of lines into a table that already contains ~3 billions of lines. The problem is that this table is now very slow because of the huge amount of lines. Even a simple select if very very long. I'm new in Teradata (vantage) and I didnt create the table but I think that there are some possible optimizations.
It's a fact table, so only "insert" is uses, no update.
Here is the ddl (I renamed the table / column names):
CREATE MULTISET TABLE MY_TABLE ,FALLBACK ,
 NO BEFORE JOURNAL,
 NO AFTER JOURNAL,
 CHECKSUM = DEFAULT,
 DEFAULT MERGEBLOCKRATIO,
 MAP = TD_MAP1
 (
  SK_ID BIGINT GENERATED ALWAYS AS IDENTITY
       (START WITH 1
        INCREMENT BY 1
        MINVALUE -999999999999999999
        MAXVALUE 999999999999999999
        NO CYCLE),
  col1 VARCHAR(50) CHARACTER SET LATIN NOT CASESPECIFIC,
  col2 VARCHAR(15) CHARACTER SET LATIN NOT CASESPECIFIC,
  col3 TIMESTAMP(6) NOT NULL,
  col4 TIMESTAMP(6) NOT NULL,
  col5 VARCHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  col6 TIMESTAMP(6) NOT NULL,
  col7 DATE FORMAT 'yyyy-mm-dd' NOT NULL,
  col8 INTEGER NOT NULL,
  col9 INTEGER NOT NULL,
  col10 BIGINT NOT NULL,
  col11 INTEGER NOT NULL,
  col12 INTEGER NOT NULL,
  col13 BIGINT NOT NULL,
  col14 INTEGER NOT NULL,
  col15 DECIMAL(16,4) NOT NULL,
  col16 DECIMAL(16,4) NOT NULL,
  col17 VARCHAR(4) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  col18 INTEGER NOT NULL,
  col19 DECIMAL(16,4) NOT NULL,
  col20 INTEGER NOT NULL,
  col21 DECIMAL(16,4) NOT NULL,
  col22 INTEGER NOT NULL,
  col23 DECIMAL(16,4) NOT NULL,
  col24 INTEGER NOT NULL,
  col25 DECIMAL(16,4) NOT NULL,
  col26 INTEGER NOT NULL,
  col27 DECIMAL(16,4) NOT NULL,
  col28 INTEGER NOT NULL,
  col29 DECIMAL(16,4) NOT NULL,
  col30 VARCHAR(1) CHARACTER SET LATIN NOT CASESPECIFIC,
  col31 VARCHAR(1) CHARACTER SET LATIN NOT CASESPECIFIC,
  col32 INTEGER,
  col34 INTEGER,
  col35 VARCHAR(6) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  col36 VARCHAR(6) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  col37 BIGINT NOT NULL,
  col38 VARCHAR(5) CHARACTER SET LATIN NOT CASESPECIFIC,
  col39 VARCHAR(1) CHARACTER SET LATIN NOT CASESPECIFIC,
  col40 CHAR(1) CHARACTER SET LATIN NOT CASESPECIFIC,
  col41 DATE FORMAT 'yyyy-mm-dd',
  col42 DATE FORMAT 'yyyy-mm-dd',
  col43 DATE FORMAT 'yyyy-mm-dd');
 UNIQUE PRIMARY INDEX (SK_ID)

As you can see there is A PI on the auto increment column, is it really usefull ? Because obviously this column will never be used in a "join" or where" clause. I checked and there is no other uniq column in the whole table.
Do you see any possible optimizations to make this big tables healthier ?
Thank you for your help,
Regards,
Thomas


text:
Q: Python uses 'ascii' codec in decoding where it should use 'UTF-8' I have a piece of code:
with open('filename.txt','r') as textfile:
    kwList = [x.strip('\n') for x in textfile.readlines()]

I get a: UnicodeDecodeError : 'ascii' codec can't decode byte 0xc4 in position 5595: ordinal not in range(128) on line 2
The problem is that according the python docs :
https://docs.python.org/3/library/functions.html#open
Python3 uses locale.getpreferredencoding(False) to get the default encoding to use when there is no encoding specified in the open method.
When I run locale.getpreferredencoding(False), I get 'UTF-8'.
Why do I get 'ascii' codec failed in the UnicodeDecodeError when Python should use 'utf-8' to do this?

A: The locale is taken from the context; on POSIX systems, that means the environment variables, see the POSIX locale documentation. You'll need to reproduce the exact context of your production environment if you want to test what encoding Python will decide on (e.g. copy the environment variables used by the production environment too).
You are probably running your program as a subprocess of something that only sets (or inherits) the effective user, but does not copy the environment for that user. Either an explicit locale has been set by that parent process or, if none is set, the default C locale is used. The default encoding for that locale is ASCII; some systems will report this by the name ANSI_X3.4-1968:
$ LANG=C python -c 'import locale; print(locale.getpreferredencoding(False))'
ANSI_X3.4-1968

If, for example, your production code is run from cron, then the environment variables are not set when you set a specific user. Set LC_ALL environment variable explicitly at the top of your crontab:
LC_ALL=en.UTF-8

if your cron implementation supports setting variables this way, or set it on the command line you are going to run:
* * * * *    LC_ALL=nb_NO.UTF-8 /path/to/your/program

See Where can I set environment variables that crontab will use?


text:
Q: A vector of complex numbers as a linear combination Is it possible to state a vector of complex numbers as a linear combination of a real numbers vector (Re(z)) and a another real numbers vector (Im(z)) multiplied by i?

A: Yes, for example, $$(83+42i,96-15i)=(83,96)+i(42,-15)$$

A: Every element in $\mathbb{R}^n $ can be written as a linear combination of the basis vectors $(e_i)_{i=1}^n$, where $e_i=(0.\ldots,0,1,0,\ldots,0)$ where $1$ is at the $i$th position. Now for any $z\in\mathbb{C}^n$ we have $z=x+iy$ where $x,y\in\mathbb{R}^n$ and each of the $x$ and $y$ can be expressed as a linear combination of $e_i$'s.


text:
Q: How to insert array field in Laravel 5.6 How can I insert multiple input radio data with Laravel?
When I select a radio button and click submit form to insert into my database
Here is my html:

            Question No

            Yes

            No

1.You Like It's

              <input name="q1[]" type="radio" value="1">

              <input name="q1[]" type="radio" value="0">

2.you don't like it's

              <input name="q2[]" type="radio" value="1">

              <input name="q2[]" type="radio" value="0">

My QuestionController.php :
$question = new Question;
$question ->id = $request->get(id);
$question ->question_no = 'question1';
$question ->score = $request->get('q1');
$question ->save();
return redirect('/questionForm/create');

But it can insert to database only one row and I want to insert data to database table like this:
|id|user_id|question_no|score|
|1 |  1    | question1 |  1  |
|2 |  1    | question2 |  0  |

How to insert multiple data to database table?

A: Multiple data means you have to insert multiple times. $request->get('q1') and $request->get('q2') both produce arrays so you have to loop over them (or array_sum(), or whatever you need to do to aggregate your q1/2 values to a single score column).
Now, assuming score is the sum of the checked values, and id is an autoincrement column it would look something like this:
    // deal with the q1 array
    $q1_array = $request->input('q1');
    $question = new Question;
    foreach ($q1_array as $q1_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q1_total =+ $q1_answer;
    }
    $question->question_no = 'question1';
    $question->score = $q1_total;
    $question->save();

    // now deal with the q2 array
    $q2_array = $request->input('q2');
    $question = new Question;
    foreach ($q2_array as $q2_answer) {
        // i'm assuming table.score is the sum of the values of the arrays
        $q2_total =+ $q2_answer;
    }
    $question->question_no = 'question2';
    $question->score = $q2_total;
    $question->save();

Of course this was written only for clarity. You could have a separate loop outside so you don't repeat the question1 and question2 code.
Here is a more abbreviated version, assuming your table is named answers:
    DB::table('answers')->insert([
        ['user_id' => $userId, 'question_no' => 'question1', 'score' => array_sum($request->input('q1'))],
        ['user_id' => $userId, 'question_no' => 'question2', 'score' => array_sum($request->input('q2'))],
    ]);


text:
Q: How to check if figures are on the same page of call out/text? If a figure is mentioned in a text, say page 10, but the corresponding figure appears on page 11, how can I automatically introduce some additional text (e.g.: on page 11) beside the figure mention in the text.
Instead of doing this:
Figure \ref{fig:test} on page \pageref{fig:test} shows bla bla.
Autocheck:
Figure \\ref{fig:test} \check shows bla bla.
Where \check is a macro to check the co-existence of the figure referencing and figure (float), whether they are on the same page. If true, return Null, else return on page \pageref{fig:test}.

A: Consider using the varioref package and its \vpageref command to reference the page associated with another \label. It does a check to see whether the reference is on the same page. If so, the default text (on this page) is printed. You can override this globally, or locally by supplying an optional argument. You're most likely looking for \vpageref[]{<label>} with an empty optional argument (so as to print nothing).

\documentclass{article}

\usepackage{graphicx,lipsum}
\usepackage[nospace]{varioref}

\begin{document}

\lipsum[1]

\begin{figure}
  \centering
  \includegraphics[width=.3\linewidth]{example-image}
  \caption{A figure}
  \label{fig:figure}
\end{figure}

\lipsum[2]

See Figure~\ref{fig:figure} on page~\pageref{fig:figure}.

See Figure~\ref{fig:figure} \vpageref{fig:figure}.

See Figure~\ref{fig:figure} \vpageref[]{fig:figure}.% Note the empty optional argument

\lipsum[3]

\end{document}

Since \vpageref itself sets a \label in order to compare the page numbers its referencing, you'll need to compile twice with every change in the location of \vpageref.

A: OpTeX users can create following definition of the \check macro:
\def\check{\label[x/\_lastreflabel]\wlabel{}%
   \space
   \ea\ifx\csname _pgref:x/\_lastreflabel\ea\endcsname
          \csname _pgref:\_lastreflabel\endcsname
   \else on page \pgref[\_lastreflabel] \fi
}

% Test:

Figure \ref[fig:label]\check shows bla bla.

%\vfil\break   %% <-- you can comment out this to show the effect

... a figure ...
\cskip
\caption/f [fig:label] Figure blba bla

\bye

Of course, you have to run TeX twice when changes were done.
The macro \check creates its own label x/label an writes its position to the .ref file using \wlabel{}. The following \ifx checks it the reference macros \_pgref:x/label and \_pgref:label are the same. If it is true then it does nothing else it writes the text on page \pgref[label] .


text:
Q: I am using ionic framework and want to use cordova themeablebrowser to open few urls inside the app But I am not able to show the close images and hence not able to perform close action. Can someone please help me with where exactly should my close images be?
Here is my code:
cordova.ThemeableBrowser.open(url, '_blank', {
          statusbar: {
              color: '#ffffff'
          },
          toolbar: {
              height: 44,
              color: '#56ad9b'
          },
          title: {
              color: '#ffffff',
              showPageTitle: true
          },
          "browserProgress": {
            "showProgress": true,
            "progressBgColor": "#016585",
            "progressColor": "#FFAA16"
          },
          closeButton: {
              image: 'close.png',
              imagePressed: 'close_pressed.png',
              align: 'left',
              event: 'closePressed'
          },
          backButtonCanClose: true
        }).addEventListener('backPressed', function(e) {
            alert('back pressed');
        }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function(e) {
            console.error(e.message);
        }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function(e) {
            console.log(e.message);
        });

A: Check "Import Native Images" section in readme file.
https://github.com/initialxy/cordova-plugin-themeablebrowser/blob/master/README.md#import-native-images
For android images should be inside "res" folder and for iOS it should be inside "Resource" folder.
And you do not need to add file extension in your code.


text:
Q: WPF MVVM Change GUI after clicking Item I currently try to visualize an RSS feed. I have created 2 objects: FeedChannel and FeedElement. The FeedChannel may contain FeedElements.
This feed may have multiple channels, which will be displayed like this:
<Grid>
    <ScrollViewer>
        <ListBox ItemsSource="{Binding Feed, IsAsync=True}" x:Name="ListFeed">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <i:InvokeCommandAction Command="{Binding ChannelClickCommand}" CommandParameter="{Binding ElementName=ListFeed, Path=SelectedItem}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Margin="0,0,10,0" Source="{Binding ImageLink}" VerticalAlignment="Top" Width="100" Height="50"/>
                            <StackPanel Grid.Column="1" Orientation="Vertical">
                                <TextBlock Text="{Binding Title}" FontWeight="ExtraBold" />
                                <TextBlock Text="{Binding Description}" />
                                <TextBlock Text="{Binding PublicationDate}" HorizontalAlignment="Right" FontWeight="Thin"/>
                            </StackPanel>
                        </Grid>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </ScrollViewer>
</Grid>

The ChannelClickCommand will save the clicked Channel into the ActiveChannel property. From my view, I should now access the ActiveChannel and display the FeedElements inside it.
That's all quite easily done, but I struggle in finding the correct approach for the following:
Given that the User first sees all Channels (and only Channels!), he may now click one of them and then all Elements will be displayed (no Channels are visible anymore). He may go back to view all Channels with a Button-click or something similar.
I thought about using Stackpanels and turning them visible/collapsed depending on what's needed, but is there a better solution to this problem?

A: Not sure that from a UI/UX point of view having the channels and elements in the same list is the best way to handle it. But to answer your question, you can have a look at the DataTemplateSelector property or you could use the DataType property on the DataTemplate element.
Without getting into too much details (a little search on the website will give you all required info), here is a solution with the DataType property:
<Grid>
    <ListBox ItemsSource="{Binding Feed, IsAsync=True}" x:Name="ListFeed">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonUp">
                <i:InvokeCommandAction Command="{Binding ChannelClickCommand}" CommandParameter="{Binding ElementName=ListFeed, Path=SelectedItem}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <ListBox.Resources>
            <ResourceDictionary>
                <DataTemplate DataType="{x:Type my:FeedChannel}">
                    <StackPanel Orientation="Horizontal">
                        <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Margin="0,0,10,0" Source="{Binding ImageLink}" VerticalAlignment="Top" Width="100" Height="50"/>
                            <StackPanel Grid.Column="1" Orientation="Vertical">
                                <TextBlock Text="{Binding Title}" FontWeight="ExtraBold" />
                                <TextBlock Text="{Binding Description}" />
                                <TextBlock Text="{Binding PublicationDate}" HorizontalAlignment="Right" FontWeight="Thin"/>
                            </StackPanel>
                        </Grid>
                    </StackPanel>
                </DataTemplate>

                <DataTemplate DataType="{x:Type my:FeedElement}">
                    <!-- Your data template for FeedElement -->
                </DataTemplate>
            </ResourceDictionary>
        </ListBox.Resources>
    </ListBox>
</Grid>

Just replace the elements in your Feed property from the ChannelClickCommand and it should work fine.


text:
Q: How to block specific user id in custom login form? I've been looking for this method for weeks, but still can't find it. There are so many sites that discuss how to create a custom login page, but they don't cover how to block a specific id like the one I was looking for.
The algorithm is as below:
first I will determine the user id number that I will block via code in php.
On the front end page, the user will input their username and password. Then when they click the login button, wordpress does not immediately check the compatibility between the user's username and password.
Wordpress will first check the id of the username that has been entered by the user. If it turns out that the username has the same ID as the ID I blocked, an error message will appear and the user cannot log in, but if the username does not have the same ID as the ID I blocked, then the user can login.
I hope you guys can help. Thank you in advance

A: There is a simple plugin which you could use to lock user account and it's FREE.
https://wordpress.org/plugins/lock-user-account/
Simply works great!

*

*Install and activate the plugin

*Navigate to Users Page (From WP Dashboard)

*Select the specific user(s) you want to lock

*Choose 'lock' option from the 'Bulk action' dropdown

*That's it!

A: You can add a low priority authenticate hook that runs after all the other hooks and rejects authentication for a specific user ID:
function wpse_384212_ban_user_id( $user, $username, $password ) {
    // At this point $user is either a WP_User object if they've successfully logged in,
    // or null or a WP_Error if they haven't. We want to reject users by ID.

    if ( $user instanceof WP_User ) {
        // This is a successfully authenticated user. Check their ID.
        $banned_user_ids = array( 3, 6, 10 ); // could also store these in a site option

        if ( in_array( $user->ID, $banned_user_ids ) ) {
            return new WP_Error( 'user_banned', 'You are banned' );
        }
    }

    // Else return the user or error from previous authentication filters
    return $user;
}

add_filter( 'authenticate', 'wpse_384212_ban_user_id', 999, 3 );

This rejects users who have otherwise logged in successfully. If you wanted to reject them whether they managed to log in or not, you'll need to look up the user to fetch their ID for the extra check:
function wpse_384212_ban_user_id( $user, $username, $password ) {
    // At this point $user is either a WP_User object if they've successfully logged in,
    // or null or a WP_Error if they haven't. We want to reject users by ID.
    $banned_user_ids = array( 3, 6, 10 ); // could also store these in a site option

    if ( $user instanceof WP_User ) {
        // This is a successfully authenticated user. Check their ID.

        if ( in_array( $user->ID, $banned_user_ids ) ) {
            return new WP_Error( 'user_banned', 'You are banned' );
        }
    } elseif ($username) {
        // Unsuccessful login but we have a username.
        // Look up the user by username or email to see if they are a banned user
        $login_user = get_user_by( 'login', $username );
        if ( ! $login_user && is_email( $username ) ) {
            $login_user = get_user_by( 'email', $username );
        }
        if ( $login_user instanceof WP_User ) {
            // This was a failed login for a valid user. Check the user's ID
            if ( in_array( $login_user->ID, $banned_user_ids ) ) {
                return new WP_Error( 'user_banned', 'You are banned' );
            }
        }
    }

    // Else return the user or error from previous authentication filters
    return $user;
}

add_filter( 'authenticate', 'wpse_384212_ban_user_id', 999, 3 );

If this is a multisite then these would need to go in a mu-plugin.


text:
Q: Try to get all or nothing from a sequence based on a precondition The following code will not work as I expected it to:
// Gets all or nothing. If predicate is false for at least one item
// in the sequence, returns None. If seq is empty, returns the empty seq.
let tryGetAllOrNone predicate (source: seq<_>) =
    let mutable condition = true
    let resultSeq =
        seq {
            use e = source.GetEnumerator()
            while condition && e.MoveNext() && (condition <- predicate e.Current; condition) do
                yield e.Current
        }
    if condition then Some resultSeq
    else None

The reason is quite clear: a sequence is lazily evaluated, which means that here the if statement will be evaluated first, returning the sequence. Then, when we consume the resulting sequence we will always get Some results, until the condition turns false:
// expect: None (predicate is false for the first item)
> [1;2;3] |> tryGetAllOrNone (fun x -> x = 2);;
val it : seq<int> option = Some (seq [])

// expect None (predicate is false for the second item)
> [1;2;3] |> tryGetAllOrNone (fun x -> x = 1);;
val it : seq<int> option = Some (seq [1])

// correct (predicate is always true)
> [1;2;3] |> tryGetAllOrNone (fun x -> x > 0);;
val it : seq<int> option = Some (seq [1; 2; 3])

I might just have to consume the sequence first, i.e. by using [...yield ...] instead of seq { .. yield ...}, but maybe there's a simpler solution that retains the laziness (just asking the question makes it sound backwards, so my gut tells me: consume first, right)?
EDIT: thinking about this is a tad longer has me come to the conclusion that what I'm asking is not possible. You cannot first lazily return one after the other from a sequence and then, upon hitting an invalid item, say: "hey, all those items you got thus far, give them back, if one is invalid, all are invalid!".
Leaving it out here nonetheless in case it helps someone else or in case someone has a better idea ;).

A: You are right that, in general, you will need to iterate over the whole sequence until you can return None or Some. If the last element of the sequence does not satsify the condition, then you need to first read all the preceding elements until you know that you have failed.
The only optimization you can do is that you can return None as soon as you find a first element that does not satisfy the condition. This is slightly better than building the whole sequence and then checking if the condition was false for any of the elemnetns (in that, if an earlier element fails to satisfy the condition, you can return None sooner). The following implementation does that:
// Gets all or nothing. If predicate is false for at least one item
// in the sequence, returns None. If seq is empty, returns the empty seq.
let tryGetAllOrNone predicate (source: seq<_>) =
    let results = ResizeArray<_>()
    let mutable failed = false
    use e = source.GetEnumerator()
    while not failed && e.MoveNext() do
      if not (predicate e.Current) then failed <- true
      else results.Add(e.Current)
    if failed then None
    else Some(seq results)


text:
Q: Which sections of the webcomic/graphic novel are covered by "Agatha H. and the Clockwork Princess" After spending some time reading Girl-Genius web-comic I was convinced to buy the first book and I loved it!
The book spanned the time from the beginning to when Agatha escaped the Airship City.  She has not yet been in the wilderness, met the carnival or anything else.
What range of webcomic story does the next book, "Agatha H. and the Clockwork Princess" cover?  I'm hoping it starts from the end of the first book and goes on until she is close to castle Heterodyne.  I would like a confirmation whether or not this is the case.

A: As the other answer said, "Agatha H and the Clockwork Princess covers Volumes 4 thru 6"
Here's an image of where to see the volume numbers in the dropdown on the chapter selection menu on the Girl Genius website:

This should make it simple to see which volume you're reading and find volumes 4-6. By the way, the link to the GG site above is the link to page one of vloume four.


text:
Q: AWS API Gateway websocket with spring boot backend I'm building an application using spring boot. I'm planning to add a chat feature to it via websocket. Considering that I'm hosting it on AWS, how can I integrate the websocket properly via api gateway websocket? Do I do my spring controller mapping for websocket via api gateway websocket endpoint?

A: AWS API Gateway provides you with an option of HTTP integration, so you can keep your application in an ECS container and expose an endpoint that can be ingested by the API gateway side.


text:
Q: PHP Strtotime erratic function The following code should take the fourth friday of February and the fourth friday of April and return it.
$datei1 = date(strtotime('fourth friday', strtotime('february', strtotime(date('01-m-Y')))));

$datei2 = date(strtotime('fourth friday', strtotime('april', strtotime(date('01-m-Y')))));

Its working but taking the 5th friday of April not the fourth. I can only assume that it does not believe the first of April counts.
Any ideas,
Marvellous

A: Your code is very complicated for no reason. Try this (PHP 5.3):
$date = date('Y-m-d', strtotime('fourth friday of april 2011'));

This will give you:
2011-04-22

In PHP 5.2, this syntax seems to work in all cases:
$date = date('Y-m-d', strtotime('fourth friday', strtotime('april - 1 second')));

A: strtotime('fourth friday', $now) probably really means "the fourth Friday relative to $now".
The $now parameter you give is 1st April 2011, which is a Friday. The fourth Friday after Fri 1st April is the fifth Friday of the month.

A: It appears you're using an older version of PHP. Major changes have been introduced to handle the edge case you're experiencing here. In which case I believe the following is the cleanest approach:
echo date('Y-m-d', strtotime('+4 fridays', mktime(0,0,0,4,0,date('Y'))));
// or
echo date('Y-m-d', strtotime('fourth friday', mktime(0,0,0,4,0,date('Y'))));

This should give you the fourth friday in april of the current year. I've tested successfully in 5.3 but you'll have to test on you older installation.

A: PHP Changelog ::
5.2.7    In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.


text:
Q: GWT Visualization problem creating a graph with data from database I'm experiencing problem creating a graph. The data for the graph is coming from database as a HashMap. Following is my code:
public void onModuleLoad()
{

    Runnable onLoadCallback = new Runnable()
    {
        public void run()
        {
            AbstractDataTable data = createLineTable();
            Options options = createLineOptions();
            LineChart line = new LineChart(data, options);
            vPanelWithGraph.add(line);
            vPanelWithGraph.add(closeGraphPopUp);
    };
    VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);
    popUpGraph.add(vPanelWithGraph);
}

private LineChart.Options createLineOptions()
{
    Options options = Options.create();
    options.setWidth(400);
    options.setHeight(240);
    options.setTitle("Graph Name");
    return options;
}

private AbstractDataTable createLineTable()
{
    DataTable data = DataTable.create();
    data.addColumn(ColumnType.STRING, "Date");
    data.addColumn(ColumnType.NUMBER, "Number");

    HashMap<String,String> map = getDateAndWarningCount();
    data.addRows(2);

    String [] arrDate = new String [2];
    int  [] arrWarCount = new int [2];
    int i=0;
    Iterator it = map.entrySet().iterator();

    while (it.hasNext())
    {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        arrDate[i]=""+pairs.getKey();
        arrWarCount[i]=Integer.parseInt((String)pairs.getValue());
        i++;
    }
    data.setValue(0, 0, arrDate[0]);// row column
    data.setValue(0, 1, 5);

    data.setValue(1, 0, arrDate[1]);
    data.setValue(1, 1, 6);

    return data;
}

private HashMap<String,String> getDateAndWarningCount()
{
    HashMap<String,String> map = null;
    SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
    AsyncCallback<HashMap<String,String>>  callback = new AsyncCallback<HashMap<String,String>>()
    {
        @Override
        public void onFailure(Throwable caught)
        {}

        @Override
        public void onSuccess(HashMap<String,String> result)
        {
            map  = (HashMap<String,String>)result;
        }
    };
    service.getHashMapValues(callback);
    return map;
    }

}

The app is creating a pop-up with a graph. When the pop-up graph come up, it shows all 0. I printed out the values of the hashmap, the hashmap is getting populated with the correct data. Can't figure out what I'm doing wrong here. Any help will be appreciated. Thanks
Following is my edited code....it works...thanks everyone!
public DialogBox getPopUpWarningGraph()
    {
        SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
        AsyncCallback<LinkedHashMap<String, Integer>> callback = new AsyncCallback<LinkedHashMap<String, Integer>>()
        {
            @Override
            public void onFailure(Throwable caught)
            {
            }

            @Override
            public void onSuccess(LinkedHashMap<String, Integer> result)
            {
                map = new LinkedHashMap<String,Integer>(result);

                Runnable onLoadCallback = new Runnable()
                {
                    public void run()
                    {
                        AbstractDataTable data = createLineTable(map);
                        Options options = createLineOptions();
                        LineChart lineChart = new LineChart(data, options);
                        vPanelWithGraph.add(lineChart);
                        vPanelWithGraph.add(closeGraphPopUp);
                    }
                };
                VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);
            }
        };
        service.getDateAndWarningCount("",callback);
        popUpGraph.add(vPanelWithGraph);
        return popUpGraph;
    }

    private LineChart.Options createLineOptions()
    {
        Options options = Options.create();
        options.setWidth(400);
        options.setHeight(240);
        options.setTitle("");
        return options;
    }

    private AbstractDataTable createLineTable(HashMap<String,Integer> map )
    {
        DataTable data = DataTable.create();
        data.addColumn(ColumnType.STRING, "Task");
        data.addColumn(ColumnType.NUMBER, "");

        data.addRows(map.size());

        Iterator it = map.entrySet().iterator();
        int i=0;
        while (it.hasNext())
        {
            Map.Entry pairs = (Map.Entry)it.next();
            data.setValue(i,0,pairs.getKey()+"");
            data.setValue(i,1,Integer.parseInt(pairs.getValue()+""));
            i++;
        }
        return data;
    }
}

so basically, getPopUpWarningGraph() function can be called from any class and it will return a popup with a graph!

A: Your getDateAndWarningCount() returns immediately, before data is loaded - and it always returns null.
In GWT (and javascript) you have to program asynchronously - execute your code when system calls you.
In your case you have to execute drawing when onSuccess() is called, because this is when you have the data available.
public void onModuleLoad()
{

    Runnable onLoadCallback = new Runnable()
    {
        public void run() {
            // first get the data
            getDateAndWarningCount()
        }
    };
    VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);
    popUpGraph.add(vPanelWithGraph);
}

private LineChart.Options createLineOptions()
{
    Options options = Options.create();
    options.setWidth(400);
    options.setHeight(240);
    options.setTitle("Graph Name");
    return options;
}

private AbstractDataTable createLineTable(HashMap<String,String> map)
{
    DataTable data = DataTable.create();
    data.addColumn(ColumnType.STRING, "Date");
    data.addColumn(ColumnType.NUMBER, "Number");

    data.addRows(2);

    String [] arrDate = new String [2];
    int  [] arrWarCount = new int [2];
    int i=0;
    Iterator it = map.entrySet().iterator();

    while (it.hasNext())
    {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        arrDate[i]=""+pairs.getKey();
        arrWarCount[i]=Integer.parseInt((String)pairs.getValue());
        i++;
    }
    data.setValue(0, 0, arrDate[0]);// row column
    data.setValue(0, 1, 5);

    data.setValue(1, 0, arrDate[1]);
    data.setValue(1, 1, 6);

    return data;
}

private HashMap<String,String> getDateAndWarningCount()
{
    HashMap<String,String> map = null;
    SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
    AsyncCallback<HashMap<String,String>>  callback = new AsyncCallback<HashMap<String,String>>()
    {
        @Override
        public void onFailure(Throwable caught)
        {}

        @Override
        public void onSuccess(HashMap<String,String> result)
        {
                            Runnable onLoadCallback = new Runnable()
            {
                public void run()
                {
                    AbstractDataTable data = createLineTable(map);
                    Options options = createLineOptions();
                    LineChart lineChart = new LineChart(data, options);
                    vPanelWithGraph.add(lineChart);
                    vPanelWithGraph.add(closeGraphPopUp);
                }
            };
            VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);
        }
    };
    service.getHashMapValues(callback);
    return map;
    }

}


text:
Q: Website menu is hidden behind page - Z-index I have an issue with a site i'm working on in that the menu displays only the first child items on the homepage (overlayed on top of a metaslider), but the menu displays correctly on the remaining pages. I have tried manipulating the z-index of the menu, the slider and the page content to no avail.
What I have figured out is when the site content contain div is given a z-index of 100 (as it is now):
.site-content-contain {
    z-index: 100!important;
}

the site content shows but the menu has an issue.
As soon as It's value is 99 or less, I can access the menu properly but then the site container has issues.
Other relevant information is that the theme being used is a customized child of TwentySeventeen.
Here is the link:
https://www.enitan.co.uk/home/

A: CSS
#masthead {
    z-index: 999;
    background-color: red !important; /*You need to use gradient color here */
}

A: I make your menu works if you remove the z-index from both your header (.site-header) and your site container (.site-content-contain) :

But it is not really readable (white/white), maybe you could add a border or a box-shadow


text:
Q: Load Parse data into a fragment list view I am building an app using android studio and it is a navigation drawer application with fragments. I was successfully able to connect my app to Parse.com and it receives notifications wonderfully. However, I am not able to successfully implement the following feature :
I have a Parse.com object which contains a "name" column. I am able to load the data within that column from Parse.com BUT I can't place that data into a list view.
Here is my Alerts.java page that fetches that data from Parse.com:
package com.rayyan_nasr.apple.besgb.activity;

import com.parse.ParseClassName;
import com.parse.ParseObject;
import com.parse.ParseQuery;

/**
 * Created by Apple on 10/25/15.
*/
@ParseClassName("Recipe")
public class Alerts extends ParseObject {

public Alerts(){

}

public String getTitle() {
    return getString("name");
}

public void setTitle(String title) {
    put("name", title);
}

}

Here is my application class which registers my Alerts.java class (MyApplication.java) :
package com.rayyan_nasr.apple.besgb.activity;

import android.app.Application;
import android.content.res.Configuration;

import com.parse.Parse;
import com.parse.ParseClassName;
import com.parse.ParseInstallation;
import com.parse.ParseObject;

/**
* Created by Apple on 10/13/15.
*/
public class MyApplication extends Application {

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}
@Override
public void onCreate() {
    super.onCreate();
    ParseObject.registerSubclass(Alerts.class);
    Parse.initialize(this, "xxxxxx", "ccccc");
    ParseInstallation.getCurrentInstallation().saveInBackground();

}
@Override
public void onLowMemory() {
    super.onLowMemory();
}
@Override
public void onTerminate() {
    super.onTerminate();
}
}

Here is the fragment I wish to populate with my Parse.com data, Parse.java (and I have commented out the line that is giving me an error) :
package com.rayyan_nasr.apple.besgb.activity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.rayyan_nasr.apple.besgb.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Apple on 10/27/15.
 */
public class Parse extends Fragment {

public ArrayList<String> foos = new ArrayList<String>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_alerts, container, false);

    Toast.makeText(getActivity(), "Loading...", Toast.LENGTH_LONG).show();

    ParseQuery<Alerts> query = ParseQuery.getQuery(Alerts.class);
    query.findInBackground(new FindCallback<Alerts>() {
        @Override
        public void done(List<Alerts> results, ParseException e) {
            if (e == null) {
                for (int i = 0; i < results.size(); i++) {
                    String c = results.get(i).getString("name");
                    foos.add(c);
                }
            } else {
                Toast.makeText(getActivity(), "Error",
                        Toast.LENGTH_LONG).show();
            }
        }
    });

    ListView lv = (ListView) view.findViewById(R.id.listView);  //I'm getting an error in the below code from (this.. foos);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, foos);
    lv.setAdapter(arrayAdapter);

    return view;

}

}

Finally here is my layout file, fragment_alerts.XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listView"
    android:layout_gravity="center_horizontal" />
</LinearLayout>

I've tried Parse's MealSpotting tutorial and what not but nothing seems to be working for me and I am desperate for a solution and really If someone does have an answer, maybe show some code or at least point to some tutorial that could help. Thanks in advance..
Cheers.

A: You can not pass context as this in Fragment class. You should pass getActivity() in place of this.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, foos);

EDIT :
Your ParseObject subclass name and @ParseClassName annotation name does not match.
@ParseClassName("Recipe")
public class Alerts extends ParseObject {

Also when retrieving data in done() method of findInBackground() callback if use parse subclass object then retrieve records by parse subclass method name. Try like this :
ParseQuery<Alerts> query = ParseQuery.getQuery(Alerts.class);
query.findInBackground(new FindCallback<Alerts>() {
    @Override
    public void done(List<Alerts> results, ParseException e) {
        if (e == null) {
            for (int i = 0; i < results.size(); i++) {
                String c = results.get(i).getTitle();
                foos.add(c);
            }
        } else {
            Toast.makeText(getActivity(), "Error",
                    Toast.LENGTH_LONG).show();
        }
    }
});


text:
Q: Convert list of characters into a list with strings If a user inputs a string "Hello world"
how can i get an output list to look like ["Hello", "world"]
instead of ['H','e','l','l','o',' ','w','o','r','l','d']
Whats an efficient way to do this?
I used a for loop, and omitted the whitespace but my output does not include the last character
def reverse_string(x):
    reversed_list= []
    temp_string = ""
    count= 0
    for i in x:
        if i == " " or i == x[-1]:
            reversed_list.insert(count, temp_string)
            temp_string = ""
            count+=1
            continue
        temp_string += i

my output: ['Hello', 'worl']
sorry if this is a repost

A: Use split().
Example.
x = "Hello world"
x.split( )

Please add any character you want to split at if you want to split on whitespace use like this
x.split(" ")


text:
Q: How can I monitor the Task queues in the .NET TaskSchedulers (across AppDomain) As a developer, I would like to monitor the size (and progress) of work in the Task Queues in the TaskSchedulers so that I can evaluate whether an experienced slowdown under production load is due to the magnitude or perhaps stall of tasks scheduled.
Normally I would simply attach the debugger and inspect task sizes, but:

*

*The application is running under mono and in production, so I cannot attach to it using visual studio

*I would like to deliver output of analysis on this data as surveillance input for health-monitoring of the service

I have been through the docs and found

*

*TaskScheduler.GetScheduledTasks, which delivers this information to the debugger. It is protected (which I could circumvent), but also seem to require some guarantees about frozen threads which I cannot honor. However, I am willing to use inconsistent data.

*how to get a list of running tasks in .net 4.0. Which focuses on the running Tasks, which are not that interesting to me. I am interested in the size of the backlog and whether work is progressing.

I am willing to:

*

*Use code designed for other purposes (such as for the debugger)

*Accept that i get inconsistent data (this is for statistics and analysis)

Things that I do not want to do are:

*

*Add tracking to each task created.

*

*Some of the code is 3rd party and cannot be refactored

*There is lots of code, and injecting this into that is worse than not being able to tell how it is progressing.

*Use a custom TaskScheduler

*

*Some of the code is 3rd party and cannot be refactored

*Some of the code use TaskSchedulers which sets thread-priority and max-concurrency. Factoring in the monitoring aspect would be awful.

A: I am able to retrieve the information using reflection and the GetScheduledTasksForDebugger:
public static class ScheduledTaskAccess
{
    public static Task[] GetScheduledTasksForDebugger(this TaskScheduler ts)
    {
        var mi = ts.GetType().GetMethod("GetScheduledTasksForDebugger", BindingFlags.NonPublic | BindingFlags.Instance);
        if (mi == null)
            return null;
        return (Task[])mi.Invoke(ts, new object[0]);
    }
    public static TaskScheduler[] GetTaskSchedulersForDebugger()
    {
        var mi = typeof(TaskScheduler).GetMethod("GetTaskSchedulersForDebugger", BindingFlags.NonPublic | BindingFlags.Static);
        if (mi == null)
            return null;
        return (TaskScheduler[])mi.Invoke(null, new object[0]);
    }
}

using a custom IEqualityComparer I am able to maintain how long they have been queued. Very useful meta-information :)
Now I just wish there was some statistics on the the tasks that one could access, CPU-time spent, idle-time, task-switchcount, ...

A: Unfortunately the TaskScheduler.GetScheduledTasks is designed for debuggers only and there is no direct way to get scheduled tasks.
But MSDN says (source):

Developers who are implementing custom debuggers shouldn't call this method directly, but should use the internal wrapper method GetScheduledTasksForDebugger instead: internal Task[] GetScheduledTasksForDebugger(). This wrapper method returns an array of tasks instead of an enumerable. To retrieve a list of active schedulers, use the internal method internal static TaskScheduler[] GetTaskSchedulersForDebugger(). This static method returns an array of all active TaskScheduler instances. You can then use GetScheduledTasksForDebugger on each scheduler instance to retrieve its list of scheduled tasks.

So why not use reflection? This is a safe and easy way to achieve what you want because GetScheduledTasksForDebugger will exist in future and it's designed for debugging and probably for profiling.


text:
Q: SendInBlue - sib-api-v3-sdk sendTransacEmail() returns 403 Forbidden I'm trying to send a transactional email with my new SendInBlue account and I keep receiving an error that simply says "Forbidden". I followed the example on SendInBlue's Nodejs docs to write this code:
const SibApiV3Sdk = require('sib-api-v3-sdk');

const defaultClient = SibApiV3Sdk.ApiClient.instance;

// Configure API key authorization: api-key
const apiKey = defaultClient.authentications['api-key'];
apiKey.apiKey = 'xxx';
// Uncomment the following line to set a prefix for the API key, e.g. 'Token' (defaults to null)
//apiKey.apiKeyPrefix = 'Token'

// Configure API key authorization: partner-key
//const partnerKey = defaultClient.authentications['partner-key'];
//partnerKey.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. 'Token' (defaults to null)
//partnerKey.apiKeyPrefix['partner-key'] = 'Token'

const apiInstance = new SibApiV3Sdk.TransactionalEmailsApi();

const sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail(); // SendSmtpEmail | Values to send a transactional email

const sendEmail = async (to, subject, htmlBody, textBody) => {

    sendSmtpEmail.to = [{ email: to }];
    sendSmtpEmail.sender = { email: 'voluntime.aryanm@gmail.com', name: 'Voluntime' };
    sendSmtpEmail.htmlContent = `Voluntime

${htmlBody}

You can update your email preferences for Voluntime in the Account page.
${Date.now()}`;
    sendSmtpEmail.textContent = `Voluntime:\n\n${textBody}\n\nYou can update your email preferences for Voluntime in the Account page.\n\nTimestamp: ${Date.now()}`;
    sendSmtpEmail.subject = `Voluntime - ${subject}`;
    sendSmtpEmail.replyTo = { email: 'voluntime.aryanm@gmail.com' };

    const result = await apiInstance.sendTransacEmail(sendSmtpEmail);
    console.log(result);
    return result;
};

export { sendEmail };

The apiInstance.sendTransacEmail(sendSmtpEmail) line throws a 403 error that simply says "Forbidden". How do I fix this?

A: Your transactional account is not activated. Create a ticket on SendinBlue support. They will activate it and your issue will be resolved.


text:
Q: R code: Merge two data based on the information from one column of one data and one variable name of the other data I have a huge data set, but to ask my question I create simplified data..
I would like to merge two different database based on the information from one column of one data and a variable name of the other data.
  d1 <- data.frame(subject = c(1,1,1,1,1,1,2,2,2,2,2,2),stime=c('4/16/2012','4/17/2012','4/18/2012','4/19/2012','4/20/2012','4/21/2012','4/16/2012','4/17/2012','4/18/2012','4/19/2012','4/20/2012','4/21/2012'))
  d2 <- data.frame(x1 = c(11.5,12.3,22,34,25,35),x2=c(4,16,23,25,33,45),stime=c('4/16/2012','4/17/2012','4/18/2012','4/19/2012','4/20/2012','4/21/2012'))

> d1
   subject     stime
1        1 4/16/2012
2        1 4/17/2012
3        1 4/18/2012
4        1 4/19/2012
5        1 4/20/2012
6        1 4/21/2012
7        2 4/16/2012
8        2 4/17/2012
9        2 4/18/2012
10       2 4/19/2012
11       2 4/20/2012
12       2 4/21/2012

> d2
    x1 x2     stime
1 11.5  4 4/16/2012
2 12.3 16 4/17/2012
3 22.0 23 4/18/2012
4 34.0 25 4/19/2012
5 25.0 33 4/20/2012
6 35.0 45 4/21/2012

Basically, I would like to create data like this..
It means that I would like to merge these datas based on variable names of d2 such as x1, x2 and the information from "subject" of d1.
Is it possible? Please help me.. thank you so much!
   subject     stime Variable
1        1 4/16/2012  11.5
2        1 4/17/2012  12.3
3        1 4/18/2012  22.0
4        1 4/19/2012  34.0
5        1 4/20/2012  25.0
6        1 4/21/2012  35.0
7        2 4/16/2012  4
8        2 4/17/2012  16
9        2 4/18/2012  23
10       2 4/19/2012  25
11       2 4/20/2012  33
12       2 4/21/2012  45

A: All the answers here so far, in one way or other, transforms d2 into long form first and then performs a merge. This results in allocating memory for the (intermediate) molten data, and once again for the final merge/join. Since you mention huge data (but not mention the dimensions), I'm assuming that optimising for both speed and memory would be most desirable.
Here is how:
require(data.table) ## 1.9.4+
setkey(setDT(d2), stime)
setDT(d1)
get_cols = function(d1_subject, d1_time) {
    d2[J(d1_time), list(stime, var = if (d1_subject==1) x1 else x2)]
}
d1[, get_cols(subject, stime), by=subject]
#     subject     stime  var
#  1:       1 4/16/2012 11.5
#  2:       1 4/17/2012 12.3
#  3:       1 4/18/2012 22.0
#  4:       1 4/19/2012 34.0
#  5:       1 4/20/2012 25.0
#  6:       1 4/21/2012 35.0
#  7:       2 4/16/2012  4.0
#  8:       2 4/17/2012 16.0
#  9:       2 4/18/2012 23.0
# 10:       2 4/19/2012 25.0
# 11:       2 4/20/2012 33.0
# 12:       2 4/21/2012 45.0

We first convert the data.frames to data.tables using setDT() function. Then we set d2's key column as stime, which sorts d2 by that column in increasing order, and marks that column as key column, on which we will join in the next step.
In the next step, we first group d1 by subject, and for each group, we call the function get_cols which takes subject and stime values from d1 corresponding to that group. For each group, we perform a join on d2's key column stime using the value d1_time which corresponds to d1$stime corresponding to that subject and we extract column x1 or x2 depending on subject == 1 or 2.
Here, the intermediate result from melt is never materialised, and is therefore memory efficient and the joins are fast using binary search.

A: Using tidyr and dplyr:
From @docendodiscimus suggestion for a more idiomatic solution
library(tidyr)
library(dplyr)

gather(d2, subject, value, x1:x2) %>%
  mutate(subject = as.numeric(gsub("^x", "", subject))) %>%
  inner_join(., d1)

#Joining by: c("stime", "subject")
#       stime subject value
#1  4/16/2012       1  11.5
#2  4/17/2012       1  12.3
#3  4/18/2012       1  22.0
#4  4/19/2012       1  34.0
#5  4/20/2012       1  25.0
#6  4/21/2012       1  35.0
#7  4/16/2012       2   4.0
#8  4/17/2012       2  16.0
#9  4/18/2012       2  23.0
#10 4/19/2012       2  25.0
#11 4/20/2012       2  33.0
#12 4/21/2012       2  45.0

A: What you're doing is kind of a combination of merge and melt. Really just melting d2 seems to returns what you want
library(reshape2)
melt(d2)

of course you get the column "variable" with the subset name combined with "x". But you can transform the other ID's to include an "x" and then merge
mm <- merge(transform(d1, variable=paste0("x",subject)), melt(d2))
mm

#        stime variable subject value
# 1  4/16/2012       x1       1  11.5
# 2  4/16/2012       x2       2   4.0
# 3  4/17/2012       x1       1  12.3
# 4  4/17/2012       x2       2  16.0
# 5  4/18/2012       x1       1  22.0
# 6  4/18/2012       x2       2  23.0
# 7  4/19/2012       x1       1  34.0
# 8  4/19/2012       x2       2  25.0
# 9  4/20/2012       x1       1  25.0
# 10 4/20/2012       x2       2  33.0
# 11 4/21/2012       x1       1  35.0
# 12 4/21/2012       x2       2  45.0

If you want to resort and drop the extra column you can do
subset(mm[order(mm$subject),], select=-variable)

A: The desired result can be achieved by using a combination of melt and merge.
library(reshape)
colnames(d2)<-c("1","2","stime") #change the column names from "x1","x2" to "1","2"

We use melt on d2. The id variable stimeis left unchanged, while a new column subject is formed by using the other columns.
x2 <- melt(d2,id=c("stime"),variable_name="subject")
#>x2
#       stime subject value
#1  4/16/2012       1  11.5
#2  4/17/2012       1  12.3
#3  4/18/2012       1  22.0
#4  4/19/2012       1  34.0
#5  4/20/2012       1  25.0
#6  4/21/2012       1  35.0
#7  4/16/2012       2   4.0
#8  4/17/2012       2  16.0
#9  4/18/2012       2  23.0
#10 4/19/2012       2  25.0
#11 4/20/2012       2  33.0
#12 4/21/2012       2  45.0

We can now merge d1 and x2 by common variables subject and stime to get the desired result.
dd2 <- merge(d1, x2, by=c("subject","stime"))
#> dd2
#   subject     stime value
#1        1 4/16/2012  11.5
#2        1 4/17/2012  12.3
#3        1 4/18/2012  22.0
#4        1 4/19/2012  34.0
#5        1 4/20/2012  25.0
#6        1 4/21/2012  35.0
#7        2 4/16/2012   4.0
#8        2 4/17/2012  16.0
#9        2 4/18/2012  23.0
#10       2 4/19/2012  25.0
#11       2 4/20/2012  33.0
#12       2 4/21/2012  45.0


text:
Q: How use a different language with Django? Is it possible to customise every error message in Django? I am using a language that does not seem to be supported by Django so the translation method won't work. Also, I prefer to write my own error messages.
If I have to manually change everything, is there somewhere I can see all the error messages and where they're used in Django?
For example, all the error messages associated with a form or a field, such as unique, min_length, etc.


text:
Q: mobx-deep-action with Typescript async/await functions and @action decorator I am struggeling to setup my project correctly to get rid of the mobx error when running in useStrict(true)
Error
mobx.module.js:2238 Uncaught (in promise) Error: [mobx] Invariant failed: Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: WikiStore@1.tags
    at invariant (mobx.module.js:2238)
    at fail (mobx.module.js:2233)
    at checkIfStateModificationsAreAllowed (mobx.module.js:2794)
    at ObservableValue.prepareNewValue (mobx.module.js:750)
    at setPropertyValue (mobx.module.js:1605)
    at WikiStore.set [as tags] (mobx.module.js:1575)
    at WikiStore.<anonymous> (WikiStore.tsx:25)
    at step (tslib.es6.js:91)
    at Object.next (tslib.es6.js:72)
    at fulfilled (tslib.es6.js:62)

My setup compiles but the error is still there, so there must be a mistake in my build chain.
I have used the information provided from the GitHub repo here, but its all a bit vague.
.babelrc
{
"passPerPreset": true,
"presets": [
    {
        "plugins": ["transform-regenerator"]
    },
    {
        "plugins": ["mobx-deep-action"]
    },
    {
      "plugins": ["babel-plugin-transform-decorators-legacy"]
    },
    "es2015", "react", "stage-0"
]
}

webpack.config.js
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require("webpack");
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

const clientBundleOutputDir = "./wwwroot/dist";

module.exports = (env) => {

    const clientConfig = {
        stats: { modules: false },
        entry: { "main-client": "./Client/index.tsx" },
        resolve: { extensions: [".js", ".jsx", ".ts", ".tsx" ] },
        output: {
            filename: "[name].js",
            path: path.join(__dirname, clientBundleOutputDir),
            publicPath: "/dist/"
        },
        module: {
            rules: [
                { test: /\.s?css$/, use: ["css-hot-loader"].concat(ExtractTextPlugin.extract({fallback: "style-loader", use: ["css-loader", "sass-loader"]})) },
                { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
                { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
                { test: /\.(png|svg|jpg|gif|ico)$/, use: ["file-loader"] },
                // { test: /\.tsx?$/, include: /Client/, use: "awesome-typescript-loader?silent=true&useBabel=true&useCache=true" }
                { test: /\.tsx?$/, include: /Client/, use: ["babel-loader", "ts-loader"] }
            ]
        },
        plugins: [
            new CheckerPlugin(),
            new ExtractTextPlugin("site.css"),
            new webpack.SourceMapDevToolPlugin({
                filename: "[file].map",
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]')
            })
        ]
    };

    return [clientConfig];
};

I have tried the awesome typescript loader and also the ts-loader, babel-loader combo.
And here my store (short version)
import { autorun, observable, action } from "mobx";
import { Wiki } from "../models/Wiki";
import { Tag } from "../models/Tag";
import * as Api from "../api/api";

export class WikiStore {
    @observable public tags: Tag[] = [];

    constructor() {
        this.getTags();
    }

    @action
    public async getTags() {
        this.tags = await Api.getTags();
    }
}

export const wikiStore = new WikiStore();

As soon as i call wikiStore.getTags() from a React component i get the error. Everything just works fine without useStrict(true) (as expected)
Maybe someone has an idea.

A: I think you still need to split up the await and the assignment:
@action
public async getTags() {
  const tags = await Api.getTags();
  this.tags.replace(tags);
}

A: Please read here:
https://mobx.js.org/best/actions.html#async-await

As a result, @action only applies to the code block until the first await

So const tags = await Api.getTags(); must be wrapped again
@action
public async getTags() {
    const tags = await Api.getTags();
    runInAction(() => {
      this.tags = tags;
    })
}


text:
Q: Using LIKE with multiple WHERE clauses I'm fairly new to PHP and database management, but I'm picking it up pretty quickly.
I'm trying to create a search bar, I have the searchbar working it just doesn't quite return the results I would like.
Essentially, I want to look for a film in my database based on its title (name), subtitle and release date.
Here's the code I currently have:
if(isset($_POST['search'])){
    $resultArray = '';
    $searchTerm = $_POST['searchTerm'];
    if($getSearchResults = $conn->query("SELECT type, name, subtitle, release_date, poster_url, slug FROM media WHERE (name OR subtitle OR release_date) LIKE '%$searchTerm%' LIMIT 5")){
        $resultArray = array();
        while($data = $getSearchResults->fetch_assoc()){
            $resultArray[] = $data;
        }
    }else{
        echo 'No Data';
    }
    echo json_encode($resultArray);
}

This (likely obviously) doesn't work. If the field is empty the returned search results are all the films without a subtitle because that field is empty. However, if I type in a film name, like Avengers, or a release date, like 2018, nothing comes up. It literally only works for the blank fields for some reason?
Ultimately I'd just like your help getting this to return results LIKE the search term, I can live with it searching for blank fields, but if you have a solution for that too then - great!
Thanks

A: I believe you need to do the following.
SELECT type, name, subtitle, release_date, poster_url, slug
  FROM media
    WHERE name LIKE '%$searchTerm%'
    OR subtitle LIKE '%$searchTerm%'
    OR release_date LIKE '%$searchTerm%'
LIMIT 5


text:
Q: Google API HTTP exception handling doesn't work (python) I am trying to catch HTTP errors. I used following options:
1) googleapiclient.errors.HttpError
2) google.api_core.exceptions.NotFound
Neither of these options work for me. Any ideas why? Thank you!
from pprint import pprint

from googleapiclient import discovery, errors
from oauth2client.client import GoogleCredentials
#from google.api_core.exceptions import NotFound

credentials = GoogleCredentials.get_application_default()

service = discovery.build('compute', 'v1', credentials=credentials)

# Project ID for this request.
project = 'aweqwfnwrueifubwerfbiu'  # TODO: Update placeholder value.

try:
    request = service.firewalls().list(project=project)
except errors.HttpError:
    pprint('Error!')

while request is not None:
    response = request.execute()

    for firewall in response['items']:
        # TODO: Change code below to process each `firewall` resource:
        pprint(firewall)

    request = service.firewalls().list_next(previous_request=request, previous_response=response)

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    response = request.execute()
  File "/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/lib/python3.6/site-packages/googleapiclient/http.py", line 856, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://compute.googleapis.com/compute/v1/projects/aweqwfnwrueifubwerfbiu/global/firewalls?alt=json returned "The resource 'projects/aweqwfnwrueifubwerfbiu' was not found">

A: Try this for handling the error
from googleapiclient.errors import HttpError

However, the error doesn't appear to be raising where your exception catch is. It's here
while request is not None:
    response = request.execute()

Not here
try:
    request = service.firewalls().list(project=project)
except errors.HttpError:
    pprint('Error!')

So try changing it to this
while request is not None:
    try:
        response = request.execute()
    except errors.HttpError:
        pprint('Error!')


text:
Q: Not able to create or import existing conda project in Pycharm I am trying to create or open existing conda project in PyCharm. In both cases I get this error:
TypeError: LoadLibrary() argument 1 must be str, not None

I have Anaconda3 package installed (conda 4.7.5) on my Windows machine. I was able to use it successfully from Anaconda Prompt (create and use environments, install packages and create project). But every time I try to create a project in PyCharm by selecting "File -> New Project -> Scientific -> New environment using Conda" with Python 3.6 I am getting the error above while the project is being created.
Alternatively, when I open existing conda project (from Anaconda Prompt) in PyCharm and then trying to select conda as interpreter I am getting exact same error.
I have been trying to solve this problem for 3 hours: reading forums, installing older versions, trying miniconda instead. Is that the problem with PyCharm?
Edit: Attached full stack trace.
Traceback (most recent call last):
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1043, in __call__
    return func(*args, **kwargs)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main
    exit_code = do_call(args, p)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 80, in do_call
    module = import_module(relative_mod, __name__.rsplit('.', 1)[0])
  File "C:\Users\Eduard\Anaconda3\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\main_create.py", line 10, in <module>
    from .install import install
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\install.py", line 19, in <module>
    from ..core.index import calculate_channel_urls, get_index
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\core\index.py", line 9, in <module>
    from .package_cache_data import PackageCacheData
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\core\package_cache_data.py", line 15, in <module>
    from conda_package_handling.api import InvalidArchiveError
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda_package_handling\api.py", line 3, in <module>
    from libarchive.exception import ArchiveError as _LibarchiveArchiveError
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\__init__.py", line 1, in <module>
    from .entry import ArchiveEntry
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\entry.py", line 6, in <module>
    from . import ffi
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\ffi.py", line 27, in <module>
    libarchive = ctypes.cdll.LoadLibrary(libarchive_path)
  File "C:\Users\Eduard\Anaconda3\lib\ctypes\__init__.py", line 434, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\Eduard\Anaconda3\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
TypeError: LoadLibrary() argument 1 must be str, not None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Eduard\Anaconda3\Scripts\conda-script.py", line 12, in <module>
    sys.exit(main())
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\main.py", line 150, in main
    return conda_exception_handler(_main, *args, **kwargs)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1335, in conda_exception_handler
    return_value = exception_handler(func, *args, **kwargs)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1046, in __call__
    return self.handle_exception(exc_val, exc_tb)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1090, in handle_exception
    return self.handle_unexpected_exception(exc_val, exc_tb)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1101, in handle_unexpected_exception
    self.print_unexpected_error_report(error_report)
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\exceptions.py", line 1171, in print_unexpected_error_report
    from .cli.main_info import get_env_vars_str, get_main_info_str
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\cli\main_info.py", line 19, in <module>
    from ..core.index import _supplement_index_with_system
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\core\index.py", line 9, in <module>
    from .package_cache_data import PackageCacheData
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda\core\package_cache_data.py", line 15, in <module>
    from conda_package_handling.api import InvalidArchiveError
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda_package_handling\api.py", line 7, in <module>
    from .tarball import CondaTarBZ2 as _CondaTarBZ2
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\conda_package_handling\tarball.py", line 7, in <module>
    import libarchive
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\__init__.py", line 1, in <module>
    from .entry import ArchiveEntry
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\entry.py", line 6, in <module>
    from . import ffi
  File "C:\Users\Eduard\Anaconda3\lib\site-packages\libarchive\ffi.py", line 27, in <module>
    libarchive = ctypes.cdll.LoadLibrary(libarchive_path)
  File "C:\Users\Eduard\Anaconda3\lib\ctypes\__init__.py", line 434, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\Eduard\Anaconda3\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
TypeError: LoadLibrary() argument 1 must be str, not None

A: I was getting the same issue while making a conda environment through command prompt. I added this in my environment variables. It helped in my case. Maybe it can help you as well

Your path to anaconda folder/Anaconda3/library/bin


text:
Q: Why does mysql deadlock here? Once in a while I get a mysql error. The error is
Deadlock found when trying to get lock; try restarting transaction

The query is
var res = cn.Execute("insert ignore into
    Post(desc, item_id, user, flags)
    select @desc, @itemid, @userid, 0",
    new { desc, itemid, userid });

How on earth can this query cause it? When googling I saw something about how querys that take long lock rows and cause this problem but no rows need to be touched for this insert

A: Deadlocks are caused by inter-transaction ordering and lock acquisitions. Generally there is one active transaction per connection (although different databases may work differently). So it is only in the case of multiple connections and thus multiple overlapping transactions that deadlocks can occur. A single connection/transaction cannot deadlock itself because there is no lock it can't acquire: it has it, or it can get it.
An insert deadlock can be caused by a unique constraint - so check for a unique key constraint as a culprit. Other causes could be locks held for select "for update" statements, etc.
Also, ensure all transactions are completed immediately (committed or rolled back) after the operation(s) that require them. If a transaction is not closed in a timely manner it can lead to such deadlock behavior trivially. While "autocommit" usually handles this, it can be changed and should not be relied upon: I recommend proper manual transaction usage.
See Mysql deadlock explanation needed and How to Cope with Deadlocks for more information. In this case, it is likely sufficient to "just try again".


text:
Q: how to change Scene size in Scene Builder? Under the modify tab you can chose from four standard scene size but i couldn't find any way to set specific size to the scene in the scene builder

A: Modify -> Scene Size is a bit misleading: it does set the size of the Scene object but size of the root object. It's a kind of shortcut.
You can do the same by selecting the root object and changing the preferred size in the Inspector. This way, you can choose any size.


text:
Q: Can not get CORS to work with restify, all preflight OPTIONS return with 405 I've read MANY articles at this point and tried just about every configuration I can think of to make CORS work with restify.  I've used restify.CORS() with restify.fullResponse() and every other combination. I've also tried just using the cors lib (npm install cors) to no avail.  My app looks like:
/**
 * Setup middlewares.
 */
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.cors());
server.use(restify.fullResponse());
server.use(morgan('dev'));

I've also tried adding opts handling with:
server.opts('/\.*/', (req, res, next) => {
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');
  res.send(204);
  return next();
});

In every case, I get back:
XMLHttpRequest cannot load http://localhost:3000/1.0.0/clients. Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://run.plnkr.co' is therefore not
allowed access. The response had HTTP status code 405.

Any ideas?  This is with restify 4.0.3.  Thanks!

A: Use the built-in module for CORS:
server.use(restify.CORS({
  origins: ['*'],
  credentials: false, // defaults to false
  headers: ['']  // sets expose-headers
}));

Your solution should work as well if you actually add the Access-Control-Allow-Origin header ;-)

A: Use server.opts method to wirte your own handler for OPTIONS request. Below is the example you can use.
Also tell me if you are using set-credentials flag to true while making request from the browser. This handle in that case would have to respond with access cookies.
In the example below, I am returning the allowed origin for exact match. You can tweak it to be substring match also. But always return the exact value as found in request header origin in the response header 'Access-Control-Allow-Origin'. Its a good practice.
server.opts('/\.*/', (req, res) => {
const origin = req.header('origin');
const allowedOrigins = ['example.com', 'example.org'];
if (allowedOrigins.indexOf(origin) === -1) {
    //origin is not allowed
    return res.send(405);
}
//set access control headers to allow the preflight/options request
res.setHeader('Access-Control-Allow-Origin', header);
res.setHeader('Access-Control-Allow-Headers', 'Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

// Access-Control-Max-Age header catches the preflight request in the browser for the desired
// time. 864000 is ten days in number of seconds. Also during development you may want to keep
// this number too low e.g. 1.
res.setHeader('Access-Control-Max-Age', 864000);
return res.send(200);


text:
Q: Cancel componentWillUnmount if a form is incomplete I have a form setup with redux-form and basically want to create a scenario where if there's content filled in any of the form's inputs and you try to navigate away from the page you get a prompt.
The intent is to cancel the page unmount or page nav if they click Cancel. I tried creating a conditional, that if fulfilled would just return but it still navigates away from the current page.
This is probably natural and that I'm not privy to the react/react-router workflow just yet but for the time being would anyone be able to explain the best approach for this? Is there something in general that would allow me to stop an unmount if something is unmet?
import { reduxForm } from 'redux-form';

class Form extends Component {
  componentWillUnmount() {
    if (!this.props.pristine && !confirm('Are you sure you want to navigate away from this page?')) {
      return;
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={ handleSubmit(this.props.onSubmit) }>
        ...
      </form>
    );
  }
}

...

export default connect(mapStateToProps, null)(reduxForm({
  form: 'Form',
  enableReinitialize: true,
  validate
})(Form));

A: If you're using react-router, then you can tap into routerWillLeave; see the documentation: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md
UPDATE
It's a bit tough to provide an example, this is rough and untested.
import { reduxForm } from 'redux-form';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dirty: false
    };
  }

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave.bind(this));
  }

  routerWillLeave(nextLocation) {
    const { dirty } = this.state;

    if (dirty) {
      return 'You have unsaved information, are you sure you want to leave this page?'
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={ handleSubmit(this.props.onSubmit) }>
        ...
      </form>
    );
  }
}

Basically routerWillLeave will fire anytime the user attempts to navigate. When a user makes a change, update the dirty state value to true. The documentation should cover the rest that you need to know (also make sure you're running version 2.4.0+).


text:
Q: Automatically reclassify grid into 5 classes using Processing I am using the graphical modeler of QGIS to rasterize a vector, and then reclassify it automatically into 5 values, without the intervention of the user.
I have reviewed the reclassify algorithm of SAGA but need user information to tabulate old value and new value.
How could you automatically calculate a grid in 5 values using the graphical modeler of QGIS?