text:
Q: Get json data from multiple api pages into one main json output I'm trying to get the json data from every page on an API and put that into one big json output.
(Docs for API i'm using: https://docs.scoresaber.com/#/Leaderboards/get_api_leaderboards)
When doing the following API call:
https://scoresaber.com/api/leaderboards?qualified=true&withMetadata=true
i get the object metadata which has total and itemsPerPage
Example:
"metadata": {
    "total": 193,
    "page": 1,
    "itemsPerPage": 14
  }

So 193/14 means i get 14 pages.
This means i can iterate through all pages by doing a request for each page with this API call: https://scoresaber.com/api/leaderboards?qualified=true&page=2
until i get to &page=4
Each page will result this json (trimmed example):
{
  "leaderboards": [
    {
      "id": 466447,
      "songHash": "E527C82AF2DEC46A23F12D742035D76CCA875904",
      "songName": "Parasite",
      "songSubName": "(feat. Hatsune Miku)",
      "songAuthorName": "DECO*27",
      "levelAuthorName": "Alice",
      "difficulty": {
        "leaderboardId": 466447,
        "difficulty": 1,
        "gameMode": "SoloStandard",
        "difficultyRaw": "_Easy_SoloStandard"
      },
      "maxScore": 0,
      "createdDate": "2022-06-01T17:16:52.000Z",
      "rankedDate": null,
      "qualifiedDate": "2022-06-14T05:53:21.000Z",
      "lovedDate": null,
      "ranked": false,
      "qualified": true,
      "loved": false,
      "maxPP": -1,
      "stars": 0,
      "plays": 70,
      "dailyPlays": 0,
      "positiveModifiers": false,
      "playerScore": null,
      "coverImage": "https://cdn.scoresaber.com/covers/E527C82AF2DEC46A23F12D742035D76CCA875904.png",
      "difficulties": null
    },
  ],
  "metadata": {
    "total": 193,
    "page": 2,
    "itemsPerPage": 14
  }
}

So what i want is to loop through all the pages and have every item in leaderboards into one json.
This is what I've tried:
import requests
import math
import json

response = requests.get("https://scoresaber.com/api/leaderboards?qualified=true&withMetadata=true")

api = json.loads(response.text)
pages = math.ceil(api['metadata']['total'] / api['metadata']['itemsPerPage'])
api = {}
for page in range(1, pages+1):
    api.update(json.loads(requests.get(f"https://scoresaber.com/api/leaderboards?qualified=true&page={page}").text))
api = json.dumps(api, indent=4)

But that seems to only get the last page and just overwrite the dictionary (i'm also not sure if i need to declare api as a dict.
So I'm just not sure what is going wrong, if im declaring stuff wrongly, if im requesting the api wrongly, or if im putting stuff wrongly into the dict, etc.

A: If I understand you correctly you want to receive all data to one big list:
import json
import math
import requests

url1 = (
    "https://scoresaber.com/api/leaderboards?qualified=true&withMetadata=true"
)
url2 = "https://scoresaber.com/api/leaderboards?qualified=true&page={}"

api = requests.get(url1).json()
pages = math.ceil(api["metadata"]["total"] / api["metadata"]["itemsPerPage"])

all_data = []
for page in range(1, pages + 1):
    data = requests.get(url2.format(page)).json()
    all_data.extend(data["leaderboards"])

print(json.dumps(all_data, indent=4))

This will print all 193 items from all pages:
[
    {
        "id": 484864,
        "songHash": "80559A7A4AC0F62F27DAF1C59DF67F305250ADFF",
        "songName": "Phony",
        "songSubName": "feat. KAFU (Hoshimachi Suisei Cover)",
        "songAuthorName": "Tsumiki",
        "levelAuthorName": "Joshabi & Shad",

...


text:
Q: Obtain multiple coordinates from a function at a particular value I have a function of the type:
F[{x_,y_}] := x^2 + y^2

One can plot this function using Plot3D:
Plot3D[F[{x,y}], {x, -2, 2}, {y, -2, 2}]

If one plots the function, it is clear that F[{x,y}] = 6 at more than one set of coordinates.
How can I obtain all sets of coordinates for which F[{x,y}] = 6?
Thanks,
Stuart.

A: Perhaps not a good job but the closest i can get to:
plot = Reap[ContourPlot[F[{x, y}], {x, -3, 3}, {y, -3, 3},
EvaluationMonitor :> If[5.95 < F[{x, y}] < 6, Sow[{x, y, F[{x, y}]}],]]][[2,1]] //
#[[All, {1, 2}]] & //ListPlot[#, PlotStyle -> Red] &

Show[ContourPlot[F[{x, y}] == 6, {x, -3, 3}, {y, -3, 3}], plot]

A: Well there is a nice way to extract points:
mYcp = ContourPlot[x^2 + y^2 == 6, {x, -3, 3}, {y, -3, 3}]

Short[Cases[Normal@mYcp, Line[x_] :> x, Infinity], 20]

{{{-1.07143,-2.20209},{-1.1106,-2.18203},{-1.17857,-2.14721},{-1.18634,-2.14286},{-1.24885,-2.10599},{-1.28571,-2.08271},{-1.38018,-2.02304},{-1.47143,-1.95714},{-1.5,-1.93609},{-1.50433,-1.9329},{-1.50952,-1.92857},{-1.62121,-1.8355},{-1.71429,-1.7479},{-1.7316,-1.7316},{-1.7479,-1.71429},<<246>>,{-0.289216,-2.43207},{-0.321429,-2.42778},{-0.363553,-2.42216},{-0.383423,-2.41914},{-0.428571,-2.41111},{-0.473545,-2.40212},{-0.634454,-2.36555},{-0.642857,-2.36335},{-0.647783,-2.36207},{-0.663265,-2.35714},{-0.857143,-2.29252},{-0.961538,-2.25275},{-0.965438,-2.25115},{-0.968045,-2.25},{-1.07143,-2.20209}}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find all $\alpha$ such that the series converges Find all values of $\alpha$ such that series $$\sum^\infty_{n=1} \left( \frac{1}{n \cdot \sin(1/n)} - \cos\left(\frac{1}{n}\right) \right)^\alpha$$ converges.

I used Maclaurin for $\sin$ and $\cos$ and got:
$$a_n = \left( \frac{1}{1 - \dfrac{1}{3!n^2} + \ldots} - 1 + \frac{1}{2!n^2} - \frac{1}{4!n^4} + \ldots \right) ^ \alpha$$
Put it together in one fraction seems to be a hard thing to do.

A: HINT:
You are on the right track.  Note that
$$\frac{1}{1-\frac1{6n^2}+O\left(\frac1{n^4}\right)}=1+\frac1{6n^2}+O\left(\frac1{n^4}\right)$$
Hence, we see that
$$\frac{1}{n\sin(1/n)}-\cos(1/n)=\frac2{3n^2}+O\left(\frac1{n^4}\right)$$

A: Hint
$$n\sin(\frac{1}{n})=1-\frac{1}{6n^2}(1+\epsilon_1(n))$$
$$\frac{1}{n\sin(\frac{1}{n})}=1+\frac{1}{6n^2}(1+\epsilon_2(n))$$
$$\cos(\frac{1}{n})=1-\frac{1}{2n^2}(1+\epsilon_3(n))$$
thus, when $n\to +\infty$, the general term of your series $u_n$, satisfies
$$u_n \sim (\frac{2}{3n^2})^\alpha $$
and by the limit comparison test,
$\sum u_n$  converges $\iff \;
\alpha>\frac{1}{2}$.


text:
Q: Caching a large SQL query - best way of structuring? Let me give an example of my issue. Let's say I have a table called users and a table called payments. To calculate a user's total balance, I'd use a query to get all the payments after a certain date and then cache the result for a while.
However, I was wondering, due to the nature of this, would it be a good idea to have a column in the users table called balance and then when the cache expires, I use a different query to gather the payments but from a shorter time and then add this amount on to whatever is in the balance column?

A:
To calculate a user's total balance,

You can create an additional table that always contains the users current balance. If a new payment is added for the user, that column needs to be updated, too. Do a transaction so adding the payment and updating the total balance is aligned.
If you need this more differentiated, you can next to the user relation, keep a date column representing the interval you need to be able to do calculations for. E.g. the week number or month number to be able to give a view back in the past.
If you need more flexibility, you can after some time compress existing payments into a total value and store that into such a balance table that is user-related and keeps a date column.
You can then UNION it with the table of the payments that are "realtime" for the dates not yet compressed / condensed. Then use an aggregation function to SUM the total balance. This might give you the best of both worlds if you need to keep recent data with more detail you can move out of the data-store after some time, just keeping statistic values.

A: Generally with these kinds of "pre-calculated" values I find that the most pain free way is to store/update them on save of any model that concerns the data
So in short, update the total balance whenever a new payment is saved. That way you can guarantee that your database and your data will always be in sync
The pre-calculation can be either a mysql trigger or a background task with something like Gearman

But as your own question suggested if you want to do some kind of incremental roll-up of the balance, I would advice going by months or some fixed date range. This would work providing that you have no payment backdating or something like that, where payment could appear for an old month.
Start of the new month, run a payment aggregator, bam, you now only have to sum the monthly tables.
It all really depends on how much data you have to deal with. But again I stress, data consistency is a lot more valuable than speed, you can always buy more servers.


text:
Q: работа со стандартным потоком ввода require JS Не понимаю как подогнать задачу под форму сдачи
    function checkStr(str) {

    let a = str.split(' ');
    let first, second;
    let b = a[0].split('');
    let c = a[1].split('');
    if (b.length !== c.length)
        console.log(0);
    for (let i = 0; i < b.length; i++) {
        if (b[i] !== c[i]) {
            first = b[i];
            second = c[i];
            // console.log(`1 word ${first}`);
            // console.log(`2 word ${second}`);
        }
        for (let j = i; j < b.length; j++) {
            if ((first == b[j] && second != c[j]) ||
                (first != b[j] && second == c[j])) {
                console.log(0);
                return 0;
            }
        }
    }
    console.log(1);
}

// let str = 'абаб ааах';
checkStr('привет прикол');

Для работы со стандартным потоком ввода в JS используйте require('readline'), а для работы со стандартным потоком вывода - console.log(String(data)).
Пример ввода-вывода на JS:
    const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
rl.on('line', (line) => {
    // Введенная строка в переменной line, тут можно написать решение
    console.log(String(result));
    rl.close();
    return;
}).on('close', () => process.exit(0));

A: Надеюсь, поможет:
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

// Решение
function checkStr(str) {
    let a = str.split(' ');
    let first, second;
    let b = a[0].split('');
    let c = a[1].split('');
    if (b.length !== c.length)
        console.log(0);
    for (let i = 0; i < b.length; i++) {
        if (b[i] !== c[i]) {
            first = b[i];
            second = c[i];
            // console.log(`1 word ${first}`);
            // console.log(`2 word ${second}`);
        }
        for (let j = i; j < b.length; j++) {
            if ((first == b[j] && second != c[j]) ||
                (first != b[j] && second == c[j])) {
                console.log(0);
                return 0;
            }
        }
    }
    console.log(1);
}

// Ввод
rl.on('line', (line) => {
    checkStr(line)
    rl.close();
    return;
}).on('close', () => process.exit(0));


text:
Q: Clear UIButton with gradient title and cornerBorder How to add gradient to UIButton title, while the button background is clear, but corner boarder is gradient as well.
I found how to add gradient border here but have no clue how make gradient label. It would be great if label gradient would match border gradient color.
Maybe I can create this effect somehow with mask that is shaped like label?

A: Hi the easies way is to create a UIColor from patternImage like so:
let image = UIImage(named: "gradient.jpeg");
let color = UIColor(patternImage: image!);

Then just use the color where you need:
buttonAction.layer.borderWidth = 1;
buttonAction.layer.cornerRadius = 5;
buttonAction.layer.borderColor = color.cgColor;

buttonAction.setTitleColor(color, for: .normal);

Result:

for creating a gradient UIColor use this method: (you can add it to an UIColor extension)
func gradientColorFrom(color color1:UIColor, toColor color2:UIColor ,withSize size:CGSize) ->UIColor
{
  UIGraphicsBeginImageContextWithOptions(size, false, 0);
  let context = UIGraphicsGetCurrentContext();
  let colorspace = CGColorSpaceCreateDeviceRGB();

  let colors = [color1.cgColor, color2.cgColor] as CFArray;

  let gradient = CGGradient(colorsSpace: colorspace, colors: colors, locations: nil);
  context!.drawLinearGradient(gradient!, start: CGPoint(x:0, y:0), end: CGPoint(x:size.width, y:0), options: CGGradientDrawingOptions(rawValue: UInt32(0)));

  let image = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

  let finalCColor = UIColor(patternImage: image!);
  return finalCColor;

}

*

*for Horizontal gradient use CGPoint(x:size.width, y:0)

*for Vertical gradient use CGPoint(x:0, y:size.height)

A: While Constantin answer does work, title label gradient will not necessarily match border color :

So here's a my solution:
class GradientButton: UIButton {
    override func awakeFromNib() {

        layoutIfNeeded()

        let gradientBorder = CAGradientLayer()
        gradientBorder.frame =      bounds
        //Set gradient to be horizontal
        gradientBorder.startPoint = CGPoint(x: 0, y: 0.5)
        gradientBorder.endPoint =   CGPoint(x: 1, y: 0.5)
        gradientBorder.colors =    [UIColor.red.cgColor, UIColor.yellow.cgColor]

        let shape = CAShapeLayer()
        shape.lineWidth =     2
        shape.path =          UIBezierPath(rect: bounds).cgPath
        shape.strokeColor =   UIColor.black.cgColor
        shape.fillColor =     UIColor.clear.cgColor
        gradientBorder.mask = shape

        layer.addSublayer(gradientBorder)

        let gradient =        CAGradientLayer()
        gradient.frame =      bounds
        //Set gradient to be horizontal
        gradient.startPoint = CGPoint(x: 0, y: 0.5)
        gradient.endPoint =   CGPoint(x: 1, y: 0.5)
        gradient.colors =     [UIColor.red.cgColor, UIColor.yellow.cgColor]

        layer.insertSublayer(gradient, at: 0)

        let overlayView = UIView(frame: bounds)
        overlayView.isUserInteractionEnabled = false
        overlayView.layer.insertSublayer(gradient, at: 0)
        overlayView.mask = titleLabel

        addSubview(overlayView)
    }
}

And the result:

A: You can create gradient layer and add the same to UIButton
CAGradientLayer *gradient = [CAGradientLayer layer];
     gradient.frame = btn.bounds;
     gradient.colors = [NSArray arrayWithObjects:
                      (id)[[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:.6f] CGColor],
                      (id)[[UIColor colorWithRed:200.0f/255.0f green:200.0f/255.0f blue:200.0f/255.0f alpha:.4f] CGColor],
                      (id)[[UIColor colorWithRed:150.0f/255.0f green:150.0f/255.0f blue:150.0f/255.0f alpha:.4f] CGColor],
                      (id)[[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:.4f] CGColor],
                      (id)[[UIColor colorWithRed:50.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:.4f] CGColor],
                      (id)[[UIColor colorWithRed:5.0f/255.0f green:5.0f/255.0f blue:5.0f/255.0f alpha:.4f] CGColor],
                      nil];
    [btn.layer insertSublayer:gradient atIndex:0];

    CAGradientLayer *glossLayer = [CAGradientLayer layer];
    glossLayer.frame = btn.bounds;
    glossLayer.colors = [NSArray arrayWithObjects:
                     (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                     (id)[UIColor colorWithWhite:1.0f alpha:0.1f].CGColor,
                     (id)[UIColor colorWithWhite:0.75f alpha:0.0f].CGColor,
                     (id)[UIColor colorWithWhite:1.0f alpha:0.1f].CGColor,
                     nil];
    glossLayer.locations = [NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:0.0f],
                        [NSNumber numberWithFloat:0.5f],
                        [NSNumber numberWithFloat:0.5f],
                        [NSNumber numberWithFloat:1.0f],
                        nil];
     [btn.layer insertSublayer:glossLayer atIndex:0];

Hope it helps.

A: swift 4 set gradient layer for Button and set title for button
let gradient = CAGradientLayer()
        gradient.frame = CGRect(x: 0, y: 0, width: buttonSchedule.frame.width, height: 34)
        gradient.colors = [
            UIColor(red:0.89, green:0.02, blue:0.07, alpha:1).cgColor,
            UIColor(red:0.93, green:0.43, blue:0.1, alpha:1).cgColor ]
        gradient.locations = [0, 1]
        gradient.startPoint = CGPoint.zero
        gradient.endPoint = CGPoint(x: 1.02, y: 1)
        gradient.cornerRadius = 17
        buttonSchedule.layer.insertSublayer(gradient, below: buttonSchedule.titleLabel?.layer)
buttonSchedule.setTitle("Schedule", for: .normal)
        buttonSchedule.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 0)
        buttonSchedule.contentHorizontalAlignment = .left
        buttonSchedule.setTitleColor(UIColor.white, for: .normal)


text:
Q: Mixed effect conditional logistic regression error I am trying to run a conditional logistic regression with a random effect on matched data. Here is how my data is structured :
outcome<-c(1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0)
strata_id<-c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6)
tmax<-c(30.7,31.3,34.7,32.9,28.2,26.0,26.7,26.5,33.5,33.9,35.3,35.5,28.1,29.2,29.4,28.9,31.5,33.8,35.1,34.2,28.3,29.4,30.1,33.7)
cntry_code<-c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C")
data<-as.data.frame(cbind(outcome,strata_id,tmax,cntry_code))
data

  outcome strata_id tmax cntry_code
1        1         1 30.7          A
2        0         1 31.3          A
3        0         1 34.7          A
4        0         1 32.9          A
5        1         2 28.2          A
6        0         2   26          A
7        0         2 26.7          A
8        0         2 26.5          A
9        1         3 33.5          B
10       0         3 33.9          B
11       0         3 35.3          B
12       0         3 35.5          B
13       1         4 28.1          B
14       0         4 29.2          B
15       0         4 29.4          B
16       0         4 28.9          B
17       1         5 31.5          C
18       0         5 33.8          C
19       0         5 35.1          C
20       0         5 34.2          C
21       1         6 28.3          C
22       0         6 29.4          C
23       0         6 30.1          C
24       0         6 33.7          C

I want to match on strata_id (fixed effect) and include a random effect for the country that each person lives in. I am using the mclogit package in R and this is the model I specified :
model1<-mclogit(cbind(outcome, strata_id)~ns(tmax, df=3), random = ~1|cntry_code, data=data)

but I get the error:
Error in mclogit(cbind(outcome, strata_id) ~ ns(tmax, df = 3), random = ~1 |  :
 No predictor variable remains in random part of the model.
 Please reconsider your model specification.

I am not sure how to address this error. Should I be using a different method such as glmer or from the lme4 package?

A: The reason the model drops the random term and thus gives the error is because the random term, e.g., cntry_code, does not vary within strata. In other words, for each strata value, the cntry_code is constant.
From the creator of the mclogit package in R (Dr. Martin Elff):
"This is a basic feature of conditional logit: everything that is constant within the conditional logit strata cancels out when the ratio
$$
\frac{\exp(\boldsymbold{x}_i\boldsymbol{\beta})}
      {\sum_k\boldsymbold{x}_k\boldsymbol{\beta}}
$$

is created.
A random slope term should work and look something like this (insert with own data):
random = dependent variable | random term variable


text:
Q: Getting the URL before making the request on AngularJS $resource module I am consuming a REST api using Angular JS, using $resource module. I have to encode the URL using a private key and send the results of the encoding process on a header. I am trying to intercept the request and getting the requested URL, but I could not do that.
return $resource(url, {}, {
    get: { method: 'GET', headers: headers, transformRequest: function(data, headersGetter) {
        // Here "data" is undefined.  headersGetter() returns the headers.
        // I need the URL here
    }
});

Any help?

A: It sounds like what you want is an interceptor. Find the Interceptors section of the $http documentation. It would look something like this:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
        // optional method
        'request': function(config) {
            //modify headers in config based on url in config
            return config;
        },
    }
});

Then register the interceptor like this:
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
}]);


