问:
lang.NumberFormatException in android
I have the following code which does nothing but reading some values from a DB in a background thread and using the values I draw a Line chart using a jar.For the line chart I use for value for each array and the problem is that the third that I pass to the constructor that draws the LineChart is float....

```<code>float[] viteza;

String[] time;

int contor=0;
</code>```

```<code>public void onResume() {

    super.onResume();

    init_task = new InitTask();

    init_task.execute(db);

}

public class InitTask extends AsyncTask<DBAdapter,String, Void> {

    String TABLE_3;

    protected Void doInBackground(DBAdapter... db) {
        try {
            db[0].createDatabase();
            db[0].openDataBase();
            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            String[] array=new String[2];
            viteza = new float[c.getCount()];
            time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    publishProgress(c.getString(3),c.getString(4));
                    Thread.sleep(500);

                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }

    protected void onProgressUpdate(String...values) {

        Aitem items[] = new Aitem[1];

        viteza[contor]=Float.valueOf(values[0]);
        time[contor]=values[1];
        if(contor>3)
        {
        items[0]=new Aitem(Color.RED, "Evolution",viteza);
        lv.setTitle("Evolutia vitezei");

        lv.setAxisValueX(time);

        setContentView(lv);
        }
        contor++;
    }

}

}
</code>```

I get error at this line:

```<code>viteza[contor]=Float.valueOf(values[0]);

java.lang.NumberFormatException:
   at org.apache.harmony.luni.util.FloatingPointParser.parseFltImpl(Native Method)
 at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:321)
</code>```

Has anyone any clue what is gooing wrong???

EDIT:

In my humble opinion values[0]=c.getString(3)  and values[1]=c.getString(4) so ....are Strings...aren't they?

答: I'm not sure just by looking at this, but I can tell you, this is where Log.v is extremely handy. Put a Log.v(TAG,"\""+values[]+"\""), and you'll see exactly what's getting to that function. If it's anything other than a pure number, that'd be what's causing the exception to occur.</p>

Title: lang.NumberFormatException in android

Body:
I have the following code which does nothing but reading some values from a DB in a background thread and using the values I draw a Line chart using a jar.For the line chart I use for value for each array and the problem is that the third that I pass to the constructor that draws the LineChart is float....

float[] viteza;

String[] time;

int contor=0;

public void onResume() {

    super.onResume();

    init_task = new InitTask();

    init_task.execute(db);

}

public class InitTask extends AsyncTask<DBAdapter,String, Void> {

    String TABLE_3;

    protected Void doInBackground(DBAdapter... db) {
        try {
            db[0].createDatabase();
            db[0].openDataBase();
            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            String[] array=new String[2];
            viteza = new float[c.getCount()];
            time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    publishProgress(c.getString(3),c.getString(4));
                    Thread.sleep(500);

                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }

    protected void onProgressUpdate(String...values) {

        Aitem items[] = new Aitem[1];

        viteza[contor]=Float.valueOf(values[0]);
        time[contor]=values[1];
        if(contor>3)
        {
        items[0]=new Aitem(Color.RED, "Evolution",viteza);
        lv.setTitle("Evolutia vitezei");

        lv.setAxisValueX(time);

        setContentView(lv);
        }
        contor++;
    }

}

}

I get error at this line:

viteza[contor]=Float.valueOf(values[0]);

java.lang.NumberFormatException:
   at org.apache.harmony.luni.util.FloatingPointParser.parseFltImpl(Native Method)
 at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:321)

Has anyone any clue what is gooing wrong???

EDIT:

In my humble opinion values[0]=c.getString(3)  and values[1]=c.getString(4) so ....are Strings...aren't they?


来源: stackexchange

问:
Django using "." as primary key gives 404
I am using DRF along with drf-nested-routers to configure my routing. I have an api route structure this way.

/posts/1/comments

Now instead of using the id I have decided to use the name of the object instead.

/posts/mypost/comments

This works perfectly but an issue occurs when a . is being added to the key.

/posts/my.post/comments

When including a . as part of the key for the resource, it returns a 404 error on Django. I have been trying to debug this issue to no avail.

答:
Probably the reason is you are not allowing dot . in your url pattern.

You can just add the characters you want to accept as part of your url inside the square brackets:

```<code>url(r'^posts/(?P<post_name>[-\w.]+)/comments/$', views.your_view)
</code>```

The above include . and - along with all word characters(alphanumeric and underscore).

ContentLicense: CC BY-SA 4.0

Body:
Probably the reason is you are not allowing dot . in your url pattern.

You can just add the characters you want to accept as part of your url inside the square brackets:

url(r'^posts/(?P<post_name>[-\w.]+)/comments/$', views.your_view)

The above include . and - along with all word characters(alphanumeric and underscore).


问:
How can I (slice) pattern match on an owned Vec with non-Copy elements?
My goal is to move elements out of an owned Vec.

fn f<F>(x: Vec<F>) -> F {
    match x.as_slice() {
        &[a, b] => a,
        _ => panic!(),
    }
}
```

<p>If <code>F</code> is copy, that is no problem as one can simply copy out of the slice. When <code>F</code> is not, slice patterns seem a no-go, as the slice is read only.</p>

<p>Is there such a thing as an "owned slice", or pattern matching on a <code>Vec</code>, to move elements out of <code>x</code>?</p>

<p><strong>Edit:</strong> I now see that this code has the more general problem. The function</p>

<pre class="lang-rust prettyprint-override"><code>fn f<T>(x: Vec<T>) -> T {
    x[0]
}
</code>```

leaves "a hole in a Vec", even though it is dropped right after. This is not allowed. This post and this discussion describe that problem.

That leads to the updated question: How can a Vec<T> be properly consumed to do pattern matching?

答:
If you insist on pattern matching, you could do this:

```<code>fn f<F>(x: Vec<F>) -> F {
    let mut it = x.into_iter();
    match (it.next(), it.next(), it.next()) {
        (Some(x0), Some(_x1), None) => x0,
        _ => panic!(),
    }
}
</code>```

However, if you just want to retrieve the first element of a 2-element vector (panicking in other cases), I guess I'd rather go with this:

```<code>fn f<F>(x: Vec<F>) -> F {
    assert_eq!(x.len(), 2);
    x.into_iter().next().unwrap()
}
</code>```

Body:
My goal is to move elements out of an owned Vec.

fn f<F>(x: Vec<F>) -> F {
    match x.as_slice() {
        &[a, b] => a,
        _ => panic!(),
    }
}

If F is copy, that is no problem as one can simply copy out of the slice. When F is not, slice patterns seem a no-go, as the slice is read only.

Is there such a thing as an "owned slice", or pattern matching on a Vec, to move elements out of x?

Edit: I now see that this code has the more general problem. The function

fn f<T>(x: Vec<T>) -> T {
    x[0]
}

leaves "a hole in a Vec", even though it is dropped right after. This is not allowed. This post and this discussion describe that problem.

That leads to the updated question: How can a Vec<T> be properly consumed to do pattern matching?

Body:
If you insist on pattern matching, you could do this:

fn f<F>(x: Vec<F>) -> F {
    let mut it = x.into_iter();
    match (it.next(), it.next(), it.next()) {
        (Some(x0), Some(_x1), None) => x0,
        _ => panic!(),
    }
}

However, if you just want to retrieve the first element of a 2-element vector (panicking in other cases), I guess I'd rather go with this:

