text:
Q: Segmentation fault ('core' created) RPC - client doesn't execute Hope you can help me on this.
I have been trying to find out where my error is almost all day. This is RPC. Client has to ask Server which IP belongs to a host. That's all.
Server works ok, but when I try to execute Client side, I received notification that I had an issue with "Segmentation fault, ('core') generated".
Here's my ips.x file:
struct envia
{
  char dominio[50];
};

struct retorno
{
  char retips[50];
};

program IPS_PROGRAMA
{
  version VERSION_IPS_PROGRAMA
  {
    struct retorno ips (struct envia) =1;
   } =1;
}=0x20000001;

Here's the ips_client.c:
/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "ips.h"

 void
ips_programa_1(char *host,char *dominio)
{
  CLIENT *clnt;
  struct retorno  *result_1;
  struct envia  ips_1_arg;

#ifndef DEBUG

clnt = clnt_create (host, IPS_PROGRAMA, VERSION_IPS_PROGRAMA, "udp");

if (clnt == NULL) {
    clnt_pcreateerror (host);
    exit (1);
}
#endif  /* DEBUG */

  strcpy(ips_1_arg.dominio,dominio);

  result_1 = ips_1(&ips_1_arg, clnt);

  if (result_1 == (struct retorno *) NULL) {
    clnt_perror (clnt, "call failed");
   }
    printf("recibido del servidor %s \n", result_1->retips);
 #ifndef    DEBUG
  clnt_destroy (clnt);
 #endif  /* DEBUG */
 }

 int
 main (int argc, char *argv[])
{
    char *host;

   if (argc < 2) {
    printf ("usage: %s server_host\n", argv[0]);
    exit (1);
 }
host = argv[1];
ips_programa_1 (host,argv[2]);
exit (0);
}

And here's my ips.server.c:
/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "ips.h"
#include<netdb.h>
#include<string.h>
#include<arpa/inet.h>

void funcionip(char * ,char []);

struct retorno *
ips_1_svc(struct envia *argp, struct svc_req *rqstp)
{
  static struct retorno  result;

  memset(result.retips,0,100);
  funcionip(argp->dominio,result.retips);

  return &result;
}

void funcionip(char * dominio, char TodasLasIp[])
{
   struct in_addr **addr_list;
   struct hostent *he = gethostbyname(dominio);

   if (he)
   {
     int i;
     puts(he->h_name);
     printf("Servidor Dice Nombre del Host : %s\n", he->h_name);
     printf("Servidor Dice Direcciones IP  ");
     addr_list = (struct in_addr **)he->h_addr_list;

     for(i = 0; addr_list[i] != NULL; i++)
       {
         printf("%s \n", inet_ntoa(*addr_list[i]));
         strcat(TodasLasIp,(char*) inet_ntoa(*addr_list[i]));
         strcat(TodasLasIp,"\n");
       }
      printf("\n");
    }
else
  {
    printf("Servidor dice error gethostbyname\n");
    strcat(TodasLasIp,"error gethostbyname\n");
  }
}

I have worked in other RPC where struct defined in ".x" file where just integer. So I think error is something about data types?
Any help is really appreciated!
Thanks in advance!!

A: I have found my stupid error!!!
When executing ips_client, I'm being required 3 THREE arguments:
argv[0], argv[1] and argv[2].
But, I'm so silly that just forget the last one.. ¬¬
Sorry!!! hehe


text:
Q: How to train single data present in a data set to a already trained neural network? I already have a neural network that is trained,
clf = neural_network.MLPClassifier(
        activation='relu',
        hidden_layer_sizes=(40,40,40,40),
        learning_rate='adaptive',
        learning_rate_init=0.01,
        solver='sgd',
        alpha=1e-6,
        max_iter=20000,
        warm_start=True,
)

I have trained it,
clf.fit(X,Y)

This classifier has two classes [0,1].
Now when i train it further by using one data from data set at a time.
    clf.fit([features_1],[1])
The error pops up
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    fav_clf.fit(X_, Y)
  File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 973, in fit
hasattr(self, "classes_")))
  File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 331, in _fit
X, y = self._validate_input(X, y, incremental)
  File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 924, in _validate_input
(self.classes_, classes))
ValueError: warm_start can only be used where `y` has the same classes as in the previous call to fit. Previously got [0 1], `y` has [1]

A: Forget about warm_start for a minute, and try to understand the usage of fit().

fit(X, y):
    Fit the model to data matrix X and target(s) y.

So the model cannot learn anything if you provide the data for only a single class. warm_start in MLPClassifier is used to:

reuse the solution of the previous call to fit as initialization

So, the training can be faster, weights from previous training will be used as initial weights, but it will still need to access multiple classes data to be able to differentiate between them.
Now seeing your question, I think you want to use the model as an incremental classifier:-

Actually, the ability to learn incrementally from a mini-batch of
  instances (sometimes called "online learning"). All estimators
  implementing the partial_fit API are candidates.

So if you just want the model to incrementally learn the newer data, you need to do partial_fit(). But note that you will have to turn warm_start = False, to use partial_fit().
# First call to partial_fit
clf.partial_fit(X, Y, classes=[0, 1])

# All next calls
clf.partial_fit(X, Y)    #<==  Here you can pass a single sample.

redpajama_set_name: RedPajamaStackExchange


text:
Q: grid-template-areas vertically distribute a set of articles I'm trying to get a set of articles to distribute vertically

Main article area

In this layout, we display the areas in source order for any screen
less that 500 pixels wide. We go to a two column layout, and then to a
three column layout by redefining the grid,and the placement of items on
the grid.

Main article area

In this layout, we display the areas in source order for any screen
less that 500 pixels wide. We go to a two column layout, and then to a
three column layout by redefining the grid, and the placement of items on
the grid.

But the two article below overlap in browser when CSS looks like so:
grid-template-columns: 1fr 3fr;
grid-template-areas:
  "header  header"
  "nav     nav"
  "sidebar article"
  " .      article"
  "footer      footer";

The actual result is that the two article above are on top of each other. I'm just reading up on grids now and gotten myself the CSS bible, as I'm trying to get away from Bootstrap.
The intended result I want is that article 2 is placed below article 1.

I was able to get the desired effect by giving the articles unique class names, here is the updated HTML; notice the names 'article' and 'article2', and the articles now distribute vertically:
That being said, it seems to me I am missing something obvious. Surely having same classname 'article' for both article divs (if they as in first post have classname 'article' should work. Or can grid-template-areas not tell the difference if so...

.header {
  grid-area: header;
}
.article {
  grid-area: article;
}
.article2 {
  grid-area: article2;
}
.nav {
  grid-area: nav;
}
.aside {
  grid-area: sidebar;
}
.footer {
  grid-area: footer;
}
.wrapper {
  display: grid;
  grid-gap: 20px;
  grid-template-areas:
    "header"
    "nav"
    "article"
    "article2"
    "sidebar"
    "footer";
}

        The header

Nav 1

Nav 2

Nav 3

Main article area

In this layout, we display the areas in source order for any screen less that 500 pixels wide. We go to a two column layout, and then to a three column layout by redefining the grid,
                and the placement of items on the grid.

Main article area

In this layout, we display the areas in source order for any screen less that 500 pixels wide. We go to a two column layout, and then to a three column layout by redefining the grid,
                and the placement of items on the grid.

        Sidebar
        The footer

A: A grid-area has no idea how to layout information with itself. If you apply the same grid area to multiple elements they will sit on top of one another like layers. You would need to wrap the articles in a div and place that in your grid-area,,,then the normal layout algorithm would apply.

The grid-area CSS property is a shorthand property for grid-row-start, grid-column-start, grid-row-end and grid-column-end, specifying a grid item's size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the edges of its grid area.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

.header {
  grid-area: header;
  background: orange;
}

main {
  grid-area: article;
}

.nav {
  grid-area: nav;
  background: pink;
}

ul {
  display: flex;
  list-style: none
}

.aside {
  grid-area: sidebar;
  background: lightblue;
}

.footer {
  grid-area: footer;
}

.wrapper {
  display: grid;
  grid-gap: 20px;
  grid-template-areas: "header header" "nav nav" "sidebar article" ".       article" "footer footer";
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Test</title>
  <link rel="stylesheet" href="../css/style.css">

    The header

Nav 1

Nav 2

Nav 3

Main article area

In this layout, we display the areas in source order for any screen less that 500 pixels wide. We go to a two column layout, and then to a three column layout by redefining the grid, and the placement of items on the grid.

Main article area

In this layout, we display the areas in source order for any screen less that 500 pixels wide. We go to a two column layout, and then to a three column layout by redefining the grid, and the placement of items on the grid.

    Sidebar
    The footer


text:
Q: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar i am trying to set up an alarm manager app but whenever i run my app a run-time exception pops up telling me the Toolbar can't be inflated and i can't seem to figure out why.
i commented out the code for the toolbar in the xml and also the mainactivity  in an attempt to debug the app. but the same error appears for the floating action button which i also have in my layout which indicated to me the problem wasn't the Toolbar but something else.
this is the logcat :
Process: com.example.alarmmanager, PID: 17402
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.alarmmanager/com.example.alarmmanager.MainActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)

     Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.Toolbar" on path: DexPathList[[zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/base.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_resources_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/lib/x86, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.view.LayoutInflater.createView(LayoutInflater.java:606)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.example.alarmmanager.MainActivity.onCreate(MainActivity.java:34)

        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.alarmmanager-kj3KUbYybMt0cIjBxRbFUw==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)

MainActivity.java :
private FloatingActionButton mAddReminderButton;
    private Toolbar mToolbar;
    AlarmCursorAdapter mCursorAdapter;
    AlarmReminderDbHelper alarmReminderDbHelper = new AlarmReminderDbHelper(this);
    ListView reminderListView;
    ProgressDialog prgDialog;

    public static final int VEHICLE_LOADER = 0;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );

        //by the way the (MainActivitty.java:34 )
        //reference in the logcat is this line
        setContentView(R.layout.activity_main);

        mToolbar = findViewById(R.id.myToolbar);
        setSupportActionBar (mToolbar);
        mToolbar.setTitle(R.string.app_name);

        reminderListView = (ListView) findViewById(R.id.list);
        View emptyView = findViewById(R.id.empty_view);
        reminderListView.setEmptyView(emptyView);

        mCursorAdapter = new AlarmCursorAdapter(this, null);
        reminderListView.setAdapter(mCursorAdapter);

        reminderListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, AddReminderActivity.class);

                Uri currentVehicleUri = ContentUris.withAppendedId(AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, id);

                // Set the URI on the data field of the intent
                intent.setData(currentVehicleUri);

                startActivity(intent);
            }
        });

        mAddReminderButton = (FloatingActionButton) findViewById(R.id.fab);

        mAddReminderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), AddReminderActivity.class);
                startActivity(intent);
            }
        });

        getLoaderManager().initLoader(VEHICLE_LOADER, null, (android.app.LoaderManager.LoaderCallbacks<Object>) this);
}

the xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/myToolbar"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minHeight="@dimen/abc_action_bar_default_height_material"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="16dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:background="@color/myColor" />

    <ListView
        android:id="@+id/list"
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <RelativeLayout
        android:id="@+id/empty_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:id="@+id/no_reminder_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:padding="16dp"
            android:gravity="center"
            android:text="@string/no_card_details"/>
    </RelativeLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add"
        app:backgroundTint="@color/colorPrimary"
        app:fabSize="normal"/>

</RelativeLayout>

Build gradle :
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.bignerdranch.android:recyclerview-multiselect:+'
    implementation 'com.wrapp.floatlabelededittext:library:0.0.6'
    implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    implementation 'com.getbase:floatingactionbutton:1.9.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

A: it could be an issue with the support v7:28.0.0
please downgrade your library to 27.1.0 and see if the problem persist
For example :
implementation 'com.android.support:appcompat-v7:27.1.0' // appcompat library
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'

You need to change the compile version and build tools to 27 too.
compileSdkVersion 27
buildToolsVersion "27.1.0"

after sync , rebuild and clean your project


text:
Q: Solved inputted algebraic equation python If a user inputs a string like "y=3x+2", how do I change the "x" in the user's input to a SymPy Symbol named x?
I have tried:
e1 = 'y = 3x+2'
y = parse_expr(e1, evaluate=True)

but an error is raised when I try to parse e1.
I don't want to use a regex or split the values into separate variables because there could be completely different formats of formulas.

A: After parsing the user string (after taking care of the =) you no longer have a string, you have a python expression in which are SymPy objects. The x will now be a generic Symbol, just like the one you assigned to the variable x. Here I just split on the = and feed the left and right hand sides into an Equality expression:
>>> from sympy import *
>>> x = Symbol('x')
>>> user = 'y=3*x+2'
>>> y = parse_expr('Eq(%s,%s)' % tuple(user.split('=')))
>>> y
Eq(y, 3*x + 2)
>>> y.subs(x,3)
Eq(y, 11)

You will not need to replace the x with anything before using solve to solve the equation(s):
>>> solve(y, x)
[y/3 - 2/3]

You can read the solve docstring to see how to solve more than one equation.
You will need to read about how to get parse_expr to recognize implied multiplication -- note that in my example I used a proper python expression on both sides of the =.

A: not sure if you want this is what you are asking for
modify the equation:
3x-y=-2
4x-y=2

    import numpy as np
    a = np.array([[3, -1], [4,-1]])
    b= np.array([-2,2])
    z=np.linalg.solve(a,b)

Answer z =
array([ 4., 14.])


text:
Q: CDN Related : Rewrite Image URLs automatically from .htaccess Recently I bought a CDN and set it up. In my site, the images are stored in a folder named 'images' and the Image urls are obviously linked in this manner. (*Ex : images/some_image.png*)
Since I want to use the CDN right way, I need to rewrite the urls without having to manually change each and every image path.
I tried an .htaccess code which was suggested for a similar problem
RewriteEngine On
RewriteBase /
RewriteRule ^images/(.*)$ http://cdn.mydomain.com/$1 [L,R=301]

But that didn't seem to work properly as all the images were linked improperly.
So I would like to know the changes in this code. Any response would be appreciated.

A: This should work:
RewriteCond %{HTTP_HOST} ^yourdomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com$
RewriteRule ^images\/?(.*)$ "http\:\/\/cdn\.yourdomain\.com\/$1" [R=301,L]

However, please note that this is just a temporary solution!In order to get the max out of your CDN, you need manually point images to your CDN in order to save one HTTP for every image.


text:
Q: Mmap access file content and perform arithmetic operations In this issue here someone asked how to make a bit-shift with a file and the suggested way was to use a mmap.
Now this is my mmap:
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>

extern int errno;

int main(int argc, char *argv[]) {
    int fd;
    void *mymap;
    struct stat attr;

    char filePath[] = "test.txt";
    fd = open(filePath, O_RDWR);
    if (fd == -1) {
        perror("Error opening file");
        exit(1);
    }
    if(fstat(fd, &attr) < 0) {
        fprintf(stderr,"Error fstat\n");
        close(fd);
        exit(1);
    }
    mymap = mmap(0, attr.st_size, PROT_READ|PROT_WRITE, MAPFILE|MAP_SHARED, fd, 0);

    if(mymap == MAP_FAILED) {
        fprintf(stderr, "%s: Fehler bei mmap\n",strerror(errno));
        close(fd);
        exit(1);
    }

    if (munmap(0,attr.st_size) == -1) {
        fprintf(stderr, "%s: Error munmap\n",strerror(errno));
        exit(0);
    }
    if (close(fd) == -1) {
        perror("Error while closing file");
    }
    exit(0);
}

how can I access the data inside the mmap? and how could I perform a bit shift or other arithmetic operations like multiplication or addition or substaction, etc?
Thanks!