text:
Q: Spark 1.5.0 (PySpark) Case When Logic & Lag Window Function I am trying to use the Spark SQL functions 'WHEN / OTHERWISE' in a HiveContext, along with LAG in a Window, to create a DIFF Field for an ascending Numeric Count Field in some sequential minute data, that frequently resets to Zero. So I need to correct for the 'counts' resetting to zero.
So my Code is as follows:
window = Window.partitionBy("car","trip_id").orderBy("car","datetime")
df = df.withColumn('new_count', F.when(df.num_count >= F.lag(df.num_count),(df.num_count- F.lag(df.num_count))).otherwise(df.num_count.astype('long')).over(window))

My ERROR in Pyspark is SAYING:
: java.lang.UnsupportedOperationException: CASE WHEN ...<"variable names">...  is not supported in window operation

Would it be better to try to use "sqlContext.sql("Select CASE WHEN...lag(num_count) OVER...")?

A: Window should be applied to each window function individually. In this particular case you can simply extract expression like this:
num_count_lag = F.lag(df.num_count).over(window)

df.withColumn(
    'new_count',
    F.when(
        df.num_count >= num_count_lag,
        df.num_count - num_count_lag
    ).otherwise(df.num_count.astype('long'))
)


text:
Q: Combinatorics Gifts Question 1) How many ways can 7 identical gifts be distributed among 10 children if no child is allowed to get more
than 1 gift?
2) How many ways can 7 identical gifts be distributed among 10 children if children are allowed to get more
than 1 gift?
For problem 1, I was able to find an answer, but I am unsure if it is correct. The way I did this was:
Number of ways of dividing n identical gifts to r children is:
n+r-1 choose r-1, where n=7 and r=3, then 16C9 or
16!/(7!*9!) ways.
For problem 2, I am unsure of where to start?