fn f<F>(x: Vec<F>) -> F {
    assert_eq!(x.len(), 2);
    x.into_iter().next().unwrap()
}


问:
Modifying of css by document.styleSheets
I try to modify CSS by changing:

```<code>document.styleSheets[0].cssRules[0].style.fontSize = '1rem';
</code>```

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

答:
Modifying styleSheets directly can be tricky.

I prefer to append a new style element to the document and place the modified CSS in there. Since it is the last style element in the document, it will override any earlier CSS rule that has a matching selector.

For example, this will set the font size of the body to 1rem:

let style = document.createElement('style');
style.innerHTML = 'body { font-size: 1rem; }';
document.head.appendChild(style);
```

Body:
I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.


问:
Is there a GREL OpenRefine function to identify and remove columns that do not contain any entries
I have a large project with many columns. Some columns have entries, but many columns do not have any entries. Is there a way of identifying which columns are completely empty and then removing these columns? Can this action be written in GREL to apply to the whole project in one go?

Currently using OpenRefine version 2.8

答:
You can identify columns that have no values in them, but you can't remove those automatically.

In OpenRefine 2.8 you can create a Custom Text Facet on any column with the GREL:

```<code>filter(row.columnNames,cn,isBlank(cells[cn].value))
</code>```

This will create a facet that lists each column with the count being the number of blank values in that column. If that count is the same as the number of rows in the project, there are only blank cells in that column

In OpenRefine 3.2 onwards the facet is directly available in the drop down menu on the "All" column

Unfortunately after identifying columns that contain only blank values your only option is to remove them using the usual mechanisms for removing columns in OpenRefine - there is no way to write a GREL that identifies the columns and removes them.

Body:
You can identify columns that have no values in them, but you can't remove those automatically.

In OpenRefine 2.8 you can create a Custom Text Facet on any column with the GREL:

filter(row.columnNames,cn,isBlank(cells[cn].value))

This will create a facet that lists each column with the count being the number of blank values in that column. If that count is the same as the number of rows in the project, there are only blank cells in that column

In OpenRefine 3.2 onwards the facet is directly available in the drop down menu on the "All" column

Unfortunately after identifying columns that contain only blank values your only option is to remove them using the usual mechanisms for removing columns in OpenRefine - there is no way to write a GREL that identifies the columns and removes them.


问:
How to modify the image in the JMeter script?
I'm uploading the image with the following JMeter script. But we have the requirement to modify the image for every request so that virus scanner scans it every time.  Can anyone please suggest how to modify the image? Thanks.

 <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true">
          <elementProp name="HTTPsampler.Files" elementType="HTTPFileArgs">
            <collectionProp name="HTTPFileArgs.files">
              <elementProp name="Sample.JPG" elementType="HTTPFileArg">
                <stringProp name="File.path">Sample.JPG</stringProp>
                <stringProp name="File.paramname">File</stringProp>
                <stringProp name="File.mimetype">image/jpeg</stringProp>
              </elementProp>
            </collectionProp>
          </elementProp>```

答:
You can use ImageIO class in order to add something to the original image

Add JSR223 PreProcessor as a child of the HTTP Request sampler which performs the image upload

Put the following code into "Script" area:

```<code>def image = javax.imageio.ImageIO.read(new File('Sample.jpg'))
def graphics = image.getGraphics()
graphics.setFont(graphics.getFont().deriveFont(16f))
graphics.drawString('User ' + ctx.getThreadNum() + '; iteration: ' + ctx.getVariables().getIteration(), 50, 50)
graphics.dispose()
javax.imageio.ImageIO.write(image, "jpg", new File("Sample.jpg"))
</code>```

That's it, when you run your test the above code will add current user and iteration text to the upper-left corner of the image (the font color is white so if your image is white you won't be able to see it using your eyes)

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

If any concurrency is assumed - consider making the copy of the image and updating the filename in the HTTP Request sampler otherwise you will run into race condition when multiple threads will be simultaneously writing into the same file so the image will get corrupt.

Body:
You can use ImageIO class in order to add something to the original image

Add JSR223 PreProcessor as a child of the HTTP Request sampler which performs the image upload

Put the following code into "Script" area:

def image = javax.imageio.ImageIO.read(new File('Sample.jpg'))
def graphics = image.getGraphics()
graphics.setFont(graphics.getFont().deriveFont(16f))
graphics.drawString('User ' + ctx.getThreadNum() + '; iteration: ' + ctx.getVariables().getIteration(), 50, 50)
graphics.dispose()
javax.imageio.ImageIO.write(image, "jpg", new File("Sample.jpg"))

That's it, when you run your test the above code will add current user and iteration text to the upper-left corner of the image (the font color is white so if your image is white you won't be able to see it using your eyes)

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

If any concurrency is assumed - consider making the copy of the image and updating the filename in the HTTP Request sampler otherwise you will run into race condition when multiple threads will be simultaneously writing into the same file so the image will get corrupt.


问:
Why Do I get Xcode 1.5 not supported?
I am trying to install Cairo/Xlib on macOS I couldn't get this to work

cmake -G "Xcode" --config Debug "-DCMAKE_BUILD_TYPE=Debug" ../.

```<code>    CMake Error:
  Xcode 1.5 not supported.

CMake Error: Could not create named generator Xcode

Generators
* Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Ninja Multi-Config           = Generates build-<Config>.ninja files.
  Xcode                        = Generate Xcode project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
</code>```

答:
First Google result for "cmake XCode" is https://cmake.org/cmake/help/v3.9/generator/Xcode.html which says

This supports Xcode 3.0 and above.

So, apparently this message comes from CMake.

Title: Why Do I get Xcode 1.5 not supported?

Body:
I am trying to install Cairo/Xlib on macOS I couldn't get this to work

cmake -G "Xcode" --config Debug "-DCMAKE_BUILD_TYPE=Debug" ../.

    CMake Error:
  Xcode 1.5 not supported.

CMake Error: Could not create named generator Xcode

Generators
* Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Ninja Multi-Config           = Generates build-<Config>.ninja files.
  Xcode                        = Generate Xcode project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.


问:
Bind Unbind onclick event not working with Ajax
I am having an issue with bind & unbind onClick listener using JQuery Ajax.

How to unbind on click event that it can't be clicked multiple times, but bind it if ajax fails. this is what I have tried so far.

```<code>$('#test').on('click', function (e) {
 e.preventDefault();
 alert('clicked');
 $( "#test" ).off( "click");// works fine,remove on click listner
 // Ajax function
 // done()  // Do nothing.
 // error() // bind it again so it can be clicked.
});
</code>```

https://jsfiddle.net/khirad1996/4nLdvq9s/2/

答:
You can disable the button while the call is happening, and re-enable if there is an error!

const fakeAjax = time => new Promise(r => setTimeout(() => r(Math.random() > .5), time))

const button = document.querySelector('button');

