text:
Q: Binding two data frames I'm trying to merging two data frames I have, the other is a long list of numbers from 1 to 6 (A) and the other is a vector with numbers 1 to 6 and name to each number (B).
How do I merge B to A so that the list of numbers in A will have the names of the corresponding numbers in B?
Best regards,
Hlynur T

A: If this replicates your situation then merge is ht answer:
 dfB <- data.frame(numb = 1:6, nams = LETTERS[1:6])
 dfA <- data.frame(nums = sample(1:6, 30, repl=TRUE))
 merge(dfA, dfB, by.x="nums", by.y="numb")

(And this mus have been asked and answered a bunch of times in the past.)

A: Use match(). Say you have the following two data frames:
A <- data.frame(num=sample(1:6,100,replace=TRUE))
B <- data.frame(num=1:6,myname=letters[1:6])

Then to make a new column "myname" for the data frame A:
A[,'myname'] <- B[match(A[,'num'],B[,'num']),'myname']

As others mentioned, things change slightly if you used rownames() instead of creating a column for the names, but this general construction should work with a few tweaks regardless of the specifics.


text:
Q: web.config match and redirect urls from root file to folder I moved my blog posts from the root of my website to a folder. I want to include a rule in my site's web.config that redirects permanently the posts from their old root location to the new folder location.
All posts have filenames of the following form, a form no other files on my website have, and the filenames are the same in the new folder location as they were in the old root location:
ROJR####.htm    or   ROJR####-#.htm
As a newbie to both web.config and regex, I am struggling to code accurately the pattern for the match url, as well as the pattern for the redirected url.
My current code is:
<rule name="redirect ROJR" stopProcessing="true">
  <match url="^(ROJR\d\d\d\d-?\d?\.htm)$" ignoreCase="true" />
  <action type="Redirect" url="^OJRU\/{R:1}" redirectType="Permanent" />
</rule>

Here are my questions:
Match URL:  Did I accurately describe the pattern?  And will the pattern look only for posts previously located in the root (and not find the moved posts with the same name in the OJRU folder)?
Redirected URL: Did I redirect accurately the old URLs to the new location?

FROM:  example.com/ROJR####-#.htm
TO:  example.com/OJRU/ROJR####-#.htm
and
FROM: example.com/ROJR####.htm
TO: example.com/OJRU/ROJR####.htm

Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP - HTTP authentication & download file (header) I want know more about download a file when the directory is protected by a http digest authentication.
In fact when I use a PHP script that changes headers to directly download this file, I can download this file without needing to authenticate with HTTP authentication. Why is this? I'm running Apache 2.2 with PHP 5.3 on Debian.

A: The thing is that the http authentication is set by apache, but the php script can access ANY file on your server, since it's a local read, not remote.
If you don't want your script to access the file if not authenticated you should implement the authentication also on the script, not only the files.


text:
Q: Loop through grouped dataframe columns to check for string values I have two dataframes, one that contains a large amount of textual data scraped from PDF documents, and another that contains categories and subcategories.
For each subcategory, I need to calculate the percentage of documents that contains at least one mention of the subcategory (e.g. for the subcategory "apple", calculate the percentage of documents that contains "apple"). I'm able to correctly calculate the subcategory percentage. However, when I attempt to populate the dataframe with the value, an incorrect value is displayed.
For each category, I need to calculate the percentage of documents that contains at least one mention of each subcategory (e.g. for the category "fruit", calculate the percentage of documents that contains "apple" or "banana"). The calculation of this value is harder, as it's not a subtotal. I'm trying to calcuate this value through a combination of GROUPBY and APPLY, but I've gotten stuck.
The document dataframe looks like this:

The categories dataframe looks like this:

This is what I'm aiming for:

This is what I have so far:
import pandas as pd
documents = {'Text': ['apple apple', 'banana apple', 'carrot carrot carrot', 'spinach','hammer']}
doc_df = pd.DataFrame(data=documents)
print(doc_df,'\n')

categories = {'Category': ['fruit', 'fruit', 'vegetable', 'vegetable'],
        'Subcategory': ['apple', 'banana', 'carrot', 'spinach']}
cat_df = pd.DataFrame(data=categories)
print(cat_df,'\n')

total_docs = doc_df.shape[0]
cat_df['Subcat_Percentage'] = 0
cat_df['Cat_Percentage'] = 0
cat_df = cat_df[['Category', 'Cat_Percentage', 'Subcategory', 'Subcat_Percentage']]

for idx, subcategory in enumerate(cat_df['Subcategory']):
    total_docs_with_subcat = doc_df[doc_df['Text'].str.contains(subcategory)].shape[0]
    subcat_percentage = total_docs_with_subcat / total_docs #calculation is correct
    cat_df.at[idx, 'Subcat_Percentage'] = subcat_percentage #wrong value is output
    cat_percentage = cat_df.groupby('Category').apply(lambda x: (doc_df[doc_df['Text'].str.contains(subcategory)].shape[0]) #this doesn't work
    cat_df.at[idx, 'Cat_Percentage'] = cat_percentage

print('\n', cat_df,'\n')

A: It Could be better optimized, but try this  :
agg_category = cat_df.groupby('Category')['Subcategory'].agg('|'.join)

def percentage_cat(category):
    return doc_df[doc_df['Text'].str.contains(agg_category[category])].size / doc_df.size

def percentage_subcat(subcategory):
    return doc_df[doc_df['Text'].str.contains(subcategory)].size / doc_df.size

cat_df['percentage_category'] = cat_df['Category'].apply(percentage_cat)
cat_df['sub_percentage'] = cat_df['Subcategory'].apply(percentage_subcat)

cat_df


text:
Q: function not writing to text file I'm trying to make a sort of logbook in a text file to avoid re-doing efforts. I have the following function that perform this task:
def write_to_logbook(target_name):

   with open('C:\Documents\logbook.txt', 'a+') as f:
      for lines in f:
          if target_name not in lines:
              f.write(target_name + '\n')
              f.close() #when I didn't have f.close() here, it also wasn't writing to the txt file

When I check the text file after I run the script, it remains empty. I'm not sure why.
I call it as such (in reality target name is pulled down from a unique ID, but since I don't want to put everything here, this is the gist):
target_name = 'abc123'
write_to_logbook(target_name)

A: You need to (potentially) read the entire file before you can decide if target_name has to be added to the file.
def write_to_logbook(target_name):
    fname = r'C:\Documents\logbook.txt')

    with open(fname) as f:
        if any(target_name in line for line in f):
            return

    with open(fname, 'a') as f:
        print(target_name, file=f)

any will return True as soon as any line containing target_name is found, at which point the function itself will return.
If the target name isn't found after reading the entire file, then the second with statement will append the target name to the file.

A: I got it sorted. I used chepner's solution as a jumping off point, since it didn't exactly work (only wrote one target_name for some reason) and kind of did a hybrid of the two:
def write_to_logbook(target_name):
    fname = 'filepath'

    with open(fname) as f:
        for lines in f:
            if target_name in lines:
                return

    with open(fname, 'a+') as f:
        f.write(target_name + '\n')

Thanks for the solution, it helped.


text:
Q: Texlipse can't find font files i have a LuaLaTeX document which should use some fonts but i get some errors which says that the font files can't be found. The fonts are in a subdirectory of the project. In the "Project Explorer" are the fonts folder and the LuaTeX file direct childs of the project. My code to include the fonts are:
\setsansfont[Path=fonts/,BoldFont={FiraSans-Regular.ttf}]{FiraSans-Light.ttf}
\setmonofont[Path=fonts/]{FiraMono-Regular.ttf}
\newfontfamily\ExtraLight[Path=fonts/,ItalicFont=FiraSans-ExtraLightItalic.ttf]{FiraSans-ExtraLight.ttf}
\newfontfamily\Light[Path=fonts/,ItalicFont=FiraSans-LightItalic.ttf]{FiraSans-Light.ttf}
\newfontfamily\Book[Path=fonts/,ItalicFont=FiraSans-Italic.ttf,BoldFont=FiraSans-Bold.ttf,BoldItalicFont=FiraSans-BoldItalic.ttf]{FiraSans-Regular.ttf}
\newfontfamily\Medium[Path=fonts/,ItalicFont=FiraSans-MediumItalic.ttf]{FiraSans-Medium.ttf}

and this is one of the errors:
lualatex.exe> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
lualatex.exe> !
lualatex.exe> ! fontspec error: "font-not-found"
lualatex.exe> !
lualatex.exe> ! The font "FiraSans-Light.ttf" cannot be found.
lualatex.exe> !
lualatex.exe> ! See the fontspec documentation for further information.
lualatex.exe> !
lualatex.exe> ! For immediate help type H <return>.
lualatex.exe> !...............................................
lualatex.exe>
lualatex.exe> l.18 ...FiraSans-Regular.ttf}]{FiraSans-Light.ttf}

Thank you for your help.


text:
Q: Build a general tree with C (use a linkedlist to hold the children) Try to build a tree in C. The children has to be contained in a linkedlist. But when I use "struct listNode*" in the definition of struct treeNode, listNode is not declared yet. So is there any way to declare this first? Or anyway to get around this? Thanks!
/*** Build a tree ***/
typedef struct treeNode {
    char* target;
    char* commands;
    struct listNode* children;
} tNode;

/*** Build a linkedlist ***/
typedef struct listNode {
    struct treeNode dependency;
    struct listNode* next;
} lNode;

A: Use what's called forward declaration. So your code should look like this
/*** Build a tree ***/
struct listNode;

typedef struct treeNode {
    char* target;
    char* commands;
    struct listNode* children;
} tNode;

/*** Build a linkedlist ***/
typedef struct listNode {
    struct treeNode dependency;
    struct listNode* next;
} lNode;

A: Prepend the following to your snippet
struct listNode;

This is called a forward declaration.
The struct is not defined at this point, but the name is known, which is sufficient as you only want to reference it (with a pointer), not include it (which would require knowledge of its size).
Note that the restriction that you can only use pointers on yet-to-be-defined types actually makes sense: It makes
struct A {
    struct B b;
    int a;
};

struct B {
    struct A a;  /* Uh, what's that? struct B contains struct A
                  * which contains struct B... Now what's the size
                  * of either of these structs? */
};

an invalid construct (because it prevents circular dependencies).


text:
Q: H2O xgboost mojo prediction warnings I am trying to produce a prediction from new data using a XGBoost mojo object in H2O. When I predict though, various messages, giving warnings, get displayed
Feb 26, 2019 12:43:47 PM ml.dmlc.xgboost4j.java.NativeLibrary extractAndLoad
WARNING: Cannot load library from path lib/linux_64/libxgboost4j_gpu.so
Feb 26, 2019 12:43:47 PM ml.dmlc.xgboost4j.java.NativeLibrary extractAndLoad
WARNING: Cannot load library from path lib/libxgboost4j_gpu.so
Feb 26, 2019 12:43:47 PM ml.dmlc.xgboost4j.java.NativeLibrary doLoad
WARNING: Failed to load library from both native path and jar!
Feb 26, 2019 12:43:47 PM ml.dmlc.xgboost4j.java.NativeLibraryLoaderChain loadNativeLibs
INFO: Cannot load library: xgboost4j_gpu (lib/linux_64/libxgboost4j_gpu.so)
Feb 26, 2019 12:43:47 PM ml.dmlc.xgboost4j.java.NativeLibrary extractAndLoad
INFO: Loaded library from lib/linux_64/libxgboost4j_omp.so (/tmp/libxgboost4j_omp7945713229272382570.so)

       predict          setosa      versicolor       virginica
1       setosa 0.9961976408958 0.0030118888244 0.0007904054946
2       setosa 0.9963765740395 0.0026796606835 0.0009437160916
3       setosa 0.9963235855103 0.0028859297745 0.0007905053790
4       setosa 0.9963260293007 0.0028859369922 0.0007880008779
5       setosa 0.9961976408958 0.0030118888244 0.0007904054946

Here is a basic reproducible example:
library(tidyverse)
library(h2o)