A: For 1, you just choose the seven children who will get gifts, so $10\choose 7$ ways
Your answer to 1 is the correct approach for 2


text:
Q: Why positive lookahead is working but negative lookahead doesn't? First of all, regex needs to be working for both the python and PCRE(PHP). I'm trying to ignore if a regex pattern is followed by the letter 'x' to distinguish dimensions from strings like "number/number" in the given example below:
dummy word 222/2334; Ø14 x Ø6,33/523,23 x 2311 mm

From here, I'm trying to extract 222/2334 but not the 6,33/523,23 since that part is actually part of dimensions. So far I came up with this regex
((\d*(?:,?\.?)\d*(?:,?\.?))\s?\/\s?(\d*(?:,?\.?)\d*(?:,?\.?)))(?=\s?x)

which can extract what I don't want it to extract and it looks like this. If I change the positive lookahead to negative it captures both of them except the last '3' from 6,33/523,23. It looks like this. How can I only capture 222/2334? What am I doing wrong here?
Desired output:
222/2334

What I got
222/2334 6,33/523,2

A: You may use this simplified regex with negative lookahead:
((\d*(?:,?\.?)\d*(?:,?\.?))\s?\/\s?(\d*(?:,?\.?)\d*(?:,?\.?)))\b(?![.,]?\d|\s?x)

Updated RegEx Demo

*

*It is important to use a word boundary in the end to avoid matching partial numbers (the reason of your regex matching till a digit before)

*Also include [.,]?\d in negative lookahead condition so that match doesn't end at position before last comma.

This shorter (and more efficient) regex may also work for OP:
(\d+(?:[,.]\d+)*)\s*\/\s*(\d+(?:[,.]\d+)*)\b(?![.,]?\d|\s?x)

RegEx Demo 2

A: There are two easy options.
The first option is ugly and long, but basically negates a positive match on the string that is followed by x, then matches the patterns without it.
(?!PATTERN(?=x))PATTERN
See regex in use here
(?!\d+(?:[,.]\d+)?\s?\/\s?\d+(?:[,.]\d+)?(?=\s?x))(\d+(?:[,.]\d+)?)\s?\/\s?(\d+(?:[,.]\d+)?)

The second option uses possessive quantifiers, but you'll have to use the regex module instead of re in python.
See regex in use here
(\d+(?:[,.]\d+)?+)\s?\/\s?(\d+(?:[,.]\d+)?+)(?!\s?x)

Additionally, I changed your subpattern to \d+(?:[,.]\d+)?. This will match one or more digits, then optionally match . or , followed by one or more digits.


text:
Q: Uniform Convergence of series expansion of $\frac{\log(1+x)}{x}$ We know that the series expansion of $\frac{\log(1+x)}{x}$ is
$$\frac{\log(1+x)}{x}=1-\frac{x}{2}+\frac{x^2}{3}-\frac{x^3}{4}....$$
It is also known that the value of dilogarithm at 1 is
$$\int_{-1}^{1} \frac{\log(1+x)}{x}=2\sum_{k=1}^{\infty}\frac{1}{(2k+1)^2}=\frac{3}{2}\zeta(2)=\frac{3}{2}Li_2(1)$$
For this to be true we must show that the RHS of the first equation that is $1-\frac{x}{2}+\frac{x^2}{3}-\frac{x^3}{4}....$ is termwise integrable. To prove that this series is termwise integral we must show that it's uniformly convergent in $(-1,1)$. Although it is simple to prove that the series converges by the ratio test.
How to show that $1-\frac{x}{2}+\frac{x^2}{3}-\frac{x^3}{4}....$ is uniformly convergent in $(-1,1)$?

A: For $x \in [-1+\delta,1-\delta]$ where $0 < \delta < 1$, we have
$$\left|(-1)^k \frac{x^k}{k+1}\right|\leqslant \frac{(1-\delta)^k}{k+1} \leqslant (1-\delta)^k$$
As the geometric series $\sum_{k \geqslant 0} (1-\delta)^k$ converges, it follows by the Weierstrass M-test that we have uniform convergence on $[-1+\delta,1+\delta]$ of the series
$$\frac{\log (1+x)}{x} = \sum_{k=0}^\infty(-1)^k \frac{x^k}{k+1}$$
Now the series may be integrated termwise over $[-1+\delta,1-\delta]$ to obtain
$$\begin{align} \int_{-1+\delta}^{1-\delta}\frac{\log(1+x)}{x} \, dx &= \sum_{k=0}^\infty (-1)^k \frac{(1-\delta)^{k+1} - (-1+\delta)^{k+1}}{(k+1)^2}\\ &= \sum_{k=0}^\infty (-1)^k \frac{(1-\delta)^{k+1} - (-1)^{k+1}(1-\delta)^{k+1}}{(k+1)^2} \\ &= \sum_{k=0}^\infty \frac{(1-\delta)^{k+1} + (-1)^{k}(1-\delta)^{k+1}}{(k+1)^2}\\&= 2\sum_{j=0}^\infty \frac{(1-\delta)^{2j+1}
}{(2j+1)^2}\end{align}$$
The series on the RHS is uniformly convergent for $\delta \in [0,1]$, and, consequently we may interchange the limit as $\delta \to 0+$ with the sum to obtain
$$ \int_{-1}^{1}\frac{\log(1+x)}{x} \, dx =  \lim_{\delta \to 0+}\int_{-1+\delta}^{1-\delta}\frac{\log(1+x)}{x} \, dx  = 2\sum_{k=0}^\infty \frac{1
}{(2j+1)^2}$$


text:
Q: awk pattern to match an XML PI at the start of a line I have an XML document containing a number of XML Processing Instructions which are of the form:
<?cpdoc something?>

I am trying to match them in awk with the pattern
/^\<\?cpdoc/

but it's not returning anything. If I remove the ^ anchor, it works (but I have other similar PIs which don't start a line which I don't want matched).
It looks as if it's being confused by the \<\? but why is it ignoring the line-start anchor?

A: Don't parse XML with regex, use a proper XML/HTML parser.
theory :
According to the compiling theory, XML can't be parsed using regex based on finite state machine. Due to hierarchical construction of XML you need to use a pushdown automaton and manipulate LALR grammar using tool like YACC.
realLife©®™ everyday tool in a shell :
You can use one of the following :
xmllint
xmlstarlet
saxon-lint (my own project)

Check: Using regular expressions with HTML tags

Example using xpath :
xmllint --xpath '//processing-instruction()' file.xml

A: Solution by OP and explanation by Ed Morton.
It works if the less-than is not escaped, as otherwise it's a word boundary. So instead of:
\<\?

I should use literal:
<\?

This is because we can't just go escaping any character and hoping for the best, we have to know which characters are metacharacters and then escape them if we want them treated as literal.


text:
Q: Issue on Jquery Background Image Fade In and Out I am trying to change a background image of a html5 canvas from dropdown select by using following code
$('select').on('change', function() {
    if (this.value ==1){
      $('#canvas').css('background-image').fadeOut();
      $('#canvas').css({'background': 'url(http://localhost/MapBox/img/cal_NAs.png) no-repeat top right, url(http://localhost/MapBox/img/bg_sh.png) no-repeat top right','background-color' : 'grey'}).fadeIn();
    }
})

but this is not doing the job and I am getting this error on console : Uncaught TypeError: undefined is not a function.
can you please let me know what I am doing wrong?

A: You're getting the error because
$('#canvas').css('background-image')

returns the value of the 'background-image' CSS property of the element, which is a string. Strings don't have a method called fadeOut so when you try to call fadeOut() it fails.
However, you have a more fundamental issue - fadeIn and fadeOut apply to elements, not styles of elements.
Check out this question for examples of fading backgrounds

A: Fading background images is not a trivial thing.
You should probably look into a solution like this: Change the body background image with fade effect in jquery


text:
Q: Global queue accessible from bottle API in python So basically I have two threads, one is running the bottle api, which has a post call. I want to be able to post to this api, and then the api will push some data from the post to the global queue, and the other thread catches this and does something with it. How do I make this queue object accessible from the post call?
def publisher(q):
    while 1:
       q.get()
       #do stuff

