text:
Q: R - update t1 with count of t2 rows where two columns are the same as for t1 I have two tables, and would like to get as output t1 with an added column giving the count of rows in t2 where (id, category) are present.
Here is an example on a small data set:
id = c(12,12,13,14,15)
category = c(101,104,102,101,102)
t1 = cbind(id, category)

id = c(12,12,13,13,12,15)
category = c(101,102,101,104,101,102)
t2 = cbind(id, category)

> t1
     id category
[1,] 12      101
[2,] 12      104
[3,] 13      102
[4,] 14      101
[5,] 15      102
> t2
     id category
[1,] 12      101
[2,] 12      102
[3,] 13      101
[4,] 13      104
[5,] 12      101
[6,] 15      102

I wish to obtain t1 updated with counts of (id, category) in t2:
> t1
      id  category  count_id_cat_in_t2
[1,]  12       101  2        # because (12,101) appears 2 times in t2
[2,]  12       104  0        # because (12,104) appears 0 times in t2
[3,]  13       102  0        # etc
[4,]  14       101  0
[5,]  15       102  1

Since I work with a large data set, I need a solution that can do this under 5 minutes if possible for large data set:

*

*t1 has 300 thousands rows

*t2 has  15 million rows

I have this working in MySQL based on this answer, but could not port it into R using sqldf.
I am working on Windows and could not get the library needed to use MySQL commands with sqldf.

A: The dplyr solution from beginnR works, but took too long for the whole data set (I stopped it after 50 minutes).
I found a fast solution with data table binary search:
id = c(12,12,13,14,15)
category = c(101,104,102,101,102)
t1 = data.frame(id, category)

id = c(12,12,13,13,12,15)
category = c(101,102,101,104,101,102)
t2 = data.frame(id, category)

library(data.table)
t2 = data.table(t2)
setkey(t2, id, category) # setting key, preparing for a FAST binary search

n = dim(t1)[1]
counts <- array(NA, n)

for(i in(1:n))
{
    id_ = t1$id[i]
    category_ = t1$category[i]

    counts[i] = dim(t2[J(id_, category_),nomatch=0])[1] # data table FAST binary search
}

t1$count_id_cat_in_tr = counts

This works in 5/10 minutes for the large data set (t1:150 thousand rows, t2: 15 million rows).

Another way using data.table:
require(data.table) ## 1.9.2
setDT(t1)
setkey(setDT(t2), id, category)
ans = t2[t1, .N]

# or a little faster
ans = t2[t1][, .N, by="id,category"]

