text:
Q: iOS APNS: Can two notification provider servers have same device token The apple documentation mentions there is no restriction on multiple provider notifications servers to send push notification to iOS devices.
Is it possible, the same device token can be used in two different provider servers deployed in 2 different network,to send push notifications to same app at any moment.
Will Apple APNS, allow 2 different provider servers, use same device key to send notification from each to same app in one device?

A: Yes you can have multiple Gateways (SNS, Urban Airship, PushIO, etc.) connected to one platform provider (APNS, GCM, Amazon, etc.), the most important thing is the token/registration ID (specific to a device and an Application) and the certificate if you are using APNS.
Many people ask how the feedback sent by the platform provider is handled in this case.
Since feedback is idempotent, it should work without problem for different gateways; tokens saved on each Gateway can be handled in the backend application. If for example APNS sends a feedback to SNS saying that an endpoint is no longer valid (maybe because the user has uninstalled the Application), the token can directly be updated/removed from all the other Gateways. You can also leave it as it is and wait for the feedback sent by APNS to other gateways when they send notifications to the endpoint, and then update your endpoints list accordingly in those gateways.
The most important thing to note here is that feedback is idempotent, if SNS sends a push notification to an endpoint and receive a feedback, another gateway that sends a push notification to the same token will receive the same feedback.

A: This is my experience while working with APNS, this is like a checklist, before you start testing notification in any environment,

*

*Certificates will decide server can connect to APN or not.

*According to the certificate you have for ex. dev certificate or production
certificate, point to respective APNS sandbox.

Production Sandbox:-
       Hostname: gateway.push.apple.com ,
       Port: 2195
Development environment:-
       Hostname: gateway.sandbox.push.apple.com ,
       Port: 2195

*There is no restriction that production certificate can be used in only one server or in only one network. The same production certificate can be used in multiple boxes or multiple networks to send notification to same app on a device.

*Most important is checking Firewall is blocking connectivity from your network to APNS Dev or Production. So do a telnet to both production and dev environment APNS. The connection should not be blocked.

*If firewall is blocking connectivity to APNS, the server code will throw "Connection Refused" or "Connection Closed" exception while sending push notification.

*This is the most weird behavior I saw with APNS and certificate, because of which I lost 2-3 days. I experienced below depending upon the case,

*

*Server is pointing to APNS Dev environment, certificate is
"Production", while sending notification to APNS, SOMETIMES
server will throw "Socket Closed Exception".

*Server is pointing to APNS Dev environment, certificate is "Production", while sending notification to APNS, server logs says
notification sent to APNS, but device will not receive the
notification.

:) If you have done wrong configurations, you should be lucky to get "Socket Closed Exception".
If all the configurations are correct(for ex credentials, firewall), correct certificate and pointing to right APNS environment, the device will defiantly get a push notification. Push notification will work like a charm. It will be instant .
Hope this checklist will help in your implementation and sanity checks.


text:
Q: Summing together multiple columns in a multiindex dataframe and then adding column with the outcome As the title suggests, I have a multi-index df that I want to group. Check if some conditions are met and later calculate a total score in an additional column. Then I would like to rank according to this score. The solution I have would be quite complicated as I have to recreate a compatible df (for example for df.update ()).
My problem arises from the fact that pandas.core.groupby.GroupBy.sum doesn't have the axis keyword like pandas.DataFrame.sum.
Minimal example:
import pandas as pd
from pandas import Timestamp
dd={'aavg': {
(Timestamp('2021-02-03 00:00:00'), 277, 403): 0.0694,
(Timestamp('2021-02-03 00:00:00'), 278, 403): 0.09393,
(Timestamp('2021-02-03 00:00:00'), 277, 415): 0.148286,
(Timestamp('2021-02-03 00:00:00'), 278, 415): 0.118842,
(Timestamp('2021-02-04 00:00:00'), 278, 403): 0.078156,
(Timestamp('2021-02-04 00:00:00'), 277, 415): 0.11675,
(Timestamp('2021-02-04 00:00:00'), 278, 415): 0.126452,
(Timestamp('2021-02-05 00:00:00'), 277, 415): 0.147857,
(Timestamp('2021-02-05 00:00:00'), 278, 415): 0.107894,
(Timestamp('2021-02-05 00:00:00'), 277, 403): 0.1245,
(Timestamp('2021-02-05 00:00:00'), 278, 403): 0.070652,
(Timestamp('2021-02-08 00:00:00'), 277, 415): 0.12475,
(Timestamp('2021-02-08 00:00:00'), 278, 415): 0.11235,
(Timestamp('2021-02-08 00:00:00'), 277, 403): 0.3435,
(Timestamp('2021-02-08 00:00:00'), 278, 403): 0.071826,
(Timestamp('2021-02-09 00:00:00'), 277, 415): 0.091,
(Timestamp('2021-02-09 00:00:00'), 278, 415): 0.116125,
(Timestamp('2021-02-09 00:00:00'), 277, 403): 0.057,
(Timestamp('2021-02-09 00:00:00'), 278, 403): 0.075733},
'acnt': {
(Timestamp('2021-02-03 00:00:00'), 277, 403): 5,
(Timestamp('2021-02-03 00:00:00'), 278, 403): 71,
(Timestamp('2021-02-03 00:00:00'), 277, 415): 7,
(Timestamp('2021-02-03 00:00:00'), 278, 415): 95,
(Timestamp('2021-02-04 00:00:00'), 278, 403): 90,
(Timestamp('2021-02-04 00:00:00'), 277, 415): 4,
(Timestamp('2021-02-04 00:00:00'), 278, 415): 115,
(Timestamp('2021-02-05 00:00:00'), 277, 415): 7,
(Timestamp('2021-02-05 00:00:00'), 278, 415): 123,
(Timestamp('2021-02-05 00:00:00'), 277, 403): 2,
(Timestamp('2021-02-05 00:00:00'), 278, 403): 92,
(Timestamp('2021-02-08 00:00:00'), 277, 415): 4,
(Timestamp('2021-02-08 00:00:00'), 278, 415): 60,
(Timestamp('2021-02-08 00:00:00'), 277, 403): 2,
(Timestamp('2021-02-08 00:00:00'), 278, 403): 46,
(Timestamp('2021-02-09 00:00:00'), 277, 415): 6,
(Timestamp('2021-02-09 00:00:00'), 278, 415): 88,
(Timestamp('2021-02-09 00:00:00'), 277, 403): 3,
(Timestamp('2021-02-09 00:00:00'), 278, 403): 60}}
ndf=pd.DataFrame.from_dict(dd,orient='columns')
ndf.index.set_names(['adate','filter_id','tr_id'],inplace=True)
print(ndf)
d = ndf.sort_index(level=0)

d['aavg_r5'] = d['aavg'].groupby(['filter_id','tr_id'],group_keys=False).rolling(5).mean() #weekly mean (trend)
d['aavg_diff'] = d['aavg'].groupby(['filter_id','tr_id'],group_keys=False).diff() #absolute change
d['aavg_pctc'] = d['aavg'].groupby(['filter_id','tr_id'],group_keys=False).pct_change() #relative change

last = d.index.levels[0].max()
l= d.loc[(last,slice(None),slice(None)),:].dropna()

l['s1']=(l['aavg_diff'].abs() > 0.1).astype(int)
l['s2']=(l['aavg_pctc'].abs() > 0.01).astype(int)
l['s3']=(((l['aavg_r5']-l['aavg'])/l['aavg_r5']).abs() > .1).astype(int)

### sum score (not working)
#print(l.loc[:,['s1','s2','s3']].groupby(['filter_id','tr_id']).sum(axis=1))

### sort by score
#l.sort_values(by=['score'],inplace=True)

for ((date,filter,tr),g) in l.loc[:,['s1','s2','s3']].groupby(['adate','filter_id','tr_id']):
        print(g.sum(axis=1))

The conditions themselves are preliminary - I need to find out good values and criteria in the future ... (if you have tips in this direction, I wouldn't mind :-), but they are not the focus of this question)
thank you for your help :-)
Phil

A: solved it with assign:
#[...]
l['s1']=(l['aavg_diff'].abs() > 0.1).astype(int)
l['s2']=(l['aavg_pctc'].abs() > 0.01).astype(int)
l['s3']=(((l['aavg_r5']-l['aavg'])/l['aavg_r5']).abs() > .1).astype(int)

l=l.assign(score=lambda x: x.s1+x.s2+x.s3)

#[...]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sort array using php Trying to understand how to sort the following array based on the value. Tried the regular functions for sort, asort, ksort etc like:
sort($array) but no luck. Any thoughts?
   Array
   (
    [0] => Array
        (
            [text] => 2015-01-01 - 2015-12-31
            [value] => 2015-01-01
        )

    [1] => Array
        (
            [text] => 2018-01-01 - 2018-12-31
            [value] => 2018-01-01
        )

    [2] => Array
        (
            [text] => 2017-01-01 - 2017-12-31
            [value] => 2017-01-01
        )

    [3] => Array
        (
            [text] => 2014-01-01 - 2014-12-31
            [value] => 2014-01-01
        )

    [4] => Array
        (
            [text] => 2013-01-01 - 2013-12-31
            [value] => 2013-01-01
        )

)


text:
Q: How to iterate, search and display a specific element in an ArrayList I'm having a problem with a specific part of a program. What I want to do is iterate, search and display an element from an ArrayList.
So I tried implementing my own snippet to the main function of the code to try:
else if (menuChoice==3) {
           System.out.println("Search Student:");
           String search = input.nextLine();

           for (Student student : students)
           {
               if (students.equals(search)){
                   System.out.println(student);
               }
           }
       }

Hoping that it would iterate through the ArrayList and access/display that specific element in the list. It returns blank, what am I doing wrong?
Here's the whole code if you're wondering:
package student;
import java.util.*;

public class Student
{
private String r_name;
private int r_age;
private String r_course;
private String r_year;
private String r_section;
private String r_studno;

public Student( String name, int age, String course, String year, String section, String studno )
{
    r_name = name;
    r_age = age;
    r_course = course;
    r_year = year;
    r_section = section;
    r_studno = studno;
}

public String getName()
{
    return r_name;
}

public int getAge()
{
    return r_age;
}

public String getCourse()
{
    return r_course;
}

public String getYear()
{
    return r_year;
}

public String getSection()
{
    return r_section;
}

public String getStudno()
{
    return r_studno;
}

public String toString()
{
    return "Name: " + r_name + ", Age: " + r_age +
           ", Course: " + r_course + ", Year: " + r_year +
           ", Section: " + r_section + ", Student Number: " + r_studno;
}

public static void main(String[] args)
{
   ArrayList<Student> students = new ArrayList<Student>();
   Scanner input = new Scanner(System.in);

   int menuChoice = 4;
   do {
       System.out.println("\t\t\tStudent Record Menu");
       System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
       try {
           System.out.println("Enter a choice: ");
           menuChoice = Integer.parseInt(input.nextLine());
       } catch (NumberFormatException e) {
           continue;
       }

       if (menuChoice==1)
       {
           System.out.println("Add a Student");
           System.out.println("Full name:");
           String name = input.nextLine();

           int age = -1;
           do {
               try {
                   System.out.println("Age:");
                   age = Integer.parseInt(input.nextLine());
               } catch (NumberFormatException e) {
                   System.out.println("Enter a number!");
                   continue;
               }
           } while (age <= 0);

           System.out.println("Course:");
           String course = input.nextLine();

           System.out.println("Year:");
           String year = input.nextLine();

           System.out.println("Section:");
           String section = input.nextLine();

           System.out.println("Student Number:");
           String studno = input.next();

           Student student = new Student(name, age, course, year, section, studno);
           students.add(student);

       } else if (menuChoice==2) {
           System.out.println("Students:");
           for (Student student : students)
           {
               System.out.println(student);
           }
       } else if (menuChoice==3) {
           System.out.println("Search Student:");
           String search = input.nextLine();

           for (Student student : students)
           {
               if (students.equals(search)){
                   System.out.println(student);
               }
           }
       }

   } while (menuChoice<4);
}
}