def main():
    q = Queue(maxsize=0)
    b = Process(target=run, kwargs=dict(host='localhost', port=1313, debug=True))
    s = Process(target=publisher, args=(q,)
    b.start()
    s.start()

@post('/process')
def my_process():
  req_obj = json.loads(request.body.read())
  q.put(req_obj)

A: EDIT: My "short" solution won't work as-is because of the multiple processes attempting to share the queue object. See comments for more info.
Short answer: Move q to global scope. (No other changes required.)
q = Queue(maxsize=0)

def publisher(q):
    while 1:
       q.get()
       #do stuff

def main():
    b = Process(target=run, kwargs=dict(host='localhost', port=1313, debug=True))
    s = Process(target=publisher, args=(q,)
    b.start()
    s.start()

@post('/process')
def my_process():
  req_obj = json.loads(request.body.read())
  q.put(req_obj)

Long answer: Use a separate task queue as @DanielRoseman suggests.


text:
Q: Unable to understand Javax Clip setMicrosecondPosition. What am I missing? I am adding a minute (60*1000*1000 microseconds) to the audio clip and starting it and I achieve the desired result only the first time i.e, I'm reaching the correct point in audio file. Next time I call getMicrosecondPosition on the Clip object, I get the microsecond position as if I didn't add anything. Have attached the sample snippet and output for this behavior. Can't quite understand what I'm doing wrong.
clip.stop();
currentPlaybackTime=clip.getMicrosecondPosition()+60L*1000*1000;
System.out.println("Playing from "+currentPlaybackTime+" ms i.e "+currentPlaybackTime/1000000.0+" seconds");
clip.setMicrosecondPosition((currentPlaybackTime));
System.out.println("Verifying: currentPlaybackTime is "+clip.getMicrosecondPosition());
clip.start();
System.out.println("Verifying 2: currentPlaybackTime is "+clip.getMicrosecondPosition());

Output is
Playing from 63326000 ms i.e 63.326 seconds [Note:this is seeking to correct point in audio file!]
Verifying: currentPlaybackTime is 3326000 [Why not here?]
Verifying 2: currentPlaybackTime is 3326000 [and here?]
Play/Pause Clicked
Pausing at 5120000 ms 5.12 seconds


text:
Q: CloudFront Cache HTML Can Amazon CloudFront be used to cache HTML pages, and no just image, css files, etc?
If not, is there a comparable service out there that does this?  I.E., I overlay the service on a domain, and literally it only queries that site again, when the cached page has expired.
I looked at CloudFlare as well and they don't yet do this.

A: Yes, you can serve HTML through Cloudfront.
The main disadvantage is when you need to update the HTML as you are unable to version HTML for SEO reasons.
So by setting a cache into cloudfront of 1 hour for example it means that the page is kept into cloudfront for maximum 1 hour, and only after cloudfront will retake the HTML from your source and update it.
You can use invalidations on cloudfront to speed up the process but you need a full list of your html pages for a fast copy and paste into aws for invalidating.
Of course all this work for fixed webpages, that do not change for user.
You can apply it even to ASP / PHP only if the generated content is fixed between all users.
So you have the PHP into your origin , and cloudfront save the HTML of it.
My English is not the best one, so i hope i clear somethink...

A: Yes, you can serve HTML through CloudFront as long as you don't mind every user getting the same content until the cache expires.
I can't imagine a CDN that would not support this.   They might not advertise it since many web sites are dynamic and can't be cached, but if your site is basically static, then any CDN should work.


text:
Q: write output with delimiter in python I want to save my output as csv file with custom name and delimiter.
I tried this code but now works for me.
out = open('out.csv', 'w')
for row in l:
for column in row:
    out.write('%d;' % column)
out.write('\n')
out.close()

Here is my data
100A7E54111FB143
100D11CF822BBBDB
1014120EE9CCB1E0
10276825CD5B4A26
10364F56076B46B7
103D1DDAD3064A66
103F4F66EEB54308
104310B0280E4F20
104E80752424B1C3
106BE9DBB186BEC5
10756F745D8A4123
107966C82D8BAD8

I want to save like this
input.csv
input_id data
number   107966C82D8BAD8 | 10756F745D8A4123 | 106BE9DBB186BEC5

The delmiter would be '|'.The data is in dtype:object
Any help will be appreciated.

A: Use a writer for the CSV object instead:
import csv

with open('out.csv', 'w', newline='') as out:
    spamwriter = csv.writer(out, delimiter='|')
    spamwriter.writerow(column)

I have omitted your for loop

A: One simple way is to use print of python 3.x, If you are using python 2.x then import print from future
from __future__ import print_function   #Needed in python 2.x

print(value, ..., sep=' ', end='\n', file=sys.stdout)

A: You can use this snippet of code as an example. I did something similar in my program, creating a text file with a comma separator, no csv module involved. Not sure about newlines. I just used it for one line in my case...
        cachef_h = [a,b,c,d]
        f = open('cachef_h.txt', 'x')
           f.write(cachef_h[0])
           for column_headers in cachef_h[1:]:
           f.write(',' + column_headers)


text:
Q: Bulk log download from GAE I'd like to download all my logs to a file with "appcfg.py".
I don't use app.yaml, but I wrote a very simple one:
"application: myAppId
version: 1
runtime: java"

I use this command:
python appcfg.py --append request_logs "app.yaml's path"  logs.txt

And I always get:
Value 'java' for key runtime does not match expression '^python$' in
"app.yaml's path", line 3, column 10

What should I do to download all my logs?

A: It seems that you are using the Java runtime, so take a look at:

http://code.google.com/appengine/docs/java/tools/uploadinganapp.html#Downloading_Logs

And the arguments can be found here:

http://code.google.com/appengine/docs/java/tools/uploadinganapp.html#Command_Line_Arguments

A: Just for posterity, if you are using Eclipse, the Java appcfg.sh script can be found inside of the Eclipse plugins directory where the GAE SDK gets installed.  On my Mac this is in:
/Applications/eclipse/plugins/com.google.appengine.eclipse.sdkbundle_1.7.4/appengine-java-sdk-1.7.4/bin/appcfg.sh

I chdir'd inside my GAE project folder that is running in Eclipse and then ran it like:
sh /Applications/Eclipse/.../bin/appcfg.sh request_logs war log_output.txt

The war is the directory of your war files inside your project.  You should see:
> ls war/WEB-INF/lib
appengine-api-1.0-sdk-1.6.6.jar
appengine-jsr107cache-1.6.6.jar
...

The script runs the jar file which should prompt you for your email and password (I don't know how/if they are protecting it).  If you are using the two-factor auth configured then you'll need to utilize the --oauth2 parameter.  This requires (I guess) a 1.7.X version of the SDK because it wasn't available in 1.6.6.  Of course their docs don't talk about versions.


text:
Q: PHP merge 2 Json into 1 I have 2 JSON files that I would like to parse, and merge into one object and output as a single JSON.
but I can't figure out how to do and get the correct result, every time i try always get a single result like this :
[
    {
        "Title": "Some title for your blog",
        "url": "\/post.php?id=1",
        "image": "https:\/\/example.com\/images\/small\/1.jpg"
    }
]

what i need is to call all the 2 json data to 1 json like this one :
[
    {
        "Title": "second title for your blog",
        "url": "\/post.php?id=2",
        "image": "https:\/\/example.com\/images\/small\/2.jpg"
    }

    {
        "Title": "second title for your blog",
        "url": "\/post.php?id=2",
        "image": "https:\/\/example.com\/images\/small\/2.jpg"
    }
    {
        "Title": "third title for your blog",
        "url": "\/post.php?id=3",
        "image": "https:\/\/example.com\/images\/small\/3.jpg"
    }

    and so on... till the end of loop
]

Here is my code :
$requestUrl="http://example.com/json1.php";
$requestUrl1="http://example.com/json2.php";

$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);

$array1 = json_decode($data);
$array2 = json_decode($data1);

$wholedata= [];
$i=0;
foreach ($array1 as $array1) {
    $item['Title'] = $array1->title;
    $item['url'] = $array1->url;
}
foreach ($array2 as $array2) {
    $item['image'] = $array2->image;
}

$wholedata[] = $item;
            $i++;

$json = json_encode($wholedata, JSON_PRETTY_PRINT);

header('Access-Control-Allow-Origin: *');
header('Content-type: Application/JSON');

echo $json;

Here's the json data :
Json 1
[
    {
        "title": "first title for your blog",
        "url": "/post.php?id=1"
    },
    {
        "title": "Second title for your blog",
        "url": "/post.php?id=2"
    },
    {
        "title": "Third title for your blog",
        "url": "/post.php?id=3"
    },
    {
        "title": "Fourth title for your blog",
        "url": "/post.php?id=4"
    },
    {
        "title": "Fifth title for your blog",
        "url": "/post.php?id=5"
    }
]

Json 2 :
[
    {
        "image": "https://example.com/images/small/1.jpg"
    },
    {
        "image": "https://example.com/images/small/2.jpg"
    },
    {
        "image": "https://example.com/images/small/3.jpg"
    },
    {
        "image": "https://example.com/images/small/4.jpg"
    },
    {
        "image": "https://example.com/images/small/5.jpg"
    }
]

A: To do this with objects (as you are currently using), you can use the index of the first array to get the data from the second array.  Then build the output in one go with the components from both objects and add them to your output...
$array1 = json_decode($data);
$array2 = json_decode($data1);

$wholedata= [];
foreach ($array1 as $key => $itemData) {
    $wholedata[] = ['Title' => $itemData->title,
        'url' => $itemData->url,
        'image' => $array2[$key]->image];
}

$json = json_encode($wholedata, JSON_PRETTY_PRINT);

A: Try deocoding the json in an array and then merge them. Check out the official PHP documentation
array-merge - Merges two array
json_decode - Converts json into an array


text:
Q: How do I make my disk unmap pending unreadable sectors I have a disk with some pending unreadable sectors, according to smartd. What would be the easiest way to make the disk remap them and stop smartd from complaining?
Today, I get two of these every hour:

Sep 10 23:15:35 hylton smartd[3353]: Device: /dev/sdc, 1 Currently unreadable (pending) sectors

The system is an x86 system running Ubuntu Linux 9.10 (jaunty). The disk is part of an LVM group. This is how smartctl identifies the disk:

Model Family:     Western Digital Caviar Second Generation Serial ATA family
Device Model:     WDC WD5000AAKS-00TMA0
Serial Number:    WD-WCAPW4207483
Firmware Version: 12.01C01
User Capacity:    500,107,862,016 bytes

A: *

*Backup your data

*Remove this device from the LVM group

*dd if=/dev/zero of=/dev/sdc bs=4k -- this will erase all data on /dev/sdc

*Include it again into the LVM group

*Restore your backup

A: A pending unreadable sector is one that returned a read error and which the drive has marked for remapping at the first possible opportunity. However, it can't do the remapping until one of two things happens:

*

*The sector is reread successfully

*The sector is rewritten

Until then, the sector remains pending. So you have two corresponding ways to deal with this:

*

*Keep trying to reread the sector until you succeed

*Overwrite that sector with new data

Obviously, (1) is non-destructive, so you should probably try it first, although keep in mind that if the drive is starting to fail in a serious way then continual reading from a bad area is likely to make it fail much more quickly. If you have a lot of pending sectors and other errors, and you care about the data on the drive, I recommend taking it out of service and using the excellent tool ddrescue to recover as much data as possible. Then discard the drive.
If the sector in question contains data you don't care about, or can restore from a backup, then overwriting it is probably the quickest and simplest solution. You can then view the reallocated and pending counts for the drive to make sure the sector was taken care of.
How do you find out what the sector corresponds to in the filesystem? I found an excellent article on the smartmontools web site, here, although it's fairly technical and is specific to ext2/3/4 and reiser file systems.
A simpler approach, which I used on one of my own (Mac) drives, is to use find / -xdev -type f -print0 | xargs -0 ... to read every file on the system. Make a note of the pending count before running this. If the sector is inside a file, you will get an error message from the tool you used to read the files (eg md5sum) showing you the path to it. You can then focus your attentions on re-reading just this file until it reads successfully. Often this will solve the problem, if it's an infrequently-used file which just needed to be reread a few times. If the error goes away, or you don't encounter any errors in reading all the files, check the pending count to see if it's decreased. If it has, the problem was solved by reading.
If the file cannot be read successfully after multiple tries (eg 20) then you need to overwrite the file, or the block within the file, to allow the drive to reallocate the sector. You can use ddrescue on the file (rather than the partition) to overwrite just the one sector, by copying to a temporary file and then copying back again. Note that just removing the file at this point is a bad idea, because the bad sector will go into the free list where it will be harder to find. Completely overwriting it is bad too, because again the sectors will go into the free list. You need to rewrite the existing blocks. The notrunc option of dd is one way to do this.
If you encounter no errors, and the pending count did not decrease, then the sector must be in the freelist or in part of the filesystem infrastructure (eg an inode table). You can try filling up all the free space with cat /dev/zero >tempfile, and then check the pending count. If it goes down, the problem was in the free list and has now gone away.
If the sector is in the infrastructure, you have a more serious problem, and you will probably encounter errors just walking the directory tree. In this situation, I think the only sensible solution is to reformat the drive, optionally using ddrescue to recover data if necessary.
Keep a very close eye on the drive. Sector reallocation is a very good canary in the coal mine, potentially giving you early warning of a drive that is failing. By taking early action you can prevent a later catastrophic and very painful landslide. I'm not suggesting that a few sector reallocations are an indication that you should discard the drive. All modern drives need to do some reallocation. However, if the drive isn't very old (< 1 yr) or you are getting frequent new reallocations (> 1/month) then I recommend you replace it asap.
I don't have empirical evidence to prove it, but my experience suggests that disk problems can be reduced by reading the whole disk once in a while, either by a dd of the raw disk or by reading every file using find. Almost all the disk problems I've experienced in the past several years have cropped up first in rarely-used files, or on machines that are not used much. This makes sense heuristically, too, in that if a sector is being reread frequently the drive has a chance to reallocate it when it first detects a minor problem with that sector rather than waiting until the sector is completely unreadable. The drive is powerless to do anything with a sector unless the host accesses it somehow, either by reading or writing it or by conducting one of the SMART tests.
I'd like to experiment with the idea of a nightly or weekly cron job that reads the whole disk. Currently I'm using a "poor man's RAID" in which I have a second hard drive in the machine and I back up the main disk to it every night. In some ways, this is actually better than RAID mirroring, because if I goof and delete a file by mistake I can get yesterday's version immediately from the backup disk. On the other hand, I believe a hardware RAID controller does a lot of good work in the background to monitor, report and fix disk problems as they emerge. My current backup script uses rsync to avoid copying data that hasn't changed, but in view of the need to reread all sectors maybe it would be better to copy everything, or to have a separate script that reads the entire raw disk every week.

A: Use Data Lifeguard Diagnostic for DOS (bootable CD) software available from Western Digital site


text:
Q: Relationship between C11 atomics and sequence points I basically have the following code snippet:
size_t counter = atomic_fetch_sub_explicit(&atomicCounter, 1, memory_order_release);
if (counter - 1 == 0
    && atomic_load_explicit(&anotherAtomicCounter, 1, memory_order_relaxed) == 0 {
      //Some code
}

For correctness, it is important that the atomic load of anotherAtomicCounter occurs after the fetch-and-sub (FAS) of atomicCounter. With the given memory orders, this would normally not be guaranteed and the load could happen before the FAS. However, I was wondering how sequence points have an affect on this particular code. The standard mentions that

If evaluation A is sequenced before evaluation B, then evaluation of A will be complete before evaluation of B begins.

Combined with rule number 2

There is a sequence point after evaluation of the first (left) operand and before evaluation of the second (right) operand of the following binary operators: && (logical AND), || (logical OR), and , (comma).

this means that the atomic load must happen after the comparison but the comparison can only be completed once the result of the FAS is known.
My question is whether these rules guarantee that the atomic load always happens after the FAS, even when using more relaxed memory orders?
Thanks in advance!

A: To answer the question in your title, there is no real relationship between atomics and sequence points.
The code as written does guarantee that the compiler must execute the atomic_fetch_sub before the atomic_load. But these functions are (in C's memory model) simply requests to the platform to perform certain actions on certain pieces of memory. Their effects, when they become visible to who, are specified by the memory model, and the ordering parameters. Thus even in the case when you know request A comes before request B, that does not mean the effects of request A are resolved before request B, unless you explicitly specify it to be.

A: I would say there is a relationship, but it's indirect.
Sequence points are how the language defines the sequenced before partial ordering on evaluations (C17 5.1.2.3), which is basically what you might generically call "program order".  It's the order that operations naively appear to be executed in, and for a single-threaded program, it completely determines how those operations interact with each other.  It promises, for instance, that if you call foo() && bar(), that bar will see all the updates to global variables that were made by foo; the evaluation of foo() will be complete before the evaluation of bar() begins.
Now the whole point of memory ordering is that the order in which loads and stores are seen by other threads does not necessarily agree with program order.  If you write
res = atomic_load_explicit(&a, memory_order_relaxed) || atomic_load_explicit(&b, memory_order_relaxed);

then the load of a is sequenced before the load of b, thanks to the sequence point provided by ||.  But because the memory order is relaxed, that is no guarantee that other threads see those operations in the same order.  If we previously had a == 0 and b == 1, and another thread does atomic_store(&a, 1); atomic_store(&b, 0); (with seq_cst order, let's say) then it is entirely possible that res ends up with the value 0.
That's the same as the situation with your example code.  You have a sequence point between the fetch_sub and the load.  (Actually two of them: one at the end of the full expression that initializes counter, and the other at the && which you pointed out.)  So the fetch_sub is most definitely sequenced before the load.  But your memory ordering isn't strong enough to promise that inter-thread visibility matches sequencing.
However, memory barriers can give you more certainty, and what they do is to ensure that, to some specified extent, the order of visibility to outside observers does agree with program order.  If you write
res = atomic_load_explicit(&a, memory_order_seq_cst) || atomic_load_explicit(&b, memory_order_seq_cst);

then the sequence point again guarantees that the load of a is sequenced before the load of b, and now the seq_cst guarantees that other threads see those operations in that order too.  Now res will always be set to 1 if another thread does atomic_store(&a, 1); atomic_store(&b, 0);.
But memory barriers only impose, at best, as much ordering as the sequencing already provided.  If you instead did
res = atomic_load_explicit(&a, memory_order_seq_cst) + atomic_load_explicit(&b, memory_order_seq_cst);

now the barriers do not help you.  There is no sequence point between the two loads, and therefore no guarantees whatsoever about the order in which they are even evaluated, much less about the order in which they become visible.
Formally, the sequenced before relation is used in defining the happens before relation of 5.1.2.4, which is the main tool in determining how loads and stores from different threads affect each other, and in particular, in determining when they do and don't cause data races.


text:
Q: Ошибка при удалении объекта У меня есть RecyclerView в который поступают данные из phpMyAdmin, я хочу сделать чтобы у каждого элемента была кнопка - "удалить". Для этого я написал такой вот код в моём Adapter.
holder.delete.setOnClickListener(view -> {
            int position = holder.getAdapterPosition();

            String url = "DELETE.php";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    response -> Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show(),
                    error -> Log.e("AAAAAAAAA", String.valueOf(error)) ) {
                @Override
                public Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();

                    params.put("position", models.get(position).getPosition());

                    return params;
                }
            };

            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(stringRequest);

            models.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, models.size());
        });

Но при удалении последнего объекта появляется ошибка
NetworkDispatcher.processRequest: Unhandled exception java.lang.IndexOutOfBoundsException: Index: 4, Size: 4

Позже я заметил, что при удалении предпоследнего объекта удаляется последний и так происходит со всеми объектами в списке, удаляется на одну позицию выше, то есть я удаляю объект 4 а удаляется объект 5.
В логах ругается на вот эту строку params.put("position", models.get(position).getPosition());
В интернете я узнал, что прописав getAdapterPosition(), проблема должна уйти, но это не сработало, как это исправить?

A: Ваша проблема в том, что запрос асинхронный - он выполняется в другом потоке в другое время.
Это значит что нет никакой гарантии, что методы StringRequest-а и колбеков выполнятся раньше чем код, следующий по тексту после их обявления. Это и происходит - удаление объекта из модели происходит раньше, чем попытка его оттуда взять.
Что можно сделать:

*

*получить позицию за пределами тела запроса

holder.delete.setOnClickListener(view -> {
            int position = holder.getAdapterPosition();
            String serverPosition = models.get(position).getPosition();
            String url = "DELETE.php";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    response -> Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show(),
                    error -> Log.e("AAAAAAAAA", String.valueOf(error)) ) {
                @Override
                public Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();

                    params.put("position", serverPosition);

                    return params;
                }
            };

*

*перенести удаление объекта и обновление адаптера в колбек. Думаю так будет логичнее - если запрос отвалился и объект на сервере не удалён, то и локально его удалять не следует

holder.delete.setOnClickListener(view -> {
            int position = holder.getAdapterPosition();

            String url = "DELETE.php";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    response -> {
                        Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();

                        models.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, models.size());
                    },
                    error -> Log.e("AAAAAAAAA", String.valueOf(error)) ) {
                @Override
                public Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();

                    params.put("position", models.get(position).getPosition());

                    return params;
                }
            };

            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(stringRequest);
        });