A: 1) Here is an sqldf solution:
sqldf(c("create index i on df2(id, category)", "select A.*, coalesce(count, 0) count
       from df1 A
       left natural join
          (select *, count(*) count from main.df2 group by id, category)"))

giving:
  id category count
1 12      101     2
2 12      104     0
3 13      102     0
4 14      101     0
5 15      102     1

Omit the indexing if speed is jnot an issue in which case replace main.df2 with df2.
2) The RMySQL package works under Windows. I ran the following using RMySQL and sqldf under Windows. See ?sqldf for more info on using sqldf with MySQL.
library(sqldf)
library(RMySQL)
sqldf(c("create index i on df2(id, category)",
      "select A.*, coalesce(kount, 0) count
       from df1 A
       left join
          (select *, count(*) kount from df2 group by id, category) B
       on A.id = B.id and A.category = B.category"))

or use the SQL statement that you already have working.  This gives:
id category count
1 12      101     2
2 12      104     0
3 13      102     0
4 14      101     0
5 15      102     1

A: using dplyr you could do the following:
id = c(12,12,13,14,15)
category = c(101,104,102,101,102)
t1 = data.frame(id, category)     #data.frame format

id = c(12,12,13,13,12,15)
category = c(101,102,101,104,101,102)
t2 = data.frame(id, category)     #data.frame format

require(dplyr)

t1 <- t1 %.%
  group_by(id, category) %.%
  summarize(count_id_cat_in_t2 = sum(t2$category == category & t2$id == id))

note that t1 and t2 are created as data.frames

A: This is a plyr solution (I'm not sure if it's fast)
library(plyr)

id = c(12,12,13,14,15)
category = c(101,104,102,101,102)
t1 = data.frame(id, category)

id = c(12,12,13,13,12,15)
category = c(101,102,101,104,101,102)
t2 = data.frame(id, category)

t3 <- join(t1,
           ddply(t2, .(id, category), c("nrow")),
           by=c("id", "category"))
t3$nrow[is.na(t3$nrow)] <- 0

A: We could use eat from my package safejoin, add a constant column to t2 and agregate it as we join it to t1.
Using data frames as in other answers:
# # devtools::install_github("moodymudskipper/safejoin")
# library(safejoin)

eat(t1, mutate(t2, n=1), n, .agg = sum) %>%
  mutate(n = replace(n, is.na(n), 0))
#   id category n
# 1 12      101 2
# 2 12      104 0
# 3 13      102 0
# 4 14      101 0
# 5 15      102 1


text:
Q: Fresh Type Argument open-close I run into following saying from C# in Nutshell.

Technically, all type arguments on a subtype are fresh: you could say
  that a subtype closes and then reopens the base type arguments. This
  means that a subclass can give new (and potentially more meaningful)
  names to the type arguments it reopens:
class List<T> {...}
class KeyedList<TElement,TKey> : List<TElement> {...}

I don't understand how the circumstance written in bold is carried out, i.e. close-reopen.

A: What they mean here is that the subclass has its own, completely independent list of generic arguments and the generic argument from the base class is not automatically "inherited" by the subclass.
Instead of closes and reopens they could have said clears and recreates.
But what's the rationale behind this clearing? Why the subclass type argument is not automatically inherited? The answer is simple - this way you are allowed to have a subclass that has less generic arguments than its base class.
Consider following examples:
public class TheBase<T> { ... }

// This subclass clears the list of generic parameters
// by instantiating T with int. Thus, the subclass has 0
// generic arguments
public class TheSubclass : TheBase<int> { ...

// This subclass reuses and gives a new name to the base class type argument
// The T from the base class is named TheType here.
// The subclass has 1 generic argument
public class AnotherSubclass<TheType> : TheBase<TheType> { ...

// This subclass reuses the generic argument but also introduces its own.
// It has 2 generic arguments.
// Base class' T is called U here.
public class YetAnothersubclass<U,V> : TheBase<U>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two identical tables: Keep them seperate or merge them with extra key column Lets assume that we have two statuses tables which are identical. Each table has his own values. They don't share the same.
Now, what is best practice?

*

*Keep those seperated, or

*Merge them with additional key column

Separate:
Table: offer_statuses
- id
- name  //For example: calculating, sent

Table: project_statuses
- id
- name  //For example: preparation, in progress

Merged:
Table: statuses
- id
- status //For example: offer, project
- name   //For example: calculating, sent, preparation, in progress

A: Id keep then separate. A project status is not an offer status.  You gain nothing by combining, and now every foreign key to the combined status table will be two columns instead of one. You can also introduce errors, as your foreign keys will not prevent you from using an offer status where only a project status is valid.

A: You can go either way.  Normally, there would be a separate reference table for each type of status, because this would allow both:

*

*foreign key relations from offers and projects to the appropriate statuses; and

*no accidental mixing of statuses between the two entities.

There are some situations where having all statuses in the same table is useful.  For instance, if the statuses really do overlap, then putting them in the same table makes sense.  Another use-case is internationalization.  If the application needs to be easily translatable, then having all language strings (such as status descriptions) in a single table (or small number thereof) is helpful.
In other words, I would usually go for separate tables.  However, there might be good reasons for combining them.

A: I'd recommend to keep them separated. It sounds like they're different from the logical point of view. Having the same attributes is an indicator two tables might model the same entity but no proof.
Keeping them different makes it easier to enforce correctness of the data, as you can use foreign key constraints, that point to the right status. If your just have one table it becomes more difficult to ensure, that e.g. offers only use status for offers.


text:
Q: Share dialog isn't working with Facebook app [android] I'm using share dialog to share a link onto the user's timeline but it's not working while the Facebook app is installed. It is functioning properly using the default browser (when the app is uninstalled).
Note that FB login is working both with and without the FB app.
This is my code:
if(click_id==R.id.comboshare_fb) //Button click
    {
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                String userid = loginResult.getAccessToken().getUserId(); //Gets the userid.
                Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }

        }); //Login is working

        shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
            @Override
            public void onSuccess(Sharer.Result result) {

            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "Share Cancelled!", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(FacebookException error) {

                Log.d("Final Problem", "onError " + error);

            }

        });
        ShareLinkContent linkContent = new ShareLinkContent.Builder()
                .setQuote("I completed 3X Combo in Wordplay! :)")
                .setContentUrl(Uri.parse("https://i2.wp.com/sbansite.files.wordpress.com/2018/07/yay-you-completed-3-combo-10.png?ssl=1&w=450"))
                .build();

        if(shareDialog.canShow(ShareLinkContent.class))
                {
                    shareDialog.show(linkContent);
                }}

The error that I'm getting from onError() of sharedialog is: D/Final Problem: onError Invalid long: "null"
Any help is welcome, thanks in advance.
P.S. My app is still in development mode at Facebook.

A: This is a bug introduced in the latest Facebook app.
Here's a link to the reported issue: https://developers.facebook.com/bugs/647119912303459/
If you want to add a workaround for your users who use this version of the app, you could add something like this in your error-callback:
@Override
public void onError(FacebookException error) {
    if (error != null && error.getMessage().equals("null") {
        // Don't use the app for sharing in case of null-error
        shareDialog.show(linkContent, ShareDialog.Mode.WEB);
    }
}

Sharing via the webview-share works


text:
Q: Sqlite self join using alias I have such sql query:
SELECT LeftCurrency.LeftCurrency, RightCurrency.RightCurrency FROM
(
  SELECT DISTINCT [SecurityData].[Value] AS 'LeftCurrency'
  FROM [SecurityData]
  JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
  WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS LeftCurrency
JOIN
(
  SELECT DISTINCT [SecurityData].[Value] AS 'RightCurrency'
  FROM [SecurityData]
  JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
  WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS RightCurrency
ON LeftCurrency.LeftCurrency != RightCurrency.RightCurrency

it works ok, but I have two similar sub-queries.
Also I tried something like this:
SELECT * FROM
(
  SELECT DISTINCT [SecurityData].[Value] AS 'Currency'
  FROM [SecurityData]
  JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
  WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS leftCurrency, leftCurrency AS rightCurrency
WHERE leftCurrency.Currency != rightCurrency.Currency

But it doesn't work.
So is it possible to get rid of sub-query duplication?

A: In SQLite 3.8.3 or later, you could use a common table expression:
WITH Currency(Currency) AS (
    SELECT DISTINCT [SecurityData].[Value]
    FROM [SecurityData]
    JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
    WHERE [Fields].[Mnemonic] = 'CRNCY'
)
SELECT LeftCurrency.Currency AS LeftCurrency,
       RightCurrency.Currency AS RightCurrency
FROM Currency AS LeftCurrency
JOIN Currency AS RightCurrency ON LeftCurrency.Currency != RightCurrency.Currency

Alternatively, use a temporary view.


text:
Q: Why does my VirtualBox VM take so long to install Windows 7 updates? I have a Windows 7 VM running in VirtualBox, on Ubuntu 12.10. I have a couple of problems that I'm thinking might be related, but I have no idea how to figure out the root problem.

*

*Whenever it installs updates, it takes forever to install and power down

*I have tried to install drivers (from those included in Windows) on a couple of devices, and the operation has timed out.

Any pointers or suggestions on how to figure out what's wrong would be great!

A: In regards to the updates, it could just be how long it takes. I've had updates take up to 1 hour on my netbook with 7 before, and I know of people who have had much longer.

A: You can't usually install drivers for real hardware in a Virtual Machine.
Windows 7, when installed under VirtualBox can't access, for example, the real graphics card or network card, it can only access a "virtual" or "emulated" one. If you try to install the real drivers for your hardware it will time-out, as it can't find them. But you should install the "Guest additions", this package contains all the drivers needed for the virtual hardware.
Sometimes, you can access the real hardware, it usually happens when you connect USB devices directly to the Virtual Machine, or when using some special advanced configurations. In those cases you need (and can) install the real drivers.


text:
Q: Add class to DIV element when quiz answer is correct or incorrect I am trying to add a CSS class to a JavaScript created element, but am experiencing a reference error for the trackerMarker element. The tracker-marker DIVs are displaying on load, but are undefined when used in conjunction with the event listener.
I have tried using the createElement function inside and outside of the for loop.
I am not sure where the issue is. I am learning JS as I go, so any tips or suggestions are greatly appreciated.

function answerTracker() {
  const answerTracker = document.querySelector(".tracker");
  let questions = document.querySelectorAll(".container");
  for (let i = 0; i < questions.length; i++) {
    let trackerMarker = document.createElement("div");
    trackerMarker.className = "tracker-marker";
    answerTracker.appendChild(trackerMarker);
  }
}

const runQuiz = (() => {
  // Generate tracker
  answerTracker();

  let answers = document.querySelectorAll(".radio");
  answers.forEach(function(answer) {
    answer.addEventListener("click", (e) => {
      let target = e.target;
      let container = target.closest(".container");
      let question = container.querySelector(".question");
      let next = container.querySelector("button");
      if (e.target.value == "t") {
        trackerMarker.classList.add("correct");
      } else {
        trackerMarker.classList.add("incorrect");
      }
      if (next !== null && next !== "") {
        next.style.display = "block";
      }
      question.style.display = "none";
    });
  });
})();
.tracker {
  display: flex;
  padding: 50px 0;
}

.tracker .tracker-marker {
  width: 28px;
  height: 28px;
  margin: 0 1.25rem;
  background-color: red;
  border-radius: 100%;
}

.tracker .tracker-marker.correct {
  background-color: blue;
}

.question {
  margin-bottom: 18px;
}

.question .question__label {
  margin-bottom: 8px;
}

<fieldset class="container">

      1
      Question One

    <input type="radio" name="form[question-one]" value="t" id="question-one0" class="radio">
    Answer A

    <input type="radio" name="form[question-one]" value="f" id="question-one1" class="radio">
    Answer B

    <input type="radio" name="form[question-one]" value="f" id="question-one2" class="radio">
    Answer C

    <input type="radio" name="form[question-one]" value="f" id="question-one3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>
<fieldset class="container" style="display: none;">

      2
      Question Two

    <input type="radio" name="form[question-two]" value="t" id="question-two0" class="radio">
    Answer A

    <input type="radio" name="form[question-two]" value="f" id="question-two1" class="radio">
    Answer B

    <input type="radio" name="form[question-two]" value="f" id="question-two2" class="radio">
    Answer C

    <input type="radio" name="form[question-two]" value="f" id="question-two3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>
<fieldset class="container" style="display: none;">

      3
      Question Three

    <input type="radio" name="form[question-three]" value="t" id="question-three0" class="radio">
    Answer A

    <input type="radio" name="form[question-three]" value="f" id="question-three1" class="radio">
    Answer B

    <input type="radio" name="form[question-three]" value="f" id="question-three2" class="radio">
    Answer C

    <input type="radio" name="form[question-three]" value="f" id="question-three3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>

A: You never set trackerMarker inside runQuiz.
I used getElementsByClassName (because how you wrote your code) which will return an array of items which is not ideal. You should add an ID to your trackerMarker div and then use getElementById.

function answerTracker() {
  const answerTracker = document.querySelector(".tracker");
  let questions = document.querySelectorAll(".container");
  for (let i = 0; i < questions.length; i++) {
    let trackerMarker = document.createElement("div");
    trackerMarker.className = "tracker-marker";
    answerTracker.appendChild(trackerMarker);
  }
}

const runQuiz = (() => {
  // Generate tracker
  answerTracker();

  let answers = document.querySelectorAll(".radio");
  answers.forEach(function(answer) {
    answer.addEventListener("click", (e) => {
      let target = e.target;
      let container = target.closest(".container");
      let question = container.querySelector(".question");
      let next = container.querySelector("button");
      let trackerMarker = document.getElementsByClassName('tracker-marker')[0];
      // ^-- I added this line only
      if (e.target.value == "t") {
        trackerMarker.classList.add("correct");
      } else {
        trackerMarker.classList.add("incorrect");
      }
      if (next !== null && next !== "") {
        next.style.display = "block";
      }
      question.style.display = "none";
    });
  });
})();
.tracker {
  display: flex;
  padding: 50px 0;
}

.tracker .tracker-marker {
  width: 28px;
  height: 28px;
  margin: 0 1.25rem;
  background-color: red;
  border-radius: 100%;
}

.tracker .tracker-marker.correct {
  background-color: blue;
}

.question {
  margin-bottom: 18px;
}

.question .question__label {
  margin-bottom: 8px;
}

<fieldset class="container">

      1
      Question One

    <input type="radio" name="form[question-one]" value="t" id="question-one0" class="radio">
    Answer A

    <input type="radio" name="form[question-one]" value="f" id="question-one1" class="radio">
    Answer B

    <input type="radio" name="form[question-one]" value="f" id="question-one2" class="radio">
    Answer C

    <input type="radio" name="form[question-one]" value="f" id="question-one3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>
<fieldset class="container" style="display: none;">

      2
      Question Two

    <input type="radio" name="form[question-two]" value="t" id="question-two0" class="radio">
    Answer A

    <input type="radio" name="form[question-two]" value="f" id="question-two1" class="radio">
    Answer B

    <input type="radio" name="form[question-two]" value="f" id="question-two2" class="radio">
    Answer C

    <input type="radio" name="form[question-two]" value="f" id="question-two3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>
<fieldset class="container" style="display: none;">

      3
      Question Three

    <input type="radio" name="form[question-three]" value="t" id="question-three0" class="radio">
    Answer A

    <input type="radio" name="form[question-three]" value="f" id="question-three1" class="radio">
    Answer B

    <input type="radio" name="form[question-three]" value="f" id="question-three2" class="radio">
    Answer C

    <input type="radio" name="form[question-three]" value="f" id="question-three3" class="radio">
    Answer D
    <button type="button" style="display: none;">Next</button>

</fieldset>


text:
Q: Binary tree, print out which level I am on I want to print out into my sorted tree on which level this number was and that must be a recursion function.
Here is my code:
void printout(KNOTEN *start) {
    if (start == NULL)
        return;

    printout(start->left);
    printf("%d\n", start->number);
    printout(start->right);

    free(start);
}

Here is an example of the output:
My input Numbers 41, 18467, 6334 , 26500, 19169
Outprint is 41,6334,18467,19169,26500

What I want is:
41 Level 1 , 6334 level 3 , 18467 level 2 , 26500 level 3 , 19169 level 4

A: I would modify it to this:
void printout(KNOTEN *start, int depth)
{
    if(start == NULL)
        return;

    printout(start->left, depth+1);
    printf("%d(%d) \n",start->number, depth);
    printout(start->right, depth+1);

    free(start);
 }

A: here is a hint. your prototype is this
printout(KNOTEN *start, int the_level)

and this is how you call it to start your search.
printout(node, 1);

and there is a the_level + 1 in two places in your code.
good luck

A: This sounds like homework, so I'm not going to give you complete code.  But the idea is to keep count of how many recursive calls you've made:
int myRecursiveFunction(Node *node, int thingToFind, int level)
{
    if (someCondition())
    {
        return level;
    }
    else
    {
        if (goLeft())
        {
            return myRecursiveFunction(node->left, thingToFind, level+1);
        }
        else
        {
            return myRecursiveFunction(node->right, thingToFind, level+1);
        }
    }
}

...

int level = myRecursiveFunction(root, thingToFind, 0);


text:
Q: Should I be generating my own ObjectID for Mongodb? My initial thought was to have MongoDB automatically create the _id field. However, the frontend of my app is PHP and I submit a job into Beanstalkd. The backend is picked up by a Python daemon that pulls the necessary info from Beanstalk. What I'm trying to accomplish is so that the user gets redirected to a status page, but I need the ObjectId that was used. The only way I can think of accomplishing this is to generate the ObjectId as part of the job info. Hence, I have this information handy and I can use it to display the status page.
So my question is, could I run into issues? I figure a timestamp is part of the ObjectId therefore it should be unique even if I pre-generate it before inserting into Mongo.

A: Pretty sure that it won't be a problem to create and attach _id to db by your code rather than mongoDB driver code. If you write your code to generate ID correctly you won't dive in any issue, because it would be quite same or similar algorithm as for mongoDB driver.
Take a look at MongoID class.


text:
Q: Tampering detection by using sobel edge in processing I have to use Sobel edge detection to detect how an image has been tampered with. I have been able to implement the edge filter, but have not been able to figure out how to use it to detect tampering. I want to show the tampering by highlighting the region that has been tampered with in another color.
Can someone help please?
PImage img, edgeImg;

int[][] sobelx = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };

int[][] sobely = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };

void setup() {
    img = loadImage("face1.jpg");
    size(img.width, img.height);
    edgeImg = createImage(img.width, img.height, RGB);
}

void draw() {
    image(img, 0, 0);
    int matrixsize = 3;
    loadPixels();
    img.loadPixels();
    int loc = 0;

    for (int x = 1; x < img.width - 1; x++) {
        for (int y = 1; y < img.height - 1; y++) {
            loc = x + y * img.width;
            int sx = convolution(x, y, sobelx, matrixsize, img);
            int sy = convolution(x, y, sobely, matrixsize, img);
            int sum = abs(sy) + abs(sx);
            sum = constrain(sum, 0, 255);
            edgeImg.pixels[loc] = sum;
        }
    }

    edgeImg.updatePixels();
    image(edgeImg, 0, 0);
    filter(THRESHOLD, 0.8);
}

int convolution(int x, int y, int [][] mat, int matrixsize, PImage img) {
    float rtotal = 0.0;
    float gtotal = 0.0;
    float btotal = 0.0;
    int total = 0;

    int offset = matrixsize/2;

    for(int i=0; i<matrixsize; i++) {
        for(int j=0; j<matrixsize; j++) {

            int xloc = x + i - offset;
            int yloc = y + j - offset;

            int loc = xloc + img.width*yloc;
            loc = constrain(loc,0,img.pixels.length - 1);

            rtotal = rtotal + red(img.pixels[loc])*mat[i][j];
            gtotal = gtotal + green(img.pixels[loc])*mat[i][j];
            btotal = btotal + blue(img.pixels[loc])*mat[i][j];

            total = total + int(brightness(img.pixels[loc])*mat[i][j]);
        }
    }

    rtotal = constrain(rtotal, 0, 255);
    gtotal = constrain(gtotal, 0, 255);
    btotal = constrain(btotal, 0, 255);

    return total;
}

A: I don't know how the algorithm can be used for your particular purpose, but I would guess you would need to run the same filter to the original image and compare the results.
PImage original = loadImage("face1.jpg");
PImage edgeImg;                             // previously created

original.loadPixels();
edgeImg.loadPixels();

for (int i=0; i<original.pixels.length; i++) {
  color origPx = original.pixels[i];
  color edgePx = edgeImg.pixels[i];

  // compare red values, since the edgeImg is B&W
  if ( (origPx >> 16 & 0xFF) != (edgePx >> 16 & 0xFF) ) {
    // don't match? do something!
  }
}


text:
Q: Canvas text rendering I can really use some help, my goal is to add few lines to the canvas in different places, it means to use the function drawText few times, for some reason if I don't use drawText inside the onload of drawImage the text does not rendering I am really stuck and can use some help, my main target it to make website that can edit pictures and make memes (e.g.: https://imgflip.com/memegenerator)and adding text line is what i am getting stuck on because I don't understand how to render new text line while save the old one, every time i start new line its like the image rendering all over again and start from the beginning.
// Function to load image on the canvas
function drawImg(url) {
    gCurrLineIdx = getCurrLineIdx();
    let currLine = gMeme.lines[gCurrLineIdx];
    const img = new Image();

    img.src = url;
    img.onload = () => {
        gCtx.drawImage(img, 0, 0, gElCanvas.width, gElCanvas.height);
        //If you dont call drawText the text does not render to the canvas
        drawText(currLine.txt, currLine.size, currLine.fontColor, currLine.strokeColor, currLine.align, currLine.font, gElCanvas.width / 2, currLine.y);
    };
}

// Function to add text on the canvas
function drawText(text = '', fontSize = 20, fontColor = 'white', strokeColor = 'black', align = 'center', font = "ariel", x = gElCanvas.width / 2, y = 20) {
    gCtx.strokeStyle = strokeColor;
    gCtx.fillStyle = fontColor;
    gCtx.font = `${fontSize}px ${font}`;
    gCtx.textAlign = align;
    gCtx.fillText(text, x, y);
    gCtx.strokeText(text, x, y);
}

//Function to add new text line on the canvas.
function onAddTextLine() {
    let textInput = document.getElementById('text-input');
    textInput.value = '';

    addTextLine();
    gCurrLineIdx = getCurrLineIdx();
    var currLine = gMeme.lines[gCurrLineIdx];
    drawText(currLine.txt, currLine.size, currLine.fontColor, currLine.strokeColor, currLine.align, currLine.font, gElCanvas.width / 2, currLine.y);
}

A: The question I see here is:

how to render new text line while save the old one

Looks like in your code you are drawing things independently, below is a different approach the class Meme has a few functions to add text and image but every time anything change the entire canvas is cleared (clearRect) and every element is re-drawn, the magic is in the this.draw(), that is the call to the common function that does all the drawing.
To keep my sample small I hard-coded many of the things you had as parameters, it should be easy for you to reintroduce them if you need

class Meme {
  constructor(ctx, width, height) {
    this.ctx = ctx;
    this.ctx.font = '80px Arial';
    this.ctx.fillStyle = "blue"
    this.ctx.textAlign = "center"
    this.width = width;
    this.height = height;
  }

  addHeadText(text) {
    this.htext = text;
    this.draw();
  }

  addFootText(text) {
    this.ftext = text;
    this.draw();
  }

  addImage(image_src) {
    this.image = new Image();
    this.image.src = image_src;
    this.image.onload = () => {
      this.draw()
    };
  }

  draw() {
    this.ctx.beginPath();
    this.ctx.clearRect(0, 0, this.width, this.height)
    if (this.image) {
      this.ctx.drawImage(this.image, 0, 0, this.width, this.height);
    }
    if (this.htext) {
      this.ctx.textBaseline = "top";
      this.ctx.fillText(this.htext, this.width / 2, 0);
    }
    if (this.ftext) {
      this.ctx.textBaseline = "bottom";
      this.ctx.fillText(this.ftext, this.width / 2, this.height);
    }
    this.ctx.closePath();
  }
}

const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');

meme = new Meme(ctx, canvas.width, canvas.height)
meme.addHeadText("Hello");
meme.addFootText("World");
meme.addImage("http://i.stack.imgur.com/UFBxY.png");

document.getElementById('htext').onkeyup = (event) => {
  meme.addHeadText(event.srcElement.value);
};
document.getElementById('ftext').onkeyup = (event) => {
  meme.addFootText(event.srcElement.value);
};
Head Text:<input type="text" id="htext" name="ftext" style="width: 140px;" value="Hello">

Foot Text:<input type="text" id="ftext" name="ftext" style="width: 140px;" value="World">

<canvas id="c" width=280 height=380 style="border:2px solid red;"></canvas>


text:
Q: "this" in global functions I was under the impression that the "this" keyword represents the current owner that is in scope. Obviously, this is wrong. Let me get to the code:
alert(this);     // alerts as [object Window] -- Okay

function p1() {
    alert(this);
}

var p2 = function() {
    alert(this);
}

p1();           // alerts as undefined  -- ???
p2();           // alerts as undefined  -- ??
window.p1();    // alerts as [object Window] -- Okay
window.p2();    // alerts as [object Window] -- Okay

The code above first alerts [object Window], as I would expect but then the next two calls to p1() and p2() alert "this" as "undefined". The final two calls to p1() and p2() alert "this" as [object Window].
Isn't it the case that p1() and p2() exist in the global (i.e., window) scope? I thought that calling window.p1() is synonymous with calling p1(), just like calling alert() is synonymous with window.alert().
To my (C#) way of thinking, p1() and p2() are in the global scope. These functions are members of the global window object so when they refer to "this" they should be referring to [object Window]. Obviously, I'm very wrong here.

A: Becasue you are using strict mode and as per the spec:

If this is evaluated within strict mode code, then the this value is not coerced to an object.

The code you have does alert window in all instances of alert, but because you are in strict mode, it is undefined (as it should be)
UPDATE: chrome dev tools alerts window not undefined, however if you wrap it in a self executing function you get undefined as expected
(function(){
   'use strict';
   alert(this);
}());

A: When you call a function like foo(), then the value of this depends on whether the code runs in strict mode or not (the default actually).
In strict mode, this will be undefined (as you already found out).
In "loose mode" this will indeed refer to window, but that's not because the functions are global, i.e. "owned" by the global scope. You get the same behavior for local functions:

(function() {
  function foo() {
    console.log(this); // logs the window object, but `foo` is not global
  }
  foo();
}());

This is simply an explicitly defined behavior:

*

*If the function code is strict code, set the ThisBinding to thisArg.

*Else if thisArg is null or undefined, set the ThisBinding to the global object.

*Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).
  ...

As you can see, in "loose" mode, if thisArg is undefined, which is the case if you call the function "normally" as foo(), then it will be set to window explicitly.

A: this is what denotes you are referring to that object you are. It is mostly used in Object Oriented Programming to differentiate between an object's self versus input variables.
Example (pseudo code):
var1 //instance variable of object
 void Constructor(var1){
     this.var1 = var1
 }
What this describes is the constructor takes in a var called var1, and sets it's own variable var1 to it.
In your case, I would assume that when in a function:
function p1() {
    alert(this);
}
being called as p1();, it is not strictly in an object context, therefore this does not mean anything. By calling it from the window's context window.p1();, you are making the window object call the function, therefore giving this a value.


text:
Q: Filtering Query with NOT EXISTS I am currently attempting to query a database using SQL Server in Visual Studio. The database in question contains payment information, primarily identifying transactions and their resulting software licenses via OrderID and License ID. Ocassionally, these licenses get revoked due to misuse.
Right now, I'm attempting to run a query that returns all customers based upon this:
Select
   [Order].LastName,
   [Order].FirstName,
   [Order].CompanyOrganization,
   [Order].EmailAddress,
   [Order].Country,
   [License].LicenseID,
   [License].InstanceCount

From [Order], [License]

Where
    [License].OrderID = [Order].OrderID
    AND [Order].Status = 1
    AND not exists (Select LicenseID From [LicenseRevocation])

Order by [License].InstanceCount DESC;

The query returns no results, and I know it's because of the "NOT EXISTS" portion. However, I'm not sure why. Can somebody clear up how "EXISTS" works and how to implement it into my query?

A: The exists() function is true if the query inside it would produce at least one record, thus not exists() is only true if the query inside it would produce zero records.
In your case you are querying the entire LicenseRevocation inside not exists(), so your query would only return anything if that table was completely empty.
You would use a condition in the query to look for a specific record in it, something like this:
not exists (Select * From [LicenseRevocation] Where LicenseID = [License].LicenceID)

That will make the query return the records where there is no corresponding record in the LicenseRevocation table.

A: You need to define a condition on which you check for values if there exist or not,
Also use ON clause syntax for your joins.
Select [Order].LastName
     , [Order].FirstName
     , [Order].CompanyOrganization
     , [Order].EmailAddress
     , [Order].Country
     , [License].LicenseID
     , [License].InstanceCount

From [Order]
INNER JOIN [License] ON [License].OrderID = [Order].OrderID

Where [Order].[Status] = 1
AND NOT EXISTS (Select 1
                From [LicenseRevocation]
                WHERE LicenseID = [License].LicenseID)  --<-- you are missing this condition
Order by [License].InstanceCount DESC;

A: this solution uses NOT IN and proper JOIN syntax but should give you the result you want
SELECT  [Order].LastName, [Order].FirstName, [Order].CompanyOrganization,
        [Order].EmailAddress, [Order].Country,
        [License].LicenseID, [License].InstanceCount
FROM    [Order]
INNER JOIN [License] ON [License].OrderID = [Order].OrderID
WHERE  [Order].Status = 1
AND  [License].LicenseID NOT IN  (
     SELECT  LicenseID
     FROM    [LicenseRevocation] )
ORDER BY [License].InstanceCount DESC;

ps. use table ALIAS

A: First of all, write your query using proper JOINS, and use a standard LEFT OUTER JOIN:
Select
   [Order].LastName,
   [Order].FirstName,
   [Order].CompanyOrganization,
   [Order].EmailAddress,
   [Order].Country,
   [License].LicenseID,
   [License].InstanceCount

From [Order]
INNER JOIN [License] ON [License].OrderID = [Order].OrderID
LEFT OUTER JOIN [LicenseRevocation] ON [License].LicenseID = [LicenseRevocation].LicenseID
Where [Order].Status = 1
AND [LicenseRevocation].LicenseID IS NULL

Order by [License].InstanceCount DESC;


text:
Q: Using "croppie" on front-end / What do I exactly need to do on back-end to actually crop the image? How do I actually crop and compress (resize to snippet size) the image on back-end?
I'm using croppie on front-end: https://foliotek.github.io/Croppie/
I'm completely lost, small guidance would be very helpful.
Thanks!

A: Why do you want crop your pic on back-end? This operation should have be done in browser. When you use result({ type, size, format, quality, circle }) function, you can get data of cropped pic. If type is base64, you can save the data to file after base64_decode it.


text:
Q: SQL Query To Create View I have some tables on my database, I am using MySQL
See the image below. It is the simple version of my database
How to create view the user detail?

A: CREATE VIEW EmpList
AS
SELECT  a.id_user,
        b.category_province_content,
        c.category_city_content,
        d.category_job_content
FROM    user_detail a
        INNER JOIN category_province b
            ON a.detail_province = b.id_category_province
        INNER JOIN  category_city c
            ON a.detail_city = c.id_category_city
        INNER JOIN category_job d
            ON a.detail_job = d.id_category_job

To further gain more knowledge about joins and MySQL views, kindly visit the links below:

*

*Visual Representation of SQL Joins

*MySQL CREATE VIEW Syntax

A: create view view1
as
    select ud.id_user_detail, cp.category_province_content,
    cc.category_city_content, cj.category_job_content
    from user_detail ud, category_province cp,
    category_city cc, category_job cj
    where ud.detail_province=cp.id_category_province
    and ud.detail_city=cc.id_category_city
    and ud.detail_job=cj.id_category_job


text:
Q: How to read .vcf file from browser? I am trying to retrieve all the email addresses from the exhibitors of the IFA Berlin.
This is pretty easy to crawl though.
But as a tricky part, they just allow us to download a .vcf file or to send an email (throught their server I guess). I would like to find that email address without downloading that vcf file. Otherwise I could download it and read it easily using PHP (since my crawler is also in PHP).
This is also my first question here after lurking for years! Nice meeting you guys.

A:
How to read .vcf file from browser?

This file will always be a file download and never displayed in a browser. One way to make it work is to setup a custom browser extension, which temporary stores the file and parses the microformat and displays the information.

PHP scraping approach

There are vcard parsers out there: https://github.com/nuovo/vCard-parser
but i think you could base this on a RegExp solution: /EMAIL;INTERNET:(.*)/.
Let's pretend, your first scraping run gives you a list of attendee IDs,
then your second (vcard) scraping run could fetch and extract the name and emails by ID:
<?php

function getVcard($id) {
    return file_get_contents('http://www.virtualmarket.ifa-berlin.de/?Action=attendeeVcard&id=' . $id);
}

function getEmailFromVcard($vcard)
{
    preg_match('/EMAIL;INTERNET:(.*)/', $vcard, $matches);
    if(isset($matches[1])) {
        return $matches[1];
    }
}

function getNameFromVcard($vcard)
{
    preg_match('/N:(.*);;/', $vcard, $matches);
    if(isset($matches[1])) {
        $array = explode(';', $matches[1]);
        $name = trim($array[1]) . ' ' . trim($array[0]);
        return $name;
    }
}

$id = 1775586;

$vcard = getVcard($id);
$email = getEmailFromVcard($vcard);
$name = getNameFromVcard($vcard);

echo $name . ' ' . $email;


text:
Q: update specific data for an object using POST method in spring boot rest I want to update specific data only name field for a restaurant object. The way I want to make it that if a field is empty or null, just leave the old value.
Is there any good solution?
Note that I'm making a rest api app with Spring Boot.
Restaurant.java:
@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant {

    @Id
    @GeneratedValue
    private long id;

    @NonNull
    @NotEmpty(message = "The restaurant must have a name")
    private String name;

    @NonNull
    @NotEmpty(message = "Please add a description for this restaurant")
    private String description;

    @NonNull
    @NotEmpty(message = "The restaurant must have a location")
    private String location;
}

My post update function:
@PostMapping("/restaurant/{id}/update")
public Restaurant updateRestaurant(@PathVariable Long id, @RequestBody Restaurant restaurantDetails, BindingResult bindingResult) {
    Optional<Restaurant> restaurantOptional = restaurantService.findById(id);

    if (restaurantOptional.isPresent()) {
        Restaurant restaurant = restaurantOptional.get();
        restaurant.setName(restaurantDetails.getName());
        restaurant.setLocation(restaurant.getLocation());
        restaurant.setDescription(restaurantDetails.getDescription());
        logger.info("restaurant information edited successfully");
        return restaurantService.save(restaurant);
    } else
        return null;
}

A: This is very similar to this question:
Spring REST partial update with @PATCH method
In REST, a POST is usually for resource creation, not updates. A PUT method is usually used for updates when you want to update the entire resource. And a PATCH method is used for partial updates.
You want to use a PATCH and then only update the fields that are present in the request body.
It's a little easier if you change your @RequestBody to a Map instead of Restaurant because if you use Restaurant you can't tell if the client is trying to set the value to null or not.
    @PatchMapping("/restaurant/{id}/update")
public Restaurant updateRestaurant(@PathVariable Long id, @RequestBody Map<String, Object> restaurantDetails, BindingResult bindingResult)
{

            Optional<Restaurant> restaurantOptional = restaurantService.findById(id);

            if (restaurantOptional.isPresent()) {
                Restaurant restaurant = restaurantOptional.get();

                // loop through the map keys here and only update the values that are present in the map.

                logger.info("restaurant information edited successfully");
                return restaurantService.save(restaurant);
            } else
                return null;
        }


text:
Q: What is the difference between tsvector_update_trigger and ts_vector generated column? Newbie to full text search, I have a feed_items table as follows
feed_items (...title varchar, summary varchar, fullarticle varchar,...)

I want to create a ts_vector column to search query from either the title or the summary with higher priority given if the query is found in the title.
Option 1
I can create a generated column which goes like this
ALTER TABLE feed_items
    ADD COLUMN textsearchable_index_col tsvector
               GENERATED ALWAYS AS (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(summary, ''))) STORED;

Option 2
I can create a trigger after insert or update like this, the example below is not perfect, I created a separate column for title_vector and summary_vector but I think I need to merge them into one column and yet decide how to give more importance to query found in title
ALTER TABLE "feed_items"
  ADD IF NOT EXISTS "title_vector" tsvector;
COMMENT ON COLUMN "feed_items"."title_vector" IS $pga$vector representation of title$pga$;
UPDATE feed_items SET title_vector = to_tsvector('english', title);
CREATE INDEX "idx_title_vector" ON "feed_items" USING gin ("title_vector");
CREATE TRIGGER "trigger_update_title_vector"
  BEFORE INSERT OR UPDATE ON "feed_items"
  FOR EACH ROW
  EXECUTE PROCEDURE "tsvector_update_trigger"($pga$title_vector$pga$, $pga$pg_catalog.english$pga$, $pga$title$pga$);

My main question is what is the difference between both? and which one should I use?

A: The trigger method is obsolete.  If you are using a version that supports using generated columns on expressions, then you should use them.  And if you are starting a new project, you should absolutely start out with a version at least that new (v12).

A: I think both ways are not ideal, since they persist unnecessary data.
I would not add an extra column, but define a GIN index on the expression:
CREATE INDEX ON feed_items USING gin (
   to_tsvector('english', concat(title, ' ', summary))
);

concat treats NULL values as empty strings, so that is simpler.
Your full-text search will then have
... WHERE to_tsvector('english', concat(title, ' ', summary)) @@ whatever


text:
Q: Can a trait give default implementation for *some* methods of a parent trait? Suppose we have a basic trait and an advanced trait as follows:
pub trait BasicTrait {
    fn key_method(&self);

    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_with_argument(&self, parameter: u32);
}

Now, every time someone will implement AdvancedTrait, the most likely implementation of BasicTrait::key_method(&self) is calling key_method_with_argument with some default argument. How can I provide this default implementation (idiomatically) so that anyone implementing AdvancedTrait will (1) only need to implement key_method_with_argument and any other required methods from BasicTrait, and (2) optionally implement key_method() and override the default implementation, only if needed?
Related questions:
having an impl block as proposed in the answer here does not work since the code is expected to implement all other methods of BasicTrait.

A: You can do it by explicitly duplicating the BasicTrait methods into AdvancedTrait, ask your users to only implement AdvancedTrait, and then do a blanket impl for anything implementing AdvancedTrait to also implement BasicTrait. It is probably advisable to give the duplicated methods a name indicating they are just for implementing BasicTrait, and to prevent ambiguous calls:
pub trait BasicTrait {
    fn key_method(&self);
    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_impl(&self) {
        self.key_method_with_argument(0)
    }
    fn other_method_impl(&self);

    fn key_method_with_argument(&self, parameter: u32);
}

impl<T: AdvancedTrait> BasicTrait for T {
    fn key_method(&self) {
        AdvancedTrait::key_method_impl(self)
    }

    fn other_method(&self) {
        AdvancedTrait::other_method_impl(self)
    }
}

You could also call key_method_impl basic_key_method instead, a bunch of naming options exist.

A: The feature you want is called specialization, and unfortunately it is nightly-only and has known soundness holes, so don't expect it to stabilize soon. However, here's how it looks like with it:
#![feature(specialization)]

pub trait BasicTrait {
    fn key_method(&self);

    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_with_argument(&self, parameter: u32);
}

default impl<T: AdvancedTrait> BasicTrait for T {
    default fn key_method(&self) {
        self.key_method_with_argument(12345);
    }
}

Playground.


text:
Q: SQL Server converting integers to decimal I looked at this post: How to convert integer to decimal in SQL Server query? but it is not doing as I had expected.
I have a simple equation - ( [X] - [Y] ) / [X] where X and Y are arbitrary int values from columns. I would like to store the result as a decimal including 1 (or 100%). But when I try to query this, I don't seem to be getting what I expect. If I use the query below - I get 0.
Here is my query so far:
CONVERT(DECIMAL(3, 2), (s4.Duration - s2.Interruption_Min_Total) / s4.Duration) AS Percentage

If you need to see more of my actual query, please ask - I will post it if need be.
Any help on this would be greatly appreciated.

A: You need to force SQL Server to convert int used in the division into a decimal first, then SQL Server will return a decimal:
DECLARE @v1 INT;
DECLARE @v2 INT;
DECLARE @v3 INT;

SET @v1 = 5;
SET @v2 = 2;
SET @v3 = 4;

SELECT (@v1 - @v2) / @v3;

SELECT (@v1 - @v2) / CONVERT(DECIMAL(10,2), @v3);

Please take a look at the answers on this question.


text:
Q: How to get Time ago in java How we can find last comment time ago in minute or hour or day using java
For example:
8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago

A: Add below maven dependency
<dependency>
    <groupId>org.ocpsoft.prettytime</groupId>
    <artifactId>prettytime</artifactId>
    <version>1.0.8.Final</version>
</dependency>

Here is sample code for
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.ocpsoft.pretty.time.PrettyTime;

    public class TestClass {

        public static void main(String[] args) {

            LocalDateTime currentTime = LocalDateTime.now();
            Date before5HrDate = Date.from(currentTime.minusHours(5).atZone(ZoneId.systemDefault()).toInstant());

            PrettyTime p = new PrettyTime();
            String is  = p.format(before5HrDate);

            System.out.println("Is : "  + is );
        }

    }

Answer : Is : 5 hours ago

A: Just perform a substraction between the two date times and give it some formatting with the SimpleDateFormat class.
Here is a link that might help you
https://www.tutorialspoint.com/java/java_date_time.htm

A: // use this class
public class TimeUtils {
  public final static long ONE_SECOND = 1000;
  public final static long SECONDS = 60;

  public final static long ONE_MINUTE = ONE_SECOND * 60;
  public final static long MINUTES = 60;

  public final static long ONE_HOUR = ONE_MINUTE * 60;
  public final static long HOURS = 24;

  public final static long ONE_DAY = ONE_HOUR * 24;

  private TimeUtils() {
  }

  /**
   * converts time (in milliseconds) to human-readable format
   *  "<w> days, <x> hours, <y> minutes and (z) seconds"
   */
  public static String millisToLongDHMS(long duration) {
    StringBuffer res = new StringBuffer();
    long temp = 0;
    if (duration >= ONE_SECOND) {
      temp = duration / ONE_DAY;
      if (temp > 0) {
        duration -= temp * ONE_DAY;
        res.append(temp).append(" day").append(temp > 1 ? "s" : "")
           .append(duration >= ONE_MINUTE ? ", " : "");
      }

      temp = duration / ONE_HOUR;
      if (temp > 0) {
        duration -= temp * ONE_HOUR;
        res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
           .append(duration >= ONE_MINUTE ? ", " : "");
      }

      temp = duration / ONE_MINUTE;
      if (temp > 0) {
        duration -= temp * ONE_MINUTE;
        res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
      }

      if (!res.toString().equals("") && duration >= ONE_SECOND) {
        res.append(" and ");
      }

      temp = duration / ONE_SECOND;
      if (temp > 0) {
        res.append(temp).append(" second").append(temp > 1 ? "s" : "");
      }
      return res.toString();
    } else {
      return "0 second";
    }
  }

  public static void main(String args[]) {
    System.out.println(millisToLongDHMS(123));
    System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
    System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
    System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
    System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
    System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
        + (2 * ONE_MINUTE) + ONE_SECOND));
    System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
        + ONE_MINUTE + (23 * ONE_SECOND) + 123));
    System.out.println(millisToLongDHMS(42 * ONE_DAY));
    /*
      output :
            0 second
            5 seconds
            1 day, 1 hour
            1 day and 2 seconds
            1 day, 1 hour, 2 minutes
            4 days, 3 hours, 2 minutes and 1 second
            5 days, 4 hours, 1 minute and 23 seconds
            42 days
     */
}

}