button.addEventListener('click', async function() {
  this.disabled = true;
  error = await fakeAjax(1000);
  this.disabled = error;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Ajax Call</button></code>```

Body:
I am having an issue with bind & unbind onClick listener using JQuery Ajax.

How to unbind on click event that it can't be clicked multiple times, but bind it if ajax fails. this is what I have tried so far.

$('#test').on('click', function (e) {
 e.preventDefault();
 alert('clicked');
 $( "#test" ).off( "click");// works fine,remove on click listner
 // Ajax function
 // done()  // Do nothing.
 // error() // bind it again so it can be clicked.
});

https://jsfiddle.net/khirad1996/4nLdvq9s/2/

Body:
You can disable the button while the call is happening, and re-enable if there is an error!

const fakeAjax = time => new Promise(r => setTimeout(() => r(Math.random() > .5), time))

const button = document.querySelector('button');

button.addEventListener('click', async function() {
  this.disabled = true;
  error = await fakeAjax(1000);
  this.disabled = error;
});

<button>Ajax Call</button>


答:
When I last dealt with this manipulating the CSSOM was not supported very well by many browsers (and I think that didn't change yet).

If you want to apply styles to single Element do it on the Element directly.

If you want to generate css rules at runtime you could also consider dropping a style tag into your document:

```<code>var style = document.createElement('style');

// set style properties
// append the style tag to the head or somewhere in the body

head.appendChild(style);
</code>```

Title: Modifying of css by document.styleSheets

Body:
When I last dealt with this manipulating the CSSOM was not supported very well by many browsers (and I think that didn't change yet).

If you want to apply styles to single Element do it on the Element directly.

If you want to generate css rules at runtime you could also consider dropping a style tag into your document:

var style = document.createElement('style');

// set style properties
// append the style tag to the head or somewhere in the body

head.appendChild(style);


问:
desktop application / script to interact with javascript on web application
My work has tasked me with determining the feasibility of migrating our existing in-house built change management services(web based) to a Sharepoint solution. I've found everything to be easy except I've run into the issue that for each change management issue (several thousand) there may be any number of attachment files associated with them, called through javascript, that need to be downloaded and put into a document library.

(ex. ... onClick="DownloadAttachment(XXXXX,'ProjectID=YYYY');return false">Attachment... ).

To keep me from manually selecting them all I've been looking over posts of people wanting to do similar, and there seem to be many possible solutions, but they often seem more complicated than they need to be.

So I suppose in a nutshell I'm asking what would be the best way to approach this issue that yields some sort of desktop application or script that can interact with web pages and will let me select and organize all the attachments.  (Making a purely web based app (php, javascript, rails, etc.) is not an option for me, so throwing that out there now).

Thanks in advance.

答:
Given a document id and project id,
XXXXX and YYYY respectively in
your example, figure out the URL
from which the file contents can be
downloaded. You can observe a few
URL links in the browser and detect
the pattern which your web
application uses.

Use a tool like Selenium to get a
list of XXXXXs and YYYYs of
documents you need to download.

Write a bash script with wget to
download the files locally and put
in the correct folders.

ContentLicense: CC BY-SA 3.0


问:
R merge two datasets based on specific columns with added condition
Both Uwe's and GKi's answer are correct. Gki received the bounty because Uwe was late for that, but Uwe's solution runs about 15x as fast

I have two datasets that contain scores for different patients on multiple measuring moments like so:

```<code>df1 <- data.frame("ID" = c("patient1","patient1","patient1","patient1","patient2","patient3"),
                  "Days" = c(0,25,235,353,100,538),
                  "Score" = c(NA,2,3,4,5,6),
                  stringsAsFactors = FALSE)
df2 <- data.frame("ID" = c("patient1","patient1","patient1","patient1","patient2","patient2","patient3"),
                  "Days" = c(0,25,248,353,100,150,503),
                  "Score" = c(1,10,3,4,5,7,6),
                  stringsAsFactors = FALSE)
> df1
        ID Days Score
1 patient1    0    NA
2 patient1   25     2
3 patient1  235     3
4 patient1  353     4
5 patient2  100     5
6 patient3  538     6

> df2
        ID Days Score
1 patient1    0     1
2 patient1   25    10
3 patient1  248     3
4 patient1  353     4
5 patient2  100     5
6 patient2  150     7
7 patient3  503     6
</code>```

Column ID shows the patient ID, column Days shows the moment of measurement (Days since patient inclusion) and column Score shows the measured score. Both datasets show the same data but in different moments in time (df1 was 2 years ago, df2 has the same data with updates from this year).

I have to compare the scores for each patient and each moment between both datasets. However, in some cases the Days variable has minor changes over time, so comparing the dataset by a simple join does not work. Example:

```<code>library(dplyr)

> full_join(df1, df2, by=c("ID","Days")) %>%
+   arrange(.[[1]], as.numeric(.[[2]]))

        ID Days Score.x Score.y
1 patient1    0      NA       1
2 patient1   25       2      10
3 patient1  235       3      NA
4 patient1  248      NA       3
5 patient1  353       4       4
6 patient2  100       5       5
7 patient2  150      NA       7
8 patient3  503      NA       6
9 patient3  538       6      NA
</code>```

Here, rows 3 and 4 contain data for the same measurement (with score 3) but are not joined because the values for the Days column are different (235 vs 248).

Question: I'm looking for a way to set a threshold on the second column (say 30 days) which would result in the following output:

```<code>> threshold <- 30
> *** insert join code ***

        ID Days Score.x Score.y
1 patient1    0      NA       1
2 patient1   25       2      10
3 patient1  248       3       3
4 patient1  353       4       4
5 patient2  100       5       5
6 patient2  150      NA       7
7 patient3  503      NA       6
8 patient3  538       6      NA

</code>```

This output shows that rows 3 and 4 of the previous output have been merged (because 248-235 < 30) and have taken the value for Days of the second df (248).

Three main conditions to keep in mind are:

Consecutive days that are within the threshold from within the same df (rows 1 and 2) are not merged.

In some cases, up to four values for the Days variable exist in the same dataframe and thus should not be merged. It might be the case that one of these values does exist within the treshold in the other dataframe, and these will have to be merged. See row 3 in the example below.

Each score/days/patient combination can only be used once. If a merge satisfies all conditions but there is still a double-merge possible, the first one should be used.

```<code>> df1
        ID Days Score
1 patient1    0     1
2 patient1    5     2
3 patient1   10     3
4 patient1   15     4
5 patient1   50     5

> df2
        ID Days Score
1 patient1    0     1
2 patient1    5     2
3 patient1   12     3
4 patient1   15     4
5 patient1   50     5

> df_combined
        ID Days Score.x Score.y
1 patient1    0       1       1
2 patient1    5       2       2
3 patient1   12       3       3
4 patient1   15       4       4
5 patient1   50       5       5
</code>```

EDIT FOR CHINSOON12

```<code>> df1
          ID Days Score
 1: patient1    0     1
 2: patient1  116     2
 3: patient1  225     3
 4: patient1  309     4
 5: patient1  351     5
 6: patient2    0     6
 7: patient2   49     7
> df2
          ID Days Score
 1: patient1    0    11
 2: patient1   86    12
 3: patient1  195    13
 4: patient1  279    14
 5: patient1  315    15
 6: patient2    0    16
 7: patient2   91    17
 8: patient2  117    18

</code>```

I wrapped your solution in a function like so:

```<code>testSO2 <- function(DT1,DT2) {
    setDT(DT1);setDT(DT2)
    names(DT1) <- c("ID","Days","X")
    names(DT2) <- c("ID","Days","Y")
    DT1$Days <- as.numeric(DT1$Days)
    DT2$Days <- as.numeric(DT2$Days)
    DT1[, c("s1", "e1", "s2", "e2") := .(Days - 30L, Days + 30L, Days, Days)]
    DT2[, c("s1", "e1", "s2", "e2") := .(Days, Days, Days - 30L, Days + 30L)]
    byk <- c("ID", "s1", "e1")
    setkeyv(DT1, byk)
    setkeyv(DT2, byk)
    o1 <- foverlaps(DT1, DT2)

    byk <- c("ID", "s2", "e2")
    setkeyv(DT1, byk)
    setkeyv(DT2, byk)
    o2 <- foverlaps(DT2, DT1)

    olaps <- funion(o1, setcolorder(o2, names(o1)))[
        is.na(Days), Days := i.Days]

    outcome <- olaps[, {
        if (all(!is.na(Days)) && any(Days == i.Days)) {
            s <- .SD[Days == i.Days, .(Days = Days[1L],
                                       X = X[1L],
                                       Y = Y[1L])]
        } else {
            s <- .SD[, .(Days = max(Days, i.Days), X, Y)]
        }
        unique(s)
    },
    keyby = .(ID, md = pmax(Days, i.Days))][, md := NULL][]
    return(outcome)
}
</code>```

Which results in:

```<code>> testSO2(df1,df2)
          ID Days  X  Y
 1: patient1    0  1 11
 2: patient1  116  2 12
 3: patient1  225  3 13
 4: patient1  309  4 14
 5: patient1  315  4 15
 6: patient1  351  5 NA
 7: patient2    0  6 16
 8: patient2   49  7 NA
 9: patient2   91 NA 17
10: patient2  117 NA 18
</code>```

As you can see, rows 4 and 5 are wrong. The value for Score in df1 is used twice (4). The correct output around those rows should be as follows, as each score (X or Y in this case) can only be used once:

```<code>          ID Days  X  Y
 4: patient1  309  4 14
 5: patient1  315 NA 15
 6: patient1  351  5 NA
</code>```

Code for dataframes below.

```<code>df1 <- data.frame(
  ID = rep(c("patient1", "patient2"), c(5L, 2L)),
  Days = c("0", "116", "225", "309", "351", "0", "49"),
  Score = 1:7
)

df2 <- data.frame(
  ID = rep(c("patient1", "patient2"), c(5L, 3L)),
  Days = c("0", "86", "195", "279", "315", "0", "91", "117"),
  Score = 11:18
)
</code>```

答:
This code lets you give a threshold then merges the scores from df1 into df1 as a new column. It will only add in scores that fall within single range of the scores in df2 +/- the threshold. Note that it is not possible to have all the scores joined since there is no threshold where all the scores match uniquely.</p>

```<code>threshold <- 40
WhereDF1inDF2 <- apply(sapply(lapply(df2$Days, function(x) (x+threshold):(x-threshold)), function(y) df1$Days %in% y),1,which)
useable <- sapply(WhereDF1inDF2, function(x) length(x) ==1 )
df2$Score1 <- NA
df2$Score1[unlist(WhereDF1inDF2[useable])] <- df1$Score[useable]

> df2
        ID Days Score Score1
1 patient1    0     1     NA
2 patient1   25    10     NA
3 patient1  248     3      3
4 patient1  353     4      4
5 patient2  100     5      5
6 patient2  150     7     NA
7 patient3  503     6      6
</code>```

Body:
Both Uwe's and GKi's answer are correct. Gki received the bounty because Uwe was late for that, but Uwe's solution runs about 15x as fast

I have two datasets that contain scores for different patients on multiple measuring moments like so:

df1 <- data.frame("ID" = c("patient1","patient1","patient1","patient1","patient2","patient3"),
                  "Days" = c(0,25,235,353,100,538),
                  "Score" = c(NA,2,3,4,5,6),
                  stringsAsFactors = FALSE)
df2 <- data.frame("ID" = c("patient1","patient1","patient1","patient1","patient2","patient2","patient3"),
                  "Days" = c(0,25,248,353,100,150,503),
                  "Score" = c(1,10,3,4,5,7,6),
                  stringsAsFactors = FALSE)
> df1
        ID Days Score
1 patient1    0    NA
2 patient1   25     2
3 patient1  235     3
4 patient1  353     4
5 patient2  100     5
6 patient3  538     6

> df2
        ID Days Score
1 patient1    0     1
2 patient1   25    10
3 patient1  248     3
4 patient1  353     4
5 patient2  100     5
6 patient2  150     7
7 patient3  503     6

Column ID shows the patient ID, column Days shows the moment of measurement (Days since patient inclusion) and column Score shows the measured score. Both datasets show the same data but in different moments in time (df1 was 2 years ago, df2 has the same data with updates from this year).

I have to compare the scores for each patient and each moment between both datasets. However, in some cases the Days variable has minor changes over time, so comparing the dataset by a simple join does not work. Example:

library(dplyr)

> full_join(df1, df2, by=c("ID","Days")) %>%
+   arrange(.[[1]], as.numeric(.[[2]]))

        ID Days Score.x Score.y
1 patient1    0      NA       1
2 patient1   25       2      10
3 patient1  235       3      NA
4 patient1  248      NA       3
5 patient1  353       4       4
6 patient2  100       5       5
7 patient2  150      NA       7
8 patient3  503      NA       6
9 patient3  538       6      NA

Here, rows 3 and 4 contain data for the same measurement (with score 3) but are not joined because the values for the Days column are different (235 vs 248).

Question: I'm looking for a way to set a threshold on the second column (say 30 days) which would result in the following output:

> threshold <- 30
> *** insert join code ***

        ID Days Score.x Score.y
1 patient1    0      NA       1
2 patient1   25       2      10
3 patient1  248       3       3
4 patient1  353       4       4
5 patient2  100       5       5
6 patient2  150      NA       7
7 patient3  503      NA       6
8 patient3  538       6      NA

This output shows that rows 3 and 4 of the previous output have been merged (because 248-235 < 30) and have taken the value for Days of the second df (248).

Three main conditions to keep in mind are:

Consecutive days that are within the threshold from within the same df (rows 1 and 2) are not merged.

In some cases, up to four values for the Days variable exist in the same dataframe and thus should not be merged. It might be the case that one of these values does exist within the treshold in the other dataframe, and these will have to be merged. See row 3 in the example below.

Each score/days/patient combination can only be used once. If a merge satisfies all conditions but there is still a double-merge possible, the first one should be used.

> df1
        ID Days Score
1 patient1    0     1
2 patient1    5     2
3 patient1   10     3
4 patient1   15     4
5 patient1   50     5

> df2
        ID Days Score
1 patient1    0     1
2 patient1    5     2
3 patient1   12     3
4 patient1   15     4
5 patient1   50     5

> df_combined
        ID Days Score.x Score.y
1 patient1    0       1       1
2 patient1    5       2       2
3 patient1   12       3       3
4 patient1   15       4       4
5 patient1   50       5       5

EDIT FOR CHINSOON12

> df1
          ID Days Score
 1: patient1    0     1
 2: patient1  116     2
 3: patient1  225     3
 4: patient1  309     4
 5: patient1  351     5
 6: patient2    0     6
 7: patient2   49     7
> df2
          ID Days Score
 1: patient1    0    11
 2: patient1   86    12
 3: patient1  195    13
 4: patient1  279    14
 5: patient1  315    15
 6: patient2    0    16
 7: patient2   91    17
 8: patient2  117    18

I wrapped your solution in a function like so:

testSO2 <- function(DT1,DT2) {
    setDT(DT1);setDT(DT2)
    names(DT1) <- c("ID","Days","X")
    names(DT2) <- c("ID","Days","Y")
    DT1$Days <- as.numeric(DT1$Days)
    DT2$Days <- as.numeric(DT2$Days)
    DT1[, c("s1", "e1", "s2", "e2") := .(Days - 30L, Days + 30L, Days, Days)]
    DT2[, c("s1", "e1", "s2", "e2") := .(Days, Days, Days - 30L, Days + 30L)]
    byk <- c("ID", "s1", "e1")
    setkeyv(DT1, byk)
    setkeyv(DT2, byk)
    o1 <- foverlaps(DT1, DT2)

    byk <- c("ID", "s2", "e2")
    setkeyv(DT1, byk)
    setkeyv(DT2, byk)
    o2 <- foverlaps(DT2, DT1)

    olaps <- funion(o1, setcolorder(o2, names(o1)))[
        is.na(Days), Days := i.Days]

    outcome <- olaps[, {
        if (all(!is.na(Days)) && any(Days == i.Days)) {
            s <- .SD[Days == i.Days, .(Days = Days[1L],
                                       X = X[1L],
                                       Y = Y[1L])]
        } else {
            s <- .SD[, .(Days = max(Days, i.Days), X, Y)]
        }
        unique(s)
    },
    keyby = .(ID, md = pmax(Days, i.Days))][, md := NULL][]
    return(outcome)
}

Which results in:

> testSO2(df1,df2)
          ID Days  X  Y
 1: patient1    0  1 11
 2: patient1  116  2 12
 3: patient1  225  3 13
 4: patient1  309  4 14
 5: patient1  315  4 15
 6: patient1  351  5 NA
 7: patient2    0  6 16
 8: patient2   49  7 NA
 9: patient2   91 NA 17
10: patient2  117 NA 18

As you can see, rows 4 and 5 are wrong. The value for Score in df1 is used twice (4). The correct output around those rows should be as follows, as each score (X or Y in this case) can only be used once:

          ID Days  X  Y
 4: patient1  309  4 14
 5: patient1  315 NA 15
 6: patient1  351  5 NA

Code for dataframes below.

df1 <- data.frame(
  ID = rep(c("patient1", "patient2"), c(5L, 2L)),
  Days = c("0", "116", "225", "309", "351", "0", "49"),
  Score = 1:7
)

df2 <- data.frame(
  ID = rep(c("patient1", "patient2"), c(5L, 3L)),
  Days = c("0", "86", "195", "279", "315", "0", "91", "117"),
  Score = 11:18
)

Body:
This code lets you give a threshold then merges the scores from df1 into df1 as a new column. It will only add in scores that fall within single range of the scores in df2 +/- the threshold. Note that it is not possible to have all the scores joined since there is no threshold where all the scores match uniquely.

threshold <- 40
WhereDF1inDF2 <- apply(sapply(lapply(df2$Days, function(x) (x+threshold):(x-threshold)), function(y) df1$Days %in% y),1,which)
useable <- sapply(WhereDF1inDF2, function(x) length(x) ==1 )
df2$Score1 <- NA
df2$Score1[unlist(WhereDF1inDF2[useable])] <- df1$Score[useable]

> df2
        ID Days Score Score1
1 patient1    0     1     NA
2 patient1   25    10     NA
3 patient1  248     3      3
4 patient1  353     4      4
5 patient2  100     5      5
6 patient2  150     7     NA
7 patient3  503     6      6


问:
LaTeX formula in gnuplot
I need to write LaTeX expression in the key, something like V_x with no italics in epslatex terminal.

I have tried $\text{V}_{\text{x}}$ but it does not give the desired output. Is there anyway to have equations using gnuplot? Below is my full script

```<code>set terminal epslatex color standalone  size 5.0in,5.25in
set output 'output.tex'
pl 'file.txt' u ($2-1):(($1-21.5) w p pt 5 ps 1.0 lc 7 title '\text{V}_{\text{x}}=0.6'
unset out
set out
system('latex output.tex && dvips output.dvi && ps2pdf output.ps')
system('mv output.ps out2.eps')
unset terminal
set out
</code>```

答:
1) insert missing close parenthesis 2) add $...$ around TeX math fragment 3) if you are not using the amsmath package, change \text to \textrm:

```<code>pl 'file.txt' u ($2-1):(($1-21.5)) w p pt 5 ps 1.0 lc 7 title '$\text{V}_{\text{x}}=0.6$',\
   'file.txt' w p pt 6 title '$\textrm{V}_{\textrm{x}}=0.6$'
</code>```

Title: LaTeX formula in gnuplot

Body:
I need to write LaTeX expression in the key, something like V_x with no italics in epslatex terminal.

I have tried $\text{V}_{\text{x}}$ but it does not give the desired output. Is there anyway to have equations using gnuplot? Below is my full script

set terminal epslatex color standalone  size 5.0in,5.25in
set output 'output.tex'
pl 'file.txt' u ($2-1):(($1-21.5) w p pt 5 ps 1.0 lc 7 title '\text{V}_{\text{x}}=0.6'
unset out
set out
system('latex output.tex && dvips output.dvi && ps2pdf output.ps')
system('mv output.ps out2.eps')
unset terminal
set out

Body:
1) insert missing close parenthesis 2) add $...$ around TeX math fragment 3) if you are not using the amsmath package, change \text to \textrm:

pl 'file.txt' u ($2-1):(($1-21.5)) w p pt 5 ps 1.0 lc 7 title '$\text{V}_{\text{x}}=0.6$',\
   'file.txt' w p pt 6 title '$\textrm{V}_{\textrm{x}}=0.6$'


问:
How to reset couchbase docker container password
I have installed 3 couchbase nodes of docker containers. After a couple of weeks when i tried to log in i could not remember my admin password. After a research i can not find a way to reset password. I am a newcomer to docker world so maybe i missed something. There is a source below but i believe that does not compromise my problem. How can i reset admin password ?

source

答:
I found a solution and wanted to share you all. After i clicked docker dashboard via docker gui i went for the container's bash then executed codes below.

```<code>couchbase-cli reset-admin-password --new-password 123456
</code>```

Above Mr. Matthew clues us in with a more sophisticated way of going for container's bash.

Body:
I found a solution and wanted to share you all. After i clicked docker dashboard via docker gui i went for the container's bash then executed codes below.

couchbase-cli reset-admin-password --new-password 123456

Above Mr. Matthew clues us in with a more sophisticated way of going for container's bash.


问:
Saving multiple values with web_reg_save_param
I need some help with web_reg_save_param.

I have a request being called 10 times after each other, with ten times another response. I would like to make a FOR loop where I save a part of the response with web_reg_save_param. In the 11th request I have to do a POST call with all the ten responses after each other.

How to approach this?

Thanks in advance.

Amit

答:
This is a programming question involving a loop, the construction of a set of dynamic parameter names within the loop.   What have you tried?

```<code>[PCODE]

Loop Definition (foo)
{

construct variable name (yada_index) which contains an index from loop variable (foo)

Define correlation conditions, saving output to (yada_index)

GET URL

}

POST URL
  &var1=(yada)_1
  &var2=(yada)_2
  &va3r=(yada)_3
  ...
  &var10=(yada)_10
  &Other_vars

[/PCODE]
</code>```

}

Body:
This is a programming question involving a loop, the construction of a set of dynamic parameter names within the loop.   What have you tried?

[PCODE]

Loop Definition (foo)
{

construct variable name (yada_index) which contains an index from loop variable (foo)

Define correlation conditions, saving output to (yada_index)

GET URL

}

POST URL
  &var1=(yada)_1
  &var2=(yada)_2
  &va3r=(yada)_3
  ...
  &var10=(yada)_10
  &Other_vars

[/PCODE]

}


问:
Qt - unresolved overload function type
I am getting the following error when trying to build my app in Qt Creator:

error (line 3): no matching function for call to ‘QGraphicsScene::QGraphicsScene()’

The source for this is simply (file name is gamscene.cpp):

```<code>#include "gamescene.h"

GameScene::GameScene() : QGraphicsScene(parent)
{

}
</code>```

I have googled around and have seen some similar issues but I don't really understand the answers given.

答:
parent on your line 3 has to come from somewhere.  Since you are defining a GameScene constructor, presumably it's really an argument to the constructor (I'm not familiar with Qt so I don't know what type parent should be -- use the appropriate type in your actual code):

```<code>GameScene::GameScene(TypeOfParent parent) : QGraphicsScene(parent)
{
}
</code>```

Or if it can make sense for the QGraphicsScene constructor to be called without a parent, then:

```<code>GameScene::GameScene() : QGraphicsScene()
{
}
</code>```

might be a possibility.  Probably not, since the error message indicates that there are no zero-argument constructors of QGraphicsScene.

Also, you didn't post the class definition, but given your constructor definition attempt I assume that GameScene publicly inherits from QtGraphicsScene.  So when you are constructing GameScene you need to call the superclass constructor (as you are attempting to do).  But any arguments to the superclass constructor can only come from arguments to your constructor.  So if the superclass constructor requires an argument, your constructor will need that argument so it can pass it to the superclass constructor (unless it makes sense for you to pass the superclass constructor a compile-time constant argument).

Title: Qt - unresolved overload function type

Body:
I am getting the following error when trying to build my app in Qt Creator:

error (line 3): no matching function for call to ‘QGraphicsScene::QGraphicsScene()’

The source for this is simply (file name is gamscene.cpp):

#include "gamescene.h"

GameScene::GameScene() : QGraphicsScene(parent)
{

}

I have googled around and have seen some similar issues but I don't really understand the answers given.

Body:
parent on your line 3 has to come from somewhere.  Since you are defining a GameScene constructor, presumably it's really an argument to the constructor (I'm not familiar with Qt so I don't know what type parent should be -- use the appropriate type in your actual code):

GameScene::GameScene(TypeOfParent parent) : QGraphicsScene(parent)
{
}

Or if it can make sense for the QGraphicsScene constructor to be called without a parent, then:

GameScene::GameScene() : QGraphicsScene()
{
}

might be a possibility.  Probably not, since the error message indicates that there are no zero-argument constructors of QGraphicsScene.

Also, you didn't post the class definition, but given your constructor definition attempt I assume that GameScene publicly inherits from QtGraphicsScene.  So when you are constructing GameScene you need to call the superclass constructor (as you are attempting to do).  But any arguments to the superclass constructor can only come from arguments to your constructor.  So if the superclass constructor requires an argument, your constructor will need that argument so it can pass it to the superclass constructor (unless it makes sense for you to pass the superclass constructor a compile-time constant argument).


问:
Reverse dataframe and merge columns in R
Hello I have a df such as :

```<code>COL1 COL2 COL3 COL4
SP1  OK   2    87
SP2  NO   8    90
SP3  NO   2    56
SP4  OK   3    45
</code>```

and I would like to put COL2,COL3 and COL4 into one unique column called Categorie and add the values associated into a column calles Value;

```<code>COL1 Categorie Value
SP1  COL2     OK
SP2 COL2     NO
SP3 COL2     NO
SP4 COL2     OK
SP1 COL3     2
SP2 COL3     8
SP3 COL3     2
SP4 COL3     3
SP1 COL4     87
SP2 COL4     90
SP3 COL4     56
SP4 COL4     45
</code>```

答:
You can use gather from the tidyr package.

```<code>library(tidyr)

df <- data.frame(COL1 = c("SP1","SP2","SP3","SP4"),
  COL2 = c("OK","NO","NO","OK"),
  COL3 = c(2,8,2,3),
  COL4 = c(87,90,56,45))

gather(df, Categorie, Value, COL2, COL3, COL4)

#>    COL1 Categorie Value
#> 1   SP1      COL2    OK
#> 2   SP2      COL2    NO
#> 3   SP3      COL2    NO
#> 4   SP4      COL2    OK
#> 5   SP1      COL3     2
#> 6   SP2      COL3     8
#> 7   SP3      COL3     2
#> 8   SP4      COL3     3
#> 9   SP1      COL4    87
#> 10  SP2      COL4    90
#> 11  SP3      COL4    56
#> 12  SP4      COL4    45
</code>```

Edit

Because you want all columns except for COL1 to be in Categorie, you can also shorten it like this:

```<code>gather(df, Categorie, Value, -COL1)
</code>```

Body:
Hello I have a df such as :

COL1 COL2 COL3 COL4
SP1  OK   2    87
SP2  NO   8    90
SP3  NO   2    56
SP4  OK   3    45

and I would like to put COL2,COL3 and COL4 into one unique column called Categorie and add the values associated into a column calles Value;

COL1 Categorie Value
SP1  COL2     OK
SP2 COL2     NO
SP3 COL2     NO
SP4 COL2     OK
SP1 COL3     2
SP2 COL3     8
SP3 COL3     2
SP4 COL3     3
SP1 COL4     87
SP2 COL4     90
SP3 COL4     56
SP4 COL4     45

Body:
You can use gather from the tidyr package.

library(tidyr)

df <- data.frame(COL1 = c("SP1","SP2","SP3","SP4"),
  COL2 = c("OK","NO","NO","OK"),
  COL3 = c(2,8,2,3),
  COL4 = c(87,90,56,45))

gather(df, Categorie, Value, COL2, COL3, COL4)

#>    COL1 Categorie Value
#> 1   SP1      COL2    OK
#> 2   SP2      COL2    NO
#> 3   SP3      COL2    NO
#> 4   SP4      COL2    OK
#> 5   SP1      COL3     2
#> 6   SP2      COL3     8
#> 7   SP3      COL3     2
#> 8   SP4      COL3     3
#> 9   SP1      COL4    87
#> 10  SP2      COL4    90
#> 11  SP3      COL4    56
#> 12  SP4      COL4    45

Edit

Because you want all columns except for COL1 to be in Categorie, you can also shorten it like this:

gather(df, Categorie, Value, -COL1)


问:
Nginx: stat() failed (13: permission denied)
I am using the default config while adding the specific directory with nginx installed on my ubuntu 12.04 machine.

```<code>server {
        #listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6

        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                root /username/test/static;
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
...

...
}
</code>```

I just want a simple static nginx server to serve files out of that directory. However, checking the error.log I see

```<code>2014/09/10 16:55:16 [crit] 10808#0: *2 stat() "/username/test/static/index.html" failed (13: Permission denied), client:, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "domain"
2014/09/10 16:55:16 [error] 10808#0: *2 rewrite or internal redirection cycle while internally redirecting to "/index.html
</code>```

I've already done chown -R www-data:www-data on /username/test/static, I've set them to chmod 755. I don't know what else needs to be set.

答: This is usually the privilege problem... For me, its because i use the /root/** as the nginx root, it need higher privilege. An easy way is just move the project into a directory created by yourself.</p>

Body:
I am using the default config while adding the specific directory with nginx installed on my ubuntu 12.04 machine.

server {
        #listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6

        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                root /username/test/static;
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
...

...
}

I just want a simple static nginx server to serve files out of that directory. However, checking the error.log I see

2014/09/10 16:55:16 [crit] 10808#0: *2 stat() "/username/test/static/index.html" failed (13: Permission denied), client:, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "domain"
2014/09/10 16:55:16 [error] 10808#0: *2 rewrite or internal redirection cycle while internally redirecting to "/index.html

I've already done chown -R www-data:www-data on /username/test/static, I've set them to chmod 755. I don't know what else needs to be set.


问:
Content not updating with firebase serve --only hosting
I'm trying to test changes to my site.  But when I make changes and restart firebase serve --only hosting the changes aren't showing up.

I'm using Vuejs if that matters...

答: I had this issue as well. The easiest way of fixing this is to clear cache and cookies, and reload.</p>


问:
Replace string between first and second occurrence of forward slash
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

```<code>const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

</code>```

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

答:
If there has to be a second forward slash present in the string:

```<code>^\/[^\/\r\n]+(?=\/)
</code>```

Explanation

^ Start of string

\/ Match the first /

[^\/\r\n]+ Match 1+ times any char except / or a newline

(?=\/) Positive lookahead, assert what is on the right is the second /

Regex demo

In the replacement use the first / followed by example

[
  '/questions/ask/1',
  '/questions/',
  '/questions'
].forEach(s =>
  console.log(s + " --> " + s.replace(/^\/[^\/\r\n]+(?=\/)/, "/example"))
)```

Body:
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

Body:
If there has to be a second forward slash present in the string:

^\/[^\/\r\n]+(?=\/)

Explanation

^ Start of string

\/ Match the first /

[^\/\r\n]+ Match 1+ times any char except / or a newline

(?=\/) Positive lookahead, assert what is on the right is the second /

Regex demo

In the replacement use the first / followed by example

[
  '/questions/ask/1',
  '/questions/',
  '/questions'
].forEach(s =>
  console.log(s + " --> " + s.replace(/^\/[^\/\r\n]+(?=\/)/, "/example"))
)


问:
Error consuming an Endpoint api-football.com (CORS related)
I'm trying to consume this endpoint at the api-football.com

Here is their documentation: https://www.api-football.com/documentation-beta#section/Authentication

The error is: Access to XMLHttpRequest at 'https://v3.football.api-sports.io/teams?id=40' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field x-rapidapi-host is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my code:

```<code>    httpOptions.headers = new HttpHeaders({
     // 'Access-Control-Allow-Origin': '*',
     // 'Access-Control-Allow-Methods': 'GET',
     // 'Accept': '*/*',
     'Content-Type': 'application/json',
     'x-rapidapi-host': 'v3.api-football.com',
     'x-rapidapi-key': this._publicKey,
    });

    const url = 'https://v3.football.api-sports.io/teams?id=40';

    return this.http.get<any>(url, httpOptions)
     .pipe(
       catchError(this.handleError('getLiverpool', []))
    );
</code>```

I understand what CORS is, but not how to fix it in this case? I am using Angular 9.

答:
Ehy!

the easiest solution would be to use your back-end as middleware to send the request to the 3rd party API. This and other more complex alternatives here

Body:
I'm trying to consume this endpoint at the api-football.com

Here is their documentation: https://www.api-football.com/documentation-beta#section/Authentication

The error is: Access to XMLHttpRequest at 'https://v3.football.api-sports.io/teams?id=40' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field x-rapidapi-host is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my code:

    httpOptions.headers = new HttpHeaders({
     // 'Access-Control-Allow-Origin': '*',
     // 'Access-Control-Allow-Methods': 'GET',
     // 'Accept': '*/*',
     'Content-Type': 'application/json',
     'x-rapidapi-host': 'v3.api-football.com',
     'x-rapidapi-key': this._publicKey,
    });

    const url = 'https://v3.football.api-sports.io/teams?id=40';

    return this.http.get<any>(url, httpOptions)
     .pipe(
       catchError(this.handleError('getLiverpool', []))
    );

I understand what CORS is, but not how to fix it in this case? I am using Angular 9.


问:
How can we get table size in Salesforce using CData driver?
I want to fetch the size of my table in Salesforce using a CData driver.</p>

答:
if you want number of rows, you can use the COUNT as follows:</p>

```<code>select count(*) FROM Account
</code>```

Body:
if you want number of rows, you can use the COUNT as follows:

select count(*) FROM Account


问:
Using two columns in the sub function in R
I have a Data Table with two Text columns. I need to use column b to determine which letters to replace in column a with an "x".

I can do it using a for loop as in the code below. however my actual data set has 250,000+ rows so the script takes ages. Is there a more efficient way to do this? I considered lappy but couldn't get my head round it.

```<code> DT <- data.table(a = c("ABCD","ABCD","ABCD","ABCD"), b = c("A","B","C", "D"))

DT$c <- ""

for (i in 1 : NROW(DT)){

  DT[i]$c <- sub(DT[i,b], "x", DT[i,a])

}
</code>```

答:
Here is one approach using the tidyverse</p>

```<code>library(tidyverse)

DT <- data.table::data.table(a = c("ABCD","ABCD","ABCD","ABCD"), b = c("A","B","C", "D"))

DT %>%
  mutate(new_vec = str_replace_all(string = a,pattern = b,replacement = "X"))
</code>```

Body:
I have a Data Table with two Text columns. I need to use column b to determine which letters to replace in column a with an "x".

I can do it using a for loop as in the code below. however my actual data set has 250,000+ rows so the script takes ages. Is there a more efficient way to do this? I considered lappy but couldn't get my head round it.

 DT <- data.table(a = c("ABCD","ABCD","ABCD","ABCD"), b = c("A","B","C", "D"))

DT$c <- ""

for (i in 1 : NROW(DT)){

  DT[i]$c <- sub(DT[i,b], "x", DT[i,a])

}

Body:
Here is one approach using the tidyverse

library(tidyverse)

DT <- data.table::data.table(a = c("ABCD","ABCD","ABCD","ABCD"), b = c("A","B","C", "D"))

DT %>%
  mutate(new_vec = str_replace_all(string = a,pattern = b,replacement = "X"))


问:
Serilog - Separate files for Information, exception using appsetting.json
I am writing all logs into one file(s) using rolling. But I want to separate them by Information, Warning and Exceptions rolling files.

my current configuration is like this

```<code>     "Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\log-{Hour}.log",
          "rollOnFileSizeLimit ": true,
          "retainedFileCountLimit ": null,
          "rollingInterval": "Hour",
          "fileSizeLimitBytes": 5000000
        }
      }
    ]
  },
</code>```

class

```<code>public ILogger GetLogger()
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        _logger =
            new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

        return _logger ;
    }
</code>```

答:
In Serilog you could do this separation either via sub-loggers or via Serilog.Sinks.Map.

You wouldn't be able to configure the whole pipeline via appsetting.json but you can easily configure the path of each file in appsetting.json using a custom key of your choice, and use that when configuring the log pipeline via code.

Example using sub-loggers with a filter applied to each of them:

```<code>Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
            .WriteTo.File("Debug.log"))
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
            .WriteTo.File("Error.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();
</code>```

Example using Serilog.Sinks.Map mapping each LogEventLevel to a different file.

```<code>Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();
</code>```

Body:
I am writing all logs into one file(s) using rolling. But I want to separate them by Information, Warning and Exceptions rolling files.

my current configuration is like this

     "Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\log-{Hour}.log",
          "rollOnFileSizeLimit ": true,
          "retainedFileCountLimit ": null,
          "rollingInterval": "Hour",
          "fileSizeLimitBytes": 5000000
        }
      }
    ]
  },