text:
Q: Significance of EXTRA_LEVEL in Android BatteryManager class What does the value of EXTRA_LEVEL for the BatteryManager class in Android signify? I am trying to understand exactly what does a change of 1% in the level signify. For example for the Galaxy Nexus battery capacity is 1750 mAh. Does that mean, that a change of 1% would signify the flow of 17.5 mAh of electric charge?

A:
What does the value of EXTRA_LEVEL for the BatteryManager class in Android signify?

Quoting the documentation: "Extra for ACTION_BATTERY_CHANGED: integer field containing the current battery level, from 0 to EXTRA_SCALE."

Does that mean, that a change of 1% would signify the flow of 17.5 mAh of electric charge?

Not precisely, though it may be close. Batteries do not discharge linearly, for example. Device manufacturers are concerned with ensuring that the reported level is reasonably accurate in terms of indicating how much charge is available. They are not necessarily concerned with maintaining accuracy with respect to a battery capacity printed on a label on the side of the battery.


text:
Q: Is it just me or is the ~/Sites folder gone in Lion? It appears that the ~/Sites directory no longer exists in OS X Lion. I preferred working on sites there than in /Library/WebServer/Documents. Is there any way to change it back, or set it up so that I can work on sites in ~/Sites and have the files automatically moved to /Library/WebServer/Documents?

A: You can link them together with a Symlink:

cd ~
ln -s /Library/WebServer/Documents Sites

This will make ~/Sites behave as a alias of /Library/WebServer/Documents on the filesystem level, so it should work for all applications that you use.
The ideal way to fix this would be to fix the configuration for the webserver to support ~/Sites for each user again, but if you're the only user using the system, this method described here should work.

A: Just turning on "Web Sharing" doesn't add the Sites folder. You have to also click the "Create Personal Website Folder" to the right.

A: If you enable Web Sharing in System Preferences, you now have the option to create a Personal Website Folder which essentially creates a ~/Sites directory.


text:
Q: USB c++ development environment I need to set up a USB with a the necessary programs to have a portable development environment. I use 64bit Windows 7 at home and 32bit Windows XP at work, where I will use this the most.
How would one go about creating one of these? I mostly do game programming so I have to include libraries in this.
I'd prefer to use the command line for compiling instead of putting a huge IDE on the drive. My computer at works isn't top of the line.
So far, I've only found what editor I would use. Notepad++.
Other than that, I got next to nothing.

A: Take a look at this, it seems to be exactly what you're looking for:
http://code.google.com/p/pocketcpp/
As for the libraries, you could compress them on the USB device if space is really tight and decompress on the target computer. It all depends on how big your device is in terms of capacity.