A: You are checking if the ArrayList students is equal to the String search. The result can only be false. I guess, you are trying to do the following:
for (Student student : students)
{
    if (student.getName().equals(search))
    {
        System.out.println(student);
        break;//assuming student name are unique. remove if not
    }
}

A: You must compare the search key with the key id of student for example if all names are unique then use
 for (Student student : students)
       {
           if (student.getname().equals(search)){
               System.out.println(student);
           }
       }

You are compairing the whole student object reference with the search key how it will compare it
if you want to display the whole content then you will have to make a method in which you will get all details using the id eg:
getStudentbyname( String studentname){

here comes the code to get all data

}

then in your for loop call the method and store in array
 for (Student student : students)
       {
           if (student.getname().equals(search)){
              Arraylist<String> studentarr = student.getStudentbyname(student.getname());

System.out.println(""+studentarr)
           }
       }


text:
Q: Receiving Xcode notification on Reality Composer animation end I have the following Reality Composer project that loads properly. As you can see, when the animation completes, it should notify with the keyword "attackComplete".
How do I get this notification?

import RealityKit
import ARKit

class ViewController: UIViewController, ARSessionDelegate {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let boxAnchor = try! Experience.loadOrcAttack()
        arView.session.delegate = self
        arView.scene.anchors.append(boxAnchor)
        print("done")
    }

    func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
        print(anchors)
    }
}

A: With Reality Composer's notifications you can implement two scenarios:
Action listener
This is your case and it's easy to implement using
public var onAction: ((RealityKit.Entity?) -> Swift.Void)?.
import UIKit
import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    let scene = try! Experience.loadScene()

    override func viewDidLoad() {
        super.viewDidLoad()
        arView.scene.anchors.append(scene)

        scene.actions.attackCompleted.onAction = notificationID   // listener
    }

    fileprivate func notificationID(_ entity: Entity?) {
         print(scene.actions.attackCompleted.identifier)
    }
}

Here is one more example of how .onAction completion handler can be used.

Trigger for action
When you need to notify Reality Composer's scene to play an action use the following scenario:
import UIKit
import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    let scene = try! Experience.loadScene()

    override func viewDidLoad() {
        super.viewDidLoad()
        arView.scene.anchors.append(scene)
    }

    @IBAction func press(_ sender: UIButton) {
        scene.notifications.spinner.post()            // trigger for action
    }
}

or use a subscript for [NAME.NotificationTrigger]:
@IBAction func press(_ sender: NSButton) {
    scene.notifications.allNotifications[0].post()
}

Here's one more example of how .post() instance method can be used.
P. S.
If you need more info, read this post.


text:
Q: Bootstrap prevent dropdown from disappearing on cursor move I have a navbar with logo on left and a navbar-right (float: right) on the far right which contains a dropdown as the first element and some other elements. The dropdown menu is large and responsive.
What I'd like to be able to do is prevent the dropdown from disappearing when I hover over the dropdown and move the cursor left in navbar (towards the logo). The dropdown should remain open as long as the cursor is still in the navbar. So this should not happen -

JS Fiddle - http://jsfiddle.net/gva90uks/10/embedded/result/
Code - http://jsfiddle.net/gva90uks/10/
I've tried adding left-padding to the dropdown-menu when the menu is open, but the padding has to be dynamic based on window size otherwise it pushes the logo. So I'm looking for better solutions rather than adding the padding.
I'm okay with both js and css based solutions.

A: I would use flexbox and flex-grow, like below.
This because flexbox allows elements to grow bigger (or shrink smaller) if there is space. So the drop-down link (the parent
-element) will at default styling be the width of the text on the link But when we hover over the link, the
-element will grow as much as possible, i.e. all the way to the brand, causing the drop-down not to hide when hovering over the top bar (which now contains the much bigger
 (dropdown) element).

.navbar .container-fluid {
  display: flex;
}

.navbar .container-fluid .navbar-collapse {
  flex-grow:2;

}

.mega-menu {
  position: absolute;
  right: 0;
  left: 0;
  /*padding: 27px 0;*/
}

.navbar-right {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

#menu-area {
  display: flex;
}

#menu-area .dropdown-toggle {
  margin-left: auto;
}

.dropdown-toggle:hover + .dropdown-menu, .dropdown-menu:hover {
    display: block;
    margin-top: 0;
}

.menu-large:hover {
  flex-grow: 2;
}

.dropdown-toggle:hover {
  flex-grow: 2;
}

.dropdown-toggle {
  text-align: right;
}

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Brand

          Dropdown

Action

Another action

Something else here

Separated link

Another Link


text:
Q: Updating two columns in the same table, using group by? I have two empty columns in a table. I want to populate these columns based off conditions. The first column should be updated with the total HR's from a batter. The second column should be updated with their highest Batting Average. I have tried:
UPDATE Spring_2021_BaseBall.dbo.People
SET [Total_HR] = (SELECT SUM(HR)
                  FROM Spring_2021_BaseBall.dbo.Batting
                  GROUP BY playerid),
     [High_BA] = (SELECT playerID,
                  FROM Spring_2021_BaseBall.dbo.Batting
                  GROUP BY playerid) B
WHERE A.playerid = B.playerid

Any thoughts?

A: Use aggregation to bring them together:
UPDATE p
    SET Total_HR = b.Total_HR,
        High_BA =  b.High_BA
    FROM Spring_2021_BaseBall.dbo.People p JOIN
         (SELECT SUM(HR) as SUM_hr, MAX(BA) as High_BA
          FROM Spring_2021_BaseBall.dbo.Batting
          GROUP BY playerid
         ) b
         ON b.playerid = p.playerid ;


text:
Q: How do I use Gio library in Vala? I'm building a Gtk application in Vala and would like to use the Gio library and more specifically the g_app_info_get_all() function. I am able to achieve this in C as follows:
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include <gio/gdesktopappinfo.h>

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

  GDesktopAppInfo *app_info;
  GList *app_list, *l;

  gtk_init(&argc, &argv);

  ...

  app_list = g_app_info_get_all();

  ...

}

How do I achieve the same in Vala?
ChatGPT suggested me to use Gio.AppInfo.get_all()
and even though
pkg-config --modversion gio-2.0 returns 2.74.3 but using Gio; throws an error saying the namespace 'Gio' could not be found even when I'm compiling with --pkg gio-2.0 flag.

A: The namespace is GLib, this is shown as {} Glib in Valadoc. The GLib namespace is used by default, so the following will work:
void main () {
    var result = AppInfo.get_all ();
    foreach (var app in result) {
        print (@"$(app.get_display_name())\n");
    }
}

Compile with:
valac example.vala --pkg gio-2.0


text:
Q: Connotations—are they to some extent instinctive? I've noticed that many synonyms are often not very alike. Yes, their core meaning is the same. But there are many differences in mood or tone. Often I understand  the kind of meaning it will have by the sound of it.
Here's how I interpret two synonyms 'happy' and 'glad'

*

*Being happy reflects a positive attitude or nature as a general overall feeling. Just feeling the wind on my skin makes me happy. Life going on peacefully and smoothly makes me happy. Being carefree makes me happy.

*Gladness requires more of a benefit to oneself. You're usually glad because something was done. It eases your life in some way or it simply makes you feel happy. Either ways, it was beneficial and that makes you glad.
"Skinny" and "Slender"

*

*Skinny has a sharp tang. It adds to the quality of being thin sometimes a certain sexiness and sometimes (mostly in Old English) an unhealthy and unattractive connotation.

*Slender has the same basic meaning as 'skinny', but it paints a more graceful and eloquent picture of thinness. I automatically associate slenderness with a refined sense of beauty.
I have never learnt it anywhere but still whenever I see these words being used, that is how I understand them. Why is it that way?
I know all of it looks very confusing. It does to me too. To be honest, I hardly understand what my question is myself. Hopefully, somebody will be able to sort this mess out and identify what I'm asking.