class

public ILogger GetLogger()
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        _logger =
            new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

        return _logger ;
    }

Body:
In Serilog you could do this separation either via sub-loggers or via Serilog.Sinks.Map.

You wouldn't be able to configure the whole pipeline via appsetting.json but you can easily configure the path of each file in appsetting.json using a custom key of your choice, and use that when configuring the log pipeline via code.

Example using sub-loggers with a filter applied to each of them:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
            .WriteTo.File("Debug.log"))
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
            .WriteTo.File("Error.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();

Example using Serilog.Sinks.Map mapping each LogEventLevel to a different file.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();


问:
Read and Write Data into Python Files
Please advise how I'm getting the following error:

```<code>File "/Users/<username>/PycharmProjects/OOP/csv_write.py", line 8
  print(f'Column names are {", ".join(row)}')
                                           ^
SyntaxError: invalid syntax
</code>```

Code:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
```
<p>As I'm trying to read from the file and display the information as follows as per the link.</p>
<p>employee_birthday.txt :</p>
```name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
```

This question has been resolved and thank you for the responses below.

答: Make sure you are using Python >= 3.6 as f-strings were introduced later. If that still doesn't work, check the indentation for the code.

Title: Read and Write Data into Python Files

Body:
Please advise how I'm getting the following error:

File "/Users/<username>/PycharmProjects/OOP/csv_write.py", line 8
  print(f'Column names are {", ".join(row)}')
                                           ^
SyntaxError: invalid syntax

Code:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

As I'm trying to read from the file and display the information as follows as per the link.

employee_birthday.txt :

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

This question has been resolved and thank you for the responses below.


问:
"Left side cannot be assigned to" for record type properties in Delphi
I'm curious to know why Delphi treats record type properties as read only:

```<code>  TRec = record
    A : integer;
    B : string;
  end;

  TForm1 = class(TForm)
  private
    FRec : TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec : TRec read FRec write FRec;
  end;
</code>```

If I try to assign a value to any of the members of Rec property, I'll get "Left side cannot be assigned to" error:

```<code>procedure TForm1.DoSomething(ARec: TRec);
begin
  Rec.A := ARec.A;
end;
</code>```

while doing the same with the underlying field is allowed:

```<code>procedure TForm1.DoSomething(ARec: TRec);
begin
  FRec.A := ARec.A;
end;
</code>```

Is there any explanation for that behavior?

答:
Because you have implicit getter and setter functions and you cannot modify the Result of a function as it is a const parameter.

(Note: In case you transform the record in an object, the result would actually be a pointer, thus equivalent to a var parameter).

If you want to stay with a Record, you have to use an intermediate variable (or the Field variable) or use a WITH statement.

See the different behaviors in the following code with the explicit getter and setter functions:

```<code>type
  TRec = record
    A: Integer;
    B: string;
  end;

  TForm2 = class(TForm)
  private
    FRec : TRec;
    FRec2: TRec;
    procedure SetRec2(const Value: TRec);
    function GetRec2: TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec: TRec read FRec write FRec;
    property Rec2: TRec  read GetRec2 write SetRec2;
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

{ TForm2 }

procedure TForm2.DoSomething(ARec: TRec);
var
  LocalRec: TRec;
begin
  // copy in a local variable
  LocalRec := Rec2;
  LocalRec.A := Arec.A; // works

  // try to modify the Result of a function (a const) => NOT ALLOWED
  Rec2.A := Arec.A; // compiler refused!

  with Rec do
    A := ARec.A; // works with original property and with!
end;

function TForm2.GetRec2: TRec;
begin
  Result:=FRec2;
end;

procedure TForm2.SetRec2(const Value: TRec);
begin
  FRec2 := Value;
end;
</code>```

OwnerDisplayName: vcldeveloper

Body:
I'm curious to know why Delphi treats record type properties as read only:

  TRec = record
    A : integer;
    B : string;
  end;

  TForm1 = class(TForm)
  private
    FRec : TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec : TRec read FRec write FRec;
  end;

If I try to assign a value to any of the members of Rec property, I'll get "Left side cannot be assigned to" error:

procedure TForm1.DoSomething(ARec: TRec);
begin
  Rec.A := ARec.A;
end;

while doing the same with the underlying field is allowed:

procedure TForm1.DoSomething(ARec: TRec);
begin
  FRec.A := ARec.A;
end;

Is there any explanation for that behavior?

Body:
Because you have implicit getter and setter functions and you cannot modify the Result of a function as it is a const parameter.

(Note: In case you transform the record in an object, the result would actually be a pointer, thus equivalent to a var parameter).

If you want to stay with a Record, you have to use an intermediate variable (or the Field variable) or use a WITH statement.

See the different behaviors in the following code with the explicit getter and setter functions:

type
  TRec = record
    A: Integer;
    B: string;
  end;

  TForm2 = class(TForm)
  private
    FRec : TRec;
    FRec2: TRec;
    procedure SetRec2(const Value: TRec);
    function GetRec2: TRec;
  public
    procedure DoSomething(ARec: TRec);
    property Rec: TRec read FRec write FRec;
    property Rec2: TRec  read GetRec2 write SetRec2;
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

{ TForm2 }

procedure TForm2.DoSomething(ARec: TRec);
var
  LocalRec: TRec;
begin
  // copy in a local variable
  LocalRec := Rec2;
  LocalRec.A := Arec.A; // works

  // try to modify the Result of a function (a const) => NOT ALLOWED
  Rec2.A := Arec.A; // compiler refused!

  with Rec do
    A := ARec.A; // works with original property and with!
end;

function TForm2.GetRec2: TRec;
begin
  Result:=FRec2;
end;

procedure TForm2.SetRec2(const Value: TRec);
begin
  FRec2 := Value;
end;

OwnerDisplayName: François

ContentLicense: CC BY-SA 2.5


问:
"SELECT ... FOR UPDATE" not working for Hibernate and MySQL
We have a system in which we must use pessimistic locking in one entity. We are using hibernate, so we use LockMode.UPGRADE. However, it does not lock.

The tables are InnoDB

We have checked that locking works correctly in the database (5.0.32), so this bug http://bugs.mysql.com/bug.php?id=18184 seems to be no problem.

We have checked that datasource includes the autoCommit = false parameter.

We have checked that the SQL hibernate (version 3.2) generates includes the " FOR UPDATE".

Thanks,

答: Lately I have had an issue like this. We where working with 2 tx managers coz we had different databases and the problem was that the transaction was using the txmanager configured to the other database and because of that on the connection to the queried database was not being disabled the autocommit mode before performing the select for update. Using the correct txmanager solved that. Hope it helps others in future.</p>