A: You could cast mymap to the type you want to work with, and perform operations like if you were working in memory.
For instance, before if (munmap(0,attr.st_size) == -1) {
char *str = (char *)mymap;
int i;
for(i=0 ; i<attr.st_size ; i++) {
    str[i] += 3; // add 3 to each byte in the file
}

or
for(i=0 ; i<attr.st_size - 1 ; i+=2) {
    str[i] *= str[i+1]; // multiply "odd" chars with the next one
    str[i] >>= 2;       // shift 2 (divide by 4)
}

After closing map & fd, the file has changed according to the operations above.


text:
Q: How to tell Vim: Open current document in Browser and Refresh? Right now I open archives in my browser (localhost) with the follow line: :! start "http://localhost" file:///"%:p""<CR>.
It is possible to tell Vim: Open Firefox and hit refresh? (I don't want to refresh the current document I'm editing in Vim because if I open, for instance, the current CSS, the results won't show up in the browser.
PS: I'm using Windows XP (Unfortunately)

A: What about using the https://addons.mozilla.org/en-US/firefox/addon/115 extension for automatic page reloads?


text:
Q: Removing overlapped buffers using Google Earth Engine I have a line split up into line segments, with each segment having a buffer around that. I'm trying to remove where they overlap (basically where the darker circles are within the line buffer itself), so that when I later mask by buffer it doesn't have duplicated results.
Anyone know how to remove those overlaps (and ideally keep the land they covered still within ONE buffered area)?
var lines = ee.FeatureCollection(
linetosplit.cutLines(ee.List.sequence(0, linetosplit.length(), 9000))
.geometries()
.map(function (geometry) { return ee.Feature(ee.Geometry(geometry));
}));

var buffered = lines.map(function (feature) {
return feature.buffer(2000);
 });

Map.addLayer(buffered);

print(buffered)

Link to code: https://code.earthengine.google.com/b6b989b9d0bed22a8882f95bd68d0d4d

A: You can first extract the individual features from the feature collection and find the intersections between them using:
//extract individual features
var f0 = buffered.filter(ee.Filter.eq("system:index", '0'));
var f1 = buffered.filter(ee.Filter.eq("system:index", '1'));
var f2 = buffered.filter(ee.Filter.eq("system:index", '2'));
var f3 = buffered.filter(ee.Filter.eq("system:index", '3'));
var f4 = buffered.filter(ee.Filter.eq("system:index", '4'));
var f5 = buffered.filter(ee.Filter.eq("system:index", '5'));
//compute spatial intersections between features
var int1 = f0.geometry().intersection(f1.geometry());
var int2 = f1.geometry().intersection(f2.geometry());
var int3 = f2.geometry().intersection(f3.geometry());
var int4 = f3.geometry().intersection(f4.geometry());
var int5 = f4.geometry().intersection(f5.geometry());

Then, you combine the intersections into a Multipolygon and compute the spatial difference using:
//combine intersections and plot
var intersections = ee.Geometry.MultiPolygon([int1, int2, int3, int4, int5]);
Map.addLayer(intersections, {color: 'FFFF00'}, 'intersections');
//compute difference and plot
var difference = buffered.geometry().difference(intersections)
Map.addLayer(difference, {color: '#24f8ff'}, 'difference');

FULL SCRIPT HERE


text:
Q: parallel loop over pairs What is the best way in C++11 to perform a pairwise computation in multiple threads? What I mean is, I have a vector of elements, and I want to compute a function for each pair of distinct elements. The caveat is that I cannot use the same element in multiple threads at the same time, e.g. the elements have states that evolve during the computation, and the computation relies on that.

A: An easy way would be to group the pairs by offsets.
If v is a vector, then the elements N apart (mod v.size()) form two collections of pairs.  Each of those collections of pairs contain no overlaps inside themselves.
Examine a 10 element vector 0 1 2 3 4 5 6 7 8 9.  The pairs 1 apart are:
0 1, 1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 0

if you split these by "parity" into two collections we get:
0 1, 2 3, 4 5, 6 7, 8 9
1 2, 3 4, 5 6, 7 8, 9 0

You can work, in parallel, on each of the above collections.  When the collection is finished, sync up, then work on the next collection.
Similar tricks work for 2 apart.
0 2, 1 3, 4 6, 5 7
2 4, 3 5, 6 8, 7 9

with leftovers:
8 0, 9 1

For every offset from 1 to n/2 there is are 2 "collections" and leftovers.
Here is offset of 4:
0 4, 1 5, 2 6, 3 7
4 8, 5 9, 6 0, 7 1

and leftovers
8 2, 9 3

(I naively think the size of leftovers is vector size mod offset)
Calculating these collections (and the leftovers) isn't hard; arranging to queue up threads and get the right tasks efficiently in the right threads is harder.
There are N choose 2, or (n^2+n)/2, pairs.  This split gives you O(1.5n) collections and leftovers, each of size at most n/2, and full parallelism within each collection.

If you have a situation where some elements are far more expensive than others, and thus waiting for each collection to finish idles threads too much, you could add fine-grained synchronization.
Maintain a vector of atomic bools.  Use that to indicate that you are currently processing an element.  Always "lock" (set to true, and check that it was false before you set it to true) the lower index one before the upper one.
If you manage to lock both, process away.  Then clear them both.
If you fail, remember the task for later, and work on other tasks.  When you have too many tasks queued, wait on a condition variable, trying to check and set the atomic bool you want to lock in the spin-lambda.
Periodically kick the condition variable when you clear the locks. How often you do this will depend on profiling.  You can kick without aquiring the mutex mayhap (but you must sometimes acquire the mutex after clearing the bools to deal with a race condition that could starve a thread).
Queue the tasks in the order indicated by the above collection system, as that reduces the likelihood of threads colliding.  But with this system, work can still progress even if there is one task that is falling behind.
It adds complexity and synchronization, which could easily make it slower than the pure collection/cohort one.


text:
Q: RollingAppander always null instead of return values My Web Config in Web APi as below
 <appender name="MyLogger" type="log4net.Appender.RollingFileAppender">
  <file value="RenameFileInCode.txt" />
  <appendToFile value="true" />
  <maximumFileSize value="10MB" />
  <maxSizeRollBackups value="5" />
  <!-- rollingStyle value="Size" /-->
  <rollingStyle value="Date" />
  <threshold value="DEBUG" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level %logger %newline%message%newline%exception%newline" />
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="DEBUG" />
    <levelMax value="ERROR" />
  </filter>
</appender>

and My Method For Handling Ex. is like below
  public static void MaintainLog(string objname, Exception e)
    {
        //string LogName = objname + ".txt";
        string LogName = "SCRMpro_Log.txt";
        var user = UserManager.GetUserById(WebUtility.GetCurrentUserId());
        string filePath = GetClientWiseFilePath(user, "LOG"); //"//ErrorLogFile//";
        filePath = filePath + LogName;
        // Bind to the root hierarchy of log4net
        log4net.Repository.Hierarchy.Hierarchy root =
          log4net.LogManager.GetRepository()
            as log4net.Repository.Hierarchy.Hierarchy;

        if (root != null)
        {
            // Bind to the RollingFileAppender
            log4net.Appender.RollingFileAppender rfa =
              (log4net.Appender.RollingFileAppender)root.Root.GetAppender("RollingLogFileAppender");

            if (rfa != null)
            {
                // Assign the value to the appender
                rfa.File = System.Web.HttpContext.Current.Server.MapPath(filePath);

                // Apply changes to the appender
                rfa.ActivateOptions();
            }
        }

and in this method i'm not able to get RollingFileAppander Value its always null
log4net.Appender.RollingFileAppender rfa =
          (log4net.Appender.RollingFileAppender)root.Root.GetAppender("RollingLogFileAppender");

can anyone had this solution much appreciated.

A: I think you have to give the logger name:
     (log4net.Appender.RollingFileAppender)root.Root.GetAppender("MyLogger");


text:
Q: Basic celery task function call from inside a django function I have a django project on an ubuntu EC2 node, that performs a computationally intensive long running process, that typically takes over 60 seconds. I need to cache the results. I've been reading http://www.caktusgroup.com/blog/2014/06/23/scheduling-tasks-celery/ and http://michal.karzynski.pl/blog/2014/05/18/setting-up-an-asynchronous-task-queue-for-django-using-celery-redis/ along with the docs. I've been able to get a basic task working at the command line, but I am unclear on how to start a task from inside a django function.
Right now the structure of my code in my django view is :
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from __future__ import absolute_import
from celery import shared_task

@csrf_exempt
def index(request):

    token = str(request.POST.get('token', False))
    calculator(token)
    return HttpResponse(token)

@shared_task
def calculator(token):

    # do calculation
    # store result in cache

    return

is it as simple as calling:
calculator(token)

in the index function?

A: Almost as simple as you said:
calculator.apply_async()

OR
calculator.delay()

See the docs on how to call tasks for more details.


text:
Q: Prove that all subsequential limits are contained within a closed interval Let $a, b$ be two real numbers such that $a < b$, and suppose that $(s_n)_{n=1}^\infty$ is a
sequence such that $\forall\,\, n\,\, a \leq s_n \leq b$. Prove that all subsequential limits are
contained in the closed interval $[a, b]$. (Note that, by B-W, there is at least
one subsequential limit of the sequence.)
I know that $a$ must be the infimum of sequence $s_{n}$ and $b$ must be the supremum of $s_n$. Also by the Bolzano-Weierstrass Theorem, there must be at least one subsequence which converges, so there is at least one subsequential limit. I'm trying to prove that this subsequential limit is neither  $<a$ nor $>b$ so it must be within $[a,b]$.
Is this the right way to approach the proof?

A: Hint Is $l$ is a subsequential limit, then there exists some subsequence $s_{k_n}$ so that
$$\lim_n s_{k_n} = l\,.$$
Now use the fact that $a \leq s_{k_n} \leq b$, and the definition or properties of limits for that (sub)sequence.


text:
Q: Checking if the array in foreach loop is empty or not I am trying to check if my array is empty or not but strangely I can't get it working.
foreach ($friend as $key => $id){

    $friendActivity = $db->friendActivity($id);

    if (!empty($friendActivity)) {

        //rest of the code

    }

}

I have used var_dump($friendActivity) before the if statement and the result is as follow:
array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { }

//////---> Something to know <--------/////////
I am not trying to see the count of arrays. Each user in database has some activities. I want to see if those activities match with the (poll of of activities). So if the user has mentioned about their activities, therefore the $friendActivity is not going to be empty.
If I use empty:
if (empty($friendActivity)){

    //rest of the code

}

I am able to get inside the if condition...
I personally think, that I have to delete the array at the end of each foreach loop, so that I don't store the other user's friends activities.

A: count() should give you an accurate array number: http://php.net/manual/en/function.count.php
if (count($friendActivity) > 0) {
   ...
}

A: You can try this solution:
if (sizeof($friendActivity) > 0) {


text:
Q: Почему error TextInputLayout увеличивает размер базового view? Доброго времени суток!
Если использовать фрагмент внутри фрагмента, то при отображении ошибок через TextInputLayout, FrameLayout, который является контейнером для дочернего фрагмента, слишком сильно увеличивается в размере.
Почему так происходит и как этого избежать?
Пример программы я оставил здесь:
https://github.com/Lacredin/SampleErrorTextInputLayout.git
Чтобы отобразить error надо щёлкнуть на текстовое поле. В примере хорошо видно, что FrameLayout начинает становиться больше вложенного фрагмента с отображение каждой, новой ошибки.
Урезано и схематично верстка выглядит так:
        <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="false">
        //Этот FrameLayout является контейнером для первого фрагмента, далее схематичное содержание первого фрагмента
        <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            //какие-то блоки
            <android.support.v4.widget.NestedScrollView
                android:id="@+id/nestedScrollViewPassport"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:fillViewport="true">
                //какие-то блоки
                    <FrameLayout
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:background="@android:color/holo_red_dark">
                        //Этот FrameLayout является контейнером для вторго фрагмента, вложенного в первый фрагмент, далее схематичное его содержание
                            <android.support.constraint.ConstraintLayout
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content">

                                <android.support.design.widget.TextInputLayout
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    ndroid.support.design:hintAnimationEnabled="true"
                                    android.support.design:hintEnabled="true"
                                    android.support.design:layout_marginTop="16dp">
                                    <android.support.design.widget.TextInputEditText
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content" />
                                </android.support.design.widget.TextInputLayout>

                                <android.support.design.widget.TextInputLayout
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    ndroid.support.design:hintAnimationEnabled="true"
                                    android.support.design:hintEnabled="true"
                                    android.support.design:layout_marginTop="16dp">
                                    <android.support.design.widget.TextInputEditText
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content" />
                                </android.support.design.widget.TextInputLayout>

                                <android.support.design.widget.TextInputLayout
                                    android:id="@+id/fragment_passport_input_subdivision_info"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android.support.design:hintAnimationEnabled="true"
                                    android.support.design:hintEnabled="true"
                                    android.support.design:layout_marginTop="16dp">

                                    <android.support.design.widget.TextInputEditText
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content" />
                                </android.support.design.widget.TextInputLayout>
                                <android.support.design.widget.TextInputLayout
                                    android:id="@+id/fragment_passport_input_date_info"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android.support.design:hintAnimationEnabled="true"
                                    android.support.design:hintEnabled="true">

                                    <android.support.design.widget.TextInputEditText
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content"/>
                                </android.support.design.widget.TextInputLayout>
                                <Button
                                    android:id="@+id/fragment_passport_input_button_save"

                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content" />
                            </android.support.constraint.ConstraintLayout>

                    </FrameLayout>
                </android.support.constraint.ConstraintLayout>
            </android.support.v4.widget.NestedScrollView>
        </android.support.constraint.ConstraintLayout>
    </FrameLayout>

Помогите пожалуйста понять в чём дело!

A:  Проблема в том, что Вы не до конца понимаете как работает ConstraintLayout, я и сам плохо понимаю :-) но вот нашел у Вас немного лишнего в разметке.

*

*В Вашем случае Вам не нужен вертикальный bias, еще и установленый в 0.bias указывает с каким соотношением, касательно указаных сторон будет располагаться виджет.

*Второе, это то, что Вы указали constraintBottom_toBottomOf="parent", что значит что Ваш FrameLayout будет стремиться притянуть свою нижнюю часть к нижней части ConstraintLayout'а, а раз у Вас высота все равно установлена в wrap_content, то это лишнее и может создавать казусы.

*Вообще лучше убирать все лишнее из кода разметки, и стараться делать ее максимально простой с минимальным количеством вложенностей.

Советую посмотреть сюда :
https://developer.android.com/reference/android/support/constraint/ConstraintLayout
А также обратить внимание на эту статью, второй пункт(хоть и староватая, но суть уловить можно): https://habr.com/post/279979/
Решение вашей проблемы смотрите ниже (все в фрагменте fragment_blank).

Ваш код --->
<FrameLayout
            android:id="@+id/fragment_passport_input_box_fragment"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_red_dark"
            app:layout_constrainedHeight="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fragment_passport_input_type_document_box"
            app:layout_constraintVertical_bias="0.0" />

ТУТ рабочий код --->
 <FrameLayout
                android:id="@+id/fragment_passport_input_box_fragment"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:background="@android:color/holo_red_dark"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/fragment_passport_input_type_document_box" />

А вообще тут проблема в app:layout_constrainedHeight="true", мне пока не понятно как оно работает, но что то вроде как ограничивает wrap_content. но в  большинстве случаев лучше не использовать, тем более если не знаеш для чего.


text:
Q: SSL certs for hosted VMs on a single domain We have 5 virtual machines on the Google Cloud platform to serve our multi-vendor web store. One domain name and 5 VMs: one for Magento, one for Akeneo, one for MySQL, one for MongoDB and the fifth for WordPress.
How many SSL certificates will we need to install to ensure full security? Is it one per VM, or one for the domain?

A: At least one per IP if you want to secure all channels.
Some SSL providers offer certificates for IPs.
https://stackoverflow.com/questions/2043617/is-it-possible-to-have-ssl-certificate-for-ip-address-not-domain-name
But make sure to enforce SSL.


text:
Q: Save GCM Registration And Login User I have an Android app where users receive push notifications about some reminders and events  they set on the website.
App. enables users to see their reminders (set on the website) but first of course asks them to log in.
App exchanges data through HTTP web service with server.
Since I have push notifications functionality I need to register app and get registration_id  and save it along with user_id in my server.
My question is - When should I get the registration id? I want LoginActivity to be the First screen for users.
I have tried to get registration_id when user log in is successful and send it back to my server together with user_id hoping that finish()-ing the LoginActivity can not  cancel AsyncTask (which sends registration_id to server).
How do you think is better? - Consider there might be cases when user might be logged in but getting new registration_id was still necessary.

A: I think the registration to GCM should be unrelated to when the login takes place, since if a user logs off and another user logs in, the registration ID doesn't change, so you don't have to perform a new GCM registration.
You should call GoogleCloudMessaging.register when your app is first launched (or when it's first launched after a new version is installed), and persist the registration ID you get in SharedPreferences.
Then, when a user logs in successfully, you can send to your server both the user ID and the registration ID, and associate the two in your DB.
When the user logs out, send a request to your server that would remove the association of the user and the registration ID.
If you get a new registration ID when user is already logged in (for example after a new version is installed), you can send the registration ID with the ID of the logged in user when you get the new registration ID from GCM.


text:
Q: Statement could not be prepared I've got a SQL Server 2008 server set up with a linked server to a 2005 server. On the 08 server i've got a view set up that's pulling data from the '05 server.
This scenario works from my dev '08 server to the '05 server, but not from my report server to the 05 server.  the '05 server has SP4 set up and the 08 servers have SP2 installed.  Also, the specific database being queried on the '05 server is on version '08.
here's the view's definition:
    select top (100) percent
    qeb.QuoteId,
    qb.TotalAmount,
    qeb.Abc_ExpectedDateofDecision,
    .95 as prcnt,
    dbo.vwPROJ_TOTALS.Actual_Revenue * .95 as projectedvalue,
    qb.Name,
    dbo.vwPROJ_TOTALS.Nitems,
    dbo.vwPROJ_TOTALS.passthrough,
    dbo.vwPROJ_TOTALS.item_totals,
    dbo.vwPROJ_TOTALS.SL_DESC_L,
    dbo.vwPROJ_TOTALS.BU_DESC_L,
    dbo.vwPROJ_TOTALS.Actual_Revenue,
    qb.QuoteNumber,
    dbo.vwQuoteStatus.Value as QuoteStatus,
    qeb.ABC_QuoteStatus,
    dbo.vwQuoteType.Value as QuoteType,
    qeb.Abc_QuoteType,
    cb.FullName as ContactName,
    qeb.ABC_QuoteDeliveryDate as DeliveryDate,
    dbo.vwPROJ_TOTALS.ServLineCode,
    ab.Name as clientname,
    dbo.vwACCOUNT_MANAGERS.Value as AccountManager,
    case aeb.ABC_CompanyDesignation
      when 1 then 'pharmaceutical'
      when 2 then 'Chemical'
    end as Industry,
    qeb.ABC_QuoteDueDate,
    qb.CreatedOn as StartQuote,
    qeb.Abc_IsthisanFTEAgreement,
    qeb.Abc_EarliestClientReadyDateNEW,
    qeb.Abc_InternalProjectStartDate
from
    appdb.ABC_LABS_MSCRM.dbo.ContactBase cb
    inner join appdb.ABC_LABS_MSCRM.dbo.ContactQuotes cq
    inner join appdb.ABC_LABS_MSCRM.dbo.QuoteBase qb
        on cq.QuoteId = qb.QuoteId
        on cb.ContactId = cq.ContactId
    inner join appdb.ABC_LABS_MSCRM.dbo.AccountBase ab
        on qb.AccountId = ab.AccountId
    inner join appdb.ABC_LABS_MSCRM.dbo.AccountExtensionBase aeb
        on ab.AccountId = aeb.AccountId
    left outer join dbo.vwPROJ_TOTALS
        on qb.QuoteId = dbo.vwPROJ_TOTALS.crmQuoteID
    left outer join dbo.vwQuoteStatus
    inner join appdb.ABC_LABS_MSCRM.dbo.QuoteExtensionBase qeb
        on dbo.vwQuoteStatus.AttributeValue = qeb.ABC_QuoteStatus
    inner join dbo.vwQuoteType
        on qeb.Abc_QuoteType = dbo.vwQuoteType.AttributeValue
        on qb.QuoteId = qeb.QuoteId
    left outer join dbo.vwACCOUNT_MANAGERS
        on qeb.Abc_ABCAccountManagerId = dbo.vwACCOUNT_MANAGERS.Abc_AccountManagerId
where
    (qeb.Abc_QuoteType = 3)
    and (ABC_QuoteStatus in (1,2)
    or ABC_QuoteStatus is null
    )

the error i get on the report server:

Msg 8180, Level 16, State 1, Line 1 Statement(s) could not be
  prepared. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1031.Abc_ABCAccountManagerId" could not be bound. Msg
  4104, Level 16, State 1, Line 1 The multi-part identifier
  "Tbl1031.Abc_EarliestClientReadyDateNEW" could not be bound. Msg 4104,
  Level 16, State 1, Line 1 The multi-part identifier
  "Tbl1031.Abc_InternalProjectStartDate" could not be bound. Msg 4104,
  Level 16, State 1, Line 1 The multi-part identifier
  "Tbl1031.Abc_IsthisanFTEAgreement" could not be bound. Msg 4104, Level
  16, State 1, Line 1 The multi-part identifier
  "Tbl1031.Abc_ABCAccountManagerId" could not be bound. Msg 4104, Level
  16, State 1, Line 1 The multi-part identifier "Tbl1031.Abc_QuoteType"
  could not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1031.ABC_QuoteStatus" could not be bound. Msg 4104,
  Level 16, State 1, Line 1 The multi-part identifier
  "Tbl1031.ABC_QuoteDueDate" could not be bound. Msg 4104, Level 16,
  State 1, Line 1 The multi-part identifier
  "Tbl1031.ABC_QuoteDeliveryDate" could not be bound. Msg 4104, Level
  16, State 1, Line 1 The multi-part identifier
  "Tbl1031.Abc_ExpectedDateofDecision" could not be bound. Msg 4104,
  Level 16, State 1, Line 1 The multi-part identifier "Tbl1031.QuoteId"
  could not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1028.Value" could not be bound. Msg 4104, Level 16,
  State 1, Line 1 The multi-part identifier
  "Tbl1009.ABC_CompanyDesignation" could not be bound. Msg 4104, Level
  16, State 1, Line 1 The multi-part identifier "Tbl1007.Name" could not
  be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1005.CreatedOn" could not be bound. Msg 4104, Level 16,
  State 1, Line 1 The multi-part identifier "Tbl1005.TotalAmount" could
  not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1005.Name" could not be bound. Msg 4104, Level 16,
  State 1, Line 1 The multi-part identifier "Tbl1005.QuoteNumber" could
  not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part
  identifier "Tbl1005.QuoteId" could not be bound.

i'm not sure what could be different between the two servers.  i did a code compare again with redgate's sql compare and everything's the same.
edit:
The curious thing though is that if i remove the where clause from the view it works fine.

A: There are a couple JOIN combinations that seem abnormal to me.
For example:
left outer join dbo.vwQuoteStatus
     inner join appdb.ABC_LABS_MSCRM.dbo.QuoteExtensionBase qeb
             on dbo.vwQuoteStatus.AttributeValue = qeb.ABC_QuoteStatus

vs.
left outer join dbo.vwQuoteStatus
                appdb.ABC_LABS_MSCRM.dbo.QuoteExtensionBase qeb
             on dbo.vwQuoteStatus.AttributeValue = qeb.ABC_QuoteStatus

A: Well, i got it working.  i did some more digging and the view dbo.vwQuoteType was causing the issue for some reason.  i cut it out of the view and replaced the field dbo.vwQuoteType.Value with some text (since this view is filtered on the QuoteType anyway it'll always be the same).  It's now working perfectly fine, but i'm still not sure why the error was being thrown.
QuoteType:
CREATE VIEW [dbo].[vwQuoteType]
AS
SELECT     TOP (100) PERCENT AttributeValue, Value, DisplayOrder, AttributeName, ObjectTypeCode
FROM         appdb.ABC_LABS_MSCRM.dbo.StringMap
WHERE     (ObjectTypeCode = 1084) AND (AttributeName = N'abc_quotetype')
ORDER BY AttributeName

the weird part too is that, on it's own, the quotetype view works fine.


text:
Q: Select option in list with Selenium + Python I'm using Selenium with Python to use this website and want to change page by clicking on the button designed for that. However, and I don't know why, this button is disabled and becomes enabled only if you choose another number of items to be displayed on the page.
I managed to programmatically click on the list to display all the options but didn't manage to select an option.

I tried with the following lines:
driver.find_element_by_xpath("//*[@id='edit-limit']/option[2]").click()
driver.find_element_by_xpath("//select[@id='edit-limit']/option[2]").click()
driver.find_element_by_link_text('50').click()

Does someone know how to solve this issue?

A: I will give a method for selecting option by value from dropdown list or select:
def set_select_element(self, element, val):

    element = ui.Select(element)

    return element.select_by_visible_text(val)

where element -- this is your select element on the page.


text:
Q: How can i control download process in linux I have to download a file to remote file via ssh using java/groovy like this
process = "ssh 113.114.115.116 sudo wget http://webserver.com/file.zip".execute()

how can i control or known when file is complete downloaded or error occurrence and response to process ?

A: You could try this:
@GrabConfig(systemClassLoader=true)
@Grab( 'org.apache.ant:ant-jsch:1.9.2' )
@Grab( 'com.jcraft:jsch:0.1.50' )

def doExec( host, uid, pwd, cmd ) {
    new AntBuilder().with {
        // Turn off logging
        project.buildListeners.firstElement().messageOutputLevel = 0

        // Execute command
        sshexec( host           : host,
                 username       : uid,
                 password       : pwd,
                 command        : cmd,
                 outputproperty : 'result' )

        // Return output
        project.properties.result
    }
}

println doExec( '113.114.115.116',
                'USERNAME',
                'PASSWORD',
                'sudo wget http://webserver.com/file.zip' )


text:
Q: Extracting day, week and month from another database using sql I have a database (not mine) that I need to extract the date from and put it in another database (mine) and have separate columns for the day, week and month. In the original database it appears like 05-APR-10 but I just can't get it appear in separate columns.
This is what I've done so far:
CREATE TABLE Seasontime (
Seasontime number(2) PRIMARY KEY,
Month number(2) NOT NULL,
Week number(2) NOT NULL,
Day number(2) NOT NULL);

CREATE SEQUENCE Seasontime_Seq
START WITH  0
INCREMENT BY 1
MINVALUE 0
NOCACHE
NOCYCLE;

insert into Seasontime
    select Seasontime_seq.nextval,
           Month,
           Week,
           Day
    from   (
            select extract(Month from PDate) as Month,
                   extract(Week from PDate) as Week,
                   extract(Day from PDate) as Day
            From notmydatabase.performance
           );

The last bit doesn't work so if anyone can help me that would be great
Thanks in advance

A: WEEK isn't a valid field for the extract() function. You'd need to use to_char() to get the week number:
select Seasontime_seq.nextval,
       Month,
       Week,
       Day
from   (
        select extract(Month from PDate) as Month,
               to_number(to_char(PDate, 'WW')) as Week,
               extract(Day from PDate) as Day
        From notmydatabase.performance
       );

You may prefer to use to_char() rather than extract() for the other fields too for consistency. You might also need the ISO week number, which you can get with the 'IW' date format element instead of 'WW'.
Or possibly, if you want the week of the month rather than the week of the year, just 'W'; but that would perhaps suggest you want the day of the week too, not the day of the month that extract() gives you.

A: You can't use extract to get the week from the date column. Try using to_char instead:
insert into Seasontime
select Seasontime_seq.nextval,
       Month,
       Week,
       Day
from   (
        select to_char(PDate, 'mm') as Month,
               to_char(PDate, 'WW) as Week,
               to_char(PDate, 'dd') as Day
        From notmydatabase.performance
       );


text:
Q: Unable to Register Service Worker in React App I have created one other component with the name of counter and imported  into the index.js but while registering the service worker; it says "
Attempted import error: './serviceWorker' does not contain a default export (imported as 'registerServiceWorker')."
so i am trying to learn react for my new project through new videos on youtube but while implementing the react i found this error and i am feeling stucked

import  React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import App from './App';

import registerServiceWorker from './serviceWorker';

import 'bootstrap/dist/css/bootstrap.css';

import Counter from './components/counter';

ReactDOM.render(<Counter/>. document.getElementById("root"));

export default registerServiceWorker;

import React, { Component } from 'react';

export default class Counter extends Component{
    state={}

    render(){

//        React.createElement
        return
Hello Worlds

    }

}


text:
Q: PHP: can variables and arguments get mixed up if they share the same name? There are 2 places where $account_name occurs in my code, one where is the name of an argument of a function:
functions.php:
function getAccountID ($account_name) {
    $account_id = mysql_query("SELECT account_id FROM accounts WHERE account_name = '$account_name'");
    $account_id = (mysql_fetch_assoc($account_id));
}

and the other where it is a variable with a value
index.php:
$account_name = $fileop[0];
$account_id = getAccountID($account_name);

I am aware that the two instances of the variable have completely separate uses: the first is just a placeholder for the function to take an argument, and the second carries a value outside the function's scope. I am trying to simplify things as much as possible which is why I would like them to be the same. Does this work and if so is it acceptable practice?

A: Take a look at understanding the PHP variable scope.
In short, yes is this possible, and there are no real issues with convention as long as the name is descriptive of what it contains. It is very common practice to reuse variable names between functions as long as there is no confusion about what they might represent.
The exception to this is if $account_name were to be a global variable, which could be accessible anywhere in the code, including in your getAccountID() function. If this were the case, then reusing the variable name would cause execution issues or errors, or at the very least, make your code difficult to understand.


text:
Q: Reading a csv file of city distance in prolog? I have a file like this as csv

Now i want this file to create facts such as this in prolog as
distance(A,E,3)
distance(A,G,5)
and so on.

As per the other answers I have tried
csv_read_file("test.csv", Rows, [functor(citydist), arity(5)]),   maplist(assert, Rows), print(Rows).
but this is returning just a row wise data. How to read it as an adjacency graph?

A: Assuming the CSV looks something like :
"Distance","E","G","C","B"
"A","3","5","7","3"
"B","4","5","6","0"
"C","4","1","0","6"
"D","5","8","3","6"

:- [library(csv)] .
:- [library(lists)] .

%! distance(CITY_A,CITY_B,DISTANCE)
%
% dynamic facts asserted based upon csv file .

:- dynamic distance/3 .

:- op(1,'xfy','csv_') .

%! csv(FILE0)
%
% read the CSV file `FILE0` and add facts to the database .

csv(FILE0)
:-
(start) csv_ (FILE0)
.

(start) csv_ (FILE0)
:-
csv:csv_read_file(FILE0,[HEADER|ROWss]) ,
row__to__list(HEADER,HEADERs) ,
(loop) csv_ (HEADERs,ROWss)
.

(loop) csv_ (_HEADERs,[])
:-
true
.

(loop) csv_ (HEADERs,[ROW|ROWss])
:-
row__to__list(ROW,ROWs) ,
lists:nth1(1,ROWs,CITY_A) ,
QUERY_A=(lists:nth1(NTH,ROWs,DISTANCE)) ,
QUERY_B=(NTH > 1) ,
QUERY_C=(lists:nth1(NTH,HEADERs,CITY_B)) ,
QUERY=(QUERY_A,QUERY_B,QUERY_C) ,
ASSERT=assertz(distance(CITY_A,CITY_B,DISTANCE)) ,
forall(QUERY,ASSERT) ,
(loop) csv_ (HEADERs,ROWss)
.

row__to__list(ROW,ROWs)
:-
ROW=..[_|ROWs]
.

/*
?- csv('data/distances.csv').
true ;
false.

?- listing(distance).

distance('A', 'E', 3).
distance('A', 'G', 5).
distance('A', 'C', 7).
distance('A', 'B', 3).
distance('B', 'E', 4).
distance('B', 'G', 5).
distance('B', 'C', 6).
distance('B', 'B', 0).
distance('C', 'E', 4).
distance('C', 'G', 1).
distance('C', 'C', 0).
distance('C', 'B', 6).
distance('D', 'E', 5).
distance('D', 'G', 8).
distance('D', 'C', 3).
distance('D', 'B', 6).

?-
*/

A: Reminder: Capital valued entities are logic variables, so your facts should have lower case letters a, b, c, etc.
Supposing you know what are your nodes, once the distances have been entered into Prolog, here's how to find the adjacent nodes for a given Node:
adjacencies(Node, Adjacencies) :-
    findall(Adj, distance(Node, Adj, _), Adjacencies).

So with some distance facts like in your illustration,
?- adjacencies(a, L).
L = [e,g,c,b]

Does this anwser your question ?


text:
Q: Cursor pointer not showing (CSS) I have read the other threads but still could not figure this out. When I hover over a button with cursor:pointer; set it does not work.
Not only that the hover effect does not work too.
I have posted all my code below, including the javascript. Not sure if it would have anything to do with the javascript or not, but I doubt it.

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');

const colors = [
  '#6C5B7B',
  '#C06C84',
  '#F67280',
  '#F8B195',
  '#EC2049',
  'A7226E',
  '45ADA8'
];

//add event listener

colorBtn.addEventListener('click', changeColor);

function changeColor() {
  // bodyBcg.style.backgroundColor = colors[2];

  //get random number, Math.floor gives you a number between 0 and 0.9999... so we round down and times by the length of the array
  let random = Math.floor(Math.random() * colors.length);
  bodyBcg.style.backgroundColor = colors[random];
}
body {
 min-height: 100vh;
 display: flex;
 justify-content: center;
 align-items: center;
}

.colorBtn {
 padding: 0.25rem 0.5rem;
 border: 3px solid #fefefe;
 border-radius: 7px;
 color: #fefefe;
 background: rgba(0, 0, 0, 0.6);
 font-size: 1.5rem;
 text-transform: capitalize;
 cursor: pointer;
 outline: none;
}

.colorBtn:hover {
 background: rgb(0, 0, 0);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="/main.css" />
  </head>
  <body>
    <button type="button" class="colorBtn">Press to change color</button>
    <script src="/script.js"></script>
  </body>
</html>

A: There were two classes named .colorBtn in the css. Should work after removing the unnecessary one.

A: If you wonder why the color sometimes doesn't change, then add a line console.log(random); like the snippet below. Sometimes it seems to not change the color just because it did change but by randomly, it could change to the same color with the previous, so it looks like it doesn't work. But in fact, it works very well.

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');

const colors = [
  '#6C5B7B',
  '#C06C84',
  '#F67280',
  '#F8B195',
  '#EC2049',
  'A7226E',
  '45ADA8'
];

//add event listener

colorBtn.addEventListener('click', changeColor);

function changeColor() {

  // bodyBcg.style.backgroundColor = colors[2];

  //get random number, Math.floor gives you a number between 0 and 0.9999... so we round down and times by the length of the array
  let random = Math.floor(Math.random() * colors.length);
  console.log(random);
  bodyBcg.style.backgroundColor = colors[random];
}
body {
 min-height: 100vh;
 display: flex;
 justify-content: center;
 align-items: center;
}

.colorBtn {
 padding: 0.25rem 0.5rem;
 border: 3px solid #fefefe;
 border-radius: 7px;
 color: #fefefe;
 background: rgba(0, 0, 0, 0.6);
 font-size: 1.5rem;
 text-transform: capitalize;
 cursor: pointer;
 outline: none;
}

.colorBtn:hover {
 background: rgb(0, 0, 0);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="/main.css" />
  </head>
  <body>
    <button type="button" class="colorBtn">Press to change color</button>
    <script src="/script.js"></script>
  </body>
</html>


text:
Q: Datatable group by with linq in vb.net I'm trying to get aggregate values from data table. But can't figure out how. Saw some examples in c#, but couldn't translate those to vb.net.
I have data table
Month, campaign, sales, leads, gross
1           1                5         10       1000
1            2               0          5         0
2            1               2          0         300
2            2               1          3         200

I need to get a result :
Month, sales, leads, gross
1           5        15       1000
2           3         3         500

I don't want to loop and combine values manually. Please help

A: You want to Group by Month? You can use Sum to sum the groups:
Dim query = From row In dt
        Group row By Month = row.Field(Of Int32)("Month") Into MonthGroup = Group
        Select New With {
            Key Month,
            .Sales = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Sales")),
            .Leads = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Leads")),
            .Gross = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Gross"))
       }

For Each x In query
    Console.WriteLine("Month:{0} {1} {2} {3}", x.Month, x.Sales, x.Leads, x.Gross)
Next

This is a mixture of Linq query- and method-syntax.


text:
Q: Cohomology ring of classifying space of spin group $\mathrm{BSpin}(n)$ $\DeclareMathOperator\BSpin{BSpin}\DeclareMathOperator\Pin{Pin}\DeclareMathOperator\BSO{BSO}\DeclareMathOperator\BO{BO}\DeclareMathOperator\BPin{BPin}$In the answer for question: Homology of classifying space of spin group BSpin(n),
it was shown that $H_i(\BSpin(\infty),\mathbb{Z})$ is $0,0,0,\mathbb{Z}$, for $i=1,2,3,4$. Here I like ask a more detailed question:

*

*What is the cohomology ring $H^*(\BSpin(\infty),Z)$?
Also what is cohomology rings $H^i(\BPin^\pm(\infty),Z)$ (where $\Pin^\pm (n)$ is a $\Pin^\pm$ group)?
This paper

*

*D.J. Benson and Jay A. Wood, Integral invariants and cohomology of $\BSpin(n)$, Topology 34 Issue 1 (1995) pp 13–28, doi:10.1016/0040-9383(94)E0019-G,

does not give an explicit result.
I cannot find a digital copy of

*

*E. Thomas, On the cohomology groups of the classifying space for the stable spinor group, Bol. Sot. Mat. Mexicana (2) 7 (1962), 57-69.

For $\BSO(n)$, this paper

*

*Edgar H. Brown, Jr., The Cohomology of $\BSO_n$ and $\BO_n$ with Integer Coefficients, Proceedings of the American Mathematical Society
Vol. 85, No. 2 (1982), pp. 283-288, doi:10.2307/2044298,

provides a full answer.

A: *

*Haibao Duan, The characteristic classes and Weyl invariants of Spinor groups, https://arxiv.org/abs/1810.03799
This recent paper gives a clean answer for your question. In particular, it provides the so-called spin classes, with explicit relations to Pontryagin classes and Stiefel-Whiteny classes


text:
Q: Application does not work on device but work on genymotion emulator I have created a projected related to android database .
It work fine on GENYMOTION  emulator only.
But when i install this on mobile device which is
android version is 5.0 so then it showed the error is" 0 requested, with a size of 0".
It also not work on android emultor.
it just only work on genymotion emulator.
 login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

        usernamee=user.getText().toString();
        userpass=pasword.getText().toString();
        DatabaseOperations DOP=new DatabaseOperations(CTX);
        Cursor CR=DOP.getInformation(DOP);
        CR.moveToFirst();
        boolean loginstatus=false;
        String NAME="";

        if(user.getText().toString().trim().length()==0||
                   pasword.getText().toString().trim().length()==0)
        {
            Toast.makeText(getBaseContext(), "Fields are empty Please enter

       user name and password", Toast.LENGTH_LONG).show();
        }
        else{

        try{
        do{

            if(usernamee.equals(CR.getString(0))&&

           (userpass.equals(CR.getString(1))))
            {

                loginstatus=true;
                NAME=CR.getString(0);
            }

        }
        while(CR.moveToNext());

        if(loginstatus)
        {
            Toast.makeText(getBaseContext(), "Log in Successed",
              Toast.LENGTH_LONG).show();
        }
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(), e.getMessage(),
         Toast.LENGTH_LONG).show();
        }
        else

        {
            Toast.makeText(getBaseContext(), "Log in failed invalid user
         name OR password or no record found", Toast.LENGTH_LONG).show();
        }

        }
        }

When i click the above log in  button it work fine on only on genymotion emulator.
But when i press this log in button in mobile device in which the app is installed.
It does not work showed the error is index 0 requested with size of 0.
and on android emulator also showed this error.
the log cat is
      08-29 13:29:35.978: I/Choreographer(1339): Skipped 93 frames!  The
      application may be doing too much work on its main thread.
      08-29 13:29:36.956: I/Choreographer(1339): Skipped 43 frames!  The
     application may be doing too much work on its main thread.
     08-29 13:29:37.498: I/Choreographer(1339): Skipped 43 frames!  The
     application may be doing too much work on its main thread.
      08-29 13:29:53.498: D/InputEventConsistencyVerifier(1339): KeyEvent:
     ACTION_UP but key was not down.
     08-29 13:29:53.498: D/InputEventConsistencyVerifier(1339):   in
    android.widget.EditText{4178dba0 VFED..CL .F....I. 0,127-320,167
     #7f080009 app:id/register_paswd}
   08-29 13:29:53.498: D/InputEventConsistencyVerifier(1339):   in
   android.widget.EditText{4178dba0 VFED..CL .F....I. 0,127-320,167
  #7f080009 app:id/register_paswd}
    08-29 13:29:53.498: D/InputEventConsistencyVerifier(1339):   0: sent at
  17891468000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB,
  scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=17891468,
    downTime=17891295, deviceId=0, source=0x101 }
     08-29 13:29:53.498: D/InputEventConsistencyVerifier(1339):   0: sent at
    17891468000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB,
    scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=17891468,
  downTime=17891295, deviceId=0, source=0x101 }
   08-29 13:29:59.698: W/dalvikvm(1339): threadid=1: thread exiting with
  uncaught exception (group=0x414c4700)

 08-29 13:29:59.718: E/AndroidRuntime(1339): FATAL EXCEPTION: main

 08-29 13:29:59.718: E/AndroidRuntime(1339):

 android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a

  size of 0

 08-29 13:29:59.718: E/AndroidRuntime(1339):    at

 android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)

 08-29 13:29:59.718: E/AndroidRuntime(1339

  08-29 13:29:59.718:

ndowedCursor.java:50)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at com.example.student_record.Setting$2.onClick(Setting.java:149)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.view.View.performClick(View.java:4240)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.view.View$PerformClick.run(View.java:17721)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.os.Handler.handleCallback(Handler.java:730)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.os.Looper.loop(Looper.java:137)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at android.app.ActivityThread.main(ActivityThread.java:5103)
08-29 13:29:59.718: E/AndroidRuntime(1339):     at java.lang.reflect.Method.invokeNative(Native Method)
   08-29 13:29:59.718: E/AndroidRuntime(1339):  at

   java.lang.reflect.Method.invoke(Method.java:525)

   08-29 13:29:59.718: E/AndroidRuntime(1339):  at

com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
   08-29 13:29:59.718: E/AndroidRuntime(1339):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

 08-29 13:29:59.718: E/AndroidRuntime(1339):    at
 dalvik.system.NativeStart.main(Native Method)

A: Your cursor is not reporting any data and crashing when you call .moveToFirst(). You should check if this is not null before trying to use the cursor.


text:
Q: Json value is not getting passed to MVC controller from AJAX call I have this AJAX call using which I am trying to call a Partial view in my project.
function ImportBundle() {
        var req = { "from": "bundle" };
        $.ajax({
            async: true,
            type: "GET",
            url: "Client/ZWS/{lang}/ImportBundles",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(req),
            dataType: 'html',
            success: function (data) {
                $(".viewdiv").html(data);
            },
            failuere: function () { alert("fail"); }
        });
    }

This is my controller for the project:
[System.Web.Http.HttpGet]
        public ActionResult ImportBundles([FromUri] string from)
        {
            return PartialView("~/Views/_ViewImportBundles.cshtml");
        }

However, when I am debugging the application, I am getting null.
Any idea why? Thanks!

A: function ImportBundle() {
        var req = { "from": "bundle" };
        $.ajax({
            async: true,
            type: "GET",
            url: "Client/ZWS/{lang}/ImportBundles",
            contentType: 'application/json; charset=utf-8',
            data: req,
            dataType: 'html',
            success: function (data) {
                $(".viewdiv").html(data);
            },
            failure: function () { alert("fail"); }
        });
    }

For url, you can use Url.Action helper method.

A: I tried this and it worked. Maybe this can help you in the right direction.
    function ImportBundle() {

        var req = { "from": "bundle" };

            $.ajax({
                async: true,
                type: "POST",
                url: "/Client/ImportBundles",
                data: { theData: JSON.stringify(req) },
                dataType: 'html',
                success: function (data) {
                    alert("Worked");
                },
                failuere: function () { alert("fail"); }
        });

     }

    [HttpPost]
    public ActionResult ImportBundles(string theData)
    {
        return null;
    }

The variable theData contained the json. If you can make this work, you can then modify the code to your need a little bit at a time.


text:
Q: more efficient way to replace items on a list based on a condition I have the following piece of code. Basically, I'm trying to replace a word if it matches one of these regex patterns. If the word matches even once, the word should be completely gone from the new list. The code below works, however, I'm wondering if there's a way to implement this so that I can indefinitely add more patterns to the 'pat' list without having to write additional if statements within the for loop.
To clarify, my regex patterns have negative lookaheads and lookbehinds to make sure it's one word.
pat = [r'(?<![a-z][ ])Pacific(?![ ])', r'(?<![a-z][ ])Global(?![ ])']

if isinstance(x, list):
    new = []
    for i in x:
        if re.search(pat[0], i):
            i = re.sub(pat[0], '', i)
        if re.search(pat[1], i):
            i = re.sub(pat[1], '', i)
        if len(i) > 0:
            new.append(i)
    x = new
else:
    x = x.strip()

A: Just add another for loop:
for patn in pat:
    if re.search(patn, i):
        i  = re.sub(patn, '', i)
if i:
    new.append(i)

A: pat = [r'(?<![a-z][ ])Pacific(?![ ])', r'(?<![a-z][ ])Global(?![ ])']

if isinstance(x, list):
    new = []
    for i in x:
        for p in pat:
            i = re.sub(p, '', i)
        if len(i) > 0:
            new.append(i)
    x = new
else:
    x = x.strip()

A: Add another loop:
pat = [r'(?<![a-z][ ])Pacific(?![ ])', r'(?<![a-z][ ])Global(?![ ])']

if isinstance(x, list):
    new = []
    for i in x:
        # iterate through pat list
        for regx in pat:
            if re.search(regx, i):
                i = re.sub(regx, '', i)
    ...

A: If in your pattern, then changes are only the words, then you can add the words joined with | to make it or. So for your two patterns from the example will become one like below one.
r'(?<![a-z][ ])(?:Pacific|Global)(?![ ])'

If you need to add more words, just add with a pipe. For example (?:word1|word2|word3)
Inside the bracket ?: means do not capture the group.

A: something like this:
[word for word in l if not any(re.search(p, word) for p in pat)]

A: I will attempt a guess here; if I am wrong, please skip to the "this is how I'd write it" and modify the code that I provide, according to what you intend to do (which I may have failed to understand).
I am assuming you are trying to eliminate the words "Global" and "Pacific" in a list of phrases that may contain them.
If that is the case, I think your regular expression does not do what you specify.  You probably intended to have something like the following (which does not work as-is!):
pat = [r'(?<=[a-z][ ])Pacific(?=[ ])', r'(?<=[a-z][ ])Global(?=[ ])']

The difference is in the look-ahead patterns, which are positive ((?=...) and (?<=...)) instead of negative ((?!...) and (?<!...)).
Furthermore, writing your regular expressions like this will not always correctly eliminate white space between your words.
This is how I'd write it:
words = ['Pacific', 'Global']
pat = "|".join(r'\b' + word + r'\b\s*' for word in words)
if isinstance(x, str):
    x = x.strip()        # I don't understand why you don't sub here, anyway!
else:
    x = [s for s in (re.sub(pat, '', s) for s in x) if s != '']

In the regular expression for patterns, notice (a) \b, standing for "the empty string, but only at the beginning or end of a word" (see the manual), (b) the use of | for separating alternative patterns, and (c) \s, standing for "characters considered whitespace".  The latter is what takes care of correctly removing unnecessary space after each eliminated word.
This works correctly in both Python 2 and Python 3.  I think the code is much clearer and, in terms of efficiency, it's best if you leave re to do its work instead of testing each pattern separately.
Given:
x = ["from Global a to Pacific b",
     "Global Pacific",
     "Pacific Global",
     "none",
     "only Global and that's it"]

this produces:
x = ['from a to b', 'none', "only and that's it"]


text:
Q: Groupby two line charts using seaborn or plotly in python with the help of pandas I have a data frame as shown below. which is a sales data of two health care product starting from December 2016 to November 2018.
product     price      sale_date       discount
   A         50         2016-12-01      5
   A         50         2017-01-03      4
   B         200        2016-12-24      10
   A         50         2017-01-18      3
   B         200        2017-01-28      15
   A         50         2017-01-18      6
   B         200        2017-01-28      20
   A         50         2017-04-18      6
   B         200        2017-12-08      25
   A         50         2017-11-18      6
   B         200        2017-08-21      20
   B         200        2017-12-28      30
   A         50         2018-03-18      10
   B         300        2018-06-08      45
   B         300        2018-09-20      50
   A         50         2018-11-18      8
   B         300        2018-11-28      35

From the above data I would like to plot month wise total sale price and total discount in a bar  plot for each products using in python.
So I would like to have two line plots for product A
X axis = year and month
Y axis1 = Total sale price
Y axis = Total discount price

The intention of this plots are to impacts the of discounts on sales.

A: df['sale_date']=pd.to_datetime(df['sale_date']).dt.to_period('M')#Coerce date to datetime Month Year
df.set_index(df['sale_date'], inplace=True)#Set date as index

 df2=df[df['product']=='A']#Boolean select product A
 df2.groupby(df2.index).agg(PriceSum=('price','sum'), DiscountSum=('discount','sum')).plot(legend=True)#Groupby index and plot

A: Try in this way:
df["sale_date"] = pd.to_datetime(df["sale_date"])
df.set_index("sale_date", inplace=True)

new_df = df.groupby(pd.Grouper(freq='M')).apply(lambda x: x.groupby(by="product")[["price","discount"]].sum()).unstack()

#convert datetime to month-year format
new_df.index = pd.Series(new_df.index).dt.strftime('%b-%Y')

new_df.plot(kind="bar", figsize=(10,7))

Barplot:

Add stacked = True to plot in case you want a stacked plot!


text:
Q: jQuery event not working on radio button? I am having an issue where the jQuery event listener i am attaching to a radio button is not working.
I want to be able to grab the value of individua radio buttons on CHANGE. Unfortunately, everything I've tried isn't working. I've looked up some answers here...none worked as well.
BELOW IS MY jQuery code
$('input[type=radio][name=method]').click(function() {

    let selectedMethod = $('input[type=radio][name=method]:checked').val();

    console.log(selectedMethod);
});

I also tried this
$('input[type=radio][name=method]').change(function() {

    let selectedMethod = $('input[type=radio][name=method]:checked').val();

    console.log(selectedMethod);
});

I also tried this from an answer here
$('input#method').on('ifChecked', function() {

    let selectedMethod = $(this).val();

    console.log(selectedMethod);
});

Below is the HTML Radio buttons. The radio buttons are custom-styled to be like CARDS

         <input type="radio" name="method" id="method" value="pp"
                class="card-input-element" required />

Paypal

None is working. I don't know what I am not doing right.

A: The second method you tried works completely fine.
Just make sure the selector selects the correct id.
This is what I did.
HTML:

        <input type="radio" name="method" id="method" value="pp" class="card-input-element" required />

Paypal

Jquery:
//test id make sure the selector is correct..
$('#method').change(function() {

 let selectedMethod = $('input[type=radio][name=method]:checked').val();
 //this console logs "pp"
 console.log(selectedMethod);
});


text:
Q: Coloring scatterplot in R based on fold enrichment I'm very new to R and have tried to search around for an answer to my question, but couldn't find quite what I was looking for (or I just couldn't figure out the right keywords to include!). I think this is a fairly common task in R though, I am just very new.
I have a x vs y scatterplot and I want to color those points for which there is at least a 2-fold enrichment, ie where x/y>=2 . Since my values are expressed as log2 values, the the transformed value needs to be x/y>=4.
I currently have the scatterplot plotted with
plot(log2(counts[,40], log2(counts[,41))

where counts is a .csv imported files and 40 & 41 are my columns of interested.
I've also created a column for fold change using
counts$fold<-counts[,41]/counts[,40]

I don't know how to incorporate these two pieces of information... Ultimately I want a graph that looks something like the example here: http://s17.postimg.org/s3k1w8r7j/error_messsage_1.png
 where those points that are at least two-fold enriched will colored in blue.
Any help would be greatly appreciated. Thanks!

A: Is this what you're looking for:
# Fake data
dat = data.frame(x=runif(100,0,50), y = rnorm(100, 10, 2))

plot(dat$x, dat$y, col=ifelse(dat$x/dat$y > 4, "blue", "red"), pch=16)

The ifelse statement creates a vector of "blue" and "red" (or whatever colors you want) based on the values of dat$x/dat$y and plot uses that to color the points.
This might be helpful if you've never worked with colors in R.

Another option is to use ggplot2 instead of base graphics. Here's an example:
library(ggplot2)
ggplot(dat, aes(x,y, colour=cut(x/y, breaks=c(-1000,4,1000),
                                labels=c("<=4",">4")))) +
  geom_point(size=5) +
  labs(colour="x/y")


text:
Q: Python tkinter bouncing balls - energy goes to infinity I have written a Python script which creates a Ball class and then creates instances of it.  The balls should bounce off the walls, and later (not implemented yet) off of each other.  Note that, instead of just reversing the direction of the ball when it reaches a wall, the wall exerts a force (or acceleration) on the ball.
Unfortunately, after bouncing off of a wall, the balls then enter an oscillatory motion, with the amplitude getting bigger and bigger.
I am very new to Python, but have written various javascript/canvas simulations before.
This particular python script uses Verlet integration to compute the positions and velocities.  I am basing the script on this:
http://physics.weber.edu/schroeder/software/demos/MolecularDynamics.html
Can anybody suggest how I should modify the code so that it is "stable" with the balls bouncing off the walls?  Thank you
from Tkinter import *
import random
window = Tk()
canvas = Canvas(window, width = 400, height = 300)
canvas.pack()
wallStiffness=0.05
dt=0.02

class Ball:

    def __init__(self):
        self.x=0
        self.y=0
        self.xvel=random.random()*2-1
        self.yvel=random.random()*2-1
        self.ax=0
        self.ay=0
        self.rad=20

def computeAccelerations(z):

        if z.x<z.rad:
             z.ax=wallStiffness*(z.rad-z.x)
        else:
            if z.x>400-z.rad:
                z.ax=wallStiffness*(400-z.rad-z.x)
        #only have horizontal bounces so far, and no bounces between balls yet

list=[]

for i in range(100):    #0 to 99, make 100 balls
    myball=Ball()
    list.append(myball)

#script to place in a crystal to begin with

current_x=30
current_y=0

for j in list:

        j.x=current_x
        current_x+=30
        j.y=current_y

        if current_x+30>370:
            current_x=30
            current_y+=30

        j.ball=canvas.create_oval(j.x,j.y,j.x+j.rad,j.y+j.rad,fill="blue")

while True:

    for i in range(10):     #10 steps per frame
        for j in list:
            j.x+=j.xvel*dt+0.5*j.ax*dt*dt
            j.y+=j.yvel*dt+0.5*j.ay*dt*dt
            j.xvel+=0.5*j.ax*dt
            j.yvel+=0.5*j.ay*dt
            computeAccelerations(j)
        for j in list:
            j.xvel+=0.5*j.ax*dt
            j.yvel+=0.5*j.ay*dt

    canvas.after(10)    #duration of frame in ms
    for z in list:
        canvas.move(z.ball,z.xvel, z.yvel)
        canvas.update()

window.mainloop()   #keeps the window open

A: I believe the issue you were having is that you forgot to put a time step into your action loop:
while True:
    for i in range(10):
        for j in list:
            j.x += j.xvel * dt + 0.5 * j.ax * dt * dt
            j.y += j.yvel * dt + 0.5 * j.ay * dt * dt
            j.xvel += 0.5 * j.ax * dt
            j.yvel += 0.5 * j.ay * dt
            compute_accelerations(j)
        for j in list:
            j.xvel += 0.5 * j.ax * dt
            j.yvel += 0.5 * j.ay * dt

Also, though your code works, I think your Ball acceleration method could be cleaned up:
# box_width = 400

def compute_accelerations(self):
        if self.x < self.rad:
             self.ax = wallStiffness * (self.rad - self.x)
        elif self.x > box_width - self.rad:
                self.ax = wallStiffness * (box_width - self.rad - self.x)

where here you'll see that self is used in place of z. This is the standard way to create methods inside a class in Python. Here the self stands for the current instance of your Ball object. Does that make sense?
You would call this newly modified method like this:
j.compute_accelerations()

A: This doesn't directly answer your question, but you're using Tkinter wrong. As a general rule of thumb you should not call update, you should never have an infinite loop, and you should never call after with a single argument. Tkinter already has an infinite loop running -- mainloop -- so why not take advantage of it? By doing so, you can eliminate all three of the bad practices I listed.
You should remove the body of the while True loop and put it into a function. Then, you have that function arrange for itself to be called again at some interval. For example:
def draw_frame():
    for i in range(10):
        for j in list:
            ...
    for z in list:
        canvas.move(z.ball,z.xvel, z.yvel)

    canvas.after(10, draw_frame)

This will draw a single frame, wait 10 ms, then draw another frame, repeating forever. If you want the ability to stop the animation, you can create a button that sets a flag variable (eg: we_should_continue=False), in which case you would do something like:
    if we_should_continue:
        canvas.after(10, draw_frame)

The advantage this has over your scheme, is that your scheme has small 10ms windows where the GUI is completely frozen, which might lead to some very slight stuttering. The bigger advantage is simply that this is how tkinter is designed to work.


text:
Q: Bootstrap mobile header alignment issues I am trying to figure out something I think should be simple but I can't seem to get it to work properly.  I have a design I am trying to follow and can't seem to get it to align correctly.
This is what I want it to look like.

My problem is it will not align anything like what I want.  I have gone through a bunch of different ways and this is my latest attempt and figure I will ask for some frontend help.  home button is just a link.  Search button will open up a div with search field not coded yet in example below.  Hamburger menu will open up other header links.
Here is where I got and you can see how it is not really close.
http://jsbin.com/fucozulecu/edit?html,css,output
css
   .navbar-nav {
      float: none;
      text-align: center;
    }

.navbar-nav li {
  float: none;
  display: inline-block;
  width: 33%;
  color: white;
}

html

                    <button type="button" class="navbar-toggle btn-home visible-sm visible-xs">

                    </button>

                <button type="button" class="navbar-toggle btn-search" data-toggle="collapse"
                        data-target=".navbar-search">

                </button>

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

                </button>

Link

Link

Link

Link

                Dropdown

Action

Another action

Something else here

Separated link

One more separated link

Link

Link

Link

Link

Any help would be appreciated as I am guessing this is fairly easy for more expereinced front end devs.

A: Since you are using bootstrap, I added the bootstrap grid classes and rearranged the home button.

             <button type="button" class="navbar-toggle btn-home visible-sm visible-xs">

            </button>

        <button type="button" class="navbar-toggle nav-btn" data-toggle="collapse"
                data-target=".navbar-search">

        </button>

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

        </button>

Woking example http://jsbin.com/quxawovude/1/edit?html,css,output


text:
Q: Host Inspector Failed I am trying to install CDH5 on EC2 instances (Ubuntu). Every time I hit the page where host inspector starts to execute, it fails on the worker nodes saying IOException thrown while collecting data from host: Connection timed out. Further digging into the logs, I find another error which says: mismatched DNS Names.
I did edit the /etc/hosts file to include the information of all the nodes in the following manner:
IP FQDN HOSTNAME
Not sure what is going on. Would be really grateful if anyone can help me out with the same.


text:
Q: How to edit a JS in order to make it works for two Ids? Firstly, I don't have strong experience working on JS.
I have found the following code in this community and it work perfectly. Basically, it makes when you scroll into view of an element it add a new class (animation).

// Returns true if the specified element has been scrolled into the viewport.
function isElementInViewport(elem) {
  var $elem = $(elem);

  // Get the scroll position of the page.
  var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
  var viewportTop = $(scrollElem).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  // Get the position of the element on the page.
  var elemTop = Math.round($elem.offset().top);
  var elemBottom = elemTop + $elem.height();

  return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {
  var $elem = $('#feedback');

  // If the animation has already been started
  if ($elem.hasClass('fadeInUp')) return;

  if (isElementInViewport($elem)) {
    // Start the animation
    $elem.addClass('fadeInUp');
  }
}

// Capture scroll events
$(window).scroll(function() {
  checkAnimation();
});

Original post: Activate CSS3 animation when the content scrolls into view
However, I would like to use this JS with two different Id (#feedback and #goback) however, when I try to add another line to the original, it only works with #goback

var $elem = $('#feedback');
  var $elem = $('#goback');

I think it was made to work with only one #.
Could someone help me to fix it in order to make it works with more than 1 id, please?
Thanks
PD: If you are thinking to give me a negative point please let me know why.

A: You can execute the method twice and use the '&&' operate to check if the results are both true.
if (isElementInViewport('#feedback') && isElementInViewport('#goback')) {
    // DO SOMETHING
}

In your example this would look something like this:
// Check if it's time to start the animation.
function checkAnimation() {
  var $elem1 = $('#feedback');
  var $elem2 = $('#goback');

  // If the animation has already been started
  if ($elem.hasClass('fadeInUp')) return;

  if (isElementInViewport($elem1) && isElementInViewport($elem2)) {
    // Start the animation
    $elem.addClass('fadeInUp');
  }
}

A: Solved

// Returns true if the specified element has been scrolled into the viewport.
function isElementInViewport(elem) {
  var $elem = $(elem);

  // Get the scroll position of the page.
  var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
  var viewportTop = $(scrollElem).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  // Get the position of the element on the page.
  var elemTop = Math.round($elem.offset().top);
  var elemBottom = elemTop + $elem.height();

  return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {
  var $elem = $('#feedback');
  var $elem2 = $('#goback');

  if ($elem2.hasClass('fadeInUp')) return;

  if (isElementInViewport($elem2)) {
    // Start the animation
    $elem2.addClass('fadeInUp');
  }

  // If the animation has already been started
  if ($elem.hasClass('fadeInUp')) return;

  if (isElementInViewport($elem)) {
    // Start the animation
    $elem.addClass('fadeInUp');
  }
}

// Capture scroll events
$(window).scroll(function() {
  checkAnimation();
});


text:
Q: Warning for importing css in gatsby In my gatsby projects I am getting this warning for importing the styles to my file pages/index.js
import { Link } from "gatsby"
import React from "react"
import Layout from "../components/Layout"
import style from "../styles/home.module.css"

export default function Home() {

  return (
    <Layout>

Design

Develop & deploy

Become web ninja

          <Link to="/projects" className={style.btn}>
            My Portfolio Projects
          </Link>

    </Layout>
  )
}

warn Attempted import error: '../styles/home.module.css' does not contain a default export (imported as 'style').
I am using the module stylesheet. So the home.module.css looks like this
.header {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 40px;
  align-items: center;
}
.header h2 {
  font-size: 4em;
}
.header h3 {
  font-size: 3em;
  font-weight: 400;
  margin-bottom: 20px;
}
.btn {
  display: inline-block;
  background: #d42990;
  padding: 10px 16px;
  border-radius: 10px;
  margin-top: 20px;
  font-weight: 500;
}

This is the gatsby version I am using
  "gatsby": "^3.0.3",
    "gatsby-source-filesystem": "^3.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"

The working tree is looks like
.
├── components
│   ├── Layout.js
│   └── Navbar.js
├── node
│   ├── bar.txt
│   └── foo.txt
├── pages
│   ├── 404.js
│   ├── about.js
│   ├── index.js
│   └── projects
│       └── index.js
└── styles
    ├── global.css
    ├── home.module.css
    └── project.module.css

I don't know whats causing the error when I run
gatsby develop

Its throwing the error as
The page didn't server render (SSR) correctly

Initially gatsby version was v2 and I upgraded to v3 in my project.So I don't know whats the reason for SSR error. If I skip the SSR It throws error like
_styles_home_module_css__WEBPACK_IMPORTED_MODULE_3__.default is undefined

Can somebody help me with this ?

A: You can try this:
import * as style from "../styles/home.module.css"

https://www.gatsbyjs.com/docs/tutorial/part-two/#-build-a-new-page-using-css-modules