text:
Q: Система проверки учебных заданий Я хотел бы реализовать проверку учебных проектов, т.е. преподаватель пишет задание и проверку, ученик выполняет задание, ученик загружает java файл(ы) система проверяет задания.
На данный момент единственным путем решения который я вижу:
- Использования Junit для тестов
- Компиляция предоставляемых классов ученика и загрузка их через собственную реализацию classloader с правами установленными в SecurityManager

*

*Как наилучшим образом реализовать это в java. Нет ли уже подобных проектов ?

*Правильно ли я понимаю, что с помощью SecurityManager я могу полностью проконтролировать реализацию ученика(что ученик не полезет в файловую систему, сеть, запустит выполнение приложения и не полезет в реализуемый код(нужно ли мне для этого еще и отделить обычный classloader от реализуемого мной) ) ?

*Я не знаком c docker но как я понимаю он позволяет запускать изолированные приложения не отъедая лишние ресурсы, не будет ли он лучшим решением чем SecurityManager+classloader ?

A: В качестве основы я бы сделал так:

*

*Ученик получает файл .java с шаблоном задания

*Для этого задания уже готов junit тест

*Ученик загружает выполненное задания в какую либо дроп зону

*Программа проверяющая задание, поднимает Docker контейнер с java, подключается к нему через ssl, компилирует там это задание при помощи javac, запускает JUnit тесты и пишет лог