h2o.init(nthreads = -1, max_mem_size = '5g') # All available cores

data(iris)
iris.hex <- as.h2o(iris, destination_frame = "iris.hex")

iris.gbm <- h2o.xgboost(y = 5, x = 1:4, training_frame = iris.hex, ntrees = 100,
                        max_depth = 3,
                        learn_rate = 0.2,
                        distribution= "AUTO")

h2o.download_mojo(iris.gbm, "Mojo_models/", get_genmodel_jar = T)
h2o.shutdown()

Warning messages occurs once I try and perform the predictions
h2o.mojo_predict_df(iris, mojo_zip_path = "Mojo_models/XGBoost_model_R_1551184956713_1.zip", genmodel_jar_path = "Mojo_models/h2o-genmodel.jar",
                    java_option =  '-Xmx1g -XX:ReservedCodeCacheSize=256m')

Is this something I should be worried about? If not, why are the messages occurring and can I suppress them somehow?
Relevant session info:
R version 3.4.2 (2017-09-28)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.4 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.0
LAPACK: /usr/lib/lapack/liblapack.so.3.0

other attached packages:
 [1] h2o_3.22.1.1    forcats_0.3.0   stringr_1.3.1   dplyr_0.7.8     purrr_0.3.0     readr_1.2.1     tidyr_0.8.2     tibble_1.4.2    ggplot2_3.1.0   tidyverse_1.2.1

A: H2O is trying to and failing to load the GPU version XGBoost. It then loads the CPU version. This is not something to be worried about unless you think the GPU version should be loading.


text:
Q: How does one add padding to Bootstrap 3's container without screwing up the grid? Many site designs call for a dark background with a lighter foreground page that contains the site's content. When using Bootstrap, it seems logical that one would merely apply the light color to the .container div and be done with it. However, Bootstrap's container does not provide any padding between its edges and the columns within, so this solution provides a light background but with the column content flush with the edges - not a good look.
This is a common problem and there are several solutions on stackoverflow and elsewhere for Bootstrap 2, but I couldn't find anything useful for Bootstrap 3.

A: One of the Bootstrap 2 solutions involved using .container-fluid which switches the internal grid from pixel to percentage based. Then one may apply padding to a a background div within .container-fluid and the internal columns will seamlessly adjust to fit. This seemed like a good approach, but the specific CSS used to tweak some of the other styles didn't work with Bootstrap 3.
After digging through the Bootstrap source, I noticed that the only difference between the .container and .container-fluid rules, in grid.less are three media queries. I wrapped my page's content in .container-fluid then overrode its definition with one that included the media queries so that the page content would respond the same as the header and footer, which use the standard .container.
Here's the HTML:

  <title>Bootstrap 3 Container Padding Example</title>

And then the .less:
.page-container > .container-fluid:first-child {
  .container-fixed();

  @media (min-width: @screen-sm-min) {
    width: @container-sm;
  }
  @media (min-width: @screen-md-min) {
    width: @container-md;
  }
  @media (min-width: @screen-lg-min) {
    width: @container-lg;
  }
}

Then added padding to the .page-container div:
.page-container {
  .page-bg {
    padding: 15px;
    background-color: #EFEFEF;
  }
}

body {
  background-color: #333
}

This seems to work. I haven't completed the styling for the interfaces that will reside within this container yet so there could be issues down the road but everything seems to render fine so far.
Here is a working example of this solution on codepen.io.
Note that the solution above uses less.css after including Bootstrap's variables and mixins .less files. Here's the compiled CSS:
.page-container > .container-fluid:first-child {
  margin-right: auto;
  margin-left: auto;
  padding-left: 15px;
  padding-right: 15px;
}
@media (min-width: 768px) {
  .page-container > .container-fluid:first-child {
    width: 750px;
  }
}
@media (min-width: 992px) {
  .page-container > .container-fluid:first-child {
    width: 970px;
  }
}
@media (min-width: 1200px) {
  .page-container > .container-fluid:first-child {
    width: 1170px;
  }
}
.page-container .page-bg {
  padding: 15px;
  background-color: #EFEFEF;
}
body {
  background-color: #333333;
}


text:
Q: ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb' What is the new import for:
ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb'

I did some internet searching and didn't find an immediate result for the error.
I am trying to upgrade from django 3.2 to django 4.1.2

A: It looks like the field type was migrated to the following location:
django.db.models.fields.json.KeyTextTransform

So for django4+:
from django.db.models.fields.json import KeyTextTransform

Instead of:
from django.contrib.postgres.fields.jsonb import KeyTextTransform


text:
Q: Should I put my logic in the underlying SQL query or in the SSRS report? In our organisation, we create a number of reports requested by users / managers and publish them on an SSRS webpage.
We tend to create an SQL procedure which returns the desired results and we call that procedure in the SSRS dataset. We then use SSRS to present this in a nice looking table and tend to create groupings etc and put graphs in etc so that it looks presentable to the user.
Any "calculated columns" such as "Age" (which would be calculated from a date of birth and the current date) or "Average sales" (calculated from a total amount / a number of sales) are calculated in the underlying SQL procedure.
SSRS has a number of functions that allow these calculated columns to be calculated in the SSRS report itself.
My question really is, "What are the advantages of creating calculated columns in the underlying dataset vs creating them in SRRS?" is there any kind of performance hit? Are there other factors we should maybe think about?

A: When you are dealing with relational databases as a source and you have control over the SQL being executed to return the data set, I would generally advise putting the logic for calculations, data type conversion etc. in the SQL and thereby offload the processing for that to the database engine which will usually be much more efficient at that than the report server.
I normally aim for the report to be a "presentation layer" which applies the formatting, layout, grouping and sorting to the data. The business logic that creates the underlying dataset is encapsulated in the query or procedure that is runs on the database. SSRS certainly does include a lot of functions that enable manipulation of data but I would normally only use these when the data source itself didn't support them. However if I was building a report which had some dynamic capability (e.g. report has a parameter that allows user to control how grouping is done in the report) then it might make sense to do the calculations in SSRS to make better use of caching.

A: I'd imagine performance isn't a massive concern unless you are doing lots of huge calculations, I can't comment on that to any huge degree.
The advantages mostly come from allowing a report designer to create reusable expressions by creating fields in the dataset instead of having to create these as expressions in the report itself.
This is easier to maintain and easier to view. In SSRS 2008 or later, you can see the name of the field in each placeholder - this makes it much easier for a designer to work out what the result of each field will be.
If you use an expression, all you see in those boxes is <<expr>>, plus if you use this same expression in multiple places, you need to update the expression in all of those places if you decide to change how the value is calculated.
It's simply an extension of the DRY principle.


text:
Q: Excel Dropdown List: Set neighboring Cell based on value selected for first cell I have a column set to 'Data Validation', 'List', 'In-Cell Dropdown'.  This is referencing a source on another sheet.  Basically, I'm pulling our Active Directory use list and OUs into a second sheet in the workbook.  The 'Users' column in the main 'Combinded' sheet is a drop down list with a source of =Users!$A$2:$A$130.
When a user is selected in the User Column (say, 'Combined'!E2) and a record is selected from the other sheet, say, 'Users'!A2, I would like 'Combined'!F2 to then equal 'Users'!B2 without having to perform any additional action.  Is that possible?
I am using Excel 2013 and have the 'Power Query' module installed if that helps any!

A: @DMM's comment to use VLOOKUP() was exactly what I was looking for!


text:
Q: Openshift rhcloud SSL not valid certificate I have problem with alias on openshift. There is a problem and I'm trying to figure it out few week without any result.
Openshift link: https://mydomain.rhcloud.com **WORKING FINE**
Alias: https://server.mydomain.com **WORKING FINE**

Openshift link: https://mydomain.rhcloud.com:8443 **WORKING FINE**
Alias: https://server.mydomain.com:8443 **NOT WORKING**

when I use port with new alias there is a problem with certificate -> Safari can't verify the identity of the website see screenshot.
Please Help.
alias without :8443

alias with :8443

A: Custom SSL certificates do not currently work with websockets (port 8443) on OpenShift Online.  To use secure websockets (wss) you would have to use the default *.rhcloud.com certificate.


text:
Q: How to edit several database entries efficiently from JSF web application? I have several database tables that the user should be able to add, edit and remove entries from the web application.
Also the input must be validated before persisting it.
Now I could simply make a table and put labeled input fields in there, but the result would be far from DRY and a horror to maintain. Composite components make this just a bit better. Is there any alternative I do not see which could reduce a lot of work?

A: If I'm not misunderstanding the question, one concept you might wanna look into is generic/generated CRUD.
Netbeans has a primefaces CRUD generator link


text:
Q: How can I solve, for example, $n^5-625n+1632=0$ for $n$ if it is solvable? I understand that some quintics in Bring-Jerrard form are solvable but first one must identify a solvable group for it or any quintic. I don't know how to identify a group for this equation or how to proceed from there. For the examples below, I know what the solution(s) will be only because I constructed them from known values.
The equations come from the product of sides of Pythagorean triples generated by Euclid's formula where:
$P=2m^5n-2mn^5\quad $and it becomes $\quad n^5-m^4n+\frac{P}{2m}=0\quad$ that I hope to solve for $n$.
I will "know" a narrow range of $m$ values to test for any given $P$ and

I seek one-to-five functions $f(b,m )$ to test to see which $m$, if any, yields an integer $n$.

Here are the samples showing also the correct values of $n$ that I seek. In the form $\qquad\qquad\qquad n^5-an+b=0\rightarrow f(b,m)=n$.
$$
n^5-16n+15=0\rightarrow f(15,2)=1\quad
n^5-81n+80=0\rightarrow f(80,3)=1\quad
n^5-81n+130=0\rightarrow f(130,3)=2\quad
n^5-256n+255=0\rightarrow f(255,4)=1\quad
n^5-256n+480=0\rightarrow f(480,4)=2\quad
n^5-256n+525=0\rightarrow f(525,4)=3\quad
n^5-625n+624=0\rightarrow f(624,5)=1\quad
n^5-625n+1218=0\rightarrow f(1218,5)=2\quad
n^5-625n+1632=0\rightarrow f(1632,5)=3\quad
n^5-625n+1476=0\rightarrow f(1476,5)=4\quad
n^5-1296n+1295=0\rightarrow f(1295,6)=1\quad
$$
The monomial  $(n-r)$, where $r$ is a root, will always factor the polynomial. For example, $n^5-625n+1632=(n - 3) (n^4 + 3 n^3 + 9 n^2 + 27 n - 544)$ but I have no use for the quartic once I find $n=3$.
I can find $n$ by testing the factors of $b$ but I want to learn what is usually done in solving a Bring-Jerrard quintic, starting with groups. I don't know group theory well enough to figure out how it relates to polynomials.

Can someone help me find the "group" for one or all of these and then show me how such is used to solve this kind of equation?

A: You seem to think that finding the Galois group of one of these polynomials would lead to a shortcut to finding eventual integer roots. In my humble opinion this is quite the wrong approach to your real problem of finding integer roots to a quintic with integer coefficients in Bring-Jerrard form.

*

*Figuring out the Galois group takes more work than checking for integer roots via the rational root test (or by other means if you cannot factor the constant term). If only for the reason that checking for the presence of rationa roots would be the first step in my approach to the task of finding in the Galois group.

*Knowing the Galois group $G$ (as a group of permutations of the roots, a subgroup of $S_5$), when it happens to be solvable, only helps in finding ALL the five roots. If we know $G$ then we already know whether the polynomial has integer roots WITHOUT SOLVING THEM. For example, unless $G$ is a subgroup of a point stabilizer, we can say right away that there are no integer roots.

In many comments you have indicated that you are not interested in the quartic factor. That is fine - for the purposes of finding integer roots you are right. But it also further underlines the fact that you are really not interested in the Galois group. This is because when there is an integer root, the Galois group only contains information about the zeros of that quartic factor.