text:
Q: Presto hive connector S3 access denied I have some hive external tables on my S3 buckets. To access the hive external tables from presto, I made presto hive catalogs for each S3 buckets as they have different aws_access_key and aws_secret_key under ${PRESTO_HOME}/etc/catalog.
hive_A.properties for s3 bucket A
connector.name=hive-hadoop2
hive.s3.use-instance-credentials=false
hive.metastore.uri=thrift://namenode:9083
hive.s3.aws-access-key=xxxxxxxxx1
hive.s3.aws-secret-key=xxxxxxxxx1
hive.non-managed-table-writes-enabled=true
hive.allow-drop-table=true

hive_B.properties for s3 bucket B
connector.name=hive-hadoop2
hive.s3.use-instance-credentials=false
hive.metastore.uri=thrift://namenode:9083
hive.s3.aws-access-key=yyyyyyyyy2
hive.s3.aws-secret-key=yyyyyyyyy2
hive.non-managed-table-writes-enabled=true
hive.allow-drop-table=true

After Presto has launched, I sent a presto query to one of the external tables in s3 bucket A using hive_B.properties. So presto definitely gave me an access denied error like this.
com.facebook.presto.spi.PrestoException: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: FB04E851EDD5E8E3; S3 Extended Request ID: HbIz8TKv7rZ11fVOA+9Hw/ikuRY6635I/fZ1tieCiYs9EWa56kLUZhOGacpvFYfZzWzIG09g2XQ=)
    at com.facebook.presto.hive.BackgroundHiveSplitLoader$HiveSplitLoaderTask.process(BackgroundHiveSplitLoader.java:194)
    at com.facebook.presto.hive.util.ResumableTasks.safeProcessTask(ResumableTasks.java:47)
    at com.facebook.presto.hive.util.ResumableTasks.access$000(ResumableTasks.java:20)
    at com.facebook.presto.hive.util.ResumableTasks$1.run(ResumableTasks.java:35)
    at io.airlift.concurrent.BoundedExecutor.drainQueue(BoundedExecutor.java:78)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: FB04E851EDD5E8E3; S3 Extended Request ID: HbIz8TKv7rZ11fVOA+9Hw/ikuRY6635I/fZ1tieCiYs9EWa56kLUZhOGacpvFYfZzWzIG09g2XQ=)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1695)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1350)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1101)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:758)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:732)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:714)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:674)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:656)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:520)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4443)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4390)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4384)
    at com.amazonaws.services.s3.AmazonS3Client.listObjects(AmazonS3Client.java:844)
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.listPrefix(PrestoS3FileSystem.java:490)
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.access$000(PrestoS3FileSystem.java:146)
    at com.facebook.presto.hive.s3.PrestoS3FileSystem$1.<init>(PrestoS3FileSystem.java:278)
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.listLocatedStatus(PrestoS3FileSystem.java:276)
    at org.apache.hadoop.fs.FilterFileSystem.listLocatedStatus(FilterFileSystem.java:263)
    at com.facebook.presto.hive.HadoopDirectoryLister.list(HadoopDirectoryLister.java:30)
    at com.facebook.presto.hive.util.HiveFileIterator$FileStatusIterator.<init>(HiveFileIterator.java:130)
    at com.facebook.presto.hive.util.HiveFileIterator$FileStatusIterator.<init>(HiveFileIterator.java:118)
    at com.facebook.presto.hive.util.HiveFileIterator.getLocatedFileStatusRemoteIterator(HiveFileIterator.java:107)
    at com.facebook.presto.hive.util.HiveFileIterator.computeNext(HiveFileIterator.java:100)
    at com.facebook.presto.hive.util.HiveFileIterator.computeNext(HiveFileIterator.java:37)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:141)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:136)
    at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1811)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.lambda$initPartialTraversalState$0(StreamSpliterators.java:294)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer(StreamSpliterators.java:206)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.doAdvance(StreamSpliterators.java:161)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)
    at java.util.Spliterators$1Adapter.hasNext(Spliterators.java:681)
    at com.facebook.presto.hive.BackgroundHiveSplitLoader.loadSplits(BackgroundHiveSplitLoader.java:261)
    at com.facebook.presto.hive.BackgroundHiveSplitLoader.access$300(BackgroundHiveSplitLoader.java:93)
    at com.facebook.presto.hive.BackgroundHiveSplitLoader$HiveSplitLoaderTask.process(BackgroundHiveSplitLoader.java:187)

So I tried the query with correct hive_A.propreties but Presto kept giving me the access denied error. When I restarted presto and sent the query again with correct hive_A.properties just before I sent the wrong one, I have no problem with getting the result.
Does anyone know how to fix using incorrect hive connector issue which is giving s3 access denied error without restarting presto and running the correct hive connector query first before running incorrect one?
I've already tried to add some properties onto hive connector files like
hive.metastore-cache-ttl=10s
hive.metastore-refresh-interval=10s

But it didn't work.


text:
Q: How to pass the form element to Ext AJAX request I have a problem with passing a form to an ExtJS6 AJAX request.
The docs state:

form :  Ext.dom.Element / HTMLElement / String
The form Element or the id of the form to pull parameters from.

Scope is not the problem, this references to Ext.form.Panel
My code is:
Ext.Ajax.request({
  scope: this,
  method: 'POST',
  url: 'someurl',
  form: this.getEl(),
  isUpload: true,
  success: this.someSuccessFunction
  failure: this.someFailureFunction
});

I have also tried this.getId(), this.getForm().getId() and this.
Whatever I try, I get this error:
Uncaught TypeError: form.submit is not a function

Does anyone know what is the problem with my code?

A: Ext.form.Panel does not contain form-tag. This feature is used in case of real html forms. Have a look the request of the following example: fiddle
Ext.application({
name: 'Fiddle',

launch: function () {
    Ext.create('Ext.button.Button', {
        text: "Submit",
        renderTo: Ext.getBody(),
        handler: function () {
            Ext.Ajax.request({
                url: 'user.json',
                form: Ext.fly('userForm').dom,
                success: function (response, opts) {
                    var obj = Ext.decode(response.responseText); // THIS IS A REAL HTML FORM
                    console.dir(obj);
                },

                failure: function (response, opts) {
                    console.log('server-side failure with status code ' + response.status);
                }
            });

        }
    })
}
});


text:
Q: C logging input to file? I'm working on a program that logs input to a file. This is my current code:
#include <stdio.h>
#include <curses.h>
#include <signal.h>
#define WAIT 3
#define INCORRECT "Incorrect input\n"
#define FILENAME ".xintrc"

int stop();

int main()
{
    char first[10], last[10];
    int i;
    FILE *fp, *fopen()
    initscr();
    scanf("%[^\n]", first);
    getchar();
    noecho();
    scanf("%[^\n]", last);
    printf("\n");
    getchar();
    echo();
    sleep(WAIT);
    if((fp = fopen(FILENAME, "a")) != NULL){
    fprintf(fp, "First:   %s Last: %s\n", first, last);
    fclose(fp);
  }

    printf(INCORRECT);
    endwin();
 }
    stop()
 {
    endwin();
    exit(0);
 }

When I compile, I get this error:
input1.c: In function 'main':
input1.c:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'initscr'
input1.c: In function 'stop':
input1.c:35: warning: incompatible implicit declaration of built-in function 'exit'

A: Well, you need a semicolon on the end of:
FILE *fp, *fopen(); /* ; here! */

You probably also want stop to match its prototype:
/* includes */
int stop();

/* main etc */
int main(int argc, char** argv)
{
    /* main code */
}

int stop()
{
    endwin();
    exit(0);
}

And for exit() you need #include <stdlib.h>
Oh and to compile this, let's say it's called test.c, then use gcc -lcurses test.c -o test. This tells gcc you want to link with libcurses.

A: Your code has quite a few problems.  See my embedded comments for a version that compiles and presumably does what you want in a more sane manner.
#include <stdio.h>
#include <stdlib.h> /* for _Exit() */
#include <string.h> /* for strcspn() */
/* #include <curses.h> you don't need curses for such a simple program */
/* #include <signal.h> this header is not needed */

#define WAIT 3
#define INCORRECT "Incorrect input\n"
#define FILENAME "testfile"

void stop(void); /* match the new prototype */

int main(void) /* main() always returns int, use void if not using argc/argv */
{
  char first[10], last[10];
  /* int i;  You never use this */
  FILE *fp; /* You don't need *fopen() here */

  /* initscr(); */
  /* noecho(); */

  printf("Enter first name: "); /* Added by me */
  fgets(first, sizeof(first), stdin); /* Don't use scanf, fgets prevents overflows */
  first[strcspn(first,"\n")] = '\0'; /* chomp the newline if it exists */

  printf("Enter last name: "); /* Added by me */
  fgets(last, sizeof(last), stdin); /* Don't use scanf, fgets prevents overflows */
  last[strcspn(last,"\n")] = '\0'; /* chomp the newline if it exists */

  /* echo(); */
  sleep(WAIT);

  if((fp = fopen(FILENAME, "a")) != NULL){
    fprintf(fp, "First:   %s Last: %s\n", first, last);
    fclose(fp);
    stop(); /* You never call this, i'm guessing you want it here */
  }

  printf(INCORRECT); /* only called if fopen() fails */

  /* endwin(); */

  return 0; /* mandatory return for main() */
}

void stop(void) /* Use 'void' if the func takes no params and returns nothing */
{
  /* endwin(); */
  _Exit(0); /* _Exit is apart of C99 */
}


text:
Q: How to add Apple Wallet Passes with custom name and QR code in Xamarin.IOS How can I add an Apple Wallet pass with a custom username and contents of a QR code? If possible can they be downloaded from a server?
I have tried altering existing passes but there is no capability to do that in Xamarin.

A: So the beauty of using Xamarin is that you have access to all the native iOS APIs that are available to Swift developers, so you can do everything in C# that you can with Swift without the need for custom binding.
So anything that you can do using Swift on XCode, you can do that in an identical way using C#. So in order to implement the Apple Wallet passes, you have to go through the same procedures. The procedure is slightly long since this is for Card Issuers only and you need a special entitlement issued by Apple:

Your app must include this entitlement before you can use this class.
  For more information on requesting this entitlement, see the Card
  Issuers section at developer.apple.com/apple-pay/.

Also, from here:

PKAddPaymentPassViewController requires the com.apple.developer.payment-pass-provisioning entitlement
  key for your app. The bad news is that not anyone can submit apps with
  this entitlement as it requires special permission from Apple, which I
  believe is reserved for card issuers like banks and similar. If you
  believe that you qualify you need to contact Apple directly at
  apple-pay-inquiries@apple.com

Once you get that done, you need to implement the delegate methods, and initialize it with a configuration as you can see in the code/picture below (Converted from Swift):
using System;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using PassKit;
using UIKit;