*Ученик получает обработанный лог

Соорудить это все можно при помощи Spring Boot.
Docker, на мой взгляд, наилучший вариант, поскольку он обладает всеми преимуществами виртуальной машины не являясь таковой. К примеру, можно использовать этот контейнер: https://hub.docker.com/r/library/java/
Если же использования докера вызывает проблемы, можно поднять виртуальную машину при помощи Vagrant, скачать образ какого-нибудь Ubuntu с OpenJDK, подключиться туда по SSL и сделать все то же самое что и с докером.
В качестве альтернативы, можно еще попробовать компилировать код прямо в рантайме: https://dzone.com/articles/how-to-compile-a-class-at-runtime-with-java-8-and
Но тогда точно придется трогать SecurityManager.


text:
Q: Controlling the order files appear in Git This is a very minor accessibility issue but I wonder if anyone has addressed it:
Whenever I do git status the files appear in alphabetical order (as they should):
❯ git status
On branch feature
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        src/source.cpp
        src/source.hpp

nothing added to commit but untracked files present (use "git add" to track)

However, I would like my headers to appear before my implementation files. One reason is that whenever I complete a bunch of work, I like to do git add -p to add stage the relevant files. It would be much nicer if I could add the headers first so that I can follow up with the implementation afterwards.
Is there some way to customize git so that I can define my own ordering of files? Something like "alphanumeric for everything before the period, then h takes precedence over everything else in the file extension."

