text:
Q: How to find out if there is anymore words after a full stop? I have some text's stored in the database and while I show them in the frontend I place the words before each full-stop within a li tag.

 {!! str_replace(".","

", $sscat->inclusion) !!}

Everything is working fine except when the text has a full-stop at the very end, it ends up showing an empty numbering.
For example, if I have "aaaaaa.Something Something." the output will be like-

*

*aaaaaa

*Something Something

*

So What can I do to prevent that empty list?

A: Instead of replacing, what I'd do is explode the string into an array, filter out empty values, then iterate through the results

@foreach(array_filter(explode('.', $sscat->inclusion)) as $item)

{!! $item !!}

@endforeach

A: If you want to show a trailing . in the last list item, you can use preg_replace instead of str_replace to avoid replacing that one if it's present.
preg_replace("/\.(?!$)/", "

", $sscat->inclusion)

If you don't want to show it, aynber's answer looks good to me, but if you'd rather not use a loop, you can also just trim it off before doing the replacements.
str_replace(".","

", rtrim($sscat->inclusion, '.'))

Another possibility you might want to consider is modifying the model to handle trailing .s in the inclusion accessor, so you won't have to do this again if you have other templates that use that property.

A: Along the lines of the other answer, just explode, filter and implode:

{!! implode("

", array_filter(explode(".", $sscat->inclusion))) !!}


text:
Q: Fitting regression model calculation in r I am working on a problem to fit a regression model and calculate the error rate of my data. I had an error message below:
Error in performance(prediction(inpPred, inpTruth), measure = metrTmp) :
could not find function "performance"
Here is my reproducible code
wifiDat <- read.table("wifi_localization.txt",sep="\t")
colnames(wifiDat) <- c("WF1", "WF2", "WF3", "WF4", "WF5", "WF6", "WF7", "RM")
wifiDat$RM <- factor(wifiDat$RM)
dim(wifiDat)
summary(wifiDat)
head(wifiDat)
ggpairs(wifiDat,aes(colour=RM))
glm.fit <- glm(RM~WF1+WF2+WF3+WF4+WF5+WF6+WF7,data=wifiDat,family=binomial)
glmPred <- predict(glm.fit,type="response")>0.5
table(wifiDat[,"RM"],glmPred)
SummPreds <- function(inpPred,inpTruth,inpMetrNms=c("err","acc","sens","spec")) {
retVals <- numeric()
for ( metrTmp in inpMetrNms ) {
retVals[metrTmp] <- performance(prediction(inpPred,inpTruth),measure=metrTmp)@y.values[[1]]   [2]
}
retVals

}
SummPreds(as.numeric(1+glmPred),as.numeric(wifiDat[,"RM"]))
Here is my sample data
V1. V2. V3. V4. V5. V6. V7. V8
-64 -56 -61 -66 -71 -82 -81 1
-68 -57 -61 -65 -71 -85 -85 2
-63 -60 -60 -67 -76 -85 -84 3
-61 -60 -68 -62 -77 -90 -80 4
-63 -65 -60 -63 -77 -81 -87 1
-64 -55 -63 -66 -76 -88 -83 1
-65 -61 -65 -67 -69 -87 -84 2
-61 -63 -58 -66 -74 -87 -82 3
-65 -60 -59 -63 -76 -86 -82 4
-62 -60 -66 -68 -80 -86 -91 1
-67 -61 -62 -67 -77 -83 -91 1
-65 -59 -61 -67 -72 -86 -81 1
-63 -57 -61 -65 -73 -84 -84 1
Please what am I doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java sum 2 negative numbers I'm trying to convert a function in java to pl/pgsql, and one problem that I found is when I'm trying to sum 2 negative numbers, and a get a positive number, more specifically :
public void sum(){
    int n1 = -1808642602;
    int n2 = -904321301;
    System.out.println(n1 + n2);// result is 1582003393
}

And in pl/pgsql I get an integer out of range error, and if I change the variables type to bigint i get a normal sum of 2 negative numbers, that is -2712963903, instead of 1582003393
How do I do to pl/pgsql get the same result without printing an integer out of range error?

A: This happens because the Java int underflows and doesn't tell you.
To get the answer you are looking for in pl, you need to use bigint. Then detect the case when the result is less than Java Integer.MIN_INT (-2^31), which is the case where Java will give a positive result. To get what Java would give you, add 2^32.

A: You are overflowing the int try the same thing with long and it should work.

A: It's overflowing, because the result is too big for an int. Use long instead.

A: Java sums them as 32 bit signed integers, which wrap at -231. Have you tried a 64 bit long instead?

A: That valid rand of int in Java is -2,147,483,648 to 2,147,483,647 (-2^31 - 2^31-1).
You are causing an Integer underflow. You should use a type long instead of int which ranges from -2^63 to 2^63-1

A: Java treats those 2 numbers as signed integers.
Basically the scope for singed integers is -2,147,483,648 to 2,147,483,647 (-2^31 - 2^31-1).
Hence the sum of those to values is -2712963903 which is less than the the minimum -2^31 so underflows and then wraps around by doing 2^32 - 2712963903 which gives you the signed int 1582003393.

A: Try using a long which will not overflow in this case (but will for large enough numbers)
System.out.println((long) n1 + n2);


text:
Q: How to write each element in a list to different columns in a dataframe? I have many different lists as output obtained from a function:

Outputs
$[1]
1 Variable_A Variable_B Variable_C

$[[2]]
1 Variable_A Variable_B Variable_C
$[[3]]
1 Variable_A Variable_B Variable_C
If I directly save these outputs in an Excel file (e.g. write.xlsx(Outputs,"Outputs.xlsx")), each list is saved in a different Sheet. However, I need these outputs in a single sheet where each list ($[1], $[[2]], $[[3]], etc) is in one column:
enter image description here


text:
Q: Cannot rails new app on newly installed Ruby on Rails by rbenv/homebrew on OS X Maverick After upgrading MacBookPro Retina (2012 model) from Mountain Lion to Maverick I decided to install the latest RoR for dev.  I follow the post on 55minutes here, except cannot installed the xcode command-line as it described, which I manually downloaded and installed from Apple Developer site, I can successfully followed other steps to install and setup homebrew, apple-gcc42, autoconf, pkg-config, git, postgresql, qt, rbenv, ruby-build, rbenv-default-gems, rbenv-update, then I can also install the Ruby 2.0.0-p247.
The problem start on 'gem regenerate_binstubs, where terminal returns:
> ERROR:  While executing gem ... (Gem::CommandLineError)
> Unknown command regenerate_binstubs

I then init the postgresSQL but did not configure it as I had second thought to use stock Sqllite.
Then I update the rbenv, brew and try to new a rails project, and terminal returns the following error:
> run  bundle install Fetching gem metadata from
> https://rubygems.org/.......... Fetching gem metadata from
> https://rubygems.org/.. Resolving dependencies...
>
> ArgumentError: invalid byte sequence in UTF-8 An error occurred while
> installing rake (10.1.0), and Bundler cannot continue. Make sure that
> `gem install rake -v '10.1.0'` succeeds before bundling.

I checked other posts and see similar error msg, try to solve by including the LANG in .bash_profile as follow but no use:
> export LANG="en_US.UTF-8"
> export LC_ALL="en_US.UTF-8"

Below is the content of my bash_profile:
export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH↲
export EDITOR='subl -w'

export PATH=/usr/local/bin:$PATH

export RBENV_ROOT="$HOME/.rbenv"

if [ -d $RBENV_ROOT ]; then
  export PATH="$RBENV_ROOT/bin:$PATH"
  eval "$(rbenv init -)"
fi

I hope someone can share a light on where I might do wrong.  Otherwise I plan to uninstall rbenv and change to rvm to continue the installation of RoR.  Thanks in advanced.

A: After struggling on this question for a week, I finally decide to drop rbenv and turn to rvm. Following this post on RailsApp, I installed RoR and new application successfully without any problem. Just remember to uninstall rbenv, clean everything related to rbenv in .bash_profile and also rm -rf ~/.rbenv before you get started.
For the answer of the question, which is about the UTF-8 error, turns out it's caused by the $PATH setting I put on the first line in .bash_profile.  Deleting it then the new application could move on (though it hits another wall about write permission to '/Library/Ruby/Gems' folder).  It's a lesson learnt that you never follow multiple posts to install a Rails' dev environment unless you know what you're doing.
However, I have to say that rbenv seems still not friendly to user, a newbie like me to install on MAC, but it's better to install on ubuntu which I got success in the first time.

A: In my case it was an issue with Ruby not linking properly to openssl, and reinstalling Ruby per this answer (https://stackoverflow.com/a/25493698) solved it.


text:
Q: Getting only 100mb from isp and using 10 gigabit router My ISP gives me only 100mb download and 100mb upload speed.
I have Ubiquiti EdgeRouter with 10 Gigabit SFP+ port and bought a SFP+ Transceiver Module so i can make SFP+ to RJ45 connection ( i'm using cat7 network cables ).
My pc have a 10GbE Ethernet PCIe adapter from ASUS.
Let say i connect my RJ45 cable using the SFP+ Transceiver Module into the first SFP+ port of the router as wan.
And i also connect a second RJ45 cable with SFP+ Transceiver Module into the second port in the router as lan and connect that cable into my pc 10GbE Ethernet PCIe adapter.
Will that work so i get internet connection on my pc and if not why?
I'm asking this to be understand if this setup works or not before buying all this stuff. I know there might be better ways, but please explain to me if that is possible or not.

A: It would work, but it feels like a bit of a waste - assuming you have 2 SFP ports (it's the edgerouter pro then) - you'd be significantly better off using a gigabit port to wan.
Without other 10GbE devices, only communication between your PC and your router would be at that speed - if you had another 10GbE device, it could go into the other port and communication between them would be at 10GbE.
You'd be spending the cost of the SFP+ module for no real advantage using it to connect to the WAN.
I mean, you would get internet, but your connection to the outside world would be only as fast as your ISP, and the connection between PCs would only be as fast as the slowest link.
Assuming you already own the router , I'd recommend not putting the wan side on the SFP device, or getting 10GbE set up unless you had a specific use for it. 10GbE hardware is dropping in price, so waiting a bit would be a great idea.
For now, the smart money is on sticking with the common, standard GbE ports.


text:
Q: Zeros of nontrivial solution of ODE Let $y$ be a nontrivial solution of the BVP, $$y''+xy=0,\, x \in [a,b],\, y(a)=y(b)=0,$$ then which of the following is/are true?

*

*$b>0$

*$y$ is monotone in $(a,0)$ if $a<0<b$

*y'(a)=0

*y has infinitely many zeros in $[a,b]$.

Option $4$ is false, by an application of Sturm Separation theorem $y$ has finitely many zeros in $[a,b].$ Any hints for other options please?

A: Hint: for $x < 0$, $y$ is convex when $y > 0$ and concave when $y < 0$.

A: The Equation $$y''+xy=0$$ is Airy ODE of second order whose two linearly independent solutions as $Ai(z)$ and $Bi(z)$. We can write its solution as
$$y(x)=C Ai(z)+D Bi(z), z=\frac{2x^{3/2}}{3}$$.
Next one can determine $C,D$ by imposing the conditions that $y(a)=0=y(b)$.
You may see
https://www.encyclopediaofmath.org/index.php/Airy_equation


text:
Q: Python: Issue with inserting large dataframe (1.2M rows) into Postgres I am using the Pandas insert method (https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method) to take CSVs that have been converted from .mdb files and insert them into Postgres. One of the tables that I am trying to convert is 1.2 million rows and is exceeding the CPU power of my EC2 instance. Is there a way to modify or break up this function in order to handle a CSV of this size? Other tables that are 150K-300K rows are working just fine. Thanks.
import csv
from io import StringIO
from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    # gets a DBAPI connection that can provide a cursor
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)

        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name

        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
            table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

def df_to_postgres(table_name, dataframe):

    df = dataframe

    engine = create_engine(f'postgresql://{PGusername}:{PGpassword}@{PGendpoint}:5432/testDB')

    df.to_sql(table_name.lower(), engine, if_exists='replace', method=psql_insert_copy)

EDIT: I added a chucksize argument into the df.to_sql statement and am still getting a memory error. Error notes are below.
  File "20191217_Access2PG.py", line 122, in <module>
    filter_mdb(args.bucket,args.profile)
  File "20191217_Access2PG.py", line 119, in filter_mdb
    s3_download(bucket, mdbList)
  File "20191217_Access2PG.py", line 103, in s3_download
    get_tables(path)
  File "20191217_Access2PG.py", line 84, in get_tables
    table_data(table_names)
  File "20191217_Access2PG.py", line 69, in table_data
    df_to_postgres(item, csv_file)
  File "20191217_Access2PG.py", line 48, in df_to_postgres
    df.to_sql(table_name.lower(), engine, if_exists='replace', method=psql_insert_copy)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 2712, in to_sql
    method=method,
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 518, in to_sql
    method=method,
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 1320, in to_sql
    table.insert(chunksize, method=method)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 734, in insert
    keys, data_list = self.insert_data()
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 710, in insert_data
    d = np.array(b.get_values(), dtype=object)
MemoryError```


text:
Q: issue with add variable in javascript source <script type="text/javascript">
window.onload = function () {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = "http://www.example.com/abc/abc.js?timestamp=" + new Date().getTime();
s.id = 'help-wall';
s.data-campaign-id ='6';
document.body.appendChild(s);
}
</script>

showing error in  s.data-campaign-id.Please help

A: Hyphens are illegal characters in Javascript identifiers, so can't be used with the object dot syntax. You have to use the square bracket syntax instead:
s['data-campaign-id'] = '6';

Alex in the comments makes the very valid point that this won't register as a data attribute, only as a property of the node. If you want it to be an attribute, you'll need setAttribute:
s.setAttribute('data-campaign-id', '6');

You needn't do this with the other properties, because the properties map onto the appropriate attributes. Because you're using a custom attribute it doesn't.

A: As others have pointed out, you obviously cannot use dot notation to denote attributes and properties whose names are not valid identifiers.
data-* attributes, however, are a special case. In this case, you can quite easily say
s.dataset.campaignId = '6';

Internally, the dataset property name is mapped between camelCase (campaignId) and dasherized form (data-campaign-id), in a way that makes it easier to set, just as one sets s.style.fontSize = "10px";.
Note that s.dataset is not supported in IE<=10, so for that you'll have to fall back to s.setAttribute('data-campaign-id', ...).


text:
Q: Sharing folder in Virtualbox I'm running Debian 9 as Host and I installed correctly Windows 7 as guest by using Oracle VirtualBox (v. 5.2.6); both the OSs work fine and I need to have a folder shared between those 2 operative systems.
In order to be able to get this, I followed these steps:

*

*GuestAddition installation, by running, as super-user:
apt-get install virtualbox-guest-dkms virtualbox-guest-x11 linux-headers-$(uname -r)

*Creating the candidate folder /home/quant/Scrivania/VirtualBox/Data by modifying the Oracle VirtualBox Manager settings (Shared Folders);

*mounting the device by running:
mount -t vboxsf Data /home/quant/Scrivania/VirtualBox/Data/
At the point (3), I got the following error message in the terminal:
/sbin/mount.vboxsf: mounting failed with the error: No such device

It seems like the folder does not exist although I manually create the local folder and set it as shared folder in the VirtualBox manager.
Someone could suggest a solution?
Hope I has been clear when I asked the question. Thanks you all in advice!

A: Your error: /sbin/mount.vboxsf: mounting failed with the error: No such device could be caused because you are mounting the SF with the same name for the share and mount point. They should be different (i.e share is called ~/share and mount point ~/host) You will also need to make sure you have followed these steps correctly:

*

*Create a folder on the Host computer (ubuntu) that you would like to share, for example ~/share

*Boot the Guest operating system in VirtualBox.

*Select Devices -> Shared Folders...

*Choose the 'Add' button.

*Select ~/share

*Optionally select the 'Make permanent' option

After you have completed that process, open your terminal on the host and run:
sudo mount -t vboxsf -o uid=$UID,gid=$(id -g) /home/quant/Scrivania/VirtualBox/Data ~/host

(/home/quant/Scrivania/VirtualBox/Data and ~/host may have to be reversed or changed to the appropriate names)
If that step completes successfully on your Windows guest you should be able to run:
net use x: \\vboxsvr\[whatever your share folder's name is]
Keep your shared folder name simple such as ~/Data or ~/share instead of /home/quant/Scrivania/VirtualBox/Data as that may be another source for your issue. Good Luck!

A: I simply solved by following those steps; first of all install Oracle Virtual Box as follows:

*

*run as super-user nano /etc/apt/sources.list.d/virtualbox.list

*paste deb http://download.virtualbox.org/virtualbox/debian stretch contrib and after type ctrl+O and ctrl+X to save and quit respectively

*run from the terminal:

*

*wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | apt-key add -

*apt update

*apt-get install virtualbox-5.2

*apt-get install dkms
After, download the .iso image from the Oracle Repository and choosing the version you need on the basis of your host OS and install GuestAdditions by selecting from the virtual machine window menu

Device > Insert ISO image for GuestAdditions

and follow what suggested by the installation guide. Finally, go through

Devices > Shared Folder

and select the path in which is contained the folder you need to share.


text:
Q: "With...ever..." grammar question
I know the correct answer is b, because that sounds correct.
I am trying to figure out why b is correct, and also why the other answers are incorrect. I think b is correct because ~ing signifies that it is happening now, and will continue into the future. c is obviously wrong because it is past tense. Also, if d did not include "ever", i.e. "having decreased", would that be correct?
What is the general grammar principle for "With..."?

A: (b) is correct. It is the present progressive tense which indicates the action is happening at this time - but 'this time' can mean very different things depending on the context.
The word 'ever' is obvious hyperbole. It cannot mean it began eons ago and will continue forever. It suggests going on for some time, perhaps years, and is not expected to stop anytime soon. The 'this time' in this sense is a period of some years. It's still the right tense to show declining rates are currently in a state of being.
The fact that actual falls in interest rates occur as intermittent and discreet steps over that period is irrelevant A state of being still exists now.


text:
Q: Find and sort files by date modified I know that there are many answers to this question online. However, I would like to know if this alternate solution would work:
ls -lt `find . -name "*.jpg" -print | head -10`

I'm aware of course that this will only give me the first 10 results. The reason I'm asking is because I'm not sure whether the ls is executing separately for each result of find or not. Thanks

A: In your solution:

*

*the ls will be executed after the find is evaluated

*it is likely that find will yield too many results for ls to process, in which case you might want to look at the xargs command

This should work better:
  find . -type f -print0 | xargs -0 stat -f"%m %Sm %N" | sort -rn

The three parts of the command to this:

*

*find all files and print their path

*use xargs to process the (long) list of files and print out the modification unixtime, human readable time, and filename for each file

*sort the resulting list in reverse numerical order

The main trick is to add the numerical unixtime when the files were last modified to the beginning of the lines, and then sort them.


text:
Q: Reducing latency with Google app engine search api Let's say we are building a product catalog using Google app engine and trying to incorporate full text search. What are the factors to consider to guarantee latency in 200 ms .
As the document index grows , how do you configure app engine to linearly scale without compromising latency.
Neo


text:
Q: No template parameter deduction of parameter pack In following example I want to type-erase Callback<FArgs...>::Handle to another class. Implementation is irrelevant for the question, so code is very minimal.
#include <memory>

template<typename... FArgs>
class Callback
{
    public:

    class Handle{};
};

class BaseCallbackHandle
{
};

using TypeErasedCallbackHandle = std::unique_ptr<BaseCallbackHandle>;

template<typename ...Args>
TypeErasedCallbackHandle makeTypeErasedCallbackHandle( typename Callback<Args...>::Handle handle)
{
   return {};
}

int main()
{
    Callback<int>::Handle h;
    auto typeErasedHandle = makeTypeErasedCallbackHandle(h);
}

See also: http://coliru.stacked-crooked.com/a/171cd34a46618c14
I thought that makeTypeErasedCallbackHandle deduce the Args automatically, but I get following compile error:
clang++ -std=c++11 -O0 main.cpp && ./a.out

main.cpp:27:29: error: no matching function for call to 'makeTypeErasedCallbackHandle'

    auto typeErasedHandle = makeTypeErasedCallbackHandle(h);

                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

main.cpp:19:26: note: candidate function [with Args = <>] not viable: no known conversion from 'Callback<int>::Handle' to 'typename Callback<>::Handle' for 1st argument

TypeErasedCallbackHandle makeTypeErasedCallbackHandle( typename Callback<Args...>::Handle handle)

                         ^

1 error generated.

What am I doing wrong?
As a workaround, I can reformulate the function like that:
template<typename H>
TypeErasedCallbackHandle makeTypeErasedCallbackHandle( H handle)
{
   return {};
}

This works but also allows the user to put anything into that function, not only Callback<FArgs...>::handle.
Question has been marked as duplicate. Reason is understood. Let me ask a further question to make this a relevant issue again: Is there any way with static_assert or enable_if helpers to ensure, that in the second working example with typename H only accepts H that are from Callback<FArgs...>::handle?


text:
Q: Large python dictionary. Storing, loading, and writing to it I have a large python dictionary of values (around 50 GB), and I've stored it as a JSON file. I am having efficiency issues when it comes to opening the file and writing to the file. I know you can use ijson to read the file efficiently, but how can I write to it efficiently?
Should I even be using a Python dictionary to store my data? Is there a limit to how large a python dictionary can be? (the dictionary will get larger).
The data basically stores the path length between nodes in a large graph. I can't store the data as a graph because searching for a connection between two nodes takes too long.
Any help would be much appreciated. Thank you!

A: Although it will truly depend on what operations you want to perform on your network dataset you might want to considering storing this as a pandas Dataframe and then write it to disk using Parquet or Arrow.
That data could then be loaded to networkx or even to Spark (GraphX) for any network related operations.
Parquet is compressed and columnar and makes reading and writing to files much faster especially for large datasets.
From the Pandas Doc:

Apache Parquet provides a partitioned binary columnar serialization
  for data frames. It is designed to make reading and writing data
  frames efficient, and to make sharing data across data analysis
  languages easy. Parquet can use a variety of compression techniques to
  shrink the file size as much as possible while still maintaining good
  read performance.
Parquet is designed to faithfully serialize and de-serialize DataFrame
  s, supporting all of the pandas dtypes, including extension dtypes
  such as datetime with tz.

Read further here: Pandas Parquet

A: try to use it with pandas: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
pandas.read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression='infer')
Convert a JSON string to pandas object

it very lightweight and useful library to work with large data


text:
Q: VS Code MSSQL Extension: Align columns and headers by default? I am using the mssql extension for VS Code, which is amazing and makes my workflow a lot smoother. Hats off to the developers.
When I run a query, I can align the column widths of the headers and the remaining columns of the resulting output by clicking-and-dragging the horizontal border of any one column header by a teensy bit.
Is there any way to make this alignment happen automatically without me doing anything?

A: This misalignment was the result of my setting a non-default font size for the output. I removed this setting and now the header widths are aligned with the column widths.


text:
Q: Need javascript regex for amounts and decimals with percentage increases I have this expression so far, link to regex101 here:
^[-+]?[0-9]\d{0,6}(.\d{1,3})?%?$
5 (valid)
5.5 (valid)
+5 (valid)
-6.999 (valid)
5% (valid but needs tweaking)
It works great except that I need to tweak it to accept a percentage at the end only if it starts with a plus or a minus, everything else is correct, so: 5% is invalid, +5% is valid, -5.5% is valid, +5 is valid (no percentage is required for +/-).
thanks.

A: You will have to unwrap this pattern a bit and use alternation:
^(?:[-+]?\d{1,6}(?:\.\d{1,3})?|[-+]\d{1,6}(?:\.\d{1,3})?%)$

See the regex demo and the regex graph:

Details

*

*^ - start of string

*(?: - start of the non-capturing group to hold alternations

*

*[-+]?\d{1,6}(?:\.\d{1,3})? - an optional + or -, 1 to 6 digits, and an optional sequence of . and 1 to 3 digits

*| - or

*[-+]\d{1,6}(?:\.\d{1,3})?% - a + or -, 1 to 6 digits, and an optional sequence of . and 1 to 3 digits and a % char

*) - end of the non-capturing group

*$ - end of string.

In JS, you needn't repeat parts of the regex, you may build the pattern dynamically:

var num_re = "\\d{1,6}(?:\\.\\d{1,3})?";
var regex = new RegExp("^(?:[-+]?" + num_re + "|[-+]" + num_re + "%)$");
var strs = ['5', '5.5', '+5', '-6.999', '5%', '+5%', '-5.5%'];
for (var s of strs) {
  console.log(s, "=>", regex.test(s));
}

Output:
5 => true
5.5 => true
+5 => true
-6.999 => true
5% => false
+5% => true
-5.5% => true

A: Try
^([-+]?\d{1,6}(\.\d{1,3})?|[-+]\d{1,6}(\.\d{1,3})?%)$

It takes ±123.12 (without percents) or 123.12% (with percents).
5% is invalid,
+5% is valid,
-5% is valid


text:
Q: Duplicate entry error for composite unique key in MySQL I'm trying to insert data in a table which has the following columns :
id, date, client, device, user

I have created a primary key on id and unique key on the combination of client, device, and user.
While inserting data I getting the following Error:-
Cause: java.sql.SQLException: Duplicate entry '200-217-Xiaomi-M200' for key 'uk_user_client_device'

I checked the data in the table using the following query using:-
SELECT user, client, device, COUNT(1) rowcount FROM mytable GROUP BY user, client, device HAVING COUNT(1) > 1;

This got an empty set in response so I am certain there are no duplicate keys in the table.
I also went through the logs and I found that the data was inserted in the table at the same time I got this error. So, the data was inserted yet I got the duplicate entry error.
I also confirmed that this doesn't happen always. Sometimes, the data is inserted without any issue and sometimes I get an error and the data is inserted anyway.
I've seen a few questions regarding this with no definitive answer. I'm unable to figure out why this error is being thrown.

A: Of course this query returns no rows:
SELECT user, client, device, COUNT(1) as rowcount
FROM mytable
GROUP BY user, client, device
HAVING COUNT(1) > 1;

You have specified that client/device/user is a primary key (or at least unique.  Hence, there are no duplicates.  The database enforces this.
If you attempt to insert a row that would create a duplicate, the database returns an error.  The row is not inserted.  The database ensure the data integrity.  Yay!
Your error is saying that the data in the insert either duplicates existing data in the table.  Or, if you are inserting multiple rows, then the data has duplicates within the insert.
You can solve this in multiple ways.  A typical method is to ignore the insert using on duplicate key update:
insert into mytable ( . . . )
     . . .
     on duplicate key update user = values(user);  -- this is a no-op

The database prevents duplicates from being inserted.  This construct prevents an error -- although no duplicate rows are inserted, of course.


text:
Q: Get full cached path of product relative images Magento Hi i have got the full cached thumbnail and main image path with my code But i want to get the full cached path of relative *image*  also Please suggest some ideas
  <?php
@ob_start();
@session_start();
ini_set('display_errors', 1);
//for order update
include '../../../../app/Mage.php';
Mage::app('default');
echo '
';
if(isset($_REQUEST['productid'])){
$productId = $_REQUEST['productid'];
}else{

$productId = '12402'; // product ID 10 is an actual product, and used here for a test
}
$product = Mage::getModel('catalog/product')->load($productId);  //load the product
echo 'product_id '.'=>'.$product->getId().'
';

echo 'created_at '.'=>'.$product->getcreated_at().'
';
echo 'description '.'=>'.$product->getdescription().'
';
echo 'short_description '.'=>'.$product->getshort_description().'
';
echo 'sku'.'=>'.$product->getsku().'
';
 'media_gallery'.'=>'.$product->getmedia_gallery().'
';
print_r($product->getmedia_gallery());
?>
<?php
$image = Mage::helper('catalog/image')->init($product, 'image');
$image1 = str_replace('/webApps/migration/productapi/new/','/',$image);
//echo '';
echo 'image => '.$image1.'
';

$thumbnail = Mage::helper('catalog/image')->init($product, 'thumbnail');
$thumbnail1 = str_replace('/webApps/migration/productapi/new/','/',$thumbnail);
echo 'thumbnail => '.$thumbnail1.'
';
?>

A: *with this code* i got the product relative *images* full path
 <?php
    @ob_start();
    @session_start();
    ini_set('display_errors', 1);
    //for order update
    include '../../../../app/Mage.php';
    Mage::app('default');
    echo '
';
    if(isset($_REQUEST['productid'])){
    $productId = $_REQUEST['productid'];
    }else{

    $productId = '12402'; // product ID 10 is an actual product, and used here for a test
    }
    $product = Mage::getModel('catalog/product')->load($productId);  //load the product
    echo 'product_id '.'=>'.$product->getId().'
';

    echo 'created_at '.'=>'.$product->getcreated_at().'
';
    echo 'description '.'=>'.$product->getdescription().'
';
    echo 'short_description '.'=>'.$product->getshort_description().'
';
    echo 'sku'.'=>'.$product->getsku().'
';

     if (count($product->getMediaGalleryImages()) > 0){
          foreach ($product->getMediaGalleryImages() as $_image){
              $thumbnail12 = Mage::helper('catalog/image')->init($product->getProduct(), 'image', $_image->getFile())->resize(2000);
              $thumbnail13 = str_replace('/webApps/migration/productapi/new/','/',$thumbnail12);
              echo 'thumbnail => '.$thumbnail13.'
';
               }
                            }

    ?>

A: Please note if you are debugging this and not understanding why you aren't getting the image path string from:
Mage::helper('catalog/image')->init($product->getProduct(), 'image', $_image->getFile())->resize(2000)

it's because it implements the toString() method so eachoing this actually gives the full path to the image. You see it by calling ->toString() or just adding (String)Mage...
(But it's not needed to use (String) or ->toString() when echoing, php does this by default)


text:
Q: Can you do website manipulation with javascript or actionscript? Using javascript or flash, is it possible to log into websites and than pull content from that page?
I am trying to make a phone app that displays content from a site that requires log in.

A: To the extent that this is possible, it's almost certainly not a good idea.  Your phone app then has brittle dependencies on the structure of the site from which you're pulling data, and you have no way except notification of failure to detect when those dependencies change.
Does the site from which you want to pull information provide an API? That would be a better solution.

A: Theoretically, yes, though depending on the browser, it may not allow cross-site scripting.  The only way I can think of on a mobile site to do this is either with an ajax call to submit login credentials and grab data, or with an iframe.  iframe would probably work better since  ajax calls would probably not set the right cookies for session id maintenance.  I dont know how elegant this solution would be.


text:
Q: Path relative to multi-project build file I have a project structure like this:
config/
foo/
    build.gradle
    settings.gradle
    bar/
        build.gradle
    baz/
        build.gradle

I want to add the config directory to the classpath in foo/build.gradle so that the subprojects bar and baz can access it. I've tried doing this in foo/build.gradle:
subprojects {
    apply plugin: 'java'
    dependencies {
        runtime files('../config')
    }
}

But that results in the following entry in the classpath:
/home/me/project/foo/config

When what I actually want is:
/home/me/project/config

I believe it's because runtime files('../config') is being evaluated in foo/bar/build.gradle instead of foo/build.gradle. So, how can I get the path to foo/? I could just use runtime files('../../config'), but it doesn't feel quite right.
Or maybe I'm going about this the wrong way and there's a better place to put the config files?

A: One way to get to your current config folder location irrespective of which project/folder level you're at is:
"$rootDir/../config"


text:
Q: Unable to Create New MVC Widget in Kentico 12 I'm trying to create a new widget called "Image Summary Section". I'm at the very beginning stages and I'm just trying to get the widget to appear in the list of widgets when adding widgets to the page. Instead, I just get existing widgets that I didn't create:

You can see that I've created a class that implements IWidgetProperties and that I've called RegisterWidget for it. I've also created _ImageSummarySection.cshtml (though, I wouldn't expect that to be necessary just for the widget to appear in the widget selection dialog).
The top solution is for the MVC website, and the bottom solution is for the Kentico CMS. Both are running, and the browser shown is the Kentico CMS (I'm trying to add my new widget in this screenshot, but it's not in the list of widgets).
Any idea of what I'm doing wrong? How can I get my widget to appear in the list of widgets?
Additional information:

*

*I've looked at various links, but here's one I was looking through: https://docs.kentico.com/k12sp/developing-websites/page-builder-development/developing-widgets-in-mvc/defining-widget-properties-in-mvc

*I'm on the latest Kentico version, which I think is 12.0.77.

.
.
.
.
.
.
EDIT:
I just watched this video, hoping it would provide insight: https://www.youtube.com/watch?v=ljQO9on5lLM
It was more basic than I anticipated, but I did notice these two frames:

Note that it shows six available widgets to select from.
And then there was this frame:

It shows only two available widgets.
From that, I infer that sections may have some feature that allows developers to constrain which widgets are allowed in them. Is there perhaps something I need to do in order to allow my widgets to appear as options in the default section (the one shown below)?

.
.
.
.
.
.
EDIT #2:
I researched widget constraints a bit and found this: https://docs.kentico.com/k12/developing-websites/page-builder-development/creating-pages-with-editable-areas-in-mvc
Specifically the section titled "Limiting widgets allowed in an editable area", which says the following:

Since my view is not passing a parameter with a whitelist of widgets, all widgets should (in theory) be allowed:
@* Index.cshtml *@
@using Kentico.PageBuilder.Web.Mvc
@using Kentico.Web.Mvc

Rhythm Agency

@Html.Kentico().EditableArea("main")

So there goes that theory. I'm still at a loss as to why my new widget isn't appearing as an option when adding new widgets to the page.

A: For the controller and widget to be recognized you need to put your controller in the '/Controllers' folder. I have my widget controllers located in the '/Controllers/Widgets' folder.
I had issues which included not having added the suffix 'Controller' in the class name and issues with the widget controller not being in the '/Controllers' folder.
Also you aren't working in an seperate project? Because this would need you to use the following in the 'AssemblyInfo.cs'
using CMS;
[assembly: AssemblyDiscoverable]

And make sure you have enabled the page builder feature in your kentico project. For example:
protected void Application_Start()
{
    ...

    // Gets the ApplicationBuilder instance
    // Allows you to enable and configure Kentico MVC features
    ApplicationBuilder builder = ApplicationBuilder.Current;

    // Enables the preview feature
    builder.UsePreview();

    // Enables the page builder feature
    builder.UsePageBuilder();

    ...
}

A: You're almost there.  You need to create another class and register your widgets in the App_Start folder. Check out the documentation here on that.  It's the section on widget registration.  Be sure to enable Page builder as well.
*** Updated ***
Based on your update and not being able to see the image well on my mobile device, I was able to see you're defining/registering your widget in your Properties model.  This needs to be done in the Controller.  See the example below.
\Models\Widgets\JobListingWidgetProperties.cs
namespace NameSpace.Models.Widgets.JobListingWidget
{
    public class JobListingWidgetProperties : IWidgetProperties
    {
        // property definitions here
    }
}

\Models\Widgets\JobListingModelView.cs
namespace NameSpace.Models.Widgets.JobListingWidget
{
    public class JobListingWidgetViewModel
    {
        // properties here
    }
}

\Controllers\Widgets\JobListingWidgetController.cs
[assembly: RegisterWidget("NameSpace.Widgets.JobListingWidget", typeof(JobListingWidgetController), "Job Listing Widget", Description = "Displays a listing of jobs for a given path", IconClass = "icon-heartshake")]
namespace NameSpace.Controllers.Widgets
{
    public class JobListingWidgetController : WidgetController<JobListingWidgetProperties>
    {
        public ActionResult Index()
        {
            // code here
        }
    }
}


text:
Q: Minimal value of longest path with free choice of starting node in undirected graph
The problem is to find minimal value (weight of every edge is equal to 1) of path to every other node having free choice of starting node in undirected graph. Data is in form of adjacency relations. Nodes are numerated from 0 to max.
So in graph above correct solution is 3, because the longest path to every other node in this case is 3 as we choose node number 2 or 4.
My solution:

*

*Iterate over every node and find it path cost to next node, the biggest of those values is our result
It's achieved using findRoad that searches recursively level by level to find connection.

*Acc keeps value of current iteration that equals to longest path that this vertex have to travel

*If acc is greater than previously finded value (min) we stop iterating this node, because this node won't give us better result

*Algorithm end after iteration on last node is finished

Algorithm works correctly hovever very slow, I tried one solutions to improve it, but it only slowed the algorithm further down:

*

*in recursive call to findRoad replacing first parameter that is always a full list of edges to filtered  list (without already checked ones)

Code:
val a: List[(Int,Int)] //list of all edges
val c: Set[(Int,Int)] //set of all edges
val max //maximum index of node

//main loop that manages iterations and limits their number
def loop(it: Int, it2: Int, acc: Int,min: Int): Int = {
    if(it > max) min
    else if(it2 > max) if(min<acc)loop(it+1,0,0,min)
    else loop(it+1,0,0,acc)
    else if(acc >= min) loop(it+1,0,0,min)
    else if(it == it2) loop(it,it2+1,acc,min)
    else {
        val z = findRoad(b,List(it),it2,1,min)
        if(z > acc) loop(it,it2+1,z,min)
        else loop(it,it2+1,acc,min)
    }
}
//finding shortest path from node s to node e
def findRoad(a: List[(Int,Int)], s: List[Int], e: Int, lev: Int,min: Int): Int = {
    if(lev > min) Int.MaxValue
    else if(s.exists( s => (a.exists(p => p == (s,e) || p == (e,s))))) lev
    else findRoad(a,connectEdges(s,Set()),e,lev+1,min)
}
//finding all predecessor and successors
def connectEdges(a: List[Int], acc: Set[Int]): List[Int] = {
    if(a.isEmpty) acc.toList
    else connectEdges(a.tail, acc++c.collect{
        case (b,c) if(b == a.head) => c
        case (b,c) if(c == a.head) => b
    })
}

Is whole idea flawed or some scala operations should be avoided (like filter, collect, transforming sets into collections)?
Maybe I should use some All-pairs shortest paths algorithm like Floyd–Warshall algorithm?

A: I think you can just run BFS from every vertex, and for each vertex remember the length of longest path traveled using BFS. Your result is the minimum value among those. It would be O(n²).
You can also find shortest paths for each pair of vertices using Floyd–Warshall algorithm and then for each vertex v find vertex u so that dist[v][u] is maximum. Among all those values for each vertex the minimal one is your answer. It would be O(n³) because of Floyd-Warshall.
n - number of vertices

A: Use BFS. Since edge cost is 1 it will give you shortest paths from vertex u to all other vertices in O(V+E) time. Now take maximum of those [u,v] distances for all vertex v from u. Lets call this d. Finally you need the vertex that gives minimum value of d. Overall running time is O((V+E)*V).
Algorithm:
min = infinity
result = -1 // which vertex yields minimum result
for all vertices u in V:
    dist = [|V|]  // array of size |V| initialized to 0
    fill dist using BFS starting from u
    max = max(dist)
    if max < min:
        min = max
        result = u
return result


text:
Q: Call a function after a time gap In Angular JS I am trying to refresh a page after showing a successfull message. I tied with many snippets but either it gets refreshed without showing message or vice-versa.
So I thought of Calling the Refresh function after an interval or Trigger again the button click event after some time to get the page refreshed.
Here is the code, How to achieve the above scenario?
JS CODE
$scope.Save = function (data) {
    debugger;
    $http.post($rootScope.WebApiURL + '/updatemanifeststatus');
    var value= $http.get($rootScope.WebApiURL + '/getmanifeststatus' );

        $scope.manifeststatus = data;

        $scope.showstatus = true;
        $scope.alert = { type: 'success', msg: 'Published Successfully.' };
        $(".statusDivPublish").show();

        $scope.Refresh1();

    }

    $scope.Refresh1 = function () {
        //refresh
        $state.go($state.current, {}, { reload: true });
    }
});

HTML Button Call
<div class="col-sm-offset-1">
    <button id="PublishButton" class="btn btn-default shiny " ng-disabled="manifeststatus.enablePublishButton" ng-click="Save(manifeststatus)">Publish</button>
</div>

What I want to do Here is Call the Refresh1() function after a time gap in such a way, the page gets refreshed after showing the message.

A: I plunkered a bit on your problem and I did not need to use a $timeout to update the model with updated data.
.controller('AController', function(ptth$) {

    var self = this;

    self.time = 'wait for it';

    self.init = function() {
      ptth$.get().then(function(data) {
        self.time = data;
      });
    };

    self.init();

    self.save = function() {
        ptth$.post().then(function() {
          //I use an alert instead of a div we show or hide.
          window.alert('hey, this is real success');
          //You either re-fetch data here and update your model
          //Or you reload after the alert...

          //This example works with a ng-model update, instead of a reload
          self.init();
        }, function() {
          window.alert('this is failure');
        });
    };
})

Eventhough this is not the way I would set up things, this example should illustrate that you do not really need a $timeout or $reload for that matter.

A: Inject $timeout and do this changes to your JS Code.
$scope.Save = function (data) {
    debugger;
    $http.post($rootScope.WebApiURL + '/updatemanifeststatus');
    var value= $http.get($rootScope.WebApiURL + '/getmanifeststatus' );

        $scope.manifeststatus = data;

        $scope.showstatus = true;
        $scope.alert = { type: 'success', msg: 'Published Successfully.' };
        $(".statusDivPublish").show();

        //Adding a 5 second delay
        $timeout($scope.Refresh1, 5000);

    }

    $scope.Refresh1 = function () {
        //refresh
        $state.go($state.current, {}, { reload: true });
    }
});


text:
Q: More edges implies larger eigenvalues of graph Laplacian? Suppose

*

*$G_1$ and $G_2$ are two connected graphs with the same nodes.

*$G_2 \subset G_1$. $G_2$ is the connected subgraph of $G_1$.

I know that $\lambda_2(L(G_2))\leq \lambda_2(L(G_1))$ since $\lambda_2$ represents the connectivity.
($L$ represents the graph Laplacian matrix.)
Can we say the following

*

*$\lambda_i (L(G_2))\leq \lambda_i(G_1)$ for all $i$?

*$L(G_1) \succeq L(G_2)$?   (We know graph Laplacian matrix is positive semi-definite.)

I believe 1. implies 2.
If you know any reference of above, please let me know.
Thanks in advance.
Note: By my old and not clear memory, I guess this is true in graph theory. But I forgot where I read it

A: This is a standard interlacing problem. We will use the well-known interlacing theorem (it is a specific case of Poincaré separation theorem):

If $B$ is a principal submatrix of a symmetric matrix $A$, then the eigenvalues of $B$ interlace the eigenvalues of $A$.

Let $G$ be a graph on $n$ vertices and let $H$ be a spanning subgraph (this is your case as $G_1$ and $G_2$ have same vertex set). I claim that for $i\in\{1,\ldots,n\}$,  $\lambda_i(L(H)) \leq \lambda(L(G))$.
Proof :
Let $N$ be the directed incidence matrix obtained by a random orientation the edges of $G$. Then it is easy to verify that $L = NN^\perp$, and that $NN^\perp$ and $N^\perp N$ have the same eigenvalues.
Removing an edge from $G$ results in removing a column from $N$ and
yields a principal submatrix of $N^\perp N$. Therefore we can apply Cauchy's interlacing theorem and the result holds. $\square$


text:
Q: Pop up a child chrome window from parent IE window Is there any way to pop up a different browser from that of a parent?
Ex: A parent window "IE" will pop up a new "chrome (or any other window)"
The problem i have is that the "window.opener.callback" javascript functions gives me an error on IE, but not on any other browser type.
Thanks!


text:
Q: Bean Type not being found in in Spring Test package So here is what the current description of the error gives me.
Description:
Field profileDoa in com.N2O2.Nitrouz_Studioz.controller.MainController required a bean of type 'com.N2O2.Nitrouz_Studioz.model.profile.ProfileDoa' that could not be found. The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.N2O2.Nitrouz_Studioz.model.profile.ProfileDoa' in your configuration.
I'm sort of lost to why this error is happening as I've only been working with Java Spring Boot recently and still getting used to working with Beans. I've Autowired the Bean in the Test class but it's still throwing the same error.
Here's what I have in my test class and the Controller and ProfileDoa class.
@WebMvcTest(MainController.class)
@ContextConfiguration(classes = NitrouzStudiozApplication.class)
public class MainControllerTest {
    @Autowired
    private MockMvc mockMvc;

    ProfileEntity profileEntity;
    @Autowired
    private ProfileDoa profileDoa;

    private MainController mainController;
    @Mock
    private Model model;
    private boolean loggedOut = true;
    private boolean loggedIn = false;

    @BeforeEach
    public void intializeController(){
        mainController = new MainController();
    }

    @Test
    @DisplayName("Navigating to Website Correctly Displays Index page")
    public void loadsIndexPage() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get("/");
        MvcResult result = mockMvc.perform(request)
            .andExpect(model().attribute("loggedOut", loggedOut))
            .andExpect(model().attribute("loggedIn", loggedIn))
            .andExpect(model().attribute("profileEntity", "Not logged In"))
            .andReturn();
        Assertions.assertEquals("index", result);
    }
}

@Controller
public class MainController {

    private boolean loggedOut = true;
    private boolean loggedIn = false;
    private ProfileEntity profileEntity;
    @Autowired
    private ProfileDoa profileDoa;

    @RequestMapping("/")
    public String home_page(Model model) {
        model.addAttribute("loggedOut", loggedOut);
        model.addAttribute("loggedIn", loggedIn);
        model.addAttribute("profileEntity", "Not logged In");
        return "index";
    }

    @RequestMapping("/about")
    public String about_page(Model model){
        model.addAttribute("loggedOut", loggedOut);
        model.addAttribute("loggedIn", loggedIn);
        model.addAttribute("profileEntity", "Not logged In");
        return "about";
    }

    @RequestMapping("/signup")
    public String sign_up(){
        return "signup";
    }

    @GetMapping("/signUpForm")
    public String signUpForm(Model model, ProfileEntity profileEntity){
        boolean checked = false;
        model.addAttribute("profileEntity", profileEntity);
        model.addAttribute("join", checked);
        return "signUpForm";
    }

    @RequestMapping("/signUpFormError")
    public String signUpFormError(Model model,
            @ModelAttribute("error") boolean error,
            @ModelAttribute("message") String message,
            ProfileEntity profileEntity){
        boolean checked = false;
        model.addAttribute("join", checked);
        model.addAttribute("error", error);
        model.addAttribute("message", message);
        model.addAttribute("profileEntity", profileEntity);
        return "signUpForm";
    }

    @RequestMapping("/ForgotPasswordPage")
    public String forgotPasswordPage(){
        return "forgotPassword";
    }

    @GetMapping("/Forgot_Password")
    public String ForgotPasswordResponse(){
        return "forgotPassword";
    }
}

@Transactional
public interface ProfileDoa extends JpaRepository<ProfileEntity, Long> {

    public ProfileEntity findByEmail(String email);
}

Any help on this would be helpful. Thanks.

A: With @WebMvcTest you can write tests for your web layer. Spring Test will create a context for you with all beans that are required to test this slice of your application: e.g. classes annotated with @Controller, @RestController, @ControllerAdvice, filter, etc.
All other beans are not created for you as they are not in the scope of the web layer. In your case, that's any other bean your MainController injects.
You have basically now two options:

*

*Mock the ProfileDoa

*Use a real bean of ProfileDoa. This would require a database and more setup on your side.

For option one you can adjust your test like the following:
@WebMvcTest(MainController.class)
public class MainControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ProfileDoa profileDoa;

    private boolean loggedOut = true;
    private boolean loggedIn = false;

    @Test
    @DisplayName("Navigating to Website Correctly Displays Index page")
    public void loadsIndexPage() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get("/");
        MvcResult result = mockMvc.perform(request)
            .andExpect(model().attribute("loggedOut", loggedOut))
            .andExpect(model().attribute("loggedIn", loggedIn))
            .andExpect(model().attribute("profileEntity", "Not logged In"))
            .andReturn();
        Assertions.assertEquals("index", result);
    }
}

As I don't see any interaction with profileDoa in your MainController there is also no need to prepare any mocked method response. If you do however call e.g. profileDao.findByEmail("mail@duke.io") somewhere, you can use Mockito to prepare the result:
ProfileEntity databaseResult = new ProfileEntitiy();
when(profileDao.findByEmail("THIS_HAS_TO_MATCH_YOUR_MAIL")).thenReturn(databaseResult);

For option two, you can use a combination of @SpringBootTest and @AutoconfigureMockMvc to load the whole Spring context (all beans) and make use of MockMvc:
@SpringBootTest
@AutoconfigureMockMvc
public class MainControllerTest {

  // no mocking required as _real_ beans are used
}

Here you might want to use e.g. Testcontainers to start a database for your test.


text:
Q: JavaFX FXML Show Updated TableView I'm having issues showing new additions to a class in a TableView for my JavaFX/FXML program. I've looked at countless tutorials but the missing piece still escapes me.
I had some errors that got fixed here: JavaFX Adding Rows to TableView on Different Page
And then found a new tutorial to sort of follow that explained things a bit better than the first one I was following (their app is a bit different than what I have to do) here: http://code.makery.ch/library/javafx-8-tutorial/part2/
I have an output printing the name field out to the console just to make sure it is pulling the right values from the add form. I also changed the way I navigated between Add Part and the Main window (nothing else works right now). I feel so silly asking this, but Java is the one language I haven't been able to wrap my head around.
Any ideas on why it isn't updating are greatly appreciated.
IMS.java
package ims;

import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

/**
 *
 * @author chelseacamper
 */
public class IMS extends Application {
    private Stage primaryStage;
    private BorderPane rootLayout;

    private ObservableList<Part> partData = FXCollections.observableArrayList();

    public IMS() {
        partData.add(new Part("Part A", 3, 4.00, 1, 5));
        partData.add(new Part("Part B", 2, 14.00, 1, 15));
    }

    public ObservableList<Part> getPartData(){
        return partData;
    }

    @Override
    public void start(Stage stage) throws Exception {

//        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
        Parent root = (Parent) loader.load();
        FXMLDocumentController ctrl = loader.getController();
        ctrl.setMainApp(this);
        Scene scene = new Scene(root);
        scene.getStylesheets().add("style.css");
        stage.setScene(scene);
        stage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

FXMLDocumentController.java
package ims;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

/**
 *
 * @author chelseacamper
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    @FXML
    private TableView<Part> partTable;
    @FXML
    private TableColumn<Part, Integer> partIDColumn;
    @FXML
    private TableColumn<Part, String> nameColumn;
    @FXML
    private TableColumn<Part, Integer> inventoryColumn;
    @FXML
    private TableColumn<Part, Double> priceColumn;

    private IMS mainApp;

    public FXMLDocumentController(){

    }

    @FXML
    private void addPart(ActionEvent event) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("addPart.fxml"));
        Parent add_part_parent = (Parent) loader.load();
        Stage stage = new Stage();
        stage.setScene(new Scene(add_part_parent));
        stage.show();
    }

    @FXML
    private void modifyPart(ActionEvent event) throws IOException {
        Parent modify_part_parent = FXMLLoader.load(getClass().getResource("modifyPart.fxml"));
        Scene modify_part_scene = new Scene(modify_part_parent);
        modify_part_scene.getStylesheets().add("style.css");
        Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        app_stage.setScene(modify_part_scene);
        app_stage.show();
    }

    @FXML
    private void addProduct(ActionEvent event) throws IOException {
        Parent add_product_parent = FXMLLoader.load(getClass().getResource("addProduct.fxml"));
        Scene add_product_scene = new Scene(add_product_parent);
        add_product_scene.getStylesheets().add("style.css");
        Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        app_stage.setScene(add_product_scene);
        app_stage.show();
    }

    @FXML
    private void modifyProduct(ActionEvent event) throws IOException {
        Parent modify_product_parent = FXMLLoader.load(getClass().getResource("modifyProduct.fxml"));
        Scene modify_product_scene = new Scene(modify_product_parent);
        modify_product_scene.getStylesheets().add("style.css");
        Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        app_stage.setScene(modify_product_scene);
        app_stage.show();
    }

    @FXML
    private void closeProgram(ActionEvent event) throws IOException {
        Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        app_stage.close();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
//        nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
//        inventoryColumn.setCellValueFactory(cellData -> cellData.getValue().instockProperty().asObject());
//        priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());

        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        inventoryColumn.setCellValueFactory(new PropertyValueFactory<>("instock"));
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));

    }

    public void setMainApp(IMS mainApp) {
        this.mainApp = mainApp;

        // Add observable list data to the table
        partTable.setItems(mainApp.getPartData());
    }

    @FXML
    private void handleDeletePart(){
        int selectedIndex = partTable.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0){
            partTable.getItems().remove(selectedIndex);
        } else {
            Alert alert = new Alert(AlertType.WARNING);
            alert.setTitle("No Part Selected");
            alert.setHeaderText("No Part Selected");
            alert.setContentText("Please select the part you would like to delete.");

            alert.showAndWait();
        }
    }
}

FXMLDocument.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import fxmltableview.*?>
<?import ims.Part?>
<?import ims.Inhouse?>
<?import ims.Outsourced?>

<BorderPane id="main" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.FXMLDocumentController" >
    <top>

    </top>

        <HBox fx:id="holding">
            <children>
                <VBox styleClass="contentBox">
                    <children>
                        <HBox styleClass="topBox">
                            <HBox styleClass="subHeading">

                            </HBox>
                            <HBox styleClass="searchBox">
                                <Button text="Search" />
                                <TextField />
                            </HBox>
                        </HBox>
                        <TableView fx:id="partTable" styleClass="dataTable">
                            <columns>
                                <TableColumn fx:id="partIDColumn" text="Part ID" />
                                <TableColumn fx:id="nameColumn" text="Part Name" />
                                <TableColumn fx:id="inventoryColumn" text="Inventory Level" />
                                <TableColumn fx:id="priceColumn" text="Price/Cost per Unit" />
                            </columns>
                        </TableView>
                        <HBox styleClass="modificationButtons">
                            <children>
                                <Button onAction="#addPart" text="Add" />
                                <Button onAction="#modifyPart" text="Modify" />
                                <Button text="Delete" />
                            </children>
                        </HBox>
                    </children>
                </VBox>
                <VBox styleClass="contentBox">
                    <children>
                        <HBox styleClass="topBox">
                            <HBox styleClass="subHeading">

                            </HBox>
                            <HBox styleClass="searchBox">
                                <Button text="Search" />
                                <TextField />
                            </HBox>
                        </HBox>
                        <TableView fx:id="productTable" styleClass="dataTable">
                            <columns>
                                <TableColumn text="Part ID" />
                                <TableColumn text="Part Name" />
                                <TableColumn text="Inventory Level" />
                                <TableColumn text="Price/Cost per Unit" />
                            </columns>
                        </TableView>
                        <HBox styleClass="modificationButtons">
                            <children>
                                <Button onAction="#addProduct" text="Add" />
                                <Button onAction="#modifyProduct" text="Modify" />
                                <Button text="Delete" />
                            </children>
                        </HBox>
                    </children>
                </VBox>
            </children>
        </HBox>

    <bottom>
        <HBox fx:id="exitButton">
            <children>
                <Button onAction="#closeProgram" text="Exit" />
            </children>
        </HBox>
    </bottom>
</BorderPane>

Part.java
package ims;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 *
 * @author chelseacamper
 */
public class Part {

    private final SimpleStringProperty name;
    private final SimpleIntegerProperty instock;
    private final SimpleDoubleProperty price;
    private final SimpleIntegerProperty min;
    private final SimpleIntegerProperty max;

    public Part(){
        this("", 0, 0.00, 0, 0);

    }

    public Part(String name, int instock, double price, int min, int max) {
        this.name = new SimpleStringProperty(name);
        this.instock = new SimpleIntegerProperty(instock);
        this.price = new SimpleDoubleProperty(price);
        this.min = new SimpleIntegerProperty(min);
        this.max = new SimpleIntegerProperty(max);
    }

    public String getName() {
        return name.get();
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public StringProperty nameProperty() {
        return name;
    }

    public Double getPrice() {
        return price.get();
    }

    public void setPrice(Double price) {
        this.price.set(price);
    }

    public DoubleProperty priceProperty(){
        return price;
    }

    public int getInstock() {
        return instock.get();
    }

    public void setInstock(int instock) {
        this.instock.set(instock);
    }

    public IntegerProperty instockProperty(){
        return instock;
    }

    public int getMin() {
        return min.get();
    }

    public void setMin(int min) {
        this.min.set(min);
    }

    public IntegerProperty minProperty(){
        return min;
    }

    public int getMax() {
        return max.get();
    }

    public void setMax(int max) {
        this.max.set(max);
    }

    public IntegerProperty maxProperty(){
        return max;
    }
}

addPartController.java
package ims;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;

/**
 * FXML Controller class
 *
 * @author chelseacamper
 */
public class AddPartController implements Initializable {
    @FXML
    ToggleButton inhouse;
    @FXML
    ToggleButton outsourced;
    @FXML
    Label inhouseLabel;
    @FXML
    Label outsourcedLabel;
    @FXML
    TextField inhouseTextField;
    @FXML
    TextField outsourcedTextField;
    @FXML
    private TableView<Part> partTable;
    @FXML
    private TextField partNameField;
    @FXML
    private TextField partInstockField;
    @FXML
    private TextField partPriceField;
    @FXML
    private TextField partMaxField;
    @FXML
    private TextField partMinField;
    @FXML
    private Button cancel;
    @FXML
    private Button save;

    private Part part = new Part();
//    private ObservableList<Part> partData = FXCollections.observableArrayList();
    private ObservableList<Part> tableItems;

    /**
     * Initializes the controller class.
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        inhouseLabel.visibleProperty().bind( inhouse.selectedProperty() );
        outsourcedLabel.visibleProperty().bind( outsourced.selectedProperty() );
        inhouseTextField.visibleProperty().bind( inhouse.selectedProperty() );
        outsourcedTextField.visibleProperty().bind( outsourced.selectedProperty() );
        inhouseLabel.managedProperty().bind( inhouse.selectedProperty() );
        outsourcedLabel.managedProperty().bind( outsourced.selectedProperty() );
        inhouseTextField.managedProperty().bind( inhouse.selectedProperty() );
        outsourcedTextField.managedProperty().bind( outsourced.selectedProperty() );

    }

    @FXML
    public void addInhouse(ActionEvent event) throws IOException{
//        Part tempPart = new Part(partNameField.getText(),
//                Integer.parseInt(partInstockField.getText()),
//                Double.parseDouble(partPriceField.getText()),
//                Integer.parseInt(partMaxField.getText()),
//                Integer.parseInt(partMinField.getText()));

//        tableItems.add(new Part(partNameField.getText(),
//                Integer.parseInt(partInstockField.getText()),
//                Double.parseDouble(partPriceField.getText()),
//                Integer.parseInt(partMaxField.getText()),
//                Integer.parseInt(partMinField.getText())
//        ));

        part
                .setName(partNameField.getText());
        part.setPrice(Double.parseDouble(partPriceField.getText()));
        part.setInstock(Integer.parseInt(partInstockField.getText()));
        part.setMin(Integer.parseInt(partMinField.getText()));
        part.setMax(Integer.parseInt(partMaxField.getText()));

        System.out.println(partNameField.getText());

        Stage stage = (Stage) cancel.getScene().getWindow();
        stage.close();
    }

    @FXML
    private void close(ActionEvent event) throws IOException {
        Stage stage = (Stage) cancel.getScene().getWindow();
        stage.close();
    }

    void setTableItems(ObservableList<Part> tableItems) {
       this.tableItems = tableItems;
    }

}

addPart.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<BorderPane id="addPage" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.AddPartController">

    <fx:define>
        <ToggleGroup fx:id="inOutGroup" />
    </fx:define>

        <VBox fx:id="verticalHolding">
            <children>
                <HBox fx:id="topRow">

                    <RadioButton fx:id="inhouse" toggleGroup="$inOutGroup" text="In-House"/>
                    <RadioButton fx:id="outsourced" toggleGroup="$inOutGroup" selected="true" text="Outsourced"/>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField promptText="Auto Gen - Disabled" disable="true" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField fx:id="partNameField" promptText="Part Name" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField fx:id="partInstockField" promptText="Inv" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField fx:id="partPriceField" promptText="Price/Cost" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField styleClass="smallTextField" fx:id="partMaxField" promptText="Max" />

                        <TextField styleClass="smallTextField" fx:id="partMinField" promptText="Min" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">

                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <TextField fx:id="inhouseTextField" promptText="Mach ID" />
                        <TextField fx:id="outsourcedTextField" promptText="Comp Nm" />
                    </HBox>
                </HBox>
                <HBox styleClass="fullWidth">
                    <HBox styleClass="halfWidthLeft">
                    </HBox>
                    <HBox styleClass="halfWidthRight">
                        <Button onAction="#addInhouse" fx:id="save" text="Save" />
                        <Button onAction="#close" fx:id="cancel" text="Cancel" />
                    </HBox>
                </HBox>
            </children>
        </VBox>

</BorderPane>


text:
Q: XML-Schema type regex or pattern for regex I want to validate if a certain attribute is a valid regex. Is there some direct built in type in xml schema maybe xs:regex?
Otherwise is there a regex that defines valid regexes?

A: There is, by definition, no regex that can validate regular expressions.
Regular expressions can match regular languages, they are not themselves a regular language. Much like there can be no regular expression to validate HTML or JavaScript.
To find out if a string is a legal regular expression, it's easiest to try and create a regex object from it. In XSD itself this is impossible, so you'd need the help of an external tool.


text:
Q: jQuery Code Hinting in Dreamweaver with noconflict Currently evaluating Dreamweaver CS 5.5. I like much of it - but wondering about the jQuery code hinting.
I like that feature quite a bit, but problem is, we use the noConflict() feature, like this:
var $j = jQuery.noConflict();

I am wondering if there is a way (built-in, code work-around, hack, or perhaps a plugin of some kind) that will enable the code-hinting to pick up $j() as opposed to $().
Thanks.

A: You'll find the code hint xml file for jQuery in
Adobe\Adobe Dreamweaver CS5.5\configuration\CodeHints
First few lines of the document you'll find  and you need to change alias="$" to alias="$j".


text:
Q: How to extend root partition I have 19.34gb unallocated space (sda7). I want this space to be added to my root partition sda11. How can I do that? I read few posts related to this but some of them suggest to use live usb and in some posts they asked only to add this command sudo resize2fs /dev/sda11. I don't know which procedure to follow. I tried to run the above command but I get this message The filesystem is already 5594368 blocks long.  Nothing to do!.
Also some posts suggested to move up or down my sda11 and then run the command but I don't know how to move sda11 up or down.
So for now I have read and tried above things. And I still don't know ho to increase/merge my root(sda11) and 19.34gb space(sda7). Please help.
Note: I am using dual boot and gparted.

A: First thing to do is back up any important information.
As explained in an answer HERE, you can't modify the systems's partitions (and parent extended partitons, like /dev/sda11) when the system is using them - so you need to modify the partitions from outside the system - the Ubuntu install disk should do for that. So first you need to boot from the disk, and open GParted.

Note about Gparted: Once you initiate a task, you must click the green check mark to execute the task. You should only do one of these tasks at a time for this session.
Now that you are booted up in a LIVE USB and using Gparted, you can navigate to the (sda7) and delete this partition, making sure that you back up any data on that partition first. This will leave a grey area that says UNALLOCATED.
Net you will need make sure that this empty space is right next to your root partition (sda11) on the RIGHT of the home partition. If there is a small partition called SWAP in between (or any other partition in bewtween) it will need to be moved to the right of the grey unallocated space.
Note - Do not move your home partition, or you will need to fix your BOOT partition.
Now that the home partition and the unallocated space are contiguous, you should be able to resize the home partition (sda11) by clicking on on it, then clicking resize, then by dragging the right edge of the rectangle in the pop up menu. After you tell GParted you want those operations to be done, you have to tell it to apply them (click the green check mark). It may take a while, but it should work without problems.

After this reboot into your normal install of Ubuntu (not the live disk), and check the partitions again with Gparted to ensure everything went as planned.
NOTE: Normally things go smoothly i.e without any problem but sometime they don't and therefore it is important that you backup your data before making any changes to your hardisk. Its better to be safe than sorry!


text:
Q: Windows form running in another thread is not getting displayed Please have a look at the following code
#pragma once

#include "Email.h"

    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Threading;
    using namespace SMSLib;

    /// <summary>
    /// Summary for NotifyAlarm
    /// </summary>
    public ref class NotifyAlarm : public System::Windows::Forms::Form
    {
        int count;
        Email ^email;

    public:
        NotifyAlarm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
            count = 10;
            //email = gcnew Email();
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~NotifyAlarm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Label^  label1;
    protected:
    private: System::Windows::Forms::Label^  secondsLabel;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Button^  sendNowBtn;
    private: System::Windows::Forms::Button^  cancelBtn;
    private: System::Windows::Forms::Timer^  timer1;
    private: System::ComponentModel::IContainer^  components;

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->components = (gcnew System::ComponentModel::Container());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->secondsLabel = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->sendNowBtn = (gcnew System::Windows::Forms::Button());
            this->cancelBtn = (gcnew System::Windows::Forms::Button());
            this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
            this->SuspendLayout();
            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->label1->Location = System::Drawing::Point(13, 27);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(405, 20);
            this->label1->TabIndex = 0;
            this->label1->Text = L"Intruder Detected. An Email and SMS will be sent within ";
            //
            // secondsLabel
            //
            this->secondsLabel->AutoSize = true;
            this->secondsLabel->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->secondsLabel->ForeColor = System::Drawing::Color::Red;
            this->secondsLabel->Location = System::Drawing::Point(408, 27);
            this->secondsLabel->Name = L"secondsLabel";
            this->secondsLabel->Size = System::Drawing::Size(51, 20);
            this->secondsLabel->TabIndex = 1;
            this->secondsLabel->Text = L"label2";
            //
            // label2
            //
            this->label2->AutoSize = true;
            this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->label2->Location = System::Drawing::Point(465, 27);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(69, 20);
            this->label2->TabIndex = 2;
            this->label2->Text = L"seconds";
            //
            // sendNowBtn
            //
            this->sendNowBtn->Location = System::Drawing::Point(370, 70);
            this->sendNowBtn->Name = L"sendNowBtn";
            this->sendNowBtn->Size = System::Drawing::Size(75, 23);
            this->sendNowBtn->TabIndex = 3;
            this->sendNowBtn->Text = L"Send Now";
            this->sendNowBtn->UseVisualStyleBackColor = true;
            this->sendNowBtn->Click += gcnew System::EventHandler(this, &NotifyAlarm::sendNowBtn_Click);
            //
            // cancelBtn
            //
            this->cancelBtn->Location = System::Drawing::Point(469, 70);
            this->cancelBtn->Name = L"cancelBtn";
            this->cancelBtn->Size = System::Drawing::Size(75, 23);
            this->cancelBtn->TabIndex = 4;
            this->cancelBtn->Text = L"Cancel";
            this->cancelBtn->UseVisualStyleBackColor = true;
            this->cancelBtn->Click += gcnew System::EventHandler(this, &NotifyAlarm::cancelBtn_Click);
            //
            // timer1
            //
            this->timer1->Enabled = true;
            this->timer1->Interval = 1000;
            this->timer1->Tick += gcnew System::EventHandler(this, &NotifyAlarm::timer1_Tick);
            //
            // NotifyAlarm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(566, 105);
            this->Controls->Add(this->cancelBtn);
            this->Controls->Add(this->sendNowBtn);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->secondsLabel);
            this->Controls->Add(this->label1);
            this->Name = L"NotifyAlarm";
            this->Text = L"NotifyAlarm";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e)
             {
                 count--;
                 DoUpdateText(count);

             }
private: System::Void sendNowBtn_Click(System::Object^  sender, System::EventArgs^  e)
         {
             timer1->Stop();

         }

public: System::Void showGUI()
                  {
                      this->Show();
                  }
private: System::Void cancelBtn_Click(System::Object^  sender, System::EventArgs^  e)
         {
             timer1->Stop();
             this->Close();
         }

        delegate void UpdateTextDelegate(int count);

private: void DoUpdateText(int count)
         {
             ISynchronizeInvoke^ i = this;

             if (i->InvokeRequired)
             {
                 UpdateTextDelegate^ tempDelegate =
                     gcnew UpdateTextDelegate(this, &NotifyAlarm::DoUpdateText);
                 cli::array<System::Object^>^ args = gcnew cli::array<System::Object^>(1);
                 args[0] = count;
                 i->BeginInvoke(tempDelegate, args);
                 return;
             }

             if(count>0 || count==0)
             {
                 secondsLabel->Text = ""+count;
             }
             else
             {
                 timer1->Stop();

                 this->Close();

             }
         }
};

The above code displays a Windows Form used for generating notifications. I am running this class inside another thread. Below is how I setup the thread inside another class
na = gcnew NotifyAlarm();
Thread ^t = gcnew Thread(gcnew System::Threading::ThreadStart(na,&NotifyAlarm::showGUI));
t->Start();

The issue I have is, the form displays fine, but after a second, it disappears. Whatever the process running inside the form seems to be running, but in background, without the form getting displayed.
Pay attention here:
    delegate void UpdateTextDelegate(int count);

private: void DoUpdateText(int count)
         {
             ISynchronizeInvoke^ i = this;

             if (i->InvokeRequired)
             {
                 UpdateTextDelegate^ tempDelegate =
                     gcnew UpdateTextDelegate(this, &NotifyAlarm::DoUpdateText);
                 cli::array<System::Object^>^ args = gcnew cli::array<System::Object^>(1);
                 args[0] = count;
                 i->BeginInvoke(tempDelegate, args);
                 return;
             }

             if(count>0 || count==0)
             {
                 secondsLabel->Text = ""+count;
             }
             else
             {
                 timer1->Stop();

                 this->Close();

             }
         }
};

This where the form work inside the thread happens.
It is very important for me to display this form in another thread. Why it is disappearing?
UPDATE
After using
System::Void showGUI() {
  Application::Run(*this);
}

I got this error
1>c:\users\yohan\documents\visual studio 2010\projects\ eesystem\eesystem\NotifyAlarm.h(182): error C2665: 'System::Windows::Forms::Application::Run' : none of the 3 overloads could convert all the argument types
1>          c:\program files\reference assemblies\microsoft\framework\.netframework\v4.0\system.windows.forms.dll: could be 'void System::Windows::Forms::Application::Run(System::Windows::Forms::Form ^)'
1>          c:\program files\reference assemblies\microsoft\framework\.netframework\v4.0\system.windows.forms.dll: or       'void System::Windows::Forms::Application::Run(System::Windows::Forms::ApplicationContext ^)'
1>          while trying to match the argument list '(NotifyAlarm)'

A: The problem here is that you are just calling this->Show().  This at most will display the form a single time.  It does not setup a message loop though so it will not respond to any user actions, nor will it ever redraw itself after the first time.  To fix this you need to setup a message loop with Application::Run
System::Void showGUI() {
  Application::Run(this);
}


text:
Q: How do I create a select statement that is checking other tables to see if there is data? How do I create a select statement that is checking other tables to see if there is data?
For example, suppose I have a City table that is filled with Cities and States, and then I have 3 other tables filled with businesses that have both Cities and States.  So then how do I get only cities that have data?
For example, let's take Florida.  How do I get cities in Florida that have at least 3 businesses in them?
I assume it would be something like
Select City C from Cities
where( Select (count) from FloridaBeds where City = C.City where (count) > 3

A: To find a city with 1-3 beds in Florida and less than 3 beds in Kansas, try:
select  c.City
from    Cities c
join    FloridaBeds fb
on      fb.City = c.City
join    KansasBeds kb
on      kb.City = c.City
group by
        c.City
having  count(distinct fb.ID) between 1 and 3
        and count(distinct kb.ID) <3

A: To get a list of cities in Florida with at least 3 businesses, you could do this:
SELECT City
FROM Cities c
WHERE City IN
    (
    SELECT City
    FROM FloridaBeds
    GROUP BY City
    HAVING COUNT(City) >= 3
    )

It appears that the city name is in your FloridaBeds table.  If this is true, and you don't have a alternate key, such as CityID, you can just do this to get a list of city names.
SELECT City
FROM FloridaBeds
GROUP BY City
HAVING COUNT(City) >= 3

A: To select cities that have data try this:
SELECT DISTINCT City
FROM Cities RIGHT JOIN
FloridaBeds ON FloridaBeds.CityId = Cities.CityId


text:
Q: Test using Apple iOS Mail app Our server is running via emails, and we would like to write automated tests to manipulate mail apps and verify our service.
I try to use Appium and other frameworks, and later on realize that those testing frameworks are for people who own the app. We don't own any email app but would like to test using them.
Does someone know whether there is a way to test with iOS Apple mail app? I try to use the iOS simulator but mail is not there. And I don't see a way to launch the mail app via Appium.
Any hints are really appreciated! Thanks.
S


text:
Q: undefined sequence for the "list of figures" due to the labels defined in my Tikz plots I got a number of Tikz plots that I include in my LaTeX source. Those Tikz plots contain \label{labelnamel} which I then use in the caption of my figure:
 \begin{figure}
 \input{Figs/tikzplot.tex}
 \caption{plot a \ref{labenameA}. plot b \ref{labelnameB} }
 \end{figure}

Now when my LaTeX project tries to make a List of Figures, the error comes up:
I get the error that it has undefined sequence (\pgfplots@show@ref@labelnameA) and it directly refers to the those \ref that corresponds to the labels in my Tikz. I can see from my PDF file that the table fails to understand what that reference is.
I do even have \cite sometimes in my caption and that works perfectly for list of figures.
Minimal example

\documentclass[a4paper]{report}
% Some useful packages for including images, colored font, etc.
\usepackage[dvips]{graphicx}
\usepackage{listings}
\usepackage{color}
\usepackage{url}

\RequirePackage{natbib}
% Global bibliography style

% Set margins in all document to 3.5cm as per guidelines for binding
\usepackage[includeheadfoot,margin=3.5cm]{geometry}
\usepackage{pdfpages}
\usepackage{fancyhdr}
\pagestyle{fancyplain}
\usepackage{titlesec}
\linespread{1.3}
\fancyhf{}
\lhead{\leftmark}
% Center on all pages
\fancyhead[C]{---Draft---}
% Page number placed on right side on odd pages and left side on even pages
\fancyfoot[RO, LE] {\thepage}
\usepackage{amsmath} % required by declare math operator
\usepackage[capitalise]{cleveref} %Referencing without need to explicitly state fig /table
% TIKZ
\usepackage{pgfplots,filecontents}
\usepackage{tikzscale}
\pgfplotsset{compat=newest}
\usetikzlibrary{plotmarks}
\usepgfplotslibrary{groupplots}
\usetikzlibrary{arrows.meta}
\usepgfplotslibrary{patchplots}
\pgfplotsset{plot coordinates/math parser=false}
\newlength\fheight
\newlength\fwidth
%to color a row by using \rowcolor{gray}
\usepackage{color, colortbl}
%define light gray
\definecolor{lightGray}{gray}{0.9}
%% language algo
\usepackage{listings}
\usepackage{subcaption}
\usepackage[ruled,vlined]{algorithm2e}
\begin{document}
% Set page numbers to roman numerals for front matter
\pagenumbering{roman}
% Include a list of figures
\addcontentsline{toc}{chapter}{List of Figures}
\listoffigures
% Set page numbering to arabic for body of Thesis
\pagenumbering{arabic}
% For example
\chapter{Test}
\begin{figure}[t]
    \setlength\fheight{0.5\columnwidth}
    \setlength\fwidth{0.4\columnwidth}
    \centering
    %
    \input{nitvali_all}
    %
    %
    \caption{
        (\ref{ref1}) reef1
        (\ref{ref2}) reef2}
    \label{fig:validation}
    %
\end{figure}
\end{document}

The Tikz file nitvali_all.tex:

% This file was created by tikzplotlib v0.9.1.
\begin{tikzpicture}

\begin{groupplot}[group style={group size=1 by 1}]

\nextgroupplot[
height=\fheight,
%legend cell align={left},
%legend columns=4,
%legend style={fill opacity=0.8, draw opacity=1, text opacity=1, draw=white!80!black,at={(-1, 1.10)}, anchor=north},
tick align=outside,
tick pos=left,
title={(c): Case 3},
width=\fwidth,
x grid style={white!69.0196078431373!black},
xlabel={Time [ms]},
xmajorgrids,
xmin=0, xmax=8.2,
xtick style={color=black},
y grid style={white!69.0196078431373!black},
ymajorgrids,
ymin=0, ymax=12.8,
ytick style={color=black}
]
\addplot [semithick, black, mark=*, mark size=1.5, mark options={solid}, only marks]
table {%
7.50304269790649 8.61112403869629
7.73022317886353 8.7830286026001
7.98580121994019 8.92600917816162
}; \label{ref1}
\addplot [semithick, black, mark=square*, mark size=1.5, mark options={solid}, only marks]
table {%
0.0701577663421631 0.345906138420105
0.106774091720581 0.548678278923035
0.216410160064697 0.89439582824707
};\label{ref2}
\end{groupplot}

\end{tikzpicture}


text:
Q: How to change the visibility of markers on Google Map using Cluster Manager? (Android) I have a simple app that show a lot of markers on a map (Google Map). At the moment I have over 3,000 markers and this number keeps growing as the database gets bigger.
I also have a few checkboxes that dictate which markers are to be shown, vice versa.
Originally I was adding each marker like this (inside a loop going through every location)
Marker marker;
marker = mMap.addMarker (markerOptions);
mMarkerArrayList.add(marker);

Then when the user interacted with the checkboxes, I simply made markers visible/invisible. This is faster removing, and re-adding the markers.
The code in the Checkbox Change Listener was something like this:
for (Marker marker : mMarkerArrayList) {
    if (condition) {
        marker.setVisible(false);
    }
}

And then make the visible again on another change of the checkbox.
However, adding all these markers individually in the beginning was taking a long time (1-2 seconds) and as the markers can only be added in the UI thread, it was freezing the UI (including my progress bar) for that amount of time.
After a lot of research, and not getting anywhere, the only thing I could do was add the markers using the ClusterManager (android-maps-utils library). This loads twice as fast, and does not block my UI.
Adding code is something like this (here myLocation is the object of my MyLocation class which holds the lcoation and relevant data for each point).
for (MyLocation myLocation : mMyLocationArrayList) {
    mClusterManager.addItem(myLocation)
}

Now the issue is linking the checkboxes to these ClusterItem objects. I cannot find any method, or field in the library to change the visibility of these markers (ClusterItem). In the previous method (changing the visibility) was almost instantaneous (fast enough that the user would not feel any lag). However, now, I need to add and remove these markers everytime, and there is a lag, and it is very obvious to the user.
Does anyone have any suggestions?

A: You should be able to use mClusterManager.getMarkerCollection().getMarkers() in order to get the Marker collection, and then hide certain Markers in the same way as you were before:
Collection<Marker> markerCollection = mClusterManager.getMarkerCollection().getMarkers();

for (Marker marker : markerCollection) {
    if (condition) {
        marker.setVisible(false);
    }
}

A: @Khash  I have had some success with the following code (i.e. hides both the Markers and Clusters), although I experience a similar issue when I zoom the map in or out the Markers and Clusters re-appear.
Hope this helps, happy coding!
if (hide) {
    /* Hide all Markers and Clusters */
    mMyClusterManager.getMarkerCollection().hideAll();
    mMyClusterManager.getClusterMarkerCollection().hideAll();
} else {
    /* Show all Markers and Clusters */
    mMyClusterManager.getMarkerCollection().showAll();
    mMyClusterManager.getClusterMarkerCollection().showAll();
}


text:
Q: Change default download folder when working remotely in VSCode in Windows When working remotely via SSH or WSL in VSCode in MS Windows, I can right-click a file in the Explorer view and choose "Download", this will download the file to the local computer. But the default download folder is always C:\Users\$USERNAME\.ssh, which doesn't make sense for me. I can't find any settings related to this.
How can I change the default download folder in VSCode when working remotely via SSH or WSL?