namespace BlankNativeApp.iOS
{
    public class PKViewController : UIViewController, IPKAddPaymentPassViewControllerDelegate
    {
        public void DidFinishAddingPaymentPass(PKAddPaymentPassViewController controller, PKPaymentPass pass, NSError error)
        {
            // Perform Post Addition Functionality
        }

        public void GenerateRequestWithCertificateChain(PKAddPaymentPassViewController controller, NSData[] certificates, NSData nonce, NSData nonceSignature, [BlockProxy(typeof(NIDActionArity1V173))] Action<PKAddPaymentPassRequest> handler)
        {
            // Do work that needs to be done with certifications
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (!PKAddPaymentPassViewController.CanAddPaymentPass)
            {
                // use other payment method / alert user
            }
            var config = new PKAddPaymentPassRequestConfiguration(PKEncryptionScheme.Ecc_V2);
            var addPaymentPassVC = new PKAddPaymentPassViewController(config, this);
            View.BackgroundColor = UIColor.White;
            Title = "My Custom View Controller";

            var btn = UIButton.FromType(UIButtonType.System);
            btn.Frame = new CGRect(20, 200, 280, 44);
            btn.SetTitle("Click Me", UIControlState.Normal);
            btn.TouchUpInside += (sender, e) => {
                //this.ShowViewController(addPaymentPassVC, (Foundation.NSObject)sender); This line will also work
                this.PresentViewControllerAsync(addPaymentPassVC, true);
            };
            View.AddSubview(btn);
        }
    }
}


text:
Q: Is there a HTTP proxy server that uses another proxy for certain sites (in black list) and access directly otherwise? Some websites are blocked in my network, so I have to use a proxy outside my local network to access them. In order to maximize the speed, only blocked sites be accessed through proxy.
Currently, my browser(with a plugin named SwitchySharp) is doing the job of unlocking the blocked sites. However, it would be much better if a proxy server, which determines whether the requested sites are blocked or not, could do the work.
I don't know if I'm understood. The diagram below expresses the same idea.
Browser
||
Local Proxy: If the requested URL is in black list, then use a proxy outside the network to access it. If not, go for it directly.
I am in China, where a lot of websites are blocked. If there is such software, life can be much better: once the proxy is set, phones, tablets, laptops etc. can suddenly access all the world wide web has to offer.
I am asking this because if there isn't such thing, I will write one myself.
Thank you for reading this.
Best regards.

A: You can use Proxy Automatic Configuration (PAC) files to achieve this.
The configuration is inside the IE:
Internet Options / LAN settings / Automatic configuration
For example:
I can use file://c:/test.pacinside the address (below "Use automatic configuration script")
And here is the example of test.pac content:
function FindProxyForURL(url, host)
{
if (url == "http://www.google.com/")
return "DIRECT";
else
return "PROXY 192.168.0.9:8088";
}

For more syntax about pac file, you can refer:
http://findproxyforurl.com/example-pac-file/
Note: The automatic configuration script's address can not only be file://, it can also be http://, thus it provide more convenient way for management.


text:
Q: unavailable cpan in cygwin I have unsuccessfully tried to install Perl module in cygwin like in an answer. I have got the following error:
$ perl -MCPAN -e shell
Can't locate CPAN.pm in @INC (you may need to install the CPAN module) (@INC   contains: /usr/lib/perl5/site_perl/5.22/x86_64-cygwin-threads /usr/lib/perl5/site_perl/5.22 /usr/lib/perl5/vendor_perl/5.22/x86_64-cygwin-threads /usr/lib/perl5/vendor_perl/5.22 /usr/lib/perl5/5.22/x86_64-cygwin-threads /usr/lib/perl5/5.22 .).
BEGIN failed--compilation aborted.

How can I obtain cpan in my cygwin?

There are some additional details. Actually my purpose was to install ack like in answer. However, it didn't work. After installing I have got an error:
$ ack
Can't locate filetest.pm in @INC (you may need to install the filetest module) (@INC contains: /usr/lib/perl5/site_perl/5.22/x86_64-cygwin-threads /usr/lib/perl5/site_perl/5.22 /usr/lib/perl5/vendor_perl/5.22/x86_64-cygwin-threads /usr/lib/perl5/vendor_perl/5.22 /usr/lib/perl5/5.22/x86_64-cygwin-threads /usr/lib/perl5/5.22 .) at /home/loom/bin/ack line 218.
BEGIN failed--compilation aborted at /home/loom/bin/ack line 218.

The following was my trying to locate cpan
$ cpan
-bash: cpan: command not found

$ ll /usr/lib/perl5/5.22/CPAN.pm
ls: cannot access '/usr/lib/perl5/5.22/CPAN.pm': No such file or directory

$ find /usr/ -name *.pm | grep CPAN
/usr/lib/perl5/5.22/CPAN/Meta/Converter.pm
/usr/lib/perl5/5.22/CPAN/Meta/Feature.pm
/usr/lib/perl5/5.22/CPAN/Meta/History.pm
/usr/lib/perl5/5.22/CPAN/Meta/Merge.pm
/usr/lib/perl5/5.22/CPAN/Meta/Prereqs.pm
/usr/lib/perl5/5.22/CPAN/Meta/Requirements.pm
/usr/lib/perl5/5.22/CPAN/Meta/Spec.pm
/usr/lib/perl5/5.22/CPAN/Meta/Validator.pm
/usr/lib/perl5/5.22/CPAN/Meta/YAML.pm
/usr/lib/perl5/5.22/CPAN/Meta.pm
/usr/lib/perl5/5.22/Parse/CPAN/Meta.pm

A: Reinstalling perl helped.
$ apt-cyg install perl


text:
Q: merge values together in a 2d array having a little bit of an issue trying to merge values in a 2d array.
For example:
const formatBids =
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];

I want to sum up the 2nd param of the array if the first param are the same, so the end result being:
 [
   [4444, 10500],
   [4455, 500],
 ];

i have tried the following but its continually adding to itself producing the wrong results:
formatBids.map(bid => {
  const map = new Map([bid]);
  formatBids.forEach(arr => (arr[1] += map.get(arr[0]) ?? 0));
});

unsure the best way to tackle this. Ideas?

A: You could just use an Object as a sort of map and use the first item in an array as the key. Then you can convert it back to an Array using Object.entries(). Like so:

const formatBids =
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];

const totals = {}

for (const bid of formatBids) {
  totals[bid[0]] = (totals[bid[0]] || 0) + bid[1];
}

console.log("as object:", totals, "as array:", Object.entries(totals));

A:

const formatBids = [
  [4444, 10000],
  [4444, 500],
  [4455, 500],
];

let merged = {}

formatBids.forEach((ele) => {
  let key = parseInt(ele[0]);
   merged[key] = (merged[key] ?? 0)+ele[1];
})

let mergedArr = Object.entries(merged);
console.log(mergedArr)

This is the another way of doing this

*

*Sort the array based on first index

*Push into array if currentArr(merged Array) is empty.

*If not empty, then check the first element at last index of currentArr is equal to the first index of CurrentElement.

*

*if yes, then add the 2nd element value to the currentArr's[n-1][1]

*else, insert currentElement into the currentArr

const formatBids = [
  [4444, 10000],
  [4444, 500],
  [4455, 500],
];
var mergedArr = formatBids.sort().reduce((currentArr, currentElement) => {
  let n = currentArr.length;
  if (n === 0) return [currentElement];

  if (currentElement[0] === currentArr[n - 1][0]) {
    currentArr[n - 1][1] += currentElement[1];
    return currentArr;
  } else return [...currentArr, currentElement];
}, []);
console.log(mergedArr)

A:

const formatBids =
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];

const result = Object.entries(formatBids.reduce((acc, [key, value]) => {
   if (!acc[key]) acc[key] = value;
   else acc[key] += value;
   return acc;
}, {}));

console.log(result);


text:
Q: XML Serialize with catel Is it neccessary to have the complete namespace in every model I save to xml.
<MyModel xmlns="http://schemas.datacontract.org/2004/07/MyProject.Models">

Is it possible to disable this?
and is it possible to save a property of this model as attribute instead as element?
<MyModel MyProperty="5" >
  <AnOtherProperty>10</AnOtherProperty>
</MyModel >

A: Set the OptimalizationMode to XmlSerializerOptimalizationMode.PrettyXml.


text:
Q: How can I work around Read-only SQL users finding out an MSSQL app login without needing to take a production outage? I've inherited a 3-tier production environment where some app servers are using a local SQL admin login to integrate to the database (terrible, I know).
Some honest developers recently disclosed to me that they found out the password for this login.
I'm looking for suggestions on how to restrict developers (or anyone already with with Read-only access to the MSSQL instance) without resetting the app-MSSQL integration login's password (which would entail an outage).
This would obviously be a temporary measure (needless to say an urgent one).

A: Depending on your infrastructure, you should be able to restrict login to particular machines. If you restrict network logins for that account apart from the application itself, you should be safe.


text:
Q: How to find the inverse Laplace transform? I'm trying to calculate
$$\mathcal{L}^{-1}\left(\frac{3s^3-3s^2+3s-5}{s^2(s^2+2s+5)}\right)$$
But I am not sure how to go from here. I would be really grateful for any help. Thanks.

A: We can work directly with the inverse Laplace transform and poles of $s = 0, -1\pm 2i$.
$$
\mathcal{L}^{-1}\{F(s)\}(t)=\frac{1}{2\pi i}\int_{\gamma - i\infty}^{\gamma + i\infty}\frac{3s^3-3s^2+3s-5}{s^2(s^2+2s+5)}e^{st}ds=\sum\text{Res}\{F(s);z_j\}
$$
Then the sum of residues are
\begin{gather}
\lim_{s\to 0}\frac{d}{ds}s^2\frac{3s^3-3s^2+3s-5}{s^2(s^2+2s+5)}e^{st}+\lim_{s\to -1+2i}(s+1-2i)\frac{3s^3-3s^2+3s-5}{s^2(s^2+2s+5)}e^{st}+\lim_{s\to -1+2i}(s+1-2i)\frac{3s^3-3s^2+3s-5}{s^2(s^2+2s+5)}e^{st}ds\\
=1-t-\frac{1}{2}e^{(-1+2i)t}-\frac{1}{2}e^{-(1+2i)t}
\end{gather}
which can be reduced however you see fit.