A: Is your question about add -p or status? Because if you only want to add your changed header files, you can specify them via wildcard:
git add -p '**.h'

If you always want to add all your files in the same order of extensions, you can define a Git alias to simplify your life and save you some keystrokes:
git config alias.addall '!f(){ git add -p "**.hpp"; git add -p "**.cpp";};f'


text:
Q: Return 410 (Gone) for URLs containing hash symbol A previous development of a flash based site used URLs of the form http://www.example.com/#!
These URLs have been indexed by Google but I need these URLs to be removed from the search index. Reading the Google documentation, I should be generating a 404 or 410 error.
However, I can't do it on the server-side because the # and everything after it is not included in the GET request. Therefore, in my .htaccess file, there is no way to check for URLs of this form.
I can detect those URLs with the Javascript line below
window.location.hash.match('#!')
then change window.location to a URL that my .htaccess file can match and then use a RewriteRule to return a 410 error.
But will this work with the search bots and/or is there a better way?
Thanks.


text:
Q: Returning UI field attributes in server JSON response Let's say I have multiple form fields to be rendered on the UI. Also, as a standard Modify flow, assume that the fields rendered would have some attributes like value, mandatory, editable, disabled, label, regex (to validate against), etc
While "value" would have to be returned from the service (since it is persisted db value), is it a good practice to also return the other attributes/flags like mandatory, editable, etc from the service which might have some business logic (e.g. the field editable state being true or false is based on some specific workflow status value)
Is it better to avoid anything related to business logic to maintain on the UI V/s the argument that since mandatory, editable, etc are UI specific, they should be maintained on the UI.
Any reference would be helpful.