To give you something useful let me demonstrate the use of modular reduction as a technique for finding eventual integer roots of a quintic in Bring-Jerrard form. If you can factor the constant $b$ of $x^5+ax+b$, then the rational root test already leads to a problem of testing a finite number of candidates. As do elementary estimates from calculus and friends. Modular reduction will simply further cut down the number of remaining alternatives.
Consider the (not quite random) quintic equation
$$
f(x)=x^5-23232x-69277=0.
$$
The task is to find integer solutions. Here it would not be difficult to factor the constant term, but let's assume that you cannot do that (or that it would leave to uncomfortably many alternatives to be tested). A point is that if $f(n)=0$, then the residue class of $n$ modulo any prime $p$ will also be a solution to the congruence $f(x)\equiv \pmod p$. Another point is that finding modular roots modulo a prime much smaller than $b$ is a lot easier (there are efficient algorithms for that when $p$ is a bit too large for paper and pencil work).
This $f(x)$ is a case in point. We see that $\root4\of{23232}$ is a bit over ten. We can then check that $f(15)$ is safely positive, and that the function is increasing from that point on. Similarly $f(-15)<0$ and $f$ is increasing in the interval $(-\infty,-15)$. Therefore any integer zeros $n$ will satisfy $|n|<15$. It would be easy to test all the integers in this range (either as zeros of $f(x)$ or as factors of $b$. But, again, I'm assuming that in a real version of this question we would instead be left with too many alternatives for a brute force check.
On we go by reducing modulo small primes $p$.

*

*Reducing the coefficients of $f$ modulo $p=2$ we arrive at $f(x)\equiv x^5+1$. The only modular zero here is $x\equiv1$. This is basically restating the obvious fact an integer root must be odd.

*Reduction modulo $p=3$ gives $f(x)\equiv x^5-1$. From this we can deduce that if $f(n)=0$ we must have $n\equiv1\pmod3$.

*With the question settled modulo two or primes we invoke the Chinese Remainder Theorem (=CRT). We know that $n\equiv1\pmod2$ and $n\equiv1\pmod3$. CRT then tells us that $n\equiv1\pmod6$. Basically knowing the remainder of $n$ modulo $2$ and $3$ leaves only a single alternative for its remainder modulo $2\cdot3=6$.

*Next in line is $p=5$. Reducing the coefficients modulo $5$ shows that
$$f(x)\equiv x^5+3x+3\pmod5.$$
Testing $x=0,1,2,3,4$ (with or without using that by Little Fermat $x^5\equiv x$) quickly reveals that we must have $x\equiv3\pmod5$.

*Another round of CRT is due. We will get information modulo $6\cdot5=30$. Combining the pieces $n\equiv1\pmod6$ and $n\equiv3\pmod5$ leaves $n\equiv13\pmod{30}$ as the only possibility.

Because we initially constrained the solutions to the range $(-15,15)$ we can conclude that the only possible integer zero of $f(x)$ is $x=13$. Of course, I set up the example carefully so that, in fact, $f(13)=0$ – something you can verify easily enough.
As a further observation we see that $69277=13\cdot73^2$. This time the rational root test would have immediately given us that the only possible integer roots are $\pm1,\pm13,\pm73,\pm13\cdot73,\pm 73^2,\pm 13\cdot73^2$.
The product of small primes grows quickly enough so that you can, in a reasonable time, cover a relatively wide range of possible roots. If, instead, you wanted to find the roots of the quintic $g(x)=x^5-23232x-69276$ then, as above, $p=2,3,5$ will give us the information that an integer root $n$ must satisfy the congruence $n\equiv24\pmod{30}$. One alternative would then be that as $x=-6$ does not work, there are no integer solutions. Another possibility would be to include reduction modulo $p=7$. For we see that
$$g(x)\equiv x^5+x+3\pmod{7}$$
and, more importantly, $n^5+n+3$ is not divisible by $7$ for any $n=0,1,2,3,4,5,6$. This also implies that $g(x)$ has no integer roots.

Conclusions:

*

*Combining the rational root test (when feasible), range estimation (trivial) and reductions modulo several small primes leaves a relatively short list of possible candidate zeros that can be tested.

*Quite often considerations modulo a single prime may leave several alternatives modulo that prime. Then you either accept a longer list of candidates or reduce modulo some other prime (this is inevitable when the original quintic has several integer roots).

*For information on the technique of finding the roots of a low degree polynomial modulo a larger prime (when testing $n=0,1,2,\ldots,p-1$ feels too painful) you can take a look at this old thread.

*I don't see a way of using Galois theory to your end. I do want to point out that if your quintic is irreducible over $\Bbb{Q}$ (when we can immediately conclude that there are no integer roots), then it will also be irreducible modulo some prime $p$. This fact is special to quintics ($5$ is a prime), and requires a result known as Chebotaryev's density theorem (or a lighter version thereof). This is in contrast to quartics – we can easily find quartic polynomials with integer coefficients, irreducible over $\Bbb{Q}$ but reducible modulo every prime.

Doing the quintic in the question title as another example. This time we easily see that any real zero of
$$
h(x)=x^5-625x+1632
$$
must satisfy $|x|<8$.

*

*Reduction modulo $p=2$ does not give us anything for $h(n)$ is even for all integers $n$.

*Modulo $p=3$ we have $h(x)\equiv x^5-x$. This isn't very useful either for we can only exclude $n\equiv2\pmod3$.

*Modulo $p=5$ we get $h(x)\equiv x^5+2$. By Little Fermat this implies that an integer root $n$ must satisfy $n\equiv3\pmod 5$.

*Modulo $p=7$ we get $h(x)\equiv x^5+5x+1$. Testing with $x=0,1,\ldots,6$ shows that $x^5+5x+1$ is divisible by seven if and only if $x\equiv1$ or $x\equiv 3\pmod 7$.

*Combining the modulo $5$ and $7$ pieces of information implies (CRT) that an eventual integer zero $n$ must be congruent to either $8$ or $3$ modulo $35$.

*This means that in our range $n=3$ is the only possibility (and actually a solution as per OP's design).

This time the constant term $1632=2^5\cdot3\cdot17$ has quite a few factors, so using the rational root test would not have helped much.

A: $$n^5-16n+15=$$
$$=n^5-n^4+n^4-n^3+n^3-n^2+n^2-n-15n+15=$$
$$=(n-1)(n^4+n^3+n^2+n-15),$$
which gives $n=1$ or $$n^4+n^3+n^2+n-15=0.$$
The last equation for any real $k$ gives $$\left(n^2+\frac{1}{2}n+k\right)^2-\frac{1}{4}n^2-k^2-kn-2kn^2+n^2+n-15=0$$ or
$$\left(n^2+\frac{1}{2}n+k\right)^2-\left(\left(2k-\frac{3}{4}\right)n^2+(k-1)n+k^2+15\right)=0.$$
Now, we'll choose a value of $k$, for which the last side of the last equation is a difference of squares,
for which we need $$ 2k-\frac{3}{4}>0$$ and $$(k-1)^2-4\left(2k-\frac{3}{4}\right)(k^2+15)=0$$ or
$$4k^3-2k^2+61k-23=0,$$ which by the Cardano's formula ( https://en.wikipedia.org/wiki/Cubic_equation ) gives:
$$k=\frac{1}{6}\left(1+\sqrt[3]{\frac{1}{2}\left(695+3\sqrt{2733033}\right)}+\sqrt[3]{\frac{1}{2}\left(695-3\sqrt{2733033}\right)}\right)$$ and since for the last value we have $$2k-\frac{3}{4}>0,$$ we obtain:
$$\left(n^2+\tfrac{1}{2}n+k-\sqrt{2k-\tfrac{3}{4}}\left(n+\tfrac{k-1}{2\left(2k-\tfrac{3}{4}\right)}\right)\right)\left(n^2+\tfrac{1}{2}n+k+\sqrt{2k-\tfrac{3}{4}}\left(n+\tfrac{k-1}{2\left(2k-\tfrac{3}{4}\right)}\right)\right)=0.$$
Id est, it remains to solve two quadratic equations.


text:
Q: Plot components of vector valued InterpolatingFunction I am very confused with how the Plot command evaluates arguments for vector valued numerical functions. For example, when I run the following commands
Clear[f]
f = Interpolation[{{0, {0, 0}}, {1, {1, 2}}}]
Plot[f[t][[2]], {t, 0, 1}]

I get the error: Part::partw: Part 2 of InterpolatingFunction[{{0,1}},{5,3,0,{2},{2},0,0,0,0,Automatic,{},{},False},{{0,1}},{{{0,0}},{{1,2}}},{Automatic}][t] does not exist..
It seems like the Plot command is trying to evaluate U[t][[2]] at some point instead of only calling U for specific numeric values. How can I force Plot to only plug evaluate U with actual numbers.
Thanks!

A: I still want to see what other answers, but I have found an inelegant solution:
Clear[f, ff]
f = Interpolation[{{0, {0, 0}}, {1, {1, 2}}}]
ff[x_?NumericQ, i_] := f[x][[i]]
Plot[Table[ff[t, i], {i, 1, 2}], {t, 0, 1}, Evaluated -> True]

The key was to make ensure that the placeholder function ff[t,i] is not evaluated when t is anything but a number. I don't like having to define an extra pattern rule, and I hope this can be done using some combination of Hold, Defer, Evaluate, etc.

A: One way is to Indexed instead of Part:
Clear[fff]
fff = Interpolation[{{0, {0, 0}}, {1, {1, 2}}, {2, {3, 2}}, {3, {1, 4}}}];
GraphicsRow@{
  Plot[Indexed[fff[t], 1], {t, 0, 1}],
  Plot[Indexed[fff[t], 2], {t, 0, 1}]}


text:
Q: Why the cpu performance counter kept reporting 0% cpu usage? PerformanceCounter cpuload = new PerformanceCounter();
cpuload.CategoryName = "Processor";
cpuload.CounterName = "% Processor Time";
cpuload.InstanceName = "_Total";
Console.WriteLine(cpuload.NextValue() + "%");

The output is always 0%, while the cpuload.RawValue is like 736861484375 or so, what happened at NextValue()?

A: The first iteration of he counter will always be 0, because it has nothing to compare to the last value.  Try this:
var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");

Then you should see some data coming out.  It's made to be seen in a constant graph or updated scenario...that's why you don't come across this problem often.
Here's the MSDN reference:

The method nextValue() always returns
  a 0 value on the first call. So you
  have to call this method a second
  time.

A: First retrieve first value (would be 0)
NextValue();

Then wait for 1000 milisec
Thread.Sleep(1000);

Then retrieve second value which is the true cpu usage.
NextValue();

The code should look like this:
float perfCounterValue = perfCounter.NextValue();

//Thread has to sleep for at least 1 sec for accurate value.
System.Threading.Thread.Sleep(1000);

perfCounterValue = perfCounter.NextValue();

Console.WriteLine("Value: {0}", perfCounterValue);


text:
Q: Visual Studio cordova tools build.bat command failed with exit code 1. You may not have the required environment or OS to build this project I have been working on my app with apache cordova tools for visual studio for a long time.
Yesterday I built my app in Release mode. Today I tried to add cordova-white-list plugin and updated cordova to 4.0. Now visual studio is totally failing to build the app.
Output:
Debug
> 1>  ------ Build configuration options: --debug 1>  Running command:
> C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\cordova\build.bat
> --debug 1>  ANDROID_HOME=E:\android 1>  JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_55 1>  Running:
> C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\gradlew
> cdvBuildDebug -b
> C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\build.gradle
> -Dorg.gradle.daemon=true 1>  :preBuild 1>  :compileDebugNdk UP-TO-DATE 1>  :preDebugBuild 1>  :checkDebugManifest 1>  :CordovaLib:compileLint
> 1>  :CordovaLib:copyDebugLint UP-TO-DATE 1>
> :CordovaLib:mergeDebugProguardFiles UP-TO-DATE 1>
> :CordovaLib:preBuild 1>  :CordovaLib:preDebugBuild 1>
> :CordovaLib:checkDebugManifest 1>
> :CordovaLib:prepareDebugDependencies 1>  :CordovaLib:compileDebugAidl
> UP-TO-DATE 1>  :CordovaLib:compileDebugRenderscript UP-TO-DATE 1>
> :CordovaLib:generateDebugBuildConfig UP-TO-DATE 1>
> :CordovaLib:generateDebugAssets UP-TO-DATE 1>
> :CordovaLib:mergeDebugAssets UP-TO-DATE 1>
> :CordovaLib:generateDebugResValues UP-TO-DATE 1>
> :CordovaLib:generateDebugResources UP-TO-DATE 1>
> :CordovaLib:packageDebugResources UP-TO-DATE 1>
> :CordovaLib:processDebugManifest UP-TO-DATE 1>
> :CordovaLib:processDebugResources UP-TO-DATE 1>
> :CordovaLib:generateDebugSources UP-TO-DATE 1>
> :CordovaLib:compileDebugJava UP-TO-DATE 1>
> :CordovaLib:processDebugJavaRes UP-TO-DATE 1>
> :CordovaLib:packageDebugJar UP-TO-DATE 1>  :CordovaLib:compileDebugNdk
> UP-TO-DATE 1>  :CordovaLib:packageDebugJniLibs UP-TO-DATE 1>
> :CordovaLib:packageDebugLocalJar UP-TO-DATE 1>
> :CordovaLib:packageDebugRenderscript UP-TO-DATE 1>
> :CordovaLib:bundleDebug UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:compileLint 1>
> :com.google.playservices:google-play-services_lib:copyDebugLint
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:mergeDebugProguardFiles
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:preBuild 1>
> :com.google.playservices:google-play-services_lib:preDebugBuild 1>
> :com.google.playservices:google-play-services_lib:checkDebugManifest
> 1>
> :com.google.playservices:google-play-services_lib:preDebugTestBuild 1>
> :com.google.playservices:google-play-services_lib:prepareAndroidCordovaLibUnspecifiedDebugLibrary
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:prepareDebugDependencies
> 1>  :com.google.playservices:google-play-services_lib:compileDebugAidl
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:compileDebugRenderscript
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:generateDebugBuildConfig
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:generateDebugAssets
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:mergeDebugAssets
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:generateDebugResValues
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:generateDebugResources
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:mergeDebugResources
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:processDebugManifest
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:processDebugResources
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:generateDebugSources
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:compileDebugJava
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:processDebugJavaRes
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:packageDebugJar
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:compileDebugNdk
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:packageDebugJniLibs
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:packageDebugLocalJar
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:packageDebugRenderscript
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:packageDebugResources
> UP-TO-DATE 1>
> :com.google.playservices:google-play-services_lib:bundleDebug
> UP-TO-DATE 1>
> :prepareAndroidComGooglePlayservicesGooglePlayServices_libUnspecifiedDebugLibrary
> UP-TO-DATE 1>  :prepareAndroidCordovaLibUnspecifiedDebugLibrary
> UP-TO-DATE 1>  :prepareDebugDependencies 1>  :compileDebugAidl
> UP-TO-DATE 1>  :compileDebugRenderscript UP-TO-DATE 1>
> :generateDebugBuildConfig UP-TO-DATE 1>  :generateDebugAssets
> UP-TO-DATE 1>  :mergeDebugAssets UP-TO-DATE 1>
> :generateDebugResValues UP-TO-DATE 1>  :generateDebugResources
> UP-TO-DATE 1>  :mergeDebugResources UP-TO-DATE 1>
> :processDebugManifest UP-TO-DATE 1>  :processDebugResources UP-TO-DATE
> 1>  :generateDebugSources UP-TO-DATE 1>  :compileDebugJava FAILED 1>
> 1>  BUILD FAILED 1> 1>  Total time: 23.655 secs
>

>
> **1>  Command finished with error code 1: C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\cordova\build.bat
> --debug 1>ERROR building one of the platforms : error : C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\cordova\build.bat:
> Command failed with exit code 1 1>  You may not have the required
> environment or OS to build this project 1>MDAVSCLI : error :
> C:\Users\Hardik\Hybrid\Ashley\Ashley\platforms\android\cordova\build.bat:
> Command failed with exit code 1
>  Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped **

1.I have API 22, 21 and 19 installed.
2.Already tried clearing cordova cache.
3.It was working very well before yesterday.


text:
Q: How to intersect two columns in r? I have a data frame as following and I want to intersect them to become one column.
ID<-c('>1','>2','>3','>4','>5')
TYPE<-c('A','B','O','A','B')
old<-data.frame(ID,TYPE)
old

  ID TYPE
  >1    A
  >2    B
  >3    O
  >4    A
  >5    B

I want to merge them and become a new data set to look like this.
  NEW_VAR
  >1
   A
  >2
   B
  >3
   O
  >4
   A
  >5
   B

I try the following code, but it does not work.
intersect(old$ID, old$TYPE)

But it shows
character(0)

Thanks in advance.

A: For the desired result you could try:
c(t(old))
 [1] ">1" "A"  ">2" "B"  ">3" "O"  ">4" "A"  ">5" "B"


text:
Q: Updating Apache Camel JPA object in database triggers deadlock So I have a Apache Camel route that reads Data elements from a JPA endpoint, converts them to DataConverted elements and stores them into a different database via a second JPA endpoint. Both endpoints are Oracle databases.
Now I want to set a flag on the original Data element that it got copied successfully. What is the best way to achieve that?
I tried it like that: saving the ID in the context and then reading it and accessing a dao method in the .onCompletion().onCompleteOnly().
    from("jpa://Data")
        .onCompletion().onCompleteOnly().process(ex -> {
            var id = Long.valueOf(getContext().getGlobalOption("id"));
            myDao().setFlag(id);
        }).end()
        .process(ex -> {
            Data data = ex.getIn().getBody(Data.class);
            DataConverted dataConverted = convertData(data);
            ex.getMessage().setBody(data);

            var globalOptions = getContext().getGlobalOptions();
            globalOptions.put("id", data.getId().toString());
            getContext().setGlobalOptions(globalOptions);
        })
        .to("jpa://DataConverted").end();

However, this seems to trigger a deadlock, the dao method is stalling on the commit of the update. The only explanation could be that the Data object gets locked by Camel and is still locked in the .onCompletion().onCompleteOnly() part of the route, therefore it can't get updated there.
Is there a better way to do it?

A: Have you tried using the recipient list EIP where first destination is the jpa:DataConverted endpoint and the second destination will be the endpoint to set the flag. This way both get the same message and will be executed sequentially.
https://camel.apache.org/components/3.17.x/eips/recipientList-eip.html
from("jpa://Data")
   .process(ex -> {
            Data data = ex.getIn().getBody(Data.class);
            DataConverted dataConverted = convertData(data);
            ex.getIn().setBody(data);
     })
   .recipientList(constant("direct:DataConverted","direct:updateFlag"))
 .end();

 from("direct:DataConverted")
  .to("jpa://DataConverted")
 .end();

 from("direct:updateFlag")
  .process(ex -> {
            var id = ((MessageConverted) ex.getIn().getBody()).getId();
            myDao().setFlag(id);
        })
 .end();

Keep in mind, you might want to make the route transactional by adding .transacted()
https://camel.apache.org/components/3.17.x/eips/transactional-client.html


text:
Q: menu items in action bar showing up weird I created a custom theme for the action bar that makes it white, and having a tad bit of trouble, and I have not been able to find the solution. First of all I want the 'options button' to be red, like the text below. but especially I want when clicked the whole row to be highlighted, not like it is shown in the picture:

Sso here is the code for the theme I'm using:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBarTheme</item>
        <item name="android:background">@color/White</item>
        <item name="android:textColorLink">@color/White</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@color/White</item>
        <item name="android:textColor">@color/Red</item>
    </style>
</resources>

I was hoping I could also get the red text to be aligned right, and have tried multiple alignment methods with no luck.thanks.

A: You need styles for android:actionMenuTextColor to change the "options" text color and android:textAppearanceLargePopupMenu to change the PopupMenu text color.
<style name="Your.Theme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionMenuTextColor">@android:color/holo_red_dark</item>
    <item name="android:textAppearanceLargePopupMenu">@style/TextAppearance.Red.PopupMenu.Large</item>
    <item name="android:popupMenuStyle">@style/PopupMenu.Example</item>
</style>

<style name="TextAppearance.Red.PopupMenu.Large" parent="@android:style/TextAppearance.DeviceDefault.Widget.PopupMenu.Large">
    <item name="android:textColor">@android:color/holo_red_dark</item>
</style>

<style name="PopupMenu.Example" parent="@android:style/Widget.ListPopupWindow">
    <item name="android:popupBackground">@drawable/your_background</item>
    <!-- Or use -->
    <item name="android:popupBackground">@android:color/white</item>
</style>


text:
Q: Is it possible to import all contents of cacerts into a jssecacerts file? Using keytool , or some other method,  is there an easy way to import all contents of cacerts into a jssecacerts file?
Basically, I want to define my own jssecacerts but I want that jssecacerts to also contain all the trusted entries of the cacerts file.   The reason for this is that I believe that when the jssecacerts file exists, the cacerts file contents are ignored.

A: I figured it out:
%JRE_HOME%\bin\keytool.exe -importkeystore -destkeystore jssecacerts
-deststoretype jks -srcstorepass changeit -deststorepass changeit
-v -noprompt -srckeystore %JRE_HOME%\lib\security\cacerts


text:
Q: Function not returning value from variable IF (@crncy_code = 'JMD') BEGIN
    SELECT @total = isnull(sum(balance),0)
    FROM [PROD_EIMDW_BOJ_REPORTS].[BOJOWN].[LOANS_TAB] blt
    WHERE currency = 'JMD'
    AND chrge = 'N' -- not charged off
    AND dpd <= @p_days_past_upper_range
    AND dpd >= @p_days_past_lower_range
    AND NOT EXISTS(SELECT 1 FROM [BOJOWN].[LOANS_EXCLUSION] WHERE acid = blt.acid)
    AND NOT EXISTS (SELECT acid FROM  [PROD_EIMDW_Archive].[ARCHOWN].[FINCL10_ALR]  WHERE BANK_ID= @bank_id  AND  acct_label = 'MUNDO' AND ACTIVE_FLAG = 'Y'  AND DELETE_FLAG='N' AND acid = blt.acid)

    SELECT @other_sum = isnull(sum(balance),0)
    FROM [PROD_EIMDW_BOJ_REPORTS].[BOJOWN].[LOANS_TAB] blt
    WHERE currency = 'JMD'
    AND chrge = 'N' -- not charged off
    AND dpd <= @p_days_past_upper_range
    AND dpd >= @p_days_past_lower_range
    AND NOT EXISTS (SELECT acid FROM  [PROD_EIMDW_Archive].[ARCHOWN].[FINCL10_ALR]   WHERE BANK_ID= @bank_id  and DELETE_FLAG='N' AND acct_label = 'MUNDO' AND ACTIVE_FLAG = 'Y' AND acid = blt.acid)
    AND EXISTS (SELECT 1 FROM [PROD_EIMDW_BOJ_REPORTS].[BOJOWN].[LOANS_EXCLUSION] WHERE acid = blt.acid)

    set @loanCount = @total + @other_sum

When I running the function its not returning the summation of the two variables its only return the value stored in the first variable. Also please note when I run the statement outside the function its okay. Below is the return statement:
RETURN isnull(@loanCount,0)

A: I'm not sure what is the problem with your query, but I would simplify it like this:
SELECT @loanCount = ISNULL(SUM(balance),0)
FROM [BOJOWN].[LOANS_TAB] blt
WHERE currency = 'JMD'
AND chrge = 'N' -- not charged off
AND dpd <= @p_days_past_upper_range
AND dpd >= @p_days_past_lower_range
AND NOT EXISTS (
    SELECT acid FROM [PROD_EIMDW_Archive].[ARCHOWN].[FINCL10_ALR]
    WHERE acct_label = 'MUNDO' AND ACTIVE_FLAG = 'Y' AND DELETE_FLAG='N'
    AND BANK_ID=@bank_id AND acid = blt.acid
)

Does this query return the correct result?


text:
Q: CodeIgniter Pagination & GET See: http://codeigniter.com/user_guide/libraries/pagination.html
I do not want to use URI segments for my pagination (as I have a lot of possible parameters to pass in unknown order). Currently, I have $config['enable_query_strings'] = FALSE;, and if I set it to TRUE, I get something like this (from CI's example):
http://example.com/index.php?c=test&m=page&per_page=20
Where "c" is the controller, "m" is the method, etc. This is not what I want.
I want something like this:
http://domain.com/?min_amount=100&max_amount=200&color=blue&size=large&limit=20&limit_offset=100
Is there a way to achieve this in CI? If not, is there some library already available that I can use?

A: In CodeIgniter, there are two configuration options when it comes to query strings.
One option ($config['allow_get_array'], enabled by default) allows you to pass additional queries on to the already segmented URI, which would then be available via the $this->input->get() controller library function. You would set the pagination config using this function, allowing you to separate the route, and the pagination instructions.
The other option ($config['enable_query_strings']) forces you to use the query strings in place of the segmented URIs.


text:
Q: Suppose the pdf of $X$ is $f(x) = \frac{-3}{4} (x-3)(x-5)$. Find the pdf of $X^2/8$.
Suppose that $X$ is a continuous random variable with a pdf $f(x) =
 \frac{-3}{4} (x-3)(x-5)$ with $3\leq x \leq 5$. What is the pdf of the random variable $Y$,
  where $Y = X^2/8$.

My attempt:
First I notice that if $X\in[3,5]$, then $Y\in[9/8, 25/8]$.
I derived the cumulative distribution function as follows:
$$P(Y<y) = P(X^2<8y)=P(-\sqrt{8y}<X<\sqrt{8y})=\int_{-\sqrt{8y}}^{\sqrt{8y}}{f(x)dx}=-\sqrt{2y}(8y+45)$$
Then differentiate this cdf to obtain the pdf of $Y$:$$\frac{d}{dy}(-\sqrt{2y}(8y+45)) = -\frac{3(8y+15)}{\sqrt{2y}}$$
However, when I tried to integrate this pdf:  $\int_{9/8}^{25/8} {-\frac{3(8y+15)}{\sqrt{2y}}dy} =-94\neq1$
It turns out that the integral does not equal to 1, which suggests that there is something wrong with my answer. Any help would be highly appreciated.

A: $$\int_{-\sqrt{8y}}^{\sqrt{8y}} f(x)\ dx = \int_{-\sqrt{8y}}^{3} f(x)\ dx +\int_{3}^{\sqrt{8y}} f(x)\ dx$$
The first term is zero because $f(x)=0$ in that range. If $3\le\sqrt{8y}\le5$, then you can go on and integrate the second term.


text:
Q: not able to solve java session asking to log in again
Possible Duplicate:
not able to solve java session

    HttpSession sess = request.getSession();
     String username=request.getParameter("firstname");
     String password=request.getParameter("pwd");
     boolean flag;
     if(username!=null && password!=null){
      flag=checking.check(username, password);  //here i check if user exists in //the data base
     }else{
     flag=false;
     }
     if(flag){
     put2.sessionAttr(username,password,sess); // here i call a java class through bean put2 and set attributes to the session
     response.sendRedirect("index.jsp");
     }

in the end i add attributes to the session i set an attribute of username..
after closing the browser without logging out i enter the same url and call the following jsp through ajax
HttpSession ses=request.getSession();
       if(ses.getAttribute("username")==null){
       out.print("falseconfirm");

        out.flush();

       }else{
       out.print("trueconfirm");

        out.flush();
       }

but the session seems have no attributes at all..
so i have to enter username and password again..

A: Closing the browser means you lost the session. Opening a new browser always creates a new session and hence you are seeing this behavior.

A: When you are closing the browser the session will automatically cleared and you can't access that session no more.


text:
Q: How to gather a tensor from Keras using its backend? I trying to compile a model in Keras with an input that is a 2D numpy array.
What I need is to take the vector at the nth place of this 2D array and use it as a tensor 1D tensor for one of the layers.
How do I do it?

A: Using a lambda layer should do it:
extracted_tensor = Lambda(lambda x: x[:,nth_index,:], output_shape=(1,dim_vector))(input)
extracted_tensor = Flatten()(extracted_tensor)

note that in the x tensor (lambda function), you take the batch dimension into account, but you don't in the output_shape parameter.
I hope this helps

A: Use tf.gather( input_tensor, indices, axis ) to collect indices along the specified axis.


text:
Q: how to remove '+' in scientific mode output I have this code:
std::cout << std::scientific << 1e9;

It outputs 1.000000e+09 but I don't want the +.
I tried using std::showpos , it doesn't work for that.
I thought about writing an output function specifically, but I'd prefer to find an easier way.


text:
Q: react-native-webview don't supported Window? I use EXPO SDK 38 and react-native-webview:10.9.0,I run the code
<View style={styles.mapView} >
            <WebView
                source={{ uri: 'https://www.google.com' }}
                onLoad={console.log('success')}
                onLoadStart={console.log('start')}
                style={{width:'100%',height:'100%'}}
            />
 </View>

Android and IOS is OK, but Web is not OK. I check the react-native-webview website,it supported Windows.


text:
Q: PostGIS throwing error during installation via PostgreSQL Installer I am new to PostgreSQL and am following a Real Python tutorial to do some geocoding and mapping. The first part of the tutorial is to install PostgreSQL and PostGIS databases. The first time I tried this through the PostgreSQL installer it froze, the second time I tried it returned the error in the screenshot below. When I try to run the suggested sudo command in terminal it returns command not found. I have tried to uninstall PostgreSQL twice now and delete associated folders but it is still presenting the same error when I try to install PostGIS.
Hoping someone may know how to help?

A: I figured out a solution.
Use Homebrew to install postgis with brew install postgis this worked.


text:
Q: Overriding of bean coming from external library If I have a project in which I have a dependency on a library in which a bean's scope is unspecified, meaning singleton by default, is there a way to override the bean definition to keep it the same but only change the scope to prototype, either at runtime or through bean configuration?

A: There are three cases:

*

*If bean which you want to override is in configuration class marked
with @Confgiuration annotation , you can exclude this configuration
class and declare all beans from there

*If annotation is present directly on class than you should exclude
those class from @ComponentScan basePackages .

*You can set the order of configuration classes marked with
@Configuration annotation , the last one configuration class will
override all previous declared beans


text:
Q: Text background with round corner like Instagram does I want to create text with background color and round corners like Instagram does. I am able to achieve the background color but could not create the round corners.
What I have till now:

Below is the source code of above screenshot:
-(void)createBackgroundColor{
    [self.txtView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, self.txtView.text.length) usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) {
        [textArray addObject:[NSNumber numberWithInteger:glyphRange.length]];
        if (glyphRange.length == 1){
            return ;
        }
        UIImageView *highlightBackView = [[UIImageView alloc] initWithFrame:CGRectMake(usedRect.origin.x, usedRect.origin.y  , usedRect.size.width, usedRect.size.height + 2)];
        highlightBackView.layer.borderWidth = 1;
        highlightBackView.backgroundColor = [UIColor orangeColor];
        highlightBackView.layer.borderColor = [[UIColor clearColor] CGColor];
        [self.txtView insertSubview:highlightBackView atIndex:0];
        highlightBackView.layer.cornerRadius = 5;
    }];
}

I call this function in shouldChangeTextInRange delegate.
What I want:

See the inner radius marked with arrows, Any help would be appreciated!

A: UPDATE
I have rewritten my implementation of this code and made it available as a SwiftPM package: the RectangleContour package. The package includes an explanation of how to use its API and demo apps for macOS and iOS.
ORIGINAL
So, you want this:

Here's an answer that I spent way too long on, and that you probably won't even like, because your question is tagged objective-c but I wrote this answer in Swift. You can use Swift code from Objective-C, but not everyone wants to.
You can find my entire test project, including iOS and macOS test apps, in this github repo.
Anyway, what we need to do is compute the contour of the union of all of the line rects. I found a 1980 paper describing the necessary algorithm:
Lipski, W. and F. Preparata. "Finding the Contour of a Union of Iso-Oriented Rectangles." J. Algorithms 1 (1980): 235-246. doi:10.1016/0196-6774(80)90011-5
This algorithm is probably more general than actually required for your problem, since it can handle rectangle arrangements that create holes:

So it might be overkill for you, but it gets the job done.
Anyway, once we have the contour, we can convert it to a CGPath with rounded corners for stroking or filling.
The algorithm is somewhat involved, but I implemented it (in Swift) as an extension method on CGPath:
import CoreGraphics

extension CGPath {
    static func makeUnion(of rects: [CGRect], cornerRadius: CGFloat) -> CGPath {
        let phase2 = AlgorithmPhase2(cornerRadius: cornerRadius)
        _ = AlgorithmPhase1(rects: rects, phase2: phase2)
        return phase2.makePath()
    }
}

fileprivate func swapped<A, B>(_ pair: (A, B)) -> (B, A) { return (pair.1, pair.0) }

fileprivate class AlgorithmPhase1 {

    init(rects: [CGRect], phase2: AlgorithmPhase2) {
        self.phase2 = phase2
        xs = Array(Set(rects.map({ $0.origin.x})).union(rects.map({ $0.origin.x + $0.size.width }))).sorted()
        indexOfX = [CGFloat:Int](uniqueKeysWithValues: xs.enumerated().map(swapped))
        ys = Array(Set(rects.map({ $0.origin.y})).union(rects.map({ $0.origin.y + $0.size.height }))).sorted()
        indexOfY = [CGFloat:Int](uniqueKeysWithValues: ys.enumerated().map(swapped))
        segments.reserveCapacity(2 * ys.count)
        _ = makeSegment(y0: 0, y1: ys.count - 1)

        let sides = (rects.map({ makeSide(direction: .down, rect: $0) }) + rects.map({ makeSide(direction: .up, rect: $0)})).sorted()
        var priorX = 0
        var priorDirection = VerticalDirection.down
        for side in sides {
            if side.x != priorX || side.direction != priorDirection {
                convertStackToPhase2Sides(atX: priorX, direction: priorDirection)
                priorX = side.x
                priorDirection = side.direction
            }
            switch priorDirection {
            case .down:
                pushEmptySegmentsOfSegmentTree(atIndex: 0, thatOverlap: side)
                adjustInsertionCountsOfSegmentTree(atIndex: 0, by: 1, for: side)
            case .up:
                adjustInsertionCountsOfSegmentTree(atIndex: 0, by: -1, for: side)
                pushEmptySegmentsOfSegmentTree(atIndex: 0, thatOverlap: side)
            }
        }
        convertStackToPhase2Sides(atX: priorX, direction: priorDirection)

    }

    private let phase2: AlgorithmPhase2
    private let xs: [CGFloat]
    private let indexOfX: [CGFloat: Int]
    private let ys: [CGFloat]
    private let indexOfY: [CGFloat: Int]
    private var segments: [Segment] = []
    private var stack: [(Int, Int)] = []

    private struct Segment {
        var y0: Int
        var y1: Int
        var insertions = 0
        var status  = Status.empty
        var leftChildIndex: Int?
        var rightChildIndex: Int?

        var mid: Int { return (y0 + y1 + 1) / 2 }

        func withChildrenThatOverlap(_ side: Side, do body: (_ childIndex: Int) -> ()) {
            if side.y0 < mid, let l = leftChildIndex { body(l) }
            if mid < side.y1, let r = rightChildIndex { body(r) }
        }

        init(y0: Int, y1: Int) {
            self.y0 = y0
            self.y1 = y1
        }

        enum Status {
            case empty
            case partial
            case full
        }
    }

    private struct /*Vertical*/Side: Comparable {
        var x: Int
        var direction: VerticalDirection
        var y0: Int
        var y1: Int

        func fullyContains(_ segment: Segment) -> Bool {
            return y0 <= segment.y0 && segment.y1 <= y1
        }

        static func ==(lhs: Side, rhs: Side) -> Bool {
            return lhs.x == rhs.x && lhs.direction == rhs.direction && lhs.y0 == rhs.y0 && lhs.y1 == rhs.y1
        }

        static func <(lhs: Side, rhs: Side) -> Bool {
            if lhs.x < rhs.x { return true }
            if lhs.x > rhs.x { return false }
            if lhs.direction.rawValue < rhs.direction.rawValue { return true }
            if lhs.direction.rawValue > rhs.direction.rawValue { return false }
            if lhs.y0 < rhs.y0 { return true }
            if lhs.y0 > rhs.y0 { return false }
            return lhs.y1 < rhs.y1
        }
    }

    private func makeSegment(y0: Int, y1: Int) -> Int {
        let index = segments.count
        let segment: Segment = Segment(y0: y0, y1: y1)
        segments.append(segment)
        if y1 - y0 > 1 {
            let mid = segment.mid
            segments[index].leftChildIndex = makeSegment(y0: y0, y1: mid)
            segments[index].rightChildIndex = makeSegment(y0: mid, y1: y1)
        }
        return index
    }

    private func adjustInsertionCountsOfSegmentTree(atIndex i: Int, by delta: Int, for side: Side) {
        var segment = segments[i]
        if side.fullyContains(segment) {
            segment.insertions += delta
        } else {
            segment.withChildrenThatOverlap(side) { adjustInsertionCountsOfSegmentTree(atIndex: $0, by: delta, for: side) }
        }

        segment.status = uncachedStatus(of: segment)
        segments[i] = segment
    }

    private func uncachedStatus(of segment: Segment) -> Segment.Status {
        if segment.insertions > 0 { return .full }
        if let l = segment.leftChildIndex, let r = segment.rightChildIndex {
            return segments[l].status == .empty && segments[r].status == .empty ? .empty : .partial
        }
        return .empty
    }

    private func pushEmptySegmentsOfSegmentTree(atIndex i: Int, thatOverlap side: Side) {
        let segment = segments[i]
        switch segment.status {
        case .empty where side.fullyContains(segment):
            if let top = stack.last, segment.y0 == top.1 {
                // segment.y0 == prior segment.y1, so merge.
                stack[stack.count - 1] = (top.0, segment.y1)
            } else {
                stack.append((segment.y0, segment.y1))
            }
        case .partial, .empty:
            segment.withChildrenThatOverlap(side) { pushEmptySegmentsOfSegmentTree(atIndex: $0, thatOverlap: side) }
        case .full: break
        }
    }

    private func makeSide(direction: VerticalDirection, rect: CGRect) -> Side {
        let x: Int
        switch direction {
        case .down: x = indexOfX[rect.minX]!
        case .up: x = indexOfX[rect.maxX]!
        }
        return Side(x: x, direction: direction, y0: indexOfY[rect.minY]!, y1: indexOfY[rect.maxY]!)
    }

    private func convertStackToPhase2Sides(atX x: Int, direction: VerticalDirection) {
        guard stack.count > 0 else { return }
        let gx = xs[x]
        switch direction {
        case .up:
            for (y0, y1) in stack {
                phase2.addVerticalSide(atX: gx, fromY: ys[y0], toY: ys[y1])
            }
        case .down:
            for (y0, y1) in stack {
                phase2.addVerticalSide(atX: gx, fromY: ys[y1], toY: ys[y0])
            }
        }
        stack.removeAll(keepingCapacity: true)
    }

}

fileprivate class AlgorithmPhase2 {

    init(cornerRadius: CGFloat) {
        self.cornerRadius = cornerRadius
    }

    let cornerRadius: CGFloat

    func addVerticalSide(atX x: CGFloat, fromY y0: CGFloat, toY y1: CGFloat) {
        verticalSides.append(VerticalSide(x: x, y0: y0, y1: y1))
    }

    func makePath() -> CGPath {
        verticalSides.sort(by: { (a, b) in
            if a.x < b.x { return true }
            if a.x > b.x { return false }
            return a.y0 < b.y0
        })

        var vertexes: [Vertex] = []
        for (i, side) in verticalSides.enumerated() {
            vertexes.append(Vertex(x: side.x, y0: side.y0, y1: side.y1, sideIndex: i, representsEnd: false))
            vertexes.append(Vertex(x: side.x, y0: side.y1, y1: side.y0, sideIndex: i, representsEnd: true))
        }
        vertexes.sort(by: { (a, b) in
            if a.y0 < b.y0 { return true }
            if a.y0 > b.y0 { return false }
            return a.x < b.x
        })

        for i in stride(from: 0, to: vertexes.count, by: 2) {
            let v0 = vertexes[i]
            let v1 = vertexes[i+1]
            let startSideIndex: Int
            let endSideIndex: Int
            if v0.representsEnd {
                startSideIndex = v0.sideIndex
                endSideIndex = v1.sideIndex
            } else {
                startSideIndex = v1.sideIndex
                endSideIndex = v0.sideIndex
            }
            precondition(verticalSides[startSideIndex].nextIndex == -1)
            verticalSides[startSideIndex].nextIndex = endSideIndex
        }

        let path = CGMutablePath()
        for i in verticalSides.indices where !verticalSides[i].emitted {
            addLoop(startingAtSideIndex: i, to: path)
        }
        return path.copy()!
    }

    private var verticalSides: [VerticalSide] = []

    private struct VerticalSide {
        var x: CGFloat
        var y0: CGFloat
        var y1: CGFloat
        var nextIndex = -1
        var emitted = false

        var isDown: Bool { return y1 < y0 }

        var startPoint: CGPoint { return CGPoint(x: x, y: y0) }
        var midPoint: CGPoint { return CGPoint(x: x, y: 0.5 * (y0 + y1)) }
        var endPoint: CGPoint { return CGPoint(x: x, y: y1) }

        init(x: CGFloat, y0: CGFloat, y1: CGFloat) {
            self.x = x
            self.y0 = y0
            self.y1 = y1
        }
    }

    private struct Vertex {
        var x: CGFloat
        var y0: CGFloat
        var y1: CGFloat
        var sideIndex: Int
        var representsEnd: Bool
    }

    private func addLoop(startingAtSideIndex startIndex: Int, to path: CGMutablePath) {
        var point = verticalSides[startIndex].midPoint
        path.move(to: point)
        var fromIndex = startIndex
        repeat {
            let toIndex = verticalSides[fromIndex].nextIndex
            let horizontalMidpoint = CGPoint(x: 0.5 * (verticalSides[fromIndex].x + verticalSides[toIndex].x), y: verticalSides[fromIndex].y1)
            path.addCorner(from: point, toward: verticalSides[fromIndex].endPoint, to: horizontalMidpoint, maxRadius: cornerRadius)
            let nextPoint = verticalSides[toIndex].midPoint
            path.addCorner(from: horizontalMidpoint, toward: verticalSides[toIndex].startPoint, to: nextPoint, maxRadius: cornerRadius)
            verticalSides[fromIndex].emitted = true
            fromIndex = toIndex
            point = nextPoint
        } while fromIndex != startIndex
        path.closeSubpath()
    }

}

fileprivate extension CGMutablePath {
    func addCorner(from start: CGPoint, toward corner: CGPoint, to end: CGPoint, maxRadius: CGFloat) {
        let radius = min(maxRadius, min(abs(start.x - end.x), abs(start.y - end.y)))
        addArc(tangent1End: corner, tangent2End: end, radius: radius)
    }
}

fileprivate enum VerticalDirection: Int {
    case down = 0
    case up = 1
}

With this, I can paint the rounded background you want in my view controller:
private func setHighlightPath() {
    let textLayer = textView.layer
    let textContainerInset = textView.textContainerInset
    let uiInset = CGFloat(insetSlider.value)
    let radius = CGFloat(radiusSlider.value)
    let highlightLayer = self.highlightLayer
    let layout = textView.layoutManager
    let range = NSMakeRange(0, layout.numberOfGlyphs)
    var rects = [CGRect]()
    layout.enumerateLineFragments(forGlyphRange: range) { (_, usedRect, _, _, _) in
        if usedRect.width > 0 && usedRect.height > 0 {
            var rect = usedRect
            rect.origin.x += textContainerInset.left
            rect.origin.y += textContainerInset.top
            rect = highlightLayer.convert(rect, from: textLayer)
            rect = rect.insetBy(dx: uiInset, dy: uiInset)
            rects.append(rect)
        }
    }
    highlightLayer.path = CGPath.makeUnion(of: rects, cornerRadius: radius)
}

A: Im pasting in the wrapper class I made for this. Thanks for the algorithm rob mayoff it works great.
Limitations that I'm aware of:

*

*If you use dynamic colors, this class is not aware of traitcollection and userinterface style changes. Highlight is cgColor so it will not adopt. So your .label color for the highlight will stay either .white or .black for example after interface style changed. Handle it outside with an update.

*Just wrote this quickly without testing too many scenarios. Insets and radius auto calculated if not specified to fit the font size but not aware or line spacing and other variables.

*Generally not tested heavily so check if it fits your purpose.

*This being a View and a textView on it, you need to lay it out with frame or constraints for width and height. No intrinsic content size. If you want to fiddle with that, please do and post the intrinsicContentSize function.

*Editing and selection for the textView is turned off. textView is public; Turn editing back on if you need it.

convenience init / update signature:
init(text:String? = nil,
     font:UIFont? = nil,
     textColor:UIColor? = nil,
     highlightColor:UIColor? = nil,
     inset:CGFloat? = nil,
     radius:CGFloat? = nil)

usage examples:
let stamp = Stamp()
let stamp = Stamp(text: "Whatever\nneeds to be\nstamped.")
let stamp = Stamp(text: "Placeholder that has no line breaks but wraps anyway.")
stamp.update(text: "Smaller Version",
             font: UIFont.systemFont(ofSize: 15, weight: .regular),
             textColor: .label,
             highlightColor:.purple)

Just make a new file and paste in this class. Use as described.
import UIKit
import CoreGraphics

class Stamp: UIView, UITextViewDelegate {

var textView = UITextView()

private var text:String = "Place holder\nline\nbroken Stamp."

private var highlightLayer = CAShapeLayer()
private var highlightColor:CGColor = UIColor.systemOrange.cgColor

private var textColor:UIColor = UIColor.label
private var font:UIFont = UIFont.systemFont(ofSize: 35, weight: .bold)

private var inset:CGFloat = 1
private var radius:CGFloat = 1

override init(frame: CGRect) {
    super.init(frame: frame)

    textView.delegate = self
    textView.isEditable = false
    textView.isSelectable = false
    textView.font = self.font

    self.inset = -font.pointSize / 5
    self.radius = font.pointSize / 4

    self.textView.text = self.text
    self.textView.textAlignment = .center
    self.textView.backgroundColor = .clear

    highlightLayer.backgroundColor = nil
    highlightLayer.strokeColor = nil
    self.layer.insertSublayer(highlightLayer, at: 0)

    highlightLayer.fillColor = self.highlightColor

    addSubview(textView)
    textView.fillSuperview()
}

convenience init(text:String? = nil,
                 font:UIFont? = nil,
                 textColor:UIColor? = nil,
                 highlightColor:UIColor? = nil,
                 inset:CGFloat? = nil,
                 radius:CGFloat? = nil) {

    self.init(frame: .zero)

    self.update(text: text,
                font: font,
                textColor: textColor,
                highlightColor: highlightColor,
                inset: inset,
                radius: radius)
}

func update(text:String? = nil,
            font:UIFont? = nil,
            textColor:UIColor? = nil,
            highlightColor:UIColor? = nil,
            inset:CGFloat? = nil,
            radius:CGFloat? = nil){

    if let text = text { self.text = text }
    if let font = font { self.font = font }
    if let textColor = textColor { self.textColor = textColor }
    if let highlightColor = highlightColor { self.highlightColor = highlightColor.cgColor }

    self.inset = inset ?? -self.font.pointSize / 5
    self.radius = radius ?? self.font.pointSize / 4

    self.textView.text = text
    self.textView.textColor = self.textColor
    self.textView.font = self.font

    highlightLayer.fillColor = self.highlightColor

    // this will re-draw the highlight
    setHighlightPath()
}

override func layoutSubviews() {
    super.layoutSubviews()
    highlightLayer.frame = self.bounds
    self.setHighlightPath()
}

func textViewDidChange(_ textView: UITextView) {
    setHighlightPath()
}

private func setHighlightPath() {
    let textLayer = textView.layer
    let textContainerInset = textView.textContainerInset
    let uiInset = CGFloat(inset)
    let radius = CGFloat(radius)
    let highlightLayer = self.highlightLayer
    let layout = textView.layoutManager
    let range = NSMakeRange(0, layout.numberOfGlyphs)
    var rects = [CGRect]()
    layout.enumerateLineFragments(forGlyphRange: range) { (_, usedRect, _, _, _) in
        if usedRect.width > 0 && usedRect.height > 0 {
            var rect = usedRect
            rect.origin.x += textContainerInset.left
            rect.origin.y += textContainerInset.top
            rect = highlightLayer.convert(rect, from: textLayer)
            rect = rect.insetBy(dx: uiInset, dy: uiInset)
            rects.append(rect)
        }
    }
    highlightLayer.path = CGPath.makeUnion(of: rects, cornerRadius: radius)
}

// Bojler
required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

extension CGPath {
    static func makeUnion(of rects: [CGRect], cornerRadius: CGFloat) -> CGPath {
        let phase2 = AlgorithmPhase2(cornerRadius: cornerRadius)
        _ = AlgorithmPhase1(rects: rects, phase2: phase2)
        return phase2.makePath()
    }
}

fileprivate func swapped<A, B>(_ pair: (A, B)) -> (B, A) { return (pair.1, pair.0) }

fileprivate class AlgorithmPhase1 {

init(rects: [CGRect], phase2: AlgorithmPhase2) {
    self.phase2 = phase2
    xs = Array(Set(rects.map({ $0.origin.x})).union(rects.map({ $0.origin.x + $0.size.width }))).sorted()
    indexOfX = [CGFloat:Int](uniqueKeysWithValues: xs.enumerated().map(swapped))
    ys = Array(Set(rects.map({ $0.origin.y})).union(rects.map({ $0.origin.y + $0.size.height }))).sorted()
    indexOfY = [CGFloat:Int](uniqueKeysWithValues: ys.enumerated().map(swapped))
    segments.reserveCapacity(2 * ys.count)
    _ = makeSegment(y0: 0, y1: ys.count - 1)

    let sides = (rects.map({ makeSide(direction: .down, rect: $0) }) + rects.map({ makeSide(direction: .up, rect: $0)})).sorted()
    var priorX = 0
    var priorDirection = VerticalDirection.down
    for side in sides {
        if side.x != priorX || side.direction != priorDirection {
            convertStackToPhase2Sides(atX: priorX, direction: priorDirection)
            priorX = side.x
            priorDirection = side.direction
        }
        switch priorDirection {
        case .down:
            pushEmptySegmentsOfSegmentTree(atIndex: 0, thatOverlap: side)
            adjustInsertionCountsOfSegmentTree(atIndex: 0, by: 1, for: side)
        case .up:
            adjustInsertionCountsOfSegmentTree(atIndex: 0, by: -1, for: side)
            pushEmptySegmentsOfSegmentTree(atIndex: 0, thatOverlap: side)
        }
    }
    convertStackToPhase2Sides(atX: priorX, direction: priorDirection)

}

private let phase2: AlgorithmPhase2
private let xs: [CGFloat]
private let indexOfX: [CGFloat: Int]
private let ys: [CGFloat]
private let indexOfY: [CGFloat: Int]
private var segments: [Segment] = []
private var stack: [(Int, Int)] = []

private struct Segment {
    var y0: Int
    var y1: Int
    var insertions = 0
    var status  = Status.empty
    var leftChildIndex: Int?
    var rightChildIndex: Int?

    var mid: Int { return (y0 + y1 + 1) / 2 }

    func withChildrenThatOverlap(_ side: Side, do body: (_ childIndex: Int) -> ()) {
        if side.y0 < mid, let l = leftChildIndex { body(l) }
        if mid < side.y1, let r = rightChildIndex { body(r) }
    }

    init(y0: Int, y1: Int) {
        self.y0 = y0
        self.y1 = y1
    }

    enum Status {
        case empty
        case partial
        case full
    }
}

private struct /*Vertical*/Side: Comparable {
    var x: Int
    var direction: VerticalDirection
    var y0: Int
    var y1: Int

    func fullyContains(_ segment: Segment) -> Bool {
        return y0 <= segment.y0 && segment.y1 <= y1
    }

    static func ==(lhs: Side, rhs: Side) -> Bool {
        return lhs.x == rhs.x && lhs.direction == rhs.direction && lhs.y0 == rhs.y0 && lhs.y1 == rhs.y1
    }

    static func <(lhs: Side, rhs: Side) -> Bool {
        if lhs.x < rhs.x { return true }
        if lhs.x > rhs.x { return false }
        if lhs.direction.rawValue < rhs.direction.rawValue { return true }
        if lhs.direction.rawValue > rhs.direction.rawValue { return false }
        if lhs.y0 < rhs.y0 { return true }
        if lhs.y0 > rhs.y0 { return false }
        return lhs.y1 < rhs.y1
    }
}

private func makeSegment(y0: Int, y1: Int) -> Int {
    let index = segments.count
    let segment: Segment = Segment(y0: y0, y1: y1)
    segments.append(segment)
    if y1 - y0 > 1 {
        let mid = segment.mid
        segments[index].leftChildIndex = makeSegment(y0: y0, y1: mid)
        segments[index].rightChildIndex = makeSegment(y0: mid, y1: y1)
    }
    return index
}

private func adjustInsertionCountsOfSegmentTree(atIndex i: Int, by delta: Int, for side: Side) {
    var segment = segments[i]
    if side.fullyContains(segment) {
        segment.insertions += delta
    } else {
        segment.withChildrenThatOverlap(side) { adjustInsertionCountsOfSegmentTree(atIndex: $0, by: delta, for: side) }
    }

    segment.status = uncachedStatus(of: segment)
    segments[i] = segment
}

private func uncachedStatus(of segment: Segment) -> Segment.Status {
    if segment.insertions > 0 { return .full }
    if let l = segment.leftChildIndex, let r = segment.rightChildIndex {
        return segments[l].status == .empty && segments[r].status == .empty ? .empty : .partial
    }
    return .empty
}

private func pushEmptySegmentsOfSegmentTree(atIndex i: Int, thatOverlap side: Side) {
    let segment = segments[i]
    switch segment.status {
    case .empty where side.fullyContains(segment):
        if let top = stack.last, segment.y0 == top.1 {
            // segment.y0 == prior segment.y1, so merge.
            stack[stack.count - 1] = (top.0, segment.y1)
        } else {
            stack.append((segment.y0, segment.y1))
        }
    case .partial, .empty:
        segment.withChildrenThatOverlap(side) { pushEmptySegmentsOfSegmentTree(atIndex: $0, thatOverlap: side) }
    case .full: break
    }
}

private func makeSide(direction: VerticalDirection, rect: CGRect) -> Side {
    let x: Int
    switch direction {
    case .down: x = indexOfX[rect.minX]!
    case .up: x = indexOfX[rect.maxX]!
    }
    return Side(x: x, direction: direction, y0: indexOfY[rect.minY]!, y1: indexOfY[rect.maxY]!)
}

private func convertStackToPhase2Sides(atX x: Int, direction: VerticalDirection) {
    guard stack.count > 0 else { return }
    let gx = xs[x]
    switch direction {
    case .up:
        for (y0, y1) in stack {
            phase2.addVerticalSide(atX: gx, fromY: ys[y0], toY: ys[y1])
        }
    case .down:
        for (y0, y1) in stack {
            phase2.addVerticalSide(atX: gx, fromY: ys[y1], toY: ys[y0])
        }
    }
    stack.removeAll(keepingCapacity: true)
}

}

fileprivate class AlgorithmPhase2 {

init(cornerRadius: CGFloat) {
    self.cornerRadius = cornerRadius
}

let cornerRadius: CGFloat

func addVerticalSide(atX x: CGFloat, fromY y0: CGFloat, toY y1: CGFloat) {
    verticalSides.append(VerticalSide(x: x, y0: y0, y1: y1))
}

func makePath() -> CGPath {
    verticalSides.sort(by: { (a, b) in
        if a.x < b.x { return true }
        if a.x > b.x { return false }
        return a.y0 < b.y0
    })

    var vertexes: [Vertex] = []
    for (i, side) in verticalSides.enumerated() {
        vertexes.append(Vertex(x: side.x, y0: side.y0, y1: side.y1, sideIndex: i, representsEnd: false))
        vertexes.append(Vertex(x: side.x, y0: side.y1, y1: side.y0, sideIndex: i, representsEnd: true))
    }
    vertexes.sort(by: { (a, b) in
        if a.y0 < b.y0 { return true }
        if a.y0 > b.y0 { return false }
        return a.x < b.x
    })

    for i in stride(from: 0, to: vertexes.count, by: 2) {
        let v0 = vertexes[i]
        let v1 = vertexes[i+1]
        let startSideIndex: Int
        let endSideIndex: Int
        if v0.representsEnd {
            startSideIndex = v0.sideIndex
            endSideIndex = v1.sideIndex
        } else {
            startSideIndex = v1.sideIndex
            endSideIndex = v0.sideIndex
        }
        precondition(verticalSides[startSideIndex].nextIndex == -1)
        verticalSides[startSideIndex].nextIndex = endSideIndex
    }

    let path = CGMutablePath()
    for i in verticalSides.indices where !verticalSides[i].emitted {
        addLoop(startingAtSideIndex: i, to: path)
    }
    return path.copy()!
}

private var verticalSides: [VerticalSide] = []

private struct VerticalSide {
    var x: CGFloat
    var y0: CGFloat
    var y1: CGFloat
    var nextIndex = -1
    var emitted = false

    var isDown: Bool { return y1 < y0 }

    var startPoint: CGPoint { return CGPoint(x: x, y: y0) }
    var midPoint: CGPoint { return CGPoint(x: x, y: 0.5 * (y0 + y1)) }
    var endPoint: CGPoint { return CGPoint(x: x, y: y1) }

    init(x: CGFloat, y0: CGFloat, y1: CGFloat) {
        self.x = x
        self.y0 = y0
        self.y1 = y1
    }
}

private struct Vertex {
    var x: CGFloat
    var y0: CGFloat
    var y1: CGFloat
    var sideIndex: Int
    var representsEnd: Bool
}

private func addLoop(startingAtSideIndex startIndex: Int, to path: CGMutablePath) {
    var point = verticalSides[startIndex].midPoint
    path.move(to: point)
    var fromIndex = startIndex
    repeat {
        let toIndex = verticalSides[fromIndex].nextIndex
        let horizontalMidpoint = CGPoint(x: 0.5 * (verticalSides[fromIndex].x + verticalSides[toIndex].x), y: verticalSides[fromIndex].y1)
        path.addCorner(from: point, toward: verticalSides[fromIndex].endPoint, to: horizontalMidpoint, maxRadius: cornerRadius)
        let nextPoint = verticalSides[toIndex].midPoint
        path.addCorner(from: horizontalMidpoint, toward: verticalSides[toIndex].startPoint, to: nextPoint, maxRadius: cornerRadius)
        verticalSides[fromIndex].emitted = true
        fromIndex = toIndex
        point = nextPoint
    } while fromIndex != startIndex
    path.closeSubpath()
}

}
    fileprivate extension CGMutablePath {
        func addCorner(from start: CGPoint, toward corner: CGPoint, to end: CGPoint, maxRadius: CGFloat) {
            let radius = min(maxRadius, min(abs(start.x - end.x), abs(start.y - end.y)))
            addArc(tangent1End: corner, tangent2End: end, radius: radius)
        }
    }

    fileprivate enum VerticalDirection: Int {
        case down = 0
        case up = 1
    }


text:
Q: Custom application icon does not appear My application's icon is not showing if I do not use an absolute path like here:
[Desktop Entry]
Type=Application
Name=MyProgram
GenericName=MyProgram
Comment=This is a comment
Icon=/opt/extras.ubuntu.com/MyProgram/Icons/myprogram.svg
Exec=myprogram
Categories=Utility;TextTools;
Hidden=false
Terminal=false
Type=Application

Instead I write
Icon=myprogram

just like I call the program with Exec=myprogram, where it searches under /usr/bin.
According to the free desktop standards I copied the icons to /usr/share/icons/hicolor and even deleted the icon-cache as described here with sudo gtk-update-icon-cache /usr/share/icons/hicolor. Still my icon does not appear.

A: If you don't specify a full path, icons must reside inside the current icon scheme location.
If you want to add a program icon that is not part of any specific scheme, put it in /usr/share/icons/.

A: Solution as described in question, plus what I did by accident:
Somehow my launcher and panel disappeared and I restored them with
#!/bin/bash
dconf reset -f /org/compiz/
unity --reset-icons

Then my icons worked. Should be easier...


text:
Q: SQL: exclude duplicates I am new to SQL and I need to remove duplicates in a SELECT statement.
The Tabel looks like this:
| name 1 | name 2|
| John   | Lukas |
| Simon  | John  |
| Lukas  | John  |
| Lukas  | Simon |

The output should be as following:
name 1   name 2
John     Lukas
Simon    John
(Lukas    John) this should be excluded
Lukas    Simon

But there is again once Lukas John in it. I tryed with Distinct, but It doesent work. Can anybody please help me? Thanks in advance!

A: One method is:
select name1, name2
from t
where name1 < name2 or
      not exists (select 1 from t t2 where t2.name1 = t.name2 and t2.name2 = t.name1);

This assumes that the duplicates are only pairs that might be in the opposite order.  If you can have complete duplicates, then use select distinct.


text:
Q: Bash - Print the full path of a file from $PATH Say I have ~/scripts in my $PATH and I have script.sh inside that path.
I can execute that script by typing script.sh directly in the terminal, but what if I want to print out the full path of that script without knowing the base path of the script (or added any function inside the script to print out its own path)? Are there any good ways to do this?

A: In bash, to locate a file (script) in the users path, you can use the which command: (https://ss64.com/bash/which.html), but as @Jetchisel says there are better alternatives for POSIX-compliant shells; see 'which' vs 'command -v' in Bash


text:
Q: Finding an upper bound using the Estimation Lemma for this expression Is my reasoning correct?

Without actually evaluating the integral, show that:
$$I = \int_\phi \frac{1}{1+z^2} \leq\frac{3\pi}{16}$$
$\text{Where } \phi \text{ is the circular arc connecting }3 \text{ to } 3i$

Here's what I tried: Let L($\phi$) denote the length of the arc
$$L|\phi(t)| = \int_0^\frac{\pi}{2}|3ie^{it}|dt = \frac{3\pi}{2}$$
Now it remains to find:
$$inf\{|1 + (3e^{it})^2|,\text{ where t}\in[0,\frac{\pi}{2}]\}$$
Expanding $|1 + (3e^{it})^2|$ gives me the expression:
$$|1 + (3e^{it})^2| = \sqrt{(1 + 9\cos(2t))^2 + (9\sin(2t))^2}
=\sqrt{82 + 18\cos(2t)}$$
Minimising this in the domain of t, we get, for t = $\frac{\pi}{2}$:
$$inf\{|1 + (3e^{it})^2|,\text{ where t}\in[0,\frac{\pi}{2}]\} = \sqrt{64} = 8$$
Hence by the Estimating Lemma, we have:
$$I \leq \frac{3\pi}{16}$$


text:
Q: Is there a way to measure uniformness of points in a 2D square? Questions : Say I have 1000 points, that are distributed in a $[0,1]\times[0,1]$ square. It is not uniformly distributed. For example I might have "clusters" of points within the square, and conversely, there may be some empty patches of space within the square. I want to get a measure of uniformness in the distribution of the points. But, I don't think it can be the $\chi^2$ test for a uniform distribution for what I want to do. The measure should be continuous with respect to the point locations.
Context: I have a dataset of variables, that are closely linked to the interaction positions within a $[0,1]\times[0,1]$ square. I do not know those points a priori, but I do know that when I map those variables to the points in the square, it has to be somewhat uniformly distributed. (It should look as if they were sampled from a 2d uniform distribution.)
I want to learn the mapping between the variables and the point locations, so I am trying to setup a neural network model that can learn to map those variables. Loss function will be a measure of uniformness, so that if the learned mapping does not give a uniformly distribution of points, it will be penalized and the model will be corrected (through backpropagation). Now I've been thinking about what could be used for such measure of uniformness. With some Google search, I learned that the $\chi^2$ test can be used to measure the uniformness of points, but I don't think it can be used for the neural network, because the method is based on dividing the square into many small squares, and  counting the number of points in each small squares. The problem is, the gradient cannot be calculated, because an infinitismal change in the point locations won't change the $\chi^2$ test results. So there is no gradient and the model cannot be trained.
So I need a measure of uniformness, with which I can calculate the gradient w.r.t. point locations. So it has to be a continuous measure. Does anyone know of such a measure? Thank you.

A: The solution depends on the possible alternatives to uniformity you need to measure.
One attractive approach that immediately yields several solutions is to use a measure of the distance between the empirical copula and the independence copula (which describes the uniform distribution on the unit square). For instance, you might use the $L^2$ norm of the difference between the copulae.  See the code at the end of this post for details.
Here are the results of a simulation study of the distribution of this norm when $n=100$ points are created with iid Beta$(1,\beta)$ coordinates. When $\beta=1$ this is uniform and as $\beta$ increases the points start favoring locations near the origin.

The first row plots the Beta density functions.  The second row plots sample data.  The third row plots the distribution of 500 values of this norm from 500 independent sets of sample data.
The distribution for $\beta=1.5$ is clearly separated from the distribution for $\beta=1,$ showing this approach has high power to discriminate the third or fourth columns from the left column.
A subtler way in which a distribution might fail to be uniform is by local clustering (or anticlustering).  To explore that, I created uniform samples of the square and snapped the results to a grid of $h+1$ equally spaced values.

This method has only a little power to distinguish $h=10$ from no clustering with $n=100$ points, but is very powerful at identifying the $h=5$ clustering at the right.
Because you are interested in datasets with about $n=1000$ points, here is a similar study for simulated data of that size.  It exhibits reasonable power to distinguish the middle plot ($\beta=1.05$) from uniformity and high power to distinguish the right plot ($\beta=1.1$).  I cannot visually discern any difference in uniformity among these cases, suggesting the $L^2$ norm works well.

If you are concerned about identifying local clustering, instead use a local measure of non-uniformity, such as the mean nearest-neighbor distance or (edge-adjusted) mean numbers of neighbors within a moving window of fixed size.

This R code snippet simulates an array of points in the unit square and (using a $O(n^2)$ brute force algorithm) computes the $L^2$ distance to the independence copula.
uv <- matrix(runif(2*n), 2)       # Coordinates in columns
y <- apply(uv, 2, function(xy) {
  z <- uv - xy                    # Vector between `xy` and a point
  mean(z[1,] <= 0 & z[2,] <= 0)   # Value of the copula at `xy`
})
sqrt(mean((uv[1,]*uv[2,] - y)^2)) # L^2 distance between the reference and the copula

A more efficient method to compute the empirical copula would use a lexicographic sort on the coordinates or an equivalent efficient spatial search structure (e.g., a quadtree).


text:
Q: Remove IP from modsecurity blacklist I have a CentOS 7.2 server with apache. I installed and configured modsecurity and I did some tests from my home and now my IP si blocked.
Where is stored the blacklist for modsecurity? I stopped the iptables and fail2ban but I'm still blocked. Thanks

A: What you actually need to do is whitelist your IP

How do I whitelist an IP address so it can pass through ModSecurity?
  The first issue to realize is that in ModSecurity 2.0, the allow
  action is only applied to the current phase. This means that if a rule
  matches in a subsequent phase it may still take a disruptive action.
  The recommended rule configuration to allow a remote IP address to
  bypass ModSecurity rules is to do the following (where 192.168.1.100
  should be substituted with the desired IP address):
SecRule REMOTE_ADDR "@ipMatch 192.168.110"
  phase:1,nolog,allow,ctl:ruleEngine=Off
If you want to allow uninterrupted access to the remote IP address,
however you still want to log rule alerts, then you can use this rule
SecRule REMOTE_ADDR "@ipMatch 192.168.110"
  phase:1,nolog,allow,ctl:ruleEngine=DetectionOnly
If you want to disable both the rule and audit engines, then you can
  optionally add another ctl action:
SecRule REMOTE_ADDR "@ipMatch 192.168.110"
  phase:1,nolog,allow,ctl:ruleEngine=Off,ctl:auditEngine=Off

See - https://github.com/SpiderLabs/ModSecurity/wiki/ModSecurity-Frequently-Asked-Questions-%28FAQ%29#How_do_I_whitelist_an_IP_address_so_it_can_pass_through_ModSecurity
If you also run mod_evasive, also make sure that you create a whitelist for it too as it will also block you out as it is intended when you are wilfully attacking your own server.


text:
Q: Detecting Click Events outside of the Ng-Modal I have a Separate Service that handles Dynamically created button and their events like keydown/keybindings ect, The issue im facing is referring whether that specific button being clicked is inside a Modal or outside a ngModal
   insideModal(){
        const shownModal = this.modalRef.shown;
        const compInstance =   this.modalRef.componentInstance;
    }

I have a Instance of the ModalRef when it is opened and I save that but i'm unsure how to detect on the button event weather or not that specific button event is happening from inside the Modal or outside it
I could pass a instance of elementRef but I'm not sure how id compare it to make sure its inside of a <ngb-modal-window>
I know you can get the ButtonID for instance with JS with something like:
  $("button").click(function() {
     alert(this.id); // or alert($(this).attr('id'));
  });

So the Question is How Do I Detect if a button is within a <ngb-modal-window> or detect weather it has a parent div with a class related to NG-Modals


text:
Q: Truncating the post date of a Wordpress post with PHP I'm trying to manipulate the output of Wordpress' the_date() function.
My code:
<?php
define('WP_USE_THEMES', false);
require('/gnews/wp-blog-header.php');
if (have_posts()) : while (have_posts()) : the_post();

$potatoes = the_date();
$themonth = substr($potatoes,3);
echo($themonth);

endwhile; else:
endif;
?>

Pardon the strange variable names, at wit's end here.
No matter what I try, the above will only output June 17th 2011.
The end result I'd like is to set it up so that I have a three character month name in one variable, a two-digit date number in another variable, and the year in a third. The date has to be the date of the Wordpress post however.
How would I do that?
Thanks!

A: If you wish these to be in 3 variables, pass the output of the_date() into strtotime() and date('Y-M-d) and then explode() it into separate variables. strtotime() is perfectly capable of parsing a date like June 17th 2011.
// Get it in YYYY-Mon-dd
$date = date('Y-M-d', strtotime(the_date());
list($year, $month, $day) = explode("-", $date);

Update
Wordpress' the_date()'s fourth parameter is a boolean which specifies whether to return or echo it. It isn't necessary to use strtotime() if done this way:
// Call the_date() with its format and FALSE to echo
$date = the_date('Y-M-d', '', '', FALSE);
list($year, $month, $day) = explode("-", $date);