A: Ordo Ab Chao
A Place to Start
English has many, many words that appear synonymous and are not real synonymous at all. One could say there is a base word or basic word (an anchor word for the set of words, [idea taken from the book cited below]) and then a series of quasi-synonyms** for many everyday words. Though some words mean the same thing in their Latin or Germanic variants (the verb to arrive can also be to get [here, there], for example, others have greater semantic specificity or uniqueness.
A very good example is the word shine: Here is a list of "synonyms": glimmer, glint, glitter, shimmer, sparkle, twinkle, flicker, wink, glisten, flash;
Lights can be described with any one of those (and of course other words as well). But each brings a particular flavor to the table. What is the difference? Well, a native speaker will be able to say straight away what the basic difference in meaning is, whether they can articulate it well or not. But each word has its specific meaning: twinkling lights are not shimmering lights. twinkling suggests and on/off type of thing, whereas shimmering suggests an extra layer of light hovering over a surface.
These semantic differences are absorbed by speakers through hearing them or reading them. Over time, their difference become apparent. I daresay, also, that education plays a role here. The more you read, the more  you will absorb this "stuff" which, in the end, translates out to small semantic differences.
Unfortunately, I only have my own head as reference and, therefore, this is an opinion. But readings in teaching vocabulary such as this book will probably go a long way to clarifying this issue for you. But to answer the question: Are these meanings instinctive? No, these meanings are absorbed by the mind as one progresses through reading (different books, etc.) or hearing them spoken. Many are part of one's passive vocabulary and are not usually spoken aloud.


text:
Q: Flip every 2nd pair in a list What would be the fastest way to break a list of random numbers into sets of two, alternately flipping every pair? For example:
pleatedTuple=(0, 1, 3, 2, 4, 5, 7, 6, 8, 9)

What I want in one operation:
flatPairs=[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

Items will be random single digits, I only made them sequential for readability. I need to do thousands of these in a run so speed is priority. Python 3.6.4.
Thank you for any ideas, I'm stumped by this one.

A: Option 1
As long as this is pairs we're talking about, let's try a list comprehension:
flatPairs = [
    [x, y] if i % 2 == 0 else [y, x] for i, (x, y) in enumerate(
        zip(pleatedTuple[::2], pleatedTuple[1::2])
    )
]

You can also build this from scratch using a loop:
flatPairs = []
for i, (x, y) in enumerate(zip(pleatedTuple[::2], pleatedTuple[1::2])):
    if i % 2 == 0:
        flatPairs.append([x, y])
    else:
        flatPairs.append([y, x])

print(flatPairs)
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

Option 2
Use Ned Batchelder's chunking subroutine chunks and flip every alternate sublist:
# https://stackoverflow.com/a/312464/4909087
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

Call chunks and exhaust the returned generator to get a list of pairs:
flatPairs = list(chunks(pleatedTuple, n=2))

Now, reverse every other pair with a loop.
for i in range(1, len(flatPairs), 2):
    flatPairs[i] = flatPairs[i][::-1]

print(flatPairs)
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

Note that in this case, the result is a list of tuples.

Performance
(of my answers only)
I'm interested in performance, so I've decided to time my answers:
# Setup
pleatedTuple = tuple(range(100000))

# List comp
21.1 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Loop
20.8 ms ± 1.71 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# chunks
26 ms ± 2.19 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

For more performance, you may replace the chunks generator with a more performant alternative:
flatPairs = list(zip(pleatedTuple[::2], pleatedTuple[1::2]))

And then reverse with a loop as required. This brings the time down considerably:
13.1 ms ± 994 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A 2x speedup, phew! Beware though, this isn't nearly as memory efficient as the generator would be...

A: You can use iter with list slicing:
pleatedTuple=(0, 1, 3, 2, 4, 5, 7, 6, 8, 9)
new_data = [list(pleatedTuple[i:i+2][::-1]) if c%2 != 0 else list(pleatedTuple[i:i+2]) for i, c in zip(range(0, len(pleatedTuple), 2), range(len(pleatedTuple)))]

Output:
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

A: You can use the standard grouping idiom and zip it with the length:
>>> by_pairs_index = zip(range(len(pleatedTuple)), *[iter(pleatedTuple)]*2)
>>> [[b, a] if i%2 else [a,b] for i,a,b in by_pairs_index]
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

If performance is critical, you may consider other approaches.

A: Option 1
Using map and reversed and slice assignment.
p = list(map(list, zip(pleatedTuple[::2], pleatedTuple[1::2])))
p[1::2] = map(list, map(reversed, p[1::2]))

p

[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

Slight variation
p = list(map(list, zip(pleatedTuple[::2], pleatedTuple[1::2])))
p[1::2] = (x[::-1] for x in p[1::2])

p

[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

Option 2
def weird(p):
    return [[p[2 * i + i % 2], p[2 * i + (i + 1) % 2]] for i in range(len(p) // 2)]

weird(pleatedTuple)

[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

More generic
def weird(p, k):
    return [list(p[i*k:(i+1)*k][::(i-1)%2*2-1]) for i in range(len(p) // k)]

weird(pleatedTuple, 2)

[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

weird(pleatedTuple * 3, 3)

[[0, 1, 3],
 [5, 4, 2],
 [7, 6, 8],
 [1, 0, 9],
 [3, 2, 4],
 [6, 7, 5],
 [8, 9, 0],
 [2, 3, 1],
 [4, 5, 7],
 [9, 8, 6]]

A: You can do this in numpy:
>>> pleatedTuple=(0, 1, 3, 2, 4, 5, 7, 6, 8, 9)
>>> pleatedArray = np.array(pleatedTuple)
>>> flat2D = pleatedArray.reshape(5,2)
>>> flat2D[1::2] = np.flip(pleated2D[1::2], axis=1)

Of course this is probably going to waste as much time converting between tuples and arrays as it saves doing a tiny loop in numpy instead of Python. (From a quick test, it takes about twice as long as Coldspeed's Option 2 at the example size, and doesn't catch up until you get to much, much longer tuples, and you have a bunch of little tuples, not a few giant ones.)
But if you're concerned with speed, the obvious thing to do is put all of these thousands of pleated tuples into one giant numpy array and do them all at once, and then it will probably be a lot faster. (Still, we're probably talking about saving milliseconds for thousands of these.)

A: What i use is :
pleatedTuple=(0, 1, 3, 2, 4, 5, 7, 6, 8, 9)

for i in range(0,len(pleatedTuple),2):
      print(pleatedTuple[i:i+2])

Is this what you are looking for ?
(0, 1)
(3, 2)
(4, 5)
(7, 6)
(8, 9)


text:
Q: Fit content inside the border Just wrote some newbie css kind of code. I don't know how to fit the image inside the border! I want to fit the water icon inside the circular border! Please run the snippet below

.notice {
  position: relative;
  margin: 1em;
  background: #f3fff2;
  padding: 1em 1em 1em 2em;
  border-left: 4px solid #DDD;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.125);
}

.notice:before {
  position: absolute;
  top: 50%;
  margin-top: -17px;
  left: -17px;
  background-color: #DDD;
  color: #FFF;
  width: 40px;
  height: 40px;
  border-radius: 100%;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-family: Georgia;
  text-shadow: 1px 1px rgba(0, 0, 0, 0.5);
}

.info {
  border-color: #e4ffe0;
}

.info:before {
  content: url('http://www.free-icons-download.net/images/water-droplet-icon-72075.png');
  background-color: #e4ffe0;
}

This is a an info notice, it provides feedback of a neutral nature to the user.

A: Use content image as a background...it will be easy for you to control the size of image
Stack Snippet

.notice {
  position: relative;
  margin: 1em;
  background: #f3fff2;
  padding: 1em 1em 1em 2em;
  border-left: 4px solid #DDD;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.125);
}

.notice:before {
  position: absolute;
  top: 50%;
  margin-top: -17px;
  left: -17px;
  background-color: #DDD;
  color: #FFF;
  width: 40px;
  height: 40px;
  border-radius: 100%;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-family: Georgia;
  text-shadow: 1px 1px rgba(0, 0, 0, 0.5);
}

.info {
  border-color: #e4ffe0;
}

.info:before {
  content: "";
  background: #e4ffe0 url('http://www.free-icons-download.net/images/water-droplet-icon-72075.png') center/20px no-repeat
}

This is a an info notice, it provides feedback of a neutral nature to the user.

A: Why not put it in as a background?

.notice {
  position: relative;
  margin: 1em;
  background: #f3fff2;
  padding: 1em 1em 1em 2em;
  border-left: 4px solid #DDD;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.125);
}

.notice:before {
  position: absolute;
  top: 50%;
  margin-top: -17px;
  left: -17px;
  background-color: #DDD;
  color: #FFF;
  width: 40px;
  height: 40px;
  border-radius: 100%;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-family: Georgia;
  text-shadow: 1px 1px rgba(0, 0, 0, 0.5);
}

.info {
  border-color: #e4ffe0;
}

.info:before {
  content: '';
  display: inline-block;
  background: #e4ffe0 url('http://www.free-icons-download.net/images/water-droplet-icon-72075.png') no-repeat center/contain;
}

This is a an info notice, it provides feedback of a neutral nature to the user.


text: Q: How can i make the DC motor spin different directions according to which button i press this is my first project on the raspberry pi. i am using 4 wheels connected to DC motors.i want 2 to go forward and backward and 2 left and right how can i make the motors spin in different directions depending on the button i click


text:
Q: How do I get the value of a named option of an already running process in Linux? I run the following command.
ps -e -o args | grep destiny | grep UNIX

I receive the following output.
/path/to/destiny -r -m UNIX -t TCP -p 1501

What command can I use the get the value of the printed arguments (for example -m or -t or -p)? I would like to achieve the following.
ps -e -o args | grep destiny | grep UNIX | <someCommand> -p this should print 1501
ps -e -o args | grep destiny | grep UNIX | <someCommand> -m this should print UNIX
ps -e -o args | grep destiny | grep UNIX | <someCommand> -t this should print TCP
Please note that -p, -m or -t may switch columns so printing with awk and choosing column by number is not an option.
Some more facts so that the parsing gets easier (I know it's possible I just lack the tooling knowledge).

*

*if an option is not present an empty string will be returned

*options that will be parsed will always have an argument/a value in this particular case

A: That is not possible in general because only the command itself knows how to parse its own arguments. Taking your example:
/path/to/destiny -r -m UNIX -t TCP -p 1501

-p could be an option that takes no argument (like a boolean: it enables or disables some behaviour) in which case 1501 would be a positional argument (like a filename or something). Or -p could be an option that takes an argument, and its argument is 1501. There's no way to know which it is!
The argument vector is just a list of zero or more strings. There is no meaning attached to those strings indicating which ones are options, which ones are arguments to those options, and which ones are non-option arguments.
Even the -r option in your example cannot be generically parsed for certain. Given that -r is followed immediately by another string that begins with -, it's overwhelmingly likely that -r is an option that takes no argument (like a boolean that enables or disabled some behaviour) but actually that's not 100% certain. -r could be an option that takes an argument and -m would be its argument. Or the command might not follow normal UNIX conventions at all, and -r is not an option at all!

A: You can use grep:
~$ echo "/path/to/destiny -r -m UNIX -t TCP -p 1501" | grep -oP -- '-t \K[^ ]+'
TCP
~$ echo "/path/to/destiny -r -m UNIX -t TCP -p 1501" | grep -oP -- '-p \K[^ ]+'
1501

(you may have/want to use things like \s instead of one space: grep -oP -- '-p\s\K[^\s]+')
The -o means "print only the matching", the \K will reset the start.
Note that this will only handle simple cases (see Celada's answer for why).
Another way, using look-behind:
grep -oP -- '(?<=-p )[^ ]+'

A: How about using sed:
ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-t\s\([A-Z0-9]*\).*/\1/'
ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-p\s\([A-Z0-9]*\).*/\1/'
ps -e -o args | grep -e 'destiny.*UNIX' | sed -e 's/.*-m\s\([A-Z0-9]*\).*/\1/'

sed -e 's/.*-t\s\([A-Z0-9]*\).*/\1/'

*

*s/search for/replace with/options

*s is to search.

*.* matches any/all character(s) until we get to the "-t".

*\s matches any whitespace.

*( begins a capture.

*[A-Z0-9]* matches any capital letter and any number of any length.

*) ends the capture.

*.* matches the remainder of the characters in the line (if there are any).

*\1 replaces everything with the capture.

A: Here's a python one-liner. (I'm using python because perl and awk don't have a simple way to get the position of a value in a list.)
ps -eo args | grep '/path/to/destiny' |
     python -c 'x=input().split(); print(x[ x.index("-p")+1 ])'

It will work as long as the arguments you're trying to extract do not contain spaces.


text:
Q: Can i make VBA change it's own code according to the user's needs? I'm kinda a beginner when it comes to VBA and programming in general so pls try to keep your answers simple. Here is a part of my code:
 Sub Makro2()

 Dim XXX As Workbook
 Dim YYY As Workbook
 Set XXX = Application.Workbooks.Open("C:\aaa.xlsx")
 Set YYY = Application.Workbooks.Open("C:\bbb.xlsx")
 n = XXX.Sheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

XXX.Sheets(1).Activate
Range("A3:A" & n + 1).Select
Selection.Copy
YYY.Sheets(1).Activate
Range("C3").Select
ActiveCell.PasteSpecial Paste:=xlPasteValues

XXX.Sheets(1).Activate
Range("N3:N" & n + 1).Select
Selection.Copy
YYY.Sheets(1).Activate
Range("H3").Select
ActiveCell.PasteSpecial Paste:=xlPasteValues

End Sub

Now this code works for me but my colleague needs Range("N3:N" & n + 1) copied to Range("J3"), not "H3" like me. From what I understand modules are hard-coded so I don't know if this is at all possible. Can I write a piece of code that would alter a previous piece of code depending on what the user wants? If not, is there a way around it?

A: You could consider allowing the user to have an input into the macro. This could take the form of an input box, or a specific part of the worksheet (or another worksheet dedicated to that purpose) that would be read into by the macro when launched (whereby a cell could contain the destination cell name, for instance).
So the macro would be the same but it would work differently depending on the user.


text:
Q: Receiving UDP multicast on macOS Big Sur I know this might be the 10.000th question on receiving UDP multicast messages. However, I already got it working half a year ago. The following snippet I got from http://www.cs.tau.ac.il/~eddiea/samples/Multicast/multicast-listen.c.html (with minor changes: The bind-ip was changed to IPADDR_ANY) worked as expected before I upgraded to macOS Big Sur.
/**************************************************************/
/* Multicast listener (server)                                */
/*                                                            */
/* Activation using: {program name} {Multicast IP} {port}     */
/*   {program name} - This program name                       */
/*   {Multicast IP} - The IP address to listen to (Class D)   */
/*   {port} - The port hnumber to listen on                   */
/*                                                            */
/* This is free software released under the GPL license.      */
/* See the GNU GPL for details.                               */
/*                                                            */
/* (c) Juan-Mariano de Goyeneche. 1998, 1999.                 */
/**************************************************************/

#include <stdio.h>          /* printf(), snprintf() */
#include <stdlib.h>         /* strtol(), exit() */
#include <sys/types.h>
#include <sys/socket.h>     /* socket(), setsockopt(), bind(), recvfrom(), sendto() */
#include <errno.h>          /* perror() */
#include <netinet/in.h>     /* IPPROTO_IP, sockaddr_in, htons(), htonl() */
#include <arpa/inet.h>      /* inet_addr() */
#include <unistd.h>         /* fork(), sleep() */
#include <sys/utsname.h>    /* uname() */
#include <string.h>         /* memset() */

#define MAXLEN 1024

int main(int argc, char* argv[])
{
  u_char no = 0;
  u_int yes = 1;      /* Used with SO_REUSEADDR.
                             In Linux both u_int */
  /* and u_char are valid. */
  int send_s, recv_s;     /* Sockets for sending and receiving. */
  u_char ttl;
  struct sockaddr_in mcast_group;
  struct ip_mreq mreq;
  struct utsname name;
  int n;
  socklen_t socklen;
  struct sockaddr_in from;
  char message [MAXLEN+1];

  if (argc != 3) {
    fprintf(stderr, "Usage: %s mcast_group port\n", argv[0]);
    exit(1);
  }

  memset(&mcast_group, 0, sizeof(mcast_group));
  mcast_group.sin_family = AF_INET;
  mcast_group.sin_port = htons((unsigned short int)strtol(argv[2], NULL, 0));
  mcast_group.sin_addr.s_addr = htonl(INADDR_ANY);

  if ( (recv_s=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    perror ("recv socket");
    exit(1);
  }

  if (setsockopt(recv_s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
    perror("reuseaddr setsockopt");
    exit(1);
  }

  if (bind(recv_s, (struct sockaddr*)&mcast_group, sizeof(mcast_group)) < 0) {
    perror ("bind");
    exit(1);
  }

  struct in_addr sin;
  inet_pton(AF_INET, argv[1], &sin);
  /* Preparatios for using Multicast */
  mreq.imr_multiaddr = sin;
  mreq.imr_interface.s_addr = 0;

  /* Tell the kernel we want to join that multicast group. */
  if (setsockopt(recv_s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
    perror ("add_membership setsockopt");
    exit(1);
  }

  for (;;) {
    socklen=sizeof(from);
    if ( (n=recvfrom(recv_s, message, MAXLEN, 0,
                     (struct sockaddr*)&from, &socklen)) < 0) {
      perror ("recv");
      exit(1);
    }
    message[n] = '\0'; /* null-terminate string */
    printf("%s: Received message from %s, size=%d !!\n",
           name.nodename,
           inet_ntoa(from.sin_addr), n);
    printf("\t%s \n", message);
  }
}

Now I try to get it running again and I can not find any reason why this does not work anymore.
Did some policies change in Big Sur and this is some permission error? I already run the Application as root with sudo ./multicast-listen 239.255.255.250 1900 but this did not work either. I'm trying to receive SSDP packages.

A: So the comment of @CraigEstey brought me to the conclusion it has to do something with the Firewall. Indeed it was a simple firewall issue. In Settings -> Security -> Firewall -> Firewall Options... you have to disable Block all incoming connections and disable stealth mode. Now I'm receiving all SSDP packages as intended.


text:
Q: Do older timelines erase or stay parallelly? I want to know if timelines erase. Let's put as an example when Barry creates Flashpoint after kissing Iris, did the timeline with Iris disappear, or did he create Flashpoint but the other remained without him, leaving his family alone. If timelines don't disappear, then the Barry we know will never go back in time to see his mother die because that would be him from the other timeline, the original.
I hope I made myself clear.

A: They seem to erase but then there's the fact that there's a version of Thawne who still exists "after" his history was erased.  So as with my first attempt at an answer, the answer is still "narrative convenience".


text:
Q: Set value of interface to struct field of type pointer to struc via reflection I'm trying to set struct.field = &otherStruct. However, I have to use reflection, and otherStruct is of type interface{}.
The error I'm getting is:
reflect.Set: value of type main.StructB is not assignable to type *main.StructB

struct is known. The (real) type of otherStruct is not known, but it is guaranteed, that the assignment is safe (the struct type is identical).
Code:
type StrucA struct {
    Field *StrucB
}

type StrucB struct {}

func main() {
    a := StrucA{}
    var b interface{} = StrucB{}
    //above is set

    // Target: Set a.Field = &b
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(reflect.ValueOf(b)) // reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB
}

Playground:
https://play.golang.org/p/LR_RgfBzsxa
I have tested a lot of different stuff, but I'm unable to solve it.

A: You first need to allocate a pointer to the type of b, in order to have somewhere to copy the value. Once you have a pointer value, you can set that to Field in a:
field := reflect.New(reflect.TypeOf(b))
field.Elem().Set(reflect.ValueOf(b))
reflect.ValueOf(&a).Elem().FieldByName("Field").Set(field)

https://play.golang.org/p/6-GNSEq0tw3


text:
Q: Restore multiple Analysis DB's from windows explorer with Powershell I am trying to maken a PS script that retores multiple Analisys DB's to SSAS from windows explorer.
Here are de DB's F:\Backup\SSAS\SQL002\ xx.abf and yy.abf and many more.
And the sript that i use is this:
$SQLInstanceName = "SQL002"
\#$DatabaseName = Get-ChildItem $BackupFilePath -Filter \*.abf -Recurse
$DatabaseName = "DBC_tst__yesterday"
$BackupFilePath = "\\localhost\\F$\\Backup\\SSAS\\SQL002"

## Add the AMO namespace

$loadInfo = \[System.Reflection.Assembly\]::LoadWithPartialName("Microsoft.AnalysisServices") | Out-Null
\[Microsoft.AnalysisServices.Server\]$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($SQLInstanceName)
if ($server.name -eq $null) {
Write-Output ("Server '{0}' not found" -f $ServerName)
break
}

# Lets restore using the default locations

\#If ($BackupFilePath -match '.abf') { $File = $BackupFilePath }
$File = (Get-ChildItem $BackupFilePath -Filter \*.abf -Recurse| Sort LastWriteTime -Descending | Select           -First 1).Fullname
Write-Host "File Variable contains " $File
Write-Host "Restoring $File on $SQLInstanceName"
$Server.restore($File, $DatabaseName, $true, $null)

if ($?) {"Successfully Restore " + $DatabaseName + " to " + $SQLInstanceName }
else {"Failed to Restore " + $DatabaseName + " to " + $SQLInstanceName }
$server.Disconnect()

It only restores 1 db, how do i get it done that it restore als db's in de directory?
I tried already with an other variable. But that didn't work.
Thank you in advanced.
The result of my script is that it restores only 1 db.
I modified the script. but doesn't still work. I even do not get a error anymore.
$BackupFilePath = "F:\Backup\SSAS\SQL002\"
$SQLInstanceName = "SQL002"
$DatabaseName = "DBC_tst__yesterday"
$Files = Get-ChildItem $BackupFilePath -Filter -File -Recurse
foreach($File in $Files)
{
Write-Host "File Variable contains " $File.Name
Write-Host "Restoring $File on $SQLInstanceName"

$Server = New-Object Microsoft.AnalysisServices.Server
$Server.Connect($SQLInstanceName)

$Server.restore($File.Fullname, $DatabaseName, $true, $null)

if ($?) {"Successfully Restore " + $DatabaseName + " to " +
$SQLInstanceName }
else {"Failed to Restore " + $DatabaseName + " to " + $SQLInstanceName }
$server.Disconnect()
 }

Please Help

A: Try following :
$BackupFilePath = "\\localhost\\F$\\Backup\\SSAS\\SQL002"
$SQLInstanceName = "SQL002"
$DatabaseName = "DBC_tst__yesterday"
$Files = Get-ChildItem $BackupFilePath -Filter \*.abf -Recurse -File
foreach($File in $Files)
{
   Write-Host "File Variable contains " $File.Fullname
   Write-Host "Restoring $File on $SQLInstanceName"
   $Server.restore($File.Fullname, $DatabaseName, $true, $null)

   if ($?) {"Successfully Restore " + $DatabaseName + " to " + $SQLInstanceName }
   else {"Failed to Restore " + $DatabaseName + " to " + $SQLInstanceName }
}
$server.Disconnect()


text:
Q: SQL/HANA query assigning incremental number per X unique values without using stored procedure Currently I'm struggling trying to write a select query to achieve the following result:

I have documents, each document has an address.
Now I want a third column that will assign a unique number for every X unique adresses found in the result list. In the example I have used X = 3.
There are a total of 7 unique adresses. Which means we need 3 unique numbers.
1 = (adres A,B,C) , 2 = (adres D,E,F), 3= (adres G).
PS. I have already worked out this logic in a stored procedure, but because of technical limitations that I can't go into detail about this has to be done using a SELECT query if possible. If this is not possible we will have to find another workaround.
I was hoping you could point me in the right direction for which HANA SQL syntax to use to achieve this.. I've been looking into ROW_NUMBER and DENSE_RANK but without success.

A: In order for your question to make sense, you need an ordering column.  This answer assumes that document orders the rows.
You want to assign the group based on the minimum document of each address (and then do arithmetic).  You can get this with two levels of window functions:
select t.*,
       ceil(dense_rank() over (order by min_document) / 3.0) as incremental_number
from (select t.*,
             min(document) over (partition by address) as min_document
      from t
     ) t;


text:
Q: R - How delete two quasi-identical rows of a data frame? I have a data frame, and i need depurate it according with two variables but both variables are "quasi-identical" in the rows. It mean that they can have a - or ' or s or :or a space in one row but in another row dont have it.
I did use unique()but this function only works with identical values. Suppose that we have this data.frame
Id<-c("RoLu1976","Rolu1976","AlBl1989","ThSa1996")
Art<-c("Econometric Policy Evaluation: A Critique","Econometric Policy Evaluations A Critique", "Rules after discretion", "Expectations and the Nonneutrality of Lucas")
Id.1<-c("FiKy1989","EdPr1986","BeBe1983","JoSt1989")
Art.1<-c("Notes on the Lucas Critique","Notes on the Lucas Critique","The Inconsistency of Optimal Plans","The Inconsistency of Optimal Plans")
N<-data.frame(Id,Art,Id.1,Art.1)

The quasi identical values are in the variable Art on the two first observation, which are different just for a sand :. How can I filter and delete these kind of values?

A: Based on your data, I used agrep to match similar strings:
yy = NULL
for(i in 1:length(N$Art)){
    temp = agrep(N[i,"Art"],N$Art,value=T)
    y = ifelse(any(N[i,"Art"]==temp),temp[1],N[i,"Art"])
    yy = c(yy,y)
}

Then replaced N$Art with yy, which will allow you to use duplicated/unique:
N$Art = yy
N.2 = N[!duplicated(N$Art), ]


text:
Q: Error while loading english module in spacy I am working on Ubuntu 16.04, on jupyter notebook.
I just installed the latest version of spaCy using the following because my english module wasn't downloading
 conda install -c conda-forge spacy=2.0.11

However while installing spaCy using the above command it said:
The following packages will be REMOVED:
   anaconda:        5.2.0-py36_3
While loading the english module via :
import spacy
nlp = spacy.load('en')

I get the following:
    KeyError                                  Traceback (most recent call last)
<ipython-input-15-76abff010c5f> in <module>()
----> 1 nlp = spacy.load('en')

~/anaconda3/lib/python3.6/site-packages/spacy/__init__.py in load(name, vocab, tokenizer, parser, tagger, entity, matcher, serializer, vectors, via)
     13     if depr_path not in (True, False, None):
     14         deprecation_warning(Warnings.W001.format(path=depr_path))
---> 15     return util.load_model(name, **overrides)
     16
     17

~/anaconda3/lib/python3.6/site-packages/spacy/util.py in get_package_by_name(name, via)
     42     """Import and load a Language class.
     43
---> 44     lang (unicode): Two-letter language code, e.g. 'en'.
     45     RETURNS (Language): Language class.
     46     """

~/anaconda3/lib/python3.6/site-packages/sputnik/__init__.py in package(app_name, app_version, package_string, data_path)
    157         data_path = default_data_path(app_name)
    158
--> 159     pool = Pool(app_name, app_version, expand_path(data_path))
    160     return pool.get(package_string)
    161

~/anaconda3/lib/python3.6/site-packages/sputnik/pool.py in __init__(self, app_name, app_version, path, **kwargs)
     17
     18     def __init__(self, app_name, app_version, path, **kwargs):
---> 19         super(Pool, self).__init__(app_name, app_version, path, **kwargs)
     20         self.logger = logging.getLogger(__name__)
     21         self.cleanup()

~/anaconda3/lib/python3.6/site-packages/sputnik/package_list.py in __init__(self, app_name, app_version, path, **kwargs)
     31             raise InvalidDataPathException(self.data_path)
     32
---> 33         self.load()
     34
     35     def packages(self):

~/anaconda3/lib/python3.6/site-packages/sputnik/package_list.py in load(self)
     49     def load(self):
     50         self._packages = {}
---> 51         for package in self.packages():
     52             self._packages[package.ident] = package
     53

~/anaconda3/lib/python3.6/site-packages/sputnik/package_list.py in packages(self)
     45                 continue
     46
---> 47             yield self.__class__.package_class(path=os.path.join(self.path, path))
     48
     49     def load(self):

~/anaconda3/lib/python3.6/site-packages/sputnik/package.py in __init__(self, path)
     13     def __init__(self, path):
     14         meta = util.json_load(os.path.join(path, default.META_FILENAME))
---> 15         super(Package, self).__init__(defaults=meta['package'])
     16
     17         self.logger = logging.getLogger(__name__)

KeyError: 'package'

Please help!

A: Have you tried python -m spacy download en ? You need to download the spacy models for the language you want to parse.


text:
Q: DyanamoDB PHP SDK Store multiple string values for primary key I am parsing an external JSON datasource which gives me list of Bus Stop codes and corresponding street names.
Data is presented to me in this format:
BusStop01 Street01 Description22 Latitude31 Longitude44
BusStop12 Street05 Description72 Latitude13 Longitude32
BusStop22 Street34 Description28 Latitude43 Longitude21
...

I am able to parse the JSON and use the AWS PHP SDK and store this in DynamoDB in the same format with BusStop a the primary key. Here's the relevant section of my code:
$putResponse = $client->putItem([
'TableName' => 'TABLEDUMMY01',
'Item' => [
     'BusStopCode'       => ['N'      => $BusStopCode        ], // Primary Key
     'RoadName'          => ['S'      => $RoadName           ],
     'Description'       => ['S'      => $Description        ],
     'Latitude'          => ['S'      => strval($Latitude)   ],
     'Longitude'         => ['S'      => strval($Longitude)  ]
     ]
]);

What I really want to achieve is to store the same data in this format using StreetName as the Primary Key:
StreetName01, BusStop01, BusStop33, BusStop43...
StreetName02, BusStop23, BusStop29, BusStop67...

NOTE: The external datasource gives me only 50 values in one API call, hence I need to be able to append/push new BusStop IDs in to existing Street Names on DynamoDB


text:
Q: Add viewbadger in to pagerTabStrip in Android L addTab is deprecated in API 21, so I have to change my tab layout to PagerTabStrip, but I can't find a way to add in custom XML layout in to pagerTabStrip tabs... As I understand, viewBadger need to inflate a custom XML. Hope my question is answered soon.
Below is my current TabPagerAdapter.
package com.example.gosh;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;

public class TabPagerAdapterMain extends FragmentStatePagerAdapter {
    private String tabtitles[] = new String[] { "Home", "Task", "Shop","Wallet" };
Context mContext;
Drawable homeIcon;
Drawable taskIcon;
Drawable shopIcon;
Drawable walletIcon;

public TabPagerAdapterMain(FragmentManager fm, Context context) {
    super(fm);
    mContext = context;
}

@Override
public Fragment getItem(int i) {
    switch (i) {
        case 0:
            return new Home();
        case 1:
            return new Task();
        case 2:
            return new Shop();
        case 3:
            return new Wallet();
    }
    return null;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return 4; // No of Tabs
}

@Override
public CharSequence getPageTitle(int position) {
    homeIcon = mContext.getResources().getDrawable(R.drawable.home_active);
    taskIcon = mContext.getResources().getDrawable(R.drawable.task_active);
    shopIcon = mContext.getResources().getDrawable(R.drawable.shop_active);
    walletIcon = mContext.getResources().getDrawable(R.drawable.wallet_active);

    if(position == 0){
        SpannableStringBuilder sb = new SpannableStringBuilder("  "+tabtitles[position]); // space added before text for convenience

        homeIcon.setBounds(0, 0, homeIcon.getIntrinsicWidth(), homeIcon.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(homeIcon, ImageSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }else if(position == 1){
        SpannableStringBuilder sb = new SpannableStringBuilder("  "+tabtitles[position]); // space added before text for convenience

        taskIcon.setBounds(0, 0, taskIcon.getIntrinsicWidth(), taskIcon.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(taskIcon, ImageSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }else if(position == 2){
        SpannableStringBuilder sb = new SpannableStringBuilder("  "+tabtitles[position]); // space added before text for convenience

        shopIcon.setBounds(0, 0, shopIcon.getIntrinsicWidth(), shopIcon.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(shopIcon, ImageSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }else if(position == 3){
        SpannableStringBuilder sb = new SpannableStringBuilder("  "+tabtitles[position]); // space added before text for convenience

        walletIcon.setBounds(0, 0, walletIcon.getIntrinsicWidth(), walletIcon.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(walletIcon, ImageSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }else{
        return null;
    }

}
}

A: You can always add a fragment to your tabs. I don't see the fragments are imported to your class. Make sure your fragments are imported.


text:
Q: How to add commands to buttons created from within a class in wxwidgets? I have searched far and wide and thought different options for quite a while, and am now absolutely stumped. I created a simple class that makes 16 buttons and assigns IDs to them in the constructor. I would like each of the buttons to have an event triggered when clicked.
Class in the header:
class step16
{
    ///signals and buttons
private:
    wxButton*       sequencer              [16];
    long*           ids          = new long[16];
public:
    step16(wxFrame* frame);
    ~step16();
};

Declaration of the functions in the source file:
///constructor for 16 step sample sequencer class
step16::step16(wxFrame* frame)
{
    ///clear all signals on initialization and create buttons
    for(int i = 0; i < 16; i++){
        ids      [i] = wxNewId();
        sequencer[i] = new wxButton(frame,ids[i],wxString::Format(_("")),
                                    wxPoint(i*30 ,     0,wxSize(30,20) );
    }
}

///destructor for the 16 step sequencer class
step16::~step16(){delete[]signals;}

The only way I know how to add click events to buttons in wxWidgets is using the Connect() method in the initialization part of the Main wxFrame, but connecting them in that part of the program would not bring the desired results. Mainly because I need a new set of 16 buttons with unique IDs and events in every instance of the step16 class. How would I go about adding unique click events to each of these buttons?

A: You can use Bind to bind a handler in any class that is derived from wxEventHandler (i.e. just about any standard wxWidgets class, including wxFrame).
Pass the ID of the button to the Bind() call so your event handler knows which button has been pressed.
For example your step16 constructor could look like this:
///constructor for 16 step sample sequencer class
step16::step16(wxFrame* frame)
{
    ///clear all signals on initialization and create buttons
    for(int i = 0; i < 16; i++)
    {
        ids      [i] = wxNewId();
        sequencer[i] = new wxButton(frame,ids[i],wxString::Format(_("")),
                                        wxPoint(i*30,0), wxSize(30,20));

        /// Add it to something so I can test this works!
        frame->GetSizer()->Add(sequencer[i]);

        /// Bind the clicked event for this button to a handler
        /// in the Main Frame.
        sequencer[i]->Bind(wxEVT_COMMAND_BUTTON_CLICKED,
                            &MainFrame::OnPress,
                            (MainFrame*)frame);
    }
}

In this example, I have created the event handler in the MainFrame class, a pointer to an instance of which is passed to ctor for step16.
You can distinguish between the button presses using event.GetId() which will be the value set by the line:
ids [i] = wxNewId();

The MainFrame::OnPress method could look like this:
void MainFrame::OnPress(wxCommandEvent& event)
{
    long firstID = *theStep16->GetIDs();

    switch(event.GetId() - firstID)
    {
        case 0:
            std::cout << "First button" << std::endl;
            break;
        case 1:
            std::cout << "Second button" << std::endl;
            break;
        default:
            std::cout << "One of the other buttons with ID "
                      << event.GetId() << std::endl;
    }
}


text:
Q: Protractor failed to start test with firefox I can not start the test with protractor on firefox version 56.0.1.
my protractor version is 5.1.2
exports.config = {
    allScriptsTimeout: 11000,
    specs: [
        './e2e/**/*.e2e-spec.ts'
    ],
    capabilities: {
        'browserName': 'firefox'
    },

    directConnect: true,
    baseUrl: 'http://localhost:4444/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000,
        print: function() {}
    },
};

this is the error:
[00:02:20] I/launcher - Running 1 instances of WebDriver
[00:02:20] I/direct - Using FirefoxDriver directly...
[00:02:27] E/launcher - Unable to parse new session response: {"value": {"sessionId":"e9d08604-1d7e-4870-85d7-4e09a2248ffa","capabilities":{"acceptInsecureCerts":false,"browserName":"firefox","browserVersion":"56.0.1","moz:accessibilityChecks":false,"moz:headless":false,"moz:processID":5804,"moz:profile":"C:\\Users\\s\\AppData\\Local\\Temp\\rust_mozprofile.sWpsKwszgKSw","pageLoadStrategy":"normal","platformName":"windows_nt","platformVersion":"6.1","rotatable":false,"specificationLevel":0,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000}}}}
[00:02:27] E/launcher - WebDriverError: Unable to parse new session response: {"value": {"sessionId":"e9d08604-1d7e-4870-85d7-4e09a2248ffa","capabilities":{"acceptInsecureCerts":false,"browserName":"firefox","browserVersion":"56.0.1","moz:accessibilityChecks":false,"moz:headless":false,"moz:processID":5804,"moz:profile":"C:\\Users\\s\\AppData\\Local\\Temp\\rust_mozprofile.sWpsKwszgKSw","pageLoadStrategy":"normal","platformName":"windows_nt","platformVersion":"6.1","rotatable":false,"specificationLevel":0,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000}}}}
    at WebDriverError (C:\Users\s\WebstormProjects\Co\node_modules\selenium-webdriver\lib\error.js:27:5)
    at doSend.then.response (C:\Users\s\WebstormProjects\Common_IDE\node_modules\selenium-webdriver\lib\http.js:445:19)
    at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.createSession()
    at Function.createSession (C:\Users\s\WebstormProjects\Co\node_modules\selenium-webdriver\lib\webdriver.js:777:24)
    at Function.createSession (C:\Users\s\WebstormProjects\Co\node_modules\selenium-webdriver\firefox\index.js:640:55)
    at Direct.getNewDriver (C:\Users\s\WebstormProjects\Co\node_modules\protractor\lib\driverProviders\direct.ts:112:25)
    at Runner.createBrowser (C:\Users\s\WebstormProjects\Co\node_modules\protractor\lib\runner.ts:225:39)
    at q.then.then (C:\Users\s\WebstormProjects\Co\node_modules\protractor\lib\runner.ts:391:27)
    at _fulfilled (C:\Users\s\WebstormProjects\Co\node_modules\protractor\node_modules\q\q.js:834:54)
    at self.promiseDispatch.done (C:\Users\s\WebstormProjects\Co\node_modules\protractor\node_modules\q\q.js:863:30)
    at Promise.promise.promiseDispatch (C:\Users\saeed\WebstormProjects\Co\node_modules\protractor\node_modules\q\q.js:796:13)
    at C:\Users\s\WebstormProjects\Co\node_modules\protractor\node_modules\q\q.js:556:49
    at runSingle (C:\Users\s\WebstormProjects\Co\node_modules\protractor\node_modules\q\q.js:137:13)
[00:02:27] E/launcher - Process exited with error code 199

do you have any idea how to solve this problem . (it it work normally with chrome but shows empty page with firefox)

A: With geckodriver, you'll need to add marionette to the capabilities:
capabilities: {
    'browserName': 'firefox',
    'marionnette': true
},

UPDATE: There is a open issue #4253 introduced in Protractor 5.1.1 . The workaround is to manually replace directConnect with seleniumAddress and manually start webdriver-manager as specified in the bug:

The solution is to use selenium standalone when testing with Firefox.
  The latest version of the selenium standalone server is compatible
  with Protractor's selenium JS bindings and with geckodriver. You can
  update and launch the standalone server with
webdriver-manager update
webdriver-manager start

and set seleniumAddress: http://localhost:4444

A: If you are opting for directconnect then you dont need to specify the base url and don't need to start explicitly the webdriver server.
exports.config = {
    allScriptsTimeout: 11000,
    specs: [
        './e2e/**/*.e2e-spec.ts'
    ],
    capabilities: {
        'browserName': 'firefox'
    },

    directConnect: true,
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000,
        print: function() {}
    },
};

A: In my case, running it with 'sudo' did not work.
I had to change file permissions and then ran it without sudo.


text:
Q: Group and Count Pivot Table I'm trying to create a pivot table that counts the number of occurrences of a certain value and also the number of possible occurrences of that value. I'm stuck after adding the case id as a row to the pivot table though. I've never used excel before so a pivot table may be the wrong tool.
Given this is my data on Sheet1:
| CaseId | QId | Validity |
| ------ | --- | -------- |
| 12345  | A1  | Valid    |
| 12345  | A2  | Error    |
| 12345  | A3  | Error    |
| 23456  | A1  | NA       |
| 23456  | A2  | NA       |
| 23456  | A3  | Valid    |

how do I transform that to the following in Sheet2? Errors is the count of validity = Error and possible errors is the count of validity != NA
| CaseId | Errors | Possible Errors |     |
| ------ | ------ | --------------- | --- |
| 12345  | 2      | 3               |     |
| 23456  | 0      | 1               |     |
| Totals | 2      | 4               | 50% |

A: If you're willing to add a helper column, you can use COUNTIF() to get your summary table.
Starting with your data table :

Add a helper column, which uses CONCATENATE to create a composite index, seperated by a delimiter (I used semicolon here) :

=CONCATENATE(A2,";",C2)

You can then build your summary table :

Calculating the number of Errors for each CaseId would simply be counting the number of times the string 'CaseID;Error' occurs in the INDEX column

=COUNTIF(D:D,CONCATENATE(F2,";Error"))

The number of "Possible Errors" would be the total number of results of that CaseID minus the CaseIds that were 'NA' :

=COUNTIF(A:A,F2)-COUNTIF(D:D,CONCATENATE(F2,";NA"))

The totals should be a simple SUM() formula :)
Hope this helps.


text:
Q: How to disable "extends" for a php class? I have a class like
<?php
   class A
   {
      function foo()
      {
        echo "hello from the foo.\n";
      }
   }
?>

Now this class can be extended like:
class B extends A{

I want to disable this feature of extends so the class A cannot be extended.
Is it possible?  How can I do this?


text:
Q: Ignore changes in specific files using git I am novice in dealing with git, but I have a repository that contains several files ending in .test
I want to know how I can check for changes made to the repository (compared to my local repo) while disregarding any changes made in these .test files.  This is part of a batch file.

A: Add this to your .gitignore file and commit the file:
#Testing files
*.[Tt]est
*_[Tt]est.*

A: Add a .gitignore file to the root of your project, and write this inside:
*.test

If .gitignore file already exists, just append *.test in the end.
Then add & commit .gitignore.
Further information: http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files


text:
Q: Prove $(a+q*d,n) = 1$ where $q$ is the product of all primes which divide n but not a.
Let $n,a,d$ be given integers with $(a,d) = 1$.
Let $m = a + q*d$ where q is the product of all primes which divide n but not a.
Prove that $m \equiv a \; (mod \; d)$ and $(m,n) = 1$.

The first part follows from the rules of congruences.
$(m,n) = (a +q*d,n) = \ldots$
My idea would be to apply the Euclid property $(a,b) = (a-bq,b)$ here. However, I didn't manage to go so far with it.
Do you see alternative strategies?
References
Apostol, Introduction to Analytic number theory, Exercise 4.

A: Let $p$ be a prime number such that $p\mid a+qd$ and that $p\mid n$. There are two possibilities:

*

*$p\mid a$: Then, since $p\mid a+qd$, $p\mid qd$. So, $p\mid q$ or $p\mid d$. Both are impossible: $p\nmid q$ by the definition of $q$ and $p\nmid d$ because $p\mid a$ and $(a,d)=1$.

*$p\nmid a$: Then, by the definition of $q$, $p\mid q$. So, $p\mid qd$. So, since we are assuming that $p\mid a+qd$, $p\mid a$, which we are assuming that it does not occur.


text:
Q: Swift String's count property time complexity I'm wondering about what the time complexity of Swift (Swift 5) String's count property is? I found it is very slow.
I guess it's O(n), linear time complexity, but cannot find any document about it. Can any one help?
I made a little test about it, compared with Array's count property which is way more faster.
Test result on my machine:
Test Case '-[TESTS.TESTS testArrayCountPerformance]' passed (1.686 seconds).
Test Case '-[TESTS.TESTS testStringCountPerformance]' passed (11.113 seconds).
class TESTS: XCTestCase {

    let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

    var randomString = ""
    var randomChars: [Character] = []

    override func setUp() {
        for _ in 0..<1000000 {
            randomString += String(letters[Int.random(in: 0..<letters.count)])
        }
        randomChars = Array(randomString)
    }

    func testStringCountPerformance() {
        measure {
            for _ in 0..<100 {
                _ = randomString.count
            }
        }
    }

    func testArrayCountPerformance() {
        measure {
            for _ in 0..<100 {
                _ = randomChars.count
            }
        }
    }

}

A: Array conforms to RandomAccessCollection. String conforms to BidirectionalCollection. If you look at the documentation for the Collection protocol you'll find this:

The performance of some collection operations depends on the type of
  index that the collection provides. For example, a random-access
  collection, which can measure the distance between two indices in O(1)
  time, can calculate its count property in O(1) time. Conversely,
  because a forward or bidirectional collection must traverse the entire
  collection to count the number of contained elements, accessing its
  count property is an O(n) operation.

So, you can expect String.count to be more computationally expensive than Array.count.


text: Q: How do I set the default app to open text files? I often find myself wanting to open a variety of text based files, that do not always have file extensions, and I'd like to use a different text editor from TextEdit and XCode. Is there an easy way to set it up so that my default text editing app is something I pick?


text:
Q: avoiding patterns using python For the sequence {6,2,3,1,5,4}, we have the corresponding diagram on the right. For every 3 increasing numbers in the sequence: {2,3,5} , {2,3,4}.
We check if it follows the pattern on the left. This is a combinatorics object called boxed-mesh patterns. My code currently checks if the sequence has 3 increasing numbers

A: You can use of following list comprehension to grub the expected sequences :
>>> [(e1,e2,e3) for i,e1 in enumerate(l) for j,e2 in enumerate(l[i+1:],1) for e3 in l[j+i+1:]]
[(6, 2, 3), (6, 2, 1), (6, 2, 5), (6, 2, 4), (6, 3, 1), (6, 3, 5), (6, 3, 4), (6, 1, 5), (6, 1, 4), (6, 5, 4), (2, 3, 1), (2, 3, 5), (2, 3, 4), (2, 1, 5), (2, 1, 4), (2, 5, 4), (3, 1, 5), (3, 1, 4), (3, 5, 4), (1, 5, 4)]

Then you can filter the result of preceding list comprehension with following function that check the alternating of your elements :
>>> def seq_check(elem):
...   return elem[2]>elem[1]>elem[0]

>>> filter(seq_check,sequences)
[(2, 3, 5), (2, 3, 4)]


text:
Q: How to block incoming ports using group policy in active directory windows server 2012 We have a domain, and there are some computers in this domain. we applied some many policies like password policy and etc to this domain which makes it easier for us to control the use PC in our organization. Now I wonder if it is possible to stipulate a certain configuration for every PC's firewall in our domain or to force every PC in domain at least block some certain Ports and maybe IPs. Can any one help me? Is it possible?

A: This is totally possible to create a policy ruling incoming connection attempts with a GPO. here is the Microsoft documentation pages on how to do that.
Go to Computer configuration, Windows Settings, Security settings, Windows Firewall with advanced security. Right clic on Windows Firewall with advanced security.
On global policy, you can chose to set it up (on), to disable it (off) or to let the computer decide on its own which policy to apply (not configured). You prefer forcing the computer to enable it (on option for firewall state). Then the Inbound connections (By default, I set up inbound connections to Block). You can also chose logging options and exceptions for allowed inbound connections (such as icmp which may help for debug purpose.
For a specific port/IP address, right click on inbound rule, new rule, select Port, and specify options you like. Once your rule is created, right click on it, the property, and Scope to specify remote/local IP address.
EDIT:
Computer configuration -> Administrative Templates -> Network -> Network Connections -> Windows Firewall is legacy configuration which will only apply to XP or 2003 Server.
Computer configuration -> Windows Settings -> Security Settings -> Windows Firewall with Advanced Security is configuration for Windows 7 or 2008 Server and later.
Pay attention that disabling firewall in one of these places will disable firewall for both cases. Have a look here


text:
Q: Triggering an event inside ReactJs component from outside I am using ReactJs to render a list of elements, call it "list-app". I have another mini app that creates an element, let's call it "create-app". Both of them are rendering functional components into different html nodes.
I have two questions for this context:

*

*How do I inject the created element into the "list-app"? Please bear in mind that I want the two mini-apps to be separate.

*How do I trigger the "list-app" from the "create-app"?

While this could have been done by using Class Based components, I don't understand how to use the useRef or useImperativeHandle in functional react components.
I tried saving a set state function to a window function. Is there a better solution?
window.refreshChildren = function() {setRefresh(!refresh)};


text:
Q: Where can I find the price list for Google Drive API? The Google API Console lists 500,000 / day as the "Courtesy limit", and provides a form allowing one to request more.
My assumption is that there will be a cost attached to a higher request limit; similar to the Google Maps pricing
Where can I find the price list for the Google Drive API?

A: Google Cloud Console is updated, strangely it took me a while to find API Quotas under few layers...
Just in case if you need the direct link, here it is:
https://console.cloud.google.com/apis/api/drive.googleapis.com/quotas

A: I had similar concern. Google Cloud Platform Services do have a price list, since Google Drive REST API doesn't. Updated quota usage is limited to 1.000.000.000 requests/day, which can be raised by applying more quota usage form to Google.
No payment needed.

A: Just in case anyone was looking for the quota as of October 2015,

*

*Log into your Google Developer Console.

*Go to API's & auth > APIs.

*Click on Drive API and then the Quotas tab.

Currently the free quota is set at 1,000,000,000 requests/day so unless you are doing something extraordinary this should be enough for most anyone I would think.

A: There is no extra charge for more quota for the Google Drive API. It will be granted as long as you are making a reasonable request.
Big apps (e.g. those that make lots of requests) are good for Google Drive, and Google encourages them.


text:
Q: Changing Radio Buttons image, help Hey guys. I'm not much of a programmer, but still need to do some coding.
Now I have a problem with changing Radio Button Image with jQuery.
I've got this code of the web but it still doesn't work.
It changes the Radio button images, but when I try to select, it changes only the picture of the first radio box.(every time)
Here's my HTML code:

asdg asdg
<FIELDSET class="radios">

<input id="q_0" type="radio" name="q_0" value="2">dgasdg

<input id="q_0" type="radio" name="q_0" value="0"> sdgas

<input id="q_0" type="radio" name="q_0" value="1">dgas

</FIELDSET>

Here's the css. I hope I got it right.
#testcontent .label_check,
#testcontent .label_radio    { padding-left: 34px; }
#testcontent .label_radio    { background: url(radio-off.png) no-repeat; }
#testcontent .label_check    { background: url(check-off.png) no-repeat; }
#testcontent label.c_on      { background: url(check-on.png) no-repeat; }
#testcontent label.r_on      { background: url(radio-on.png) no-repeat; }
#testcontent .label_check input,
#testcontent .label_radio input  { position: absolute; left: -9999px; }

And here's the jquery code.
 function setupLabel() {
        if ($('.label_check input').length) {
            $('.label_check').each(function(){
                $(this).removeClass('c_on');
            });
            $('.label_check input:checked').each(function(){
                $(this).parent('label').addClass('c_on');
            });
        };
        if ($('.label_radio input').length) {
            $('.label_radio').each(function(){
                $(this).removeClass('r_on');
            });
            $('.label_radio input:checked').each(function(){
                $(this).parent('label').addClass('r_on');
            });
        };
    };
    $(document).ready(function(){
        $('.label_check, .label_radio').click(function(){
            setupLabel();
        });
        setupLabel();
    });

Please tell me what I is wrong with this code, help is much appreciated.
Thank you.

A: I really recommend using jquery.uniform (since you are already using jQuery, or any equal alternative) for styling form elements like checkbox, radio and select.
There is a lot more to it than just placing an image above the 'real' form-element, like handling clicks on the label etc.

A: If you are using jquery.uniform, there is a trick to selecting a radio button dynamically.
After setting the value of the form element, e.g.
$("[name='buttongroup']['value='male']").attr("checked", true);

...simply do the following to update the display of the radio button selection:
$.uniform.update();

A: Your problem is that you're using the same ID for all your inputs and ID's are unique. That's why it changes the first instance of the id="q_0"


text:
Q: When are questions which build upon each other considered duplicates? Each Stack Exchange site caters to a mix of experts and novices. This means that some (expert) questions presuppose knowledge which is being asked about in other (novice) questions. In other words, we sometimes have pairs of questions where one question is "building upon" knowledge contained in another question.
Sometimes when two questions build upon each other, one of them gets marked as a duplicate of the other. Marking a question as a duplicate prevents users from adding additional answers.
I'm asking this Meta question in order to seek guidance for users and moderators of the various SE sites, as to when questions which build upon each other should be regarded as duplicates, and to solicit advice about what other ways we can or should use to record the connection between such questions.
The original version of this post was illustrated with a particular question I asked on Linguistics Stack Exchange. I've updated it with some other examples I found by searching Stack Exchange for "This question has been marked as a duplicate". Here are the examples, including my original example. I've rephrased the questions to try to clarify their connections to each other.

*

*English Language and Usage

*

*Q1: Is "it" referring to something in this sentence?

*Q2: What is "it" referring to?

*CSS (Stack Overflow)

*

*Q1: Why would someone want to make a table using CSS display:table properties rather than a regular HTML table?

*Q2: How do I make a table using CSS display:table properties?

*Python

*

*Q1: How do I keep class data from being shared between instances? By creating an instance variable

*Q2: How do I avoid sharing in an instance variable that refers to a mutable collection? By creating a copy of the collection

*Linguistics

*

*Q1: Why is Laam sometimes pronounced as the next letter in Arabic? Because the Arabic definite article Alif-Laam is assimilated if the next letter is a "sun" letter

*Q2: Why do "sun" letters cause assimilation in Arabic? Because they are coronal consonants

*Math

*

*Q1: Why is Q[x,y]/<x^2+y^2-1> an integral domain? Because x^2+y^2-1 is irreducible in Q[x,y]

*Q2: Why is x^2+y^2-1 irreducible in Q[x,y]?

*Haskell (Stack Overflow)

*

*Q1: Why is this value being evaluated twice in a declarative language? Because the compiler inferred a polymorphic type for the value and couldn't share it across occurrences

*Q2: Why is the compiler inferring a non-polymorphic type for this value? Because of the monomorphism restriction

*Space Exploration

*

*Q1: What is the "specific impulse" of an engine? It's the effective exhaust velocity divided by the gravitational acceleration at the Earth's surface

*Q2: Why do we use the gravitational acceleration at the Earth's surface when calculating the specific impulse of an engine?
In the Math and Python examples, Q2 was marked as a duplicate, but in the other examples Q1 was marked as a duplicate.
In the CSS example, the question was marked as a duplicate before it received an answer. However, in all the other examples an answer was given before the question was marked as a duplicate.
A commenter on the first version of this Meta question suggested that there could be no general rule and that I should go to the site-specific Meta for help. Perhaps that is still true for each of these examples. In any case I hope that the additional examples can give a bit more background as to what I am asking about here, than I had provided in my original question.


text:
Q: DOM tree data structure without XML file I would like to use a DOM XML tree as a data structure, but I don't want to save and read the data into an XML file or a database. Is there an implementation or a library or a framework for Java that allows me?
Also, I wish it were possible to query with XQuery on this tree.

A: Re: https://docs.oracle.com/en/java/javase/12/docs/api/java.xml/org/w3c/dom/Document.html
I recommend using the Document class.  You can try creating the Document object with the code below.  From there you can create the hierarchy of elements with its attributes and data as you wish.  You can also query by element name or ID (in lieu of XQuery).  That said, I'm a little confused with your question - DOM is usually HTML specific (HTML being XML), so either way you're using XML.  Good luck in this endeavor.
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();


text:
Q: Copy multiple ranges indicated by inputbox Until now I have a Macro to look up a year and copy that to a new sheet. However, I may want this for multiple years. My dataset is structured as follow:
Col A   Col B   Col C   Col D   ColE
Year    Week    Amount  time    forecast
2000    1       368     2000w1  400
2000    2       8646    2000w2  8500
until...
2014    52      46546   2014w52 47000

Until now, my macro is:
Sub Copyyear()
Dim Forecastyear As String
Dim Rng As Range
Dim cell As Range

Forecastyear = InputBox("Enter a year to forecast")

If Trim(Forecastyear) <> "" Then
    With Sheets(2)
        For Each cell In .Range("A:A")
            If cell.Value = Forecastyear Then 'find first occurrence of year
                Set Rng = cell
                Exit For
            End If
        Next
        '.Range(Rng.Address).Resize(52, 5).Select 'resize for 52 rows and 5 columns
        Rng.Resize(52, 5).Copy Destination:=Sheets("Moving Average").Range("A2")
    End With
End If

'   Record in new sheet
Worksheets("Moving Average").Select
    Range("A1").Value = "YEAR"
    Range("B1").Value = "WEEK"
    Range("C1").Value = "AMOUNT"
    Range("D1").Value = "TIME"
    Range("E1").Value = "FORECAST"

'   next macro
    AddForecastPerformance

End Sub

A: Use below. Years entered like 2001,2002,2003,2004 etc
Sub Copyyear()
Dim Forecastyear As String
Dim Rng As Range
Dim cell As Range

Forecastyear = InputBox("Enter year(s) to forecast, for multiple year input as 2001,2002,2003 etc")

If InStr(1, Forecastyear, ",") > 0 Then
    sp = Split(Forecastyear, ",")
    For i = 0 To UBound(sp)
        If Trim(sp(i)) <> "" Then
            With Sheets(2)
                For Each cell In .Range("A:A")
                    If cell.Value = CInt(sp(i)) Then 'find first occurrence of year
                        Set Rng = cell
                        Exit For
                    End If
                Next
                '.Range(Rng.Address).Resize(52, 5).Select 'resize for 52 rows and 5 columns
                Rng.Resize(52, 5).Copy Destination:=Sheets("Moving Average").Range("A2").Offset(0 + (52 * i), 0)
            End With
        End If
    Next
Else
    If Trim(Forecastyear) <> "" Then
        With Sheets(2)
            For Each cell In .Range("A:A")
                If cell.Value = Forecastyear Then 'find first occurrence of year
                    Set Rng = cell
                    Exit For
                End If
            Next
            '.Range(Rng.Address).Resize(52, 5).Select 'resize for 52 rows and 5 columns
            Rng.Resize(52, 5).Copy Destination:=Sheets("Moving Average").Range("A2")
        End With
    End If
End If

'   Record in new sheet
with Worksheets("Moving Average")
    .Range("A1").Value = "YEAR"
    .Range("B1").Value = "WEEK"
    .Range("C1").Value = "AMOUNT"
    .Range("D1").Value = "TIME"
    .Range("E1").Value = "FORECAST"
end with

'   next macro
    AddForecastPerformance

End Sub


text:
Q: How to check if property 'isElementContentWhitespace' is supported? I want to use isElementContentWhitespace on text nodes,
but not all browsers support it, so I need to check if its supported,
then if is, use it, if not implement jquery's $.trim...
i've tried doing something like this with no luck on IE, good on FF:
var testEl = document.createElement('span');
testEl.innerHTML = ' ';
alert( testEl.firstChild.isElementContentWhitespace );

A: Test if any Property is available for a DOM element like so:

var textNode = document.createTextNode('text');
console.log( 'isElementContentWhitespace' in textNode );

Note that isElementContentWhitespace is Obsolete


text:
Q: WebAPI JSON serialization and object property values I am writing an application in ASP.NET Core WebApi.  Given the tools provided by the framework, what is the best mechanism to use in order to inspect and change object property values during serialization?
Specifically what I need to do is perform a translation on, for example, a string value for a particular property if it meets certain criteria (for my app I'm using custom annotations to mark properties that need to be acted upon).
I assumed a ContractResolver would do the trick, but it appears to only work on Types rather than the object instance itself.
Additionally, I don't want to manually call a serialization method for this.  This needs to be part of the WebAPI processing pipeline so I assume gets placed within the AddJsonOptions within Startup.cs.


text:
Q: Close button closes active tab in tabpanel instead of tab button is attached to (tab dynamically created) EXTJS I'm not sure if this is the right place to ask. I have site I'm working with that uses EXTjs and the tabpanel functionality. I'm creating the tab in the following form.
tabWrapper = Ext.create('Ext.panel.Panel', {
    layout: 'fit',
    tools: tools,
    id: tabConfig.itemId+'-wrapper',
    title: tabConfig.title,
    hidden: tabConfig.hidden,
    hideMode: 'offsets',
    closable: tabConfig.closable,

Please notice the closable tag. When set to enable/true it creates an x button to close the tab. This button however is closing whatever tab is active instead of the tab it is attached to. Is this a known glitch or is there something in my code that does this?

A: I suspect it is because of non-unique ids. Using ids in Ext is a very bad practice that almost always leads to problems. Remove id config option (not only from this tab) and try again.
Also, do not overnest - you do not need to wrap a component in a panel for adding it to tab panel.


text:
Q: Word 2010 Fields added in header section not recognized I added a field in the header section of a word document (I am using 2010 version). I went to Developer tab --> Controls --> Added a plain Text Content control.
In the code, I am looking for fields in the header section as below but nothing would come up as header fields.
Thanks for any help!
For Each oRange As WORD.Range In doc.StoryRanges
   If oRange.StoryType = WORD.WdStoryType.wdPrimaryHeaderStory
        If oRange.Fields.Count > 0 Then
                    For Each field As WORD.Field In oRange.Fields
                        If Not String.IsNullOrEmpty(field.Result.Text) Then
                            MessageBox.Show(field.Result.Text)
                        End If
                    Next
               End If
    End If
Next

A: Content Controls and Fields are different things.
For Content controls, you need to test
oRange.ContentControls.Count

and so on


text:
Q: invalid literal w/ python range extraction Can someone explain to me what makes the below return an invalid literal?
def solution(args):
    new_args = []
    for i in args:
        if i > (i - 1) and i > (i - 2):
            new_args.append("{}-{}".format((i - 2), i))
    return list(map(float, new_args))

Exact error was: ValueError: invalid literal for float()
Example input:
-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20

Example output:
-6,-3-1,3-5,7-11,14,15,17-20

which you'll notice is a consolidated list, converted to a string, where any three original inputs that are consecutive would now be represented in a range within the list.

A: The could be much speculation about what is here going on and why is that this way, BUT ... let's leave the path of trying out what is possible and what not. The code below is a patch to the problem without changing the logic behind solution(), so I consider it an acceptable answer to the question:
def solution(args):
    new_args = []
    for i in args:
        if i > (i - 1) and i > (i - 2):
            new_args.append("{}-{}".format((i - 2), i))
    return list(map(float, map(eval, new_args)))

I haven't checked this out in detail in the documentation, but it comes to my mind that the int()/float() functions aren't designed to take any strings which are not representations of an integer/float number. It sounds quite reasonable that they shouldn't evaluate the expression before interpreting the content, right? Putting eval() in front of the conversion does the right job and fixes the problem.
For these ones who are still curious what actually causes the error:
print(float('-1-1'))
   ValueError: could not convert string to float: '-1-1'
print(int('-1-1'))
   ValueError: invalid literal for int() with base 10: '-1-1'

In this context I have to admit that I was surprised to see it happen ... because my intuition whispered that the interpreter will guess what to do and just do the one more operation on the string ... but it doesn't.

In case of ambiguity resist the temptation to guess!

is one of the known to me leading ideas behind Python.
So int('-1-1') is ambiguous in context of int() and float(). Is the problem the missing space between two numbers? Is it a special notation? Is it addition/subtraction? Why bother? Just raise an error and reject it.


text:
Q: Memory game timer implementation and error handling I've implemented a memory game where the user has to sort numbers in his head while a timer of 5 sec is running.
Please see code below:
    from random import randint
    from threading import Timer

    def timeout():
        print("Time over\n#####################\n")

    while True:
        list = []
        for i in range(5):
            list.append(randint(1000, 10000))

        t = Timer(5, timeout)
        t.start()

        print(list)
        print('[ 1  ,  2  ,  3  ,  4  ,  5  ]')

        solution = sorted(list)[2]
        print('please select the 3rd largest number in this row (1-5):')
        input_string = input()
        selection = int(input_string)

        if solution == list[selection - 1]:
            print("Your guess is correct\n")
        else:
            print("Your guess is wrong\n")

        t.join()

Here is the game interaction itself (please ignore the syntax highlighting):
USER@HOST:~/$ python3 memory_game.py
[8902, 8655, 1680, 6763, 4489]
[ 1  ,  2  ,  3  ,  4  ,  5  ]
please select the 3rd largest number in this row (1-5):
4
Your guess is correct

Time over
#####################

[5635, 3810, 1114, 5042, 1481]
[ 1  ,  2  ,  3  ,  4  ,  5  ]
please select the 3rd largest number in this row (1-5):
4
Your guess is wrong

Time over
#####################

[6111, 1430, 7999, 3352, 2742]
[ 1  ,  2  ,  3  ,  4  ,  5  ]
please select the 3rd largest number in this row (1-5):
23
Traceback (most recent call last):
  File "memory_game.py", line 24, in <module>
    if solution == list[selection - 1]:
IndexError: list index out of range
Time over
#####################

Can anybody help me with these things:
1. 'Time over' should only be written if the player needs more than 5 sec for the answer. If the player solves it in time the next challenge should appear silently.
2. If the player does not write any guess and presses 'Enter' the program terminates with error message:
Traceback (most recent call last):
  File "memory_game.py", line 22, in
    selection = int(input_string)
    ValueError: invalid literal for int with base 10:''
3. If the player enters any random number the program quits with an 'Index out of range error' - I couldn't find out where to put try: except:
Any help would be appreciated - Thanks!

A: As for your questions:

*

*You can accomplish that with t.cancel() (stop the timer and do not call the function) instead of t.join() (wait until the thread has finished; this will ALWAYS result in a timeout, of course)

*(and 3.) These are basically the same -- put the query message and all input handling into a while loop, and break out of it once you know that the input is valid

...

*As an extra, the "time over" message wasn't really doing anything useful (e.g. you could still enter a valid answer after the time over occurred. I "fixed" that in a brute force way by making the program exit if the timeout is hit. Instead of doing that, you can also use a global variable to store whether the timeout was hit or not and handle that in your input accordingly (make sure to make it threadsafe using e.g. a mutex).

In general, it might be easier to turn around the structure of the program -- let the main thread handle the timeout and verification of the input, let the thread only handle the input (this way, it's easy to kill the thread to stop the input from being handled).
Of course, using the select module, one could implement this even nicer without threads (have one pipe that gets written to by a thread/timer, and the standard input, then select both for reading and it will block until either user input or the timeout occurs).
And maybe someone will post a nice asyncio-based solution? ;)
Here's the modified solution (modifying only as little as possible to get it to work, one could refactor other parts to make it nicer in general):
import random
import threading
import os

def timeout():
    print("Time over\n#####################\n")
    # You can't use sys.exit() here, as this code is running in a thread
    # See also: https://stackoverflow.com/a/905224/1047040
    os._exit(0)

while True:
    list = []
    for i in range(5):
        list.append(random.randint(1000, 10000))

    t = threading.Timer(5, timeout)
    t.start()

    print(list)
    print('[ 1  ,  2  ,  3  ,  4  ,  5  ]')

    solution = sorted(list)[2]
    while True:
        try:
            print('please select the 3rd largest number in this row (1-5):')
            input_string = input()
            selection = int(input_string)
            chosen = list[selection - 1]
            # If we arrive here, the input was valid, break out of the loop
            break
        except Exception as e:
            # Tell the user that the input is wrong; feel free to remove "e"
            # from the print output
            print('Invalid input:', e)

    if solution == chosen:
        print("Your guess is correct\n")
    else:
        print("Your guess is wrong\n")

    # Make sure to cancel the thread, otherwise guessing correct or wrong
    # will block the CLI interface and still write "time out" at the end
    t.cancel()


text:
Q: pulling sql column names for a table Is there a way to write a query in sql that will return the column names for the table?
e.g. if table Foo had columns bar and baz, this query would return 2 rows with "bar" and "baz" in them.

A: one way that will work on SQL Server, PostgreSQL and MySQL (might work on others too, will not work on Oracle)
select * from information_schema.columns
where table_name = 'Foo'

A: Generally you can use the INFORMATION_SCHEMA tables for this. Not all databases implement them however. Which database are you using?

A: SHOW COLUMNS FROM Foo;