A: Hint (@Amzoti's comment, rephrased): Start with $$\mathcal{L}^{-1}\left(\frac1s\right),\quad \mathcal{L}^{-1}\left(\frac1{s^2}\right),\quad \mathcal{L}^{-1}\left(\frac1{s+1+2\mathrm i}\right),\quad \mathcal{L}^{-1}\left(\frac1{s+1-2\mathrm i}\right).$$


text:
Q: jQuery - How to check if img src lacks filename? I have a <img>:
 <img src="http://example.com/mmm/01.jpg" class="test">

How can I check if the src is missing the 01.jpg and replace it with some other image?
Basically
if (img src is 'http://example.com/mmm/') {
    replace src with 'http://example.com/mmm/test.jpg'
}

A: Something like this should work:
var $img = jQuery("#myImg");
var src = $img.attr("src");

// if you have more image types, just add them to the regex.
// I've used png and jpg as examples
if(!/\.(jpg|png)$/.test(src)) {

   var img = "test.jpg";

   // to see if the src url ends with / or not
   if(!/\/$/.test(src)) {
      img = "/" + img;
   }

   $img.attr("src", src + img);
}

A: Solution: jQuery/JavaScript to replace broken images
This is the first hit not just on stack overflow, but on google as well...

A: You can check the last character in the src attribute to see if it's a '/' or not...
var img = $("img.test");
var src = $(img).attr("src");

if (src.lastIndexOf("/")+1 == src.length){
    $(img).attr("src",src+"test.jpg");
}

A: Check $("img.test").attr("src")

A: $(yourImg).attr("src") will return you (or allow you to set) the url for the image as a string so you can then compare it with the values mentioned above.

A: // Can 'fix' many imgs at once (with the appropriate logic in the body)
$('img').attr('src',function(i,src){
  // If it's a JPG, leave it alone, otherwise...
  return /jpe?g$/.test(src) ? src : 'http://example.com/mmm/test.jpg';
});


text:
Q: ST_GeographyFromText() function changes the input while storing in DB- PostgreSQL I'm working on building a database for a geo referenced application which involves storing of latitude, longitude and altitude. The column to store the same is location and is declared as location geography(PointZ,4326).
I insert the points in the following manner
INSERT INTO SOMETABLE VALUES (ST_GeographyFromText('SRID=4326;POINT("+loc+")');  , where loc is a space seperated string with the latitude , longitude and altitude values (for example 2.098 5.67 3.45).
I did not find any aberration until I inserted a specific geographical point 19.4333 99.1333 2200, which on retrieval becomes 19.433299999999999 80.866699999999994 2200. My concern is about the second coordinate point changing while storing.
Could someone advise me on what's the issue.
I appreciate your help!!
Thanks.

A: I had figured out what the issue was myself when I tried to understand the specifics of ST_GeographyFromText() It takes in coordinates in this order - [longitude, latitude, altitude] and I had misordered latitude and longitude and as a matter of fact, the maximum value for latitude is 90 and that's the reason the 99.1333 was altered to 80.86669 ( a value less than 90 ).
Thanks!


text:
Q: Is it possible to include multiple modules in a single "include" statement? Is there a shorter way to do the following?
class MyClass
  include MyModule1
  include MyModule2
  include MyModule3
end

A: Try following
class MyClass
  include MyModule3, MyModule2, MyModule1
end

Edit: reversed the sequence

A: to get the same ancestry order you need to reverse the order in the one line version
class MyClass
  include MyModule3, MyModule2, MyModule1
end


text:
Q: Creating map-based online questionnaire/survey? I am planning to create map-based online questionnair/survey for my master dissertation on bicyle safety. What I want to do is, asking my potential respondants to mark their answers by adding pins/mark on Online map I create. For example, I ask them a question like, " where did you have a near-miss incident while you are on a bicycle?", then respondant can answer that question by locating pins/mark on where they had nearmiss.
My initial investigaton suggested that I can achieve this with Google map API, ArcGIS online or Crowdmap. I have seen some crowd-sourced maps with a lot of pins located by many people. But I am not sure if I can;

*

*download all these marked locations in csv/text file with xy coordinate

*make my survey map accessable only for my "group"

Can anybody suggest me what can I use (Google API, crowdmap, ArcGIS online or else) to achieve above 1 and 2 without any or with little programming?

A: Without any programming, I dont know any.
But one idea could be to ask location in your questionnary (ex: address, street name or postal code) and then use a geocoder (for reverse geocoding) to produce a map.
I think your results would be more precise because pinning a marker on a map is often approximative, it could depends on the map scale, user's skills or interpretation, etc...

A: CrowdMap can be best choice. It does both 1 and 2.

A: I think that you would be really interested in some of the most cutting-edge research that I have come across explaining crowds, open innovation, and citizen science.
http://papers.ssrn.com/sol3/cf_dev/AbsByAuth.cfm?per_id=1919614
And you may also enjoy this blog about the same too:
https://thecrowdsociety.jux.com/


text:
Q: Best way to archive attachments? My saved-messages and sent-mail "folders" (actually Unix MBX files)
are huge because of attachments, most of which I've saved to disk
anyway.
I want to keep the messages, but replace the attachment w/ a text file
saying "Attachment removed: /full/path/to/attach.txt".
How do I do this?
I'm using Alpine, but any tool that does this for Unix MBX is
fine. Alpine does let me delete attachments from emails, but I can't
replace them w/ a text file. Notes:

*

*I realize I can save the message to a file and edit the file using
emacs, but that's kludgey and probably messes up "Content-Length"
headers and stuff.

*I also realize I can forward the message, with headers, to myself
after removing the attachment. Again, kludgey.

*I don't think Alpine lets me add attachments to stored mail
(unless I want to send it somewhere [which messes up headers]), so I
can't delete the big attachment and add a smaller one.

*I realize I could write a Perl script to do this, but hoping for
an existing well-tested solution.

A: OK, I poked aorund, and when Alpine "deletes" an attachment, it actually replaces it with something like:
Content-Type: Text/Plain; charset=US-ASCII
X-Content-Type: image/jpeg
X-Content-Transfer-Encoding: base64
Content-ID: <part1.07020604.05000506@flamescape.com>

  [ The following attachment was DELETED when this message was saved:    ]
  [ A Image/JPEG segment of about 93,336 bytes.                          ]

I can then use emacs to edit this message (and it doesn't mess up any Content-Length headers or anything)

A: I use Thunderbird/icedove with the AttachmentExtractor add-on for this.


text:
Q: Ajax ModalPopupExtender button click event not firing I know this question has been asked many times. I went through all the solutions and nothing helped. Hence, am posting a question as a last resort! I am using a popup extender to input email address. There are two buttons in the control,one to submit the email address the other to cancel the action and hide the popup. The send button click event doesn't seem to fire at all! attached below is my code. The popup is in the master page(Home.Master) design. Am calling it in the login.aspx page which uses home.master as its master page.

                    <asp:ModalPopupExtender ID="idPopupExtend" runat="server" TargetControlID="lblPopupMsg"
                        PopupControlID="popUpPanel"
                        BackgroundCssClass="modalBackground"
                        DropShadow="true">
                    </asp:ModalPopupExtender>
                    <asp:Panel Width="338px" ID="popUpPanel" runat="server" CssClass="widget">

                                        <asp:Label ID="lblPopupMsg" runat="server" Text="" class="control-label"></asp:Label>

                                    Email Address * :

                                        <asp:TextBox ID="txtEmail" runat="server" placeholder=" Email Address" CssClass="span4" Width="190px" Height="29px"></asp:TextBox>

                                        <asp:Button ID="btnSend" runat="server" Text="Send" class="btn btn-sm btn-info" />
                                        <asp:Button ID="btnCancel" runat="server" Text="Cancel" class="btn btn-sm" />

                    </asp:Panel>

Login Page code where am calling the showing the popup:
   Panel pnlpopup;
    Table Tbl = new Table();
    Button btncancel = new Button();
    Label lbMessage = new Label();
    Label lbMessageConfirm = new Label();
    ModalPopupExtender popupExtend = new ModalPopupExtender();
    Button btnSend = new Button();

 protected void lnkForgotPassword_Click(object sender, EventArgs e)
    {
        Control ctrlForm = new Control();
        ctrlForm = Master.FindControl("form1");
        pnlpopup = new Panel();
        pnlpopup = (Panel)ctrlForm.FindControl("popUpPanel");
        pnlpopup.Visible = true;
        popupExtend = (ModalPopupExtender)ctrlForm.FindControl("idPopupExtend");
        btnSend = (Button)ctrlForm.FindControl("btnSend");

        popupExtend.Show();
    }

the btnsend event is not firing at all.. the initialization for the event has been done in the page load event. Please help! Thanks

A: Apoorva.. You dont have btnsend click event in aspx. OnClick event is missing.
<asp:Button ID="btnSend" runat="server" Text="Send" class="btn btn-sm btn-info" />

A: you missed button click event for "btnSend"


text:
Q: Swift multiple callback parameters in clousure I have this generic method which fetches a document from Firestore and returns the document or an error in case it fails. I'm trying to pass two parameters as callback parameters in the closure.
The problem occurs when I try to call it.
fetchDocument(documentReference: documentReference) { (_, Error?) in
   //
}

Instead of getting Document? all I get is an underscore. I do get Error? as I should but I do not get Document?
I want to get (Document?, Error?) instead of (_, Error?)
Any idea why?
func fetchDocument<Document: DocumentProtocol>(documentReference: DocumentReference, completion: @escaping (Document?, Error?) -> Void) {
    documentReference.getDocument { (document, error) in
        if let document = document, document.exists {
            completion(Document.init(document: document), nil)
        } else {
            completion(nil, error)
        }
    }
}


text:
Q: Is it possible to set Ion-Slides to only move in 1 direction? Once I get to the final slide I want to disable the bounce effect that happens when you try and swipe further. I have ion-option-buttons on the final page and swiping them causes the screen to wobble due to the slides.
I still want to be able to move back to the left / previous slide

A: If you aren't using the Swiper widget I would recommend it because it offers a lot more flexibility/options with your slide boxes.  (Ionic documention on it here, as well).
All you need to do is watch the slide delegate, if you hit the last slide, lock sliding to next (stops the bouncy effect you mentioned). Then unlock sliding if you are not on the last slide.
$scope.$watch('data.sliderDelegate', function(newVal, oldVal) {
  if (newVal != null) {
    $scope.data.sliderDelegate.on('slideChangeEnd', function() {
      $scope.data.currentPage = $scope.data.sliderDelegate.activeIndex;
      if($scope.data.currentPage == $scope.data.lastSlide){
        $scope.data.sliderDelegate.lockSwipeToNext();
      }
      else{
        $scope.data.sliderDelegate.unlockSwipeToNext();
      }
      $scope.$apply();
    });
  }
});

Here is a codepen for the exmaple.

A: I know this is an old post, but I just managed this in Ionic 4.0, and though that someone might find some value in it.
You can use the command:
this.slides.lockSwipeToNext(true);

To prevent the user from swiping right. There is similarly another command to prevent it going left:
this.slides.lockSwipeToPrev(true);

I placed it in the " ionViewWillEnter()" function to initially disable the swiping, then created a function that I call whenever I want to manually move to the next slide like this:
ionViewWillEnter(){
    this.slides.lockSwipeToNext(true);
  }

  nextSlide(){
    this.slides.lockSwipeToNext(false);
    this.slides.slideNext();
    this.slides.lockSwipeToNext(true);
  }

Hope this helps someone looking for a similar soution.