A: Hyperlinks can be transformed into forms and their parameters into input fields or sub-forms. Very complex GUIs can be generated this way, though there will be still logic which does not have anything to do with the service, e.g. on which panel to display which representation, or how are the displayed representations interrelated, etc. This information can be added to the GUI only by the client developers.
The input field flags you mention describe hyperlink parameters, so they are related to hyperlinks rather than the returned data. If there is a form involved think of it as it was auto-filled with the data, instead of thinking on it as a resource representation.
Afaik. the only REST framework which partially implements this is Hydra, but I already sent such a feature request for better support years ago, which was rejected. Still they appear to go to this direction. https://github.com/hypermedia-app/Alcaeus I am writing a similar framework based on RDF technologies, but it won't be open source. So if you need this for a current work, then probably better to do it manually, because developing a framework for it takes a lot of time.


text:
Q: Print only one line at a time from text file how can I print or display only word from a text file at a time.
When I run my script it should only display each word from the text file one by one, but only display that word.
This is what I have done, but it displays each word on separate line, but it shows all of them:
FS=$'\n'
for j in `cat read`
do
    echo "$j"
done

I want the output to look something like this:
root@matrix:~> first word  ---> this word disappear when second is displayed
root@matrix:~> second word ---> this disappear when third is displayed
root@matrix:~> third word  ---> this disappear when fourth is displayed and continues like this to the end of the file!

A: You can use sleep and clear commands in your script as following:
for word in $(< read)
do
    echo "$word"
    sleep 1
    clear
done

Explanation:
The sleep command make delay for a specified amount of time (in seconds). With sleep 1 delay would be for 1 second. You can change for more time delay by incrementing the second parameter or for delaying less than 1 second divide it to low units; Like sleep .1 for 1/10 second delay or sleep .001 for 1/1000 second delay and etc.
The clear command clear the terminal screen.
Even better you can do this through below awk command:
awk '{i=1; while(i<=NF){ print $((i++)); system("sleep 1; clear") }}' read

Explanation:
In awk, the NF specifies the total number of fields in the current input record/line, so by using a variable as a counter (i) and looping over it, we are printing all of them from 1st position to the end of them (NF). Then by using the system("sleep 1; clear") part, we are telling to awk to calling the system commands to sleeping for 1 second and clearing the screen.

In above we are displaying the input file as word by word. If you are going to display it line by line add IFS=$'\n' in the script like:
IFS=$'\n'
for word in $(< read)
do
    echo "$word"
    sleep 1
    clear
done

And change the awk command like:
awk '{ $0; system("sleep 1; clear") }1' read

*

*$0 specifies the current line. and the 1 on end enables the default awk's print command.

A: With bash, I'd do:
while IFS=$'\n' read -r line
do
    printf "%-${COLUMNS}s\r" "$line"
    sleep 1
done < file

By using the carriage return (\r) instead of line feed (\n), you can overwrite the current line. The -${COLUMNS} pads the output with spaces so that previous lines are completely overwritten.
For a per-word solution, I think a double loop is needed:
while read -ra line
do
    for word in "${line[@]}"
    do
        printf "%-${COLUMNS}s\r" "$word"
        sleep 1
    done
done < file


text:
Q: SSE instruction to interleave top 16-bits of packed 32-bit blocks of two XMM registers? I can't seem to find any SSE instruction that does exactly this
r[15:0]    = a[31:16]
r[31:16]   = a[63:48]
r[47:32]   = a[95:80]
r[63:48]   = a[127:112]
r[79:64]   = b[31:16]
r[95:80]   = b[63:48]
r[111:96]  = b[95:80]
r[127:112] = b[127:112]

Any help would be greatly appreciated.
Looked through this https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html
but it's kind of hard to find exactly what you're looking for, so I may have missed something obvious.


text:
Q: How to interpretate Box-Pierce results in Python? I have made a prediction using an ANN. After that, I have created an error array, which values are the difference between the targets or real values and the predictions.
Once this is made, I want to validate my model. My idea is to do it by using the ACF and the PACF. So far, everything is ok and I obtain the folloging autocorrelation functions:

I think this is not a bad result (ok, there are some important residuals for the first lags, but he rest seem to be within the limits).
Trouble begins when I try to make the Box-Pearce test. All the P-values are really low, under the p-value (0,05). So, I could not consider my prediction is valid.
The code below show the result of Box-Pierce test. The first Matrix shows the statistic values, and the next one shows the p-values (I understand that they are estimated by establishing similarity with the X squared function). So, they are (enormously) under the limits, as I said.

array([ 272.110743  ,  405.31175231,  439.75638084,  445.73745259,
          451.0971869 ,  451.75916969,  452.3519487 ,  452.89218161,
          452.95798727,  453.48704933,  453.62826167,  453.79590874,
          453.88635655,  453.89157604,  454.25958408,  454.26605408,
          454.64673648,  454.7396868 ,  455.01564022,  455.23178931,
          455.39501516,  456.35546367,  456.64498206,  456.73760066,
          456.73775197,  456.76631803,  456.78216617,  457.02755731,
          457.0666677 ,  457.10870398,  457.12327263,  457.13057787,
          457.18305857,  457.22595984,  457.44212799,  457.58639875,
          457.70087134,  457.7026865 ,  457.72151729,  457.83367567,
          457.84085643,  458.05775687,  458.34272957,  458.35522179,
          458.43899971,  458.83023313,  458.92382469,  459.19209704,
          459.30614482,  459.37937575,  459.50949545,  459.60762723,
          459.95879364,  460.42219166,  460.96503055,  461.83552692,
          461.8417434 ,  462.37303705,  462.4111623 ,  462.44848182,
          462.45085587,  462.52814275,  462.89330548,  463.19514212,
          463.21142978,  463.2740221 ,  463.27477873,  463.27499291,
          463.44599611,  463.56698722,  463.78137471,  463.82198247,
          463.83472034,  464.08570346,  464.20285156,  464.21131114,
          464.74779748,  464.98531181,  465.01226428,  465.04772004,
          465.08171724,  465.09383896,  465.09536112,  465.26019974,
          465.29071963,  465.35609093,  465.36409458,  465.3643095 ,
          465.44287389,  465.44294162,  465.98331855,  465.98752041,
          466.05838656,  466.2727417 ,  466.27373189,  466.40820921,
          466.49389354,  466.62259119,  466.80657811,  466.87438758,
          466.87738561,  466.88799094,  466.88934776,  466.98057218,
          466.99017527,  467.67866287,  467.70313436,  467.74555521,
          467.86168569,  468.51407921,  468.75513049,  468.89706442,
          469.25969911,  469.33234657,  469.34241964,  469.38624359,
          469.38842281,  469.40307366,  469.51403827,  469.51420302,
          469.51864191,  469.52036341,  469.54766635,  469.54783568,
          469.55055976,  469.58065015,  469.62841149,  469.64405012,
          469.64581608,  469.64732833,  469.68438062,  469.71349646,
          469.776721  ,  469.85017379,  469.8618585 ,  469.86482696,
          469.86727215,  469.87906817,  469.87921847,  470.03059261,
          470.14087279,  470.14093203,  470.30519246,  470.321453  ,
          470.38251885,  470.49461275,  470.56533691,  470.69619433,
          470.69704975,  470.7253107 ,  470.83405561,  470.85297236,
          471.28296371,  471.29249131,  471.30610246,  471.3144643 ,
          471.38383622,  471.40879785,  471.44070629,  471.4483675 ,
          471.45094532,  471.54371279,  471.54758225,  471.66917668,
          471.67299552,  471.78189924,  471.92764016,  472.26295012,
          472.48249884,  472.83264735,  472.88645481,  472.902301  ,
          472.9318239 ,  473.15098257,  473.40471359,  473.6354701 ,
          473.63612789,  473.63695487,  473.69504236,  473.71545137,
          473.74522537,  473.75902572,  473.76663223,  473.77684943,
          473.77947599,  473.77950094,  473.78420699,  473.79000749,
          473.84358855,  473.95988891,  473.98297885,  474.10741401,
          474.25230545,  474.41629502,  474.4863328 ,  474.69115645,
          474.86070165,  474.87653637,  474.98513961,  474.98533702,
          475.10368542,  475.11420696,  475.28946066,  475.29303731,
          475.29351975,  475.29435603,  475.29448767,  475.30147089,
          475.31299415,  475.33162323,  475.37251441,  475.39703623,
          475.39845353]), array([  3.93449071e-61,   9.72011179e-89,   5.40313202e-95,
           3.62522870e-95,   2.84839023e-95,   2.05263630e-94,
           1.38793137e-93,   8.87609116e-93,   6.68513169e-92,
           3.76844232e-91,   2.43330830e-90,   1.47596379e-89,
           8.88712539e-89,   5.35155942e-88,   2.60007571e-87,
           1.45359733e-86,   6.55927073e-86,   3.29881877e-85,
           1.47545308e-84,   6.60956752e-84,   2.95950172e-83,
           8.83104705e-83,   3.55130700e-82,   1.53418723e-81,
           6.77786031e-81,   2.89345428e-80,   1.21814096e-79,
           4.51465591e-79,   1.81093920e-78,   7.12643120e-78,
           2.79244008e-77,   1.07981416e-76,   4.02320583e-76,
           1.48251071e-75,   4.96551971e-75,   1.69515176e-74,
           5.78582240e-74,   2.05186551e-73,   7.12313276e-73,
           2.33834223e-72,   7.95332666e-72,   2.42766897e-71,
           7.10025320e-71,   2.32396833e-70,   7.27975796e-70,
           1.96227929e-69,   5.98784386e-69,   1.67109429e-68,
           4.94814786e-68,   1.47710577e-67,   4.25576996e-67,
           1.23174311e-66,   3.15513295e-66,   7.62138858e-66,
           1.76239471e-65,   3.49766709e-65,   1.00864087e-64,
           2.28852909e-64,   6.39750609e-64,   1.77383197e-63,
           4.95217856e-63,   1.32708539e-62,   3.11318217e-62,
           7.45182706e-62,   2.00341018e-61,   5.23877001e-61,
           1.39624593e-60,   3.69410298e-60,   9.01711271e-60,
           2.23289252e-59,   5.27663834e-59,   1.33356538e-58,
           3.38675350e-58,   7.72333994e-58,   1.85182224e-57,
           4.61772874e-57,   9.16502214e-57,   2.05035133e-56,
           4.97867896e-56,   1.19703134e-55,   2.86185175e-55,
           6.86192719e-55,   1.64240888e-54,   3.65281892e-54,
           8.53697650e-54,   1.95531743e-53,   4.55861430e-53,
           1.06002041e-52,   2.37384999e-52,   5.45807862e-52,
           1.00269083e-51,   2.27736258e-51,   5.00787940e-51,
           1.03404999e-50,   2.31437154e-50,   4.88476817e-50,
           1.04602971e-49,   2.19096283e-49,   4.46769567e-49,
           9.49396073e-49,   2.05962798e-48,   4.43266170e-48,
           9.52751333e-48,   1.96741236e-47,   4.17470494e-47,
           6.76846474e-47,   1.41544677e-46,   2.92586926e-46,
           5.85145710e-46,   9.47621400e-46,   1.79162426e-45,
           3.50433771e-45,   6.27324486e-45,   1.24966175e-44,
           2.53848888e-44,   5.06882251e-44,   1.02384444e-43,
           2.04951748e-43,   3.94002494e-43,   7.86425584e-43,
           1.56063339e-42,   3.08732409e-42,   6.02479771e-42,
           1.18282664e-41,   2.31061552e-41,   4.45048042e-41,
           8.48317233e-41,   1.62985185e-40,   3.13507931e-40,
           6.00755625e-40,   1.13203241e-39,   2.13125851e-39,
           3.94850669e-39,   7.26181236e-39,   1.36060911e-38,
           2.54783746e-38,   4.75432845e-38,   8.80987406e-38,
           1.63333642e-37,   2.85995820e-37,   5.06432903e-37,
           9.29151554e-37,   1.60356672e-36,   2.90538172e-36,
           5.16452537e-36,   8.98875322e-36,   1.58200455e-35,
           2.71809641e-35,   4.86893706e-35,   8.61092309e-35,
           1.47658413e-34,   2.60286316e-34,   3.97558599e-34,
           6.98782832e-34,   1.22257688e-33,   2.13592664e-33,
           3.64408610e-33,   6.29126594e-33,   1.08024429e-32,
           1.86413128e-32,   3.21225809e-32,   5.35566453e-32,
           9.16875664e-32,   1.50534787e-31,   2.56175677e-31,
           4.19939163e-31,   6.78266693e-31,   1.02720095e-30,
           1.61143383e-30,   2.41728017e-30,   3.98077543e-30,
           6.61733600e-30,   1.09205554e-29,   1.69149628e-29,
           2.58497509e-29,   3.96996081e-29,   6.54199200e-29,
           1.07493467e-28,   1.72987386e-28,   2.80938745e-28,
           4.53678913e-28,   7.34294648e-28,   1.18752913e-27,
           1.91375433e-27,   3.08298577e-27,   4.95713772e-27,
           7.93778548e-27,   1.26725639e-26,   1.98870385e-26,
           3.05435889e-26,   4.81343167e-26,   7.33880391e-26,
           1.10945200e-25,   1.66384536e-25,   2.56036793e-25,
           3.77617199e-25,   5.61574285e-25,   8.71983245e-25,
           1.31425282e-24,   2.04010147e-24,   3.05178795e-24,
           4.70013029e-24,   6.88416735e-24,   1.05737058e-23,
           1.62154511e-23,   2.48043736e-23,   3.78583817e-23,
           5.75307181e-23,   8.71045462e-23,   1.31304980e-22,
           1.96236933e-22,   2.93957477e-22,   4.42174505e-22]))

This has been made by calling:

from statsmodels.stats.diagnostic import acorr_ljungbox
  box_pierce=acorr_ljungbox(error, lags=int((len(error)-1)/5),boxpierce=True)

I do not understand why I get discordance between the ACF's and the Box-Pearce test. Can anybody say what's happening?
EDIT
I have used this function to calculate the Box-Pierce test.
It seems to be that I have used it in the wrong way, but I cannot find the mistake.
If I have understood well, I have written the function properly(?).
But if the ACF and PACF look not so bad (correlations seem to be within the limits of 95%), why the results of the Box-Pierce test are so bad?
I add more information. What you can see below is an image of a significative part of the predicted time series vs reference time series. By seeing this, I would say predictions are not bad. The problem is that the errors are big because the variable I'm predicting has big values. Has this something to do with the (bad) results of residuals?

And I think I got a good R coefficent:
R= 0.9762

A: The autocorrelation at the first couple of lags is too strong for the Box-Pierce test to tell you it is not statistically significant. Also the lag six is statistically significant and lags three, four and seven are borderline-significant. Pretty pronounced autocorrelation, I would say.
Normally the first lags are the ones that matter the most. We can think that autocorrelation at some further lags may spike due to chance (except for the lags corresponding to the seasonal period(s), which can sometimes be long), while the ones at the first few lags are often treated as genuine as we can find subject-matter or model-specific explanations why they could be there.
In short, both the ACF and the Box-Pierce test tells you the residuals are autocorrelated.


text:
Q: memached out-of-the-box fallback solution I want to use Memached together with native PHP sessions. However, it would be great if there was a simple solution to have the Memcached deamon write the data held in memory to a on-disk database at a fixed interval as a fallback. Are there any solutions for this? I don't want to reinvent the wheel..

A: What you will need to do is write a custom session handler that uses memcached but also writes to your database. You can use session_set_save_handler to do this.


text:
Q: C++20: generate type from given variadic types Lets say, I have a variadic type list which can grow
e.g.
#define MY_TYPES  void, float, int, vector<long>, .....

I am looking for way to generate these type definition at compile time in c++17/20 in generic way, e.g.
#define to_tuple(MY_TYPES) ==> std::tuple<future<void>, future<float>, future<int>....>
using tupleType = decltype(to_tuple<ALL_TYPES>); // this can be then used in struct as a member.

struct foo {
   ...
   ...
   tupleType tups;
}

or, alternatively if this can be done using template metaprogramming ?
Thanks for the help.

A: template <typename ...P>
using tuple_of_futures_t = std::tuple<std::future<P>...>;

using X = tuple_of_futures_t<void, float, int, std::vector<long>>;


text:
Q: Rewriting statements without using any quantifiers Let $ P$ and $Q$ be predicates on the set $S$, where $S$ has three elements, say, $S = {a, b, c}$.
Then the statement $∀xP(x)$ can also be written in full detail as $P(a)∧P(b)∧P(c)$. Rewrite
each of the statements below in a similar fashion, using P, Q, and logical operators, but
without using quantifiers.
$(b) ∃xP(x)∧∃xQ(x)$
$(c) ∃x, y(P(x)∧Q(y))$
$(d) ∀x∃y(P(x) ∧ Q(y))$
I got the same answer for both part (b) and part (c) and (d), which is
$[P(a) ∨ P(b) ∨ P(c)] ∧ [Q(a) ∨ Q(b) ∨ Q(c)]$
... except it can't be the right answer for all of these statements, i believe. I'm not sure what I did wrong in coming up with these answers.

A: For (c), think of the possible ways you can assign $(x,y)$ from the set $S$. $P(x) ∧ Q(y)$ must be true for at least one of those -- i.e. you can substitute each pair and join the expressions with a logical 'or'.
(d), from the rule you stated, can be rewritten $$\exists y (P(a) ∧ Q(y)) ∧ \exists y (P(b) ∧ Q(y)) ∧ \exists y (P(c) ∧ Q(y)).$$ From there, it shouldn't be too difficult to replace the $\exists$ with equivalent 'or' statements.


text:
Q: Accepting null hypothesis given specificity In a population of 10000 people, there is a 2% chance that someone has cancer. The false positive rate is also 2%.
Null hypothesis: no one in the population of 10000 has cancer.
From my understanding, this can be solved by first calculating the p-value (1-0.98 = 0.02 in this case), and then calculating the probability that no one has cancer. I'm a little stuck with the second portion however - it seems like an application of Bayes theorem, but I'm not sure exactly how to formulate it. Any help would be appreciated!
Edit: this is what I'm planning to do:
P(patient is actually negative) = P(patient tests negative) + P(negative|tests positive).
P(all 10000 are negative) = P(patient negative)^10000
If P(10000 negative) > 0.02, null hypothesis can be accepted
Are there any issues with this approach?


text:
Q: angular creating too many scopes My application consists of a table of results (in a ng-repeat) with a pager and pageSize options. Each time I click on the pager or change the page size, a new request is made to the API and the data inside my loop is updated, cause new scopes to appear. I'm having aperformance problem since this is creating an incredible number of scopes each page request / pageSize request when I check batarang. Is there a way to control this scope creation? I'm using Angular 1.3.3.
UPDATE: http://jsfiddle.net/z561z7ok/
contains basically the items which are too much 'scoped', and the service serving the data. the pagination call sends a request to get new data.

    <pagination total-items="totalItems" ng-model="currentPage" previous-text="«" next-text="»" ng-click="triggerPager(currentPage)" max-size="maxSize" items-per-page="itemsDisplayedByPage"></pagination>

 0">

Service:
services.factory('fruitsCollectionService', ['$rootScope', '$http',
function($rootScope, $http) {
    var fruitsCollectionModel = function() {
        var collection = []
    };
    fruitsCollectionModel.prototype.getFruitsCollection = function(params) {
        var self = this;

        return $http.get(\\APICALL, {
            cache: params.cached == true,
            params: {
                //a few params
            },
            withCredentials: true
        }).then(
            function(response) {

                self.collection = response.data.fruits;

                if(response.data.fruits.items.length > 0) {
                    angular.forEach(response.data.fruits.items, function(fruit, key) {
                        $rootScope.objectCache[fruit.id] = fruit;
                    });
                }

                return response;
            },
            function(response) {
                // bring error notification to view

            }
        );
    };

    return fruitsCollectionModel;
}]);


text:
Q: Weird tab error, can't put my finger on where I went wrong I'm trying to make use of a while loop to iterate through a list of three variables that's are also assigned to three queues implemented through linked lists. I called this list full. My while loop is supposed to keep running while my list of full queues is still at 3.
Here's the chunk of code. I get the tab error after the pop function.
while len(full) == 3:
x = random.random()
if 0 <= x <.33:
    if full[0].isEmpty() == True:
        full.pop(0)
    else:
    Runway.enqueue(airplane)

A: You have at least one tab character in your code at the start of your else: line. (There are two tabs in this editor--there may be only one in your code.) The other lines use spaces.
In Python it is a very good idea to use only spaces in your code and never use tabs. It is possible to use some tabs and get away with it, but getting away with it is very unlikely. Set your code editor to insert spaces when you press the Tab key--all good editors have a setting for that.
In the code you show us, the line after the else: is not indented at all, so that should also give you an error. Indent that line by four spaces, after you replace the tabs with spaces in the else: line.

A: You are getting a tab error because you're mixing tabs and spaces in your indentation.
I copy pasted your code and the "else" line starts with a tab instead of 4 spaces. Try changing it to 4 spaces and see if the problem is fixed.


text:
Q: how to extract the data from mysql database and plot them in highcharts using yii-framework mysql database has three elements, id,datetime and data.
Please kindly help me check what is wrong with my code. i want to extract latest 15 data form mysql database and plot them in highcharts. however, i can only display latest single data on the graph beside my x-axis has not displayed datetime data.
i tried the codes provides on web http://www.highcharts.com/demo/line-basic however it is only for predefined values and not for the mysql database values.
i tried to edit it and below is my code.
<script scr = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='http://code.highcharts.com/highcharts.js' type='text/javascript'> </script>
<script src='http://code.highcharts.com/modules/exporting.js' type='text/javascript'> </script>

</head>
<?php
$rowsA = array();
$rowsA[]= Yii::app()->db->createCommand("Select data from customername order by id desc limit 15")->queryScalar();
$datedata[] = Yii::app()->db->createCommand("Select date from customername order by id desc limit 15")->queryScalar();
>
<script type = "text/javascript">
$(function () {
    $('#container').highcharts({
        chart: {
        type: 'line',
        marginRight: 130,
        marginBottom: 25
    },
        title: {
            text: 'BABY BODY TEMPERATURE',
            x: -20
        },

        xAxis: {

       // type: 'datetime',
       // dateTimeLabelFormats:{
        //   month: '%e, %b',
          //  year: '%b'}//can work
     //  categories: ['<php echo join($datedata, "','") ?>'],
     // categories: [<php  echo join($datedata, "','"); ?>],
        //  },

        },
        yAxis: {
            title: {
            text: 'Temperature (°C)'
            },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        valueSuffix: '°C',

    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        x: -10,
        y: 100,
        borderWidth: 0
    },
    series: [{
        name: 'Baby Temperature',
        data: [<?php echo join($rowsA, "','");?>]

        //predefined data is working fine.
       // data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
 });
});

</script>

i was thinking after i am able to extract mysql data and plot it in highcharts for x axis is in number forms 1,2,3,.... then i will try to display datetime in x axis. however, i was stucked at my first stage; can only display single latest data while what i want is 15 data.
I will be very appreciated if anyone can help me. Thanks a lot inadvance.

A: Never query in your view file. Make getter in your model or query in controller and pass data to view.
For dates for x-label form array. For example i form array for last 30 days:
        $output = array();
        for($i = 30; $i >=0 ; $i--)
        $output[] = date("Y-m-d", strtotime('-'. $i .' days'));
        return $output;

It will be our x-labels. Then get your data in model or controller:
$criteria=new CDbCriteria;
        $criteria->limit=15;
        $criteria->order='id DESC';
$data=new CActiveDataProvider(, array('customername'
            'criteria'=>$criteria,
        ));

Now form your array for series from your data.
Yii-highcharts is great extension that helps alot.
Then push it to your plot:
'xAxis'=>array(
                'categories'=> $xlabels,
                'gridLineWidth' => 1,
                'gridLineDashStyle' => 'LongDash',
                'tickmarkPlacement' => 'on',
                'tickInterval' => 6
                    ),

'series'=> array(

            array('name'=> 'Failed records',
                'data'=> $data_array,
                'color' => '#ff0000',
                'shadow'=> false
            ),

With yii-highcharts or echo php variables in javascript:
var xlabels="<?php echo $xlabels?>";

Then use it in your plot:
xAxis:{
                categories: xlabels,
                gridLineWidth : 1,
                gridLineDashStyle : 'LongDash',
                tickmarkPlacement : 'on',
                tickInterval : 6
                    },


text:
Q: Display enum descriptions inside razor views I have a model with enumerated properties as below:
namespace ProjectManager.Models
{
    public class Contract
    {
        .....
        public enum ContractStatus
        {
            [System.ComponentModel.Description("جديد")]
            New,
            [System.ComponentModel.Description("در انتظار پرداخت")]
            WaitForPayment,
            [System.ComponentModel.Description("پرداخت شده")]
            Paid,
            [System.ComponentModel.Description("خاتمه يافته")]
            Finished
        };

        public ContractStatus Status { get; set; }
        .....
    }

}

Inside my razor views, I want to display enum descriptions for each item, e.g. جديد instead of New. I tried to follow instructions in this answer, but I don't know where to add extension method and how to call extension method inside my razor view file. I would be thankful if someone can complete my code:
@model IEnumerable<ProjectManager.Models.Contract>
....

        .....
        @Html.DisplayNameFor(model => model.Status)
        .....

@foreach (var item in Model) {

        ......

            @Html.DisplayFor(modelItem => item.Status)  //<---what should i write here?

        ....

            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Id })|

}

A: You can put the extension method anywhere. For example in your current project, add a folder (say) Extensions and then add a static class
namespace yourProject.Extensions
{
    public static class EnumExtensions
    {
        public static string DisplayName(this Enum value)
        {
            // the following is my variation on the extension method you linked to
            if (value == null)
            {
                return null;
            }
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field
                .GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            return value.ToString();
        }
    }
}

although I would consider creating a separate project and add a reference to it in your current project so that you can use it (and other useful extension methods) across multiple projects.
Then include a @using yourProject.Extensions; statement in the view and use it as
@item.Status.DisplayName()

Note also that to avoid the using statements in the view, you can add the assembly to your web.config.cs file
<system.web>
    ....
    <pages>
        <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="yourProject.Extensions" />


text:
Q: Spark alternative for Redshift REGEXP_SUBSTR function Trying to convert part of Redshift query into SparkSQL or some combo of SQL and UDF:
REGEXP_SUBSTR(referrer, '[^/]+\\.[^/:]+') as referrer_domain,

Tried using regexp_extract(referrer, '[^/]+\\.[^/:]+', 1), but that doesn't seem to work the same way and returns results inconsistently.
Any pointers appreciated!

A: You should be able to use regexp_extract in spark sql, something like this -
regexp_extract(columnName, '(YourRegex)', 1) as aliasName

Note the () around regex to capture the group. Hope it helps!


text:
Q: Is there any other way to get Laravel to reload env variables? I have a shared hosting account on a well known host.
I have my Laravel site uploaded and functioning for the most part. But I had to make an env change. Now I can't get Laravel to see the change.
I know this is common issue. I have tried running the artisan commands to clear config and cache (php artisan config:cache  & php artisan cache:clear  ) but this fails with an error:

Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home4/cmatthewc/cvbaptistapp/artisan on line 33

Is there any other way to get Laravel to refresh its cache from env?
TY in advance...

A: THE ISSUE
The issue lies in the php cli version of the server. Laravel 5.6 expects you to have PHP 7.1.3 or greater.
More specifically, the exact reason you're getting this error, from the documentation:

Since PHP 5.5, the class keyword is also used for class name
  resolution. You can get a string containing the fully qualified name
  of the ClassName class by using ClassName::class. This is particularly
  useful with namespaced classes.

And if you look on line 33 in the artisan file in your project root:
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

And since the server is running 5.4 when you run commands via the CLI, PHP has no idea what the syntax means, so it throws an error.
THE FIX
In order to fix this, you'll need to upgrade your PHP version.


text:
Q: Do not download file with curl if file already exists locally I am currently doing with curl:
curl https://example.com/file -o file

If I already have a file called file in my directory, it will be overwritten by this command. Instead, I would like to return an error message telling that the file already exists.
Is it possible to do so only using curl? I have not seen a flag to do it and I am not running the command in a bash script thus I cannot use a comparison operator before running the command.

A: Testing for the existence of a name in a directory may be done with the -e test:
if [ -e "filename" ]; then
    echo 'File already exists' >&2
    exit 1
fi

curl -o "filename" "URL"

If you don't want to terminate the script at that point:
if [ -e "filename" ]; then
    echo 'File already exists' >&2
else
    curl -o "filename" "URL"
fi

The test will be true if the name exists, regardless of whether the name is that of a regular file, directory, named pipe or other type of filesystem object.
See man test on your system.

A: I highly recommend checking this answer regarding the -C - curl option. Essentially, resume the download. If the file is already complete, then there's nothing to do. This will call the server for resume checking.


text:
Q: On the existence of $ \lim_{x \to 0^{+}} \frac{\log(f(x))}{\log(x)} $ under certain constraints. I am considering a continuously differentiable real-valued function $ f: (0,1) \to (0,\infty) $ such that:

*

*$ f $ is decreasing on $ (0,1) $.

*$ \displaystyle \lim_{x \to 0^{+}} f(x) = \infty $.

*The map $ x \mapsto x^{2} f'(x) $ is decreasing on $ (0,1) $.

*$ \displaystyle \lim_{x \to 0^{+}} x^{2} f'(x) = 0 $.

I am wondering if, under these constraints, the limit $ \displaystyle \lim_{x \to 0^{+}} \frac{\log(f(x))}{\log(x)} $ exists.
Thanks a lot to anybody who has any thought/counterexample, or spent time reading this question!