text:
Q: Trailing Three Years Pandas Dataframe I am looking to take the trailing three years (last three years) of my data set. I have merged the year, month and quarter columns into one column named 'date' which is a datetime function. I would like to use his 'date' column in order to get the last 3 years depending on when I run the report.
I thought of using .tail, but my issue is that the number of rows will change and therefore wanted to do filter based on the date column.
In my code below you will see I am filtering based on year, but really i need to be more precise and filter on an exact 3 year basis- For example, if i ran the report in 2 months from now, it would give me exactly 3 years back.
df1= df.loc[df['YEAR'].isin(['2014','2015','2016'])]
monthend = {'Q1':'3/31','Q2':'6/30','Q3':'9/30','Q4':'12/31'}
df1['Date']=df1['QUARTER'].map(monthend)+'/'+ df1['YEAR']
df1['Date'] = pd.to_datetime(df1['Date'])

Dataframe looks something like this:
YEAR    MONTH   QUARTER  Fruit Sales ($)    Date
2014      2       1         12           3/31/2014
2014      4       2         12           6/30/2014
2014      9       3         13           9/30/2014
2014      12      4         11           12/31/2014
2015      1       1         3            3/31/2015
2015      4       2         54           6/30/2015
2015      8       3         11           9/30/2015
2015      11      4         43           12/31/2015
2016      3       1         54           3/31/2016
2016      5       2         34           6/30/2016
2016      7       3         6            9/30/2016
2016      10      4         7            12/31/2016
2017      1       1         57           3/31/2017

Any ideas?

A: I think we can do it with saving the (current time - 3 years) as a variable and then filtering the DataFrame with that.
so
import time
then = datetime.datetime.now() - datetime.timedelta(days=3*365)
then = pd.to_datetime(then)

now back to our dataframe
df2 = df1[(df1['Date'] > then)]

I am sure there is a more elegant solution but I think this can get the job done!
Here are the sources I used:
pandas apply filter for boolean type
filtering pandas dataframes on dates
Subtract an year from a datetime column in pandas


text:
Q: N-tiered Parent/Child Breadcrumb Trail - Bottom to Top Loop I am trying to building a breadcrumb trail based on a parent/child relationship in a SQL database table. I have done these in the past, but what I need to do now is walk my way up through the hierarchy from the bottom up (backwards).
Here is what my DataTable looks like:
DocID | ParentDocID | Name
7 | 0 | Images (Root)
24 | 7 | JPG (Level 2)
34 | 24 | Size (Level 3)
So this is an N-tiered architecture. I always know what level I am at via a query string variable. I need to loop from the bottom up so that a user can bookmark what level in the tier structure they are at. I am having trouble figuring this out. I cannot use session or viewstate.
Desired Results:
User goes to this link:
Default.aspx?DocId=34 – Then they see the breadcrumb trail as such:
Home > Images > JPG > Size
Default.aspx?DocId=24 – Then they see the breadcrumb trail as such:
Home > Images > JPG
The "Home" element I have hard-coded. I also need each item in the trail to link except for the level you are on.
I would rather this be done in C# code. I also am open to SQL level Stored Procedure options.
Any help would be greatly appreciated. Thank-you in advance!
Here is some SQL I am trying but not getting the results I need. I hope this helps:
WITH Hierachy([DocID], [ParentDocID], [Name], [Level]
AS
(
SELECT [DocID], [ParentDocID], [Name], 0 AS [Level]
FROM [Documents] d
WHERE (d.[ParentDocID] = 7) AND ([Folder] = 1) AND ([Status] = 'A') AND ([AppGroupID] = 4)
UNION ALL
SELECT d.[DocID], d.[ParentDocID], d.[Name], dh.[Level] + 1
FROM [Documents] d
INNER JOIN Hierachy dh
--ON d.ParentDocID = dh.DocID
ON dh.[ParentDocID] = d.[DocID] -- bottom up apporach
WHERE ([Folder] = 1) AND ([Status] = 'A') AND ([AppGroupID] = 4)
)
SELECT [DocID], [ParentDocID], [Name]
FROM Hierachy
--WHERE [Level] > 0

I got it! Here is the SQL that works:
WITH Hierachy([DocID], [ParentDocID], [Name], [Level])
AS
(
SELECT [DocID], [ParentDocID], [Name], 0 AS [Level]
FROM [Documents] d
WHERE (d.[DocID] = @ParentDocID) AND ([Folder] = 1)
AND ([Status] = 'A') AND ([AppGroupID] = @AppGroupID)
UNION ALL
SELECT d.[DocID], d.[ParentDocID], d.[Name], dh.[Level] + 1
FROM [Documents] d
INNER JOIN Hierachy dh
ON dh.[ParentDocID] = d.[DocID]
WHERE ([Folder] = 1)
AND ([Status] = 'A') AND ([AppGroupID] = @AppGroupID)
)
SELECT [DocID], [ParentDocID], [Name]
FROM Hierachy
ORDER BY [Level] DESC
)

A: Sure you can. You can use CURSOR or WHILE LOOP or XML.
I have an example like you. Here's the WHILE LOOP with a temp Table, it selects parents of a node with a provided ID:
DECLARE @ID INT = 4
DECLARE @Parent_ID INT
DECLARE @Tree TABLE
(
    ID int,
    Value NVARCHAR(10),
    Parent_ID int
)

SELECT @Parent_ID = Parent_ID FROM Tree
WHERE ID = @ID

WHILE @Parent_ID IS NOT NULL
BEGIN
    INSERT INTO @Tree
    SELECT * FROM Tree
    WHERE ID = @Parent_ID

    SELECT @Parent_ID = Parent_ID FROM Tree
    WHERE ID = @Parent_ID
END

SELECT * FROM @Tree

A: This describes solving a similar problem, ie walking up a tree. Any inline sql, such as this is best executed within a stored procedure. Solving it in SQL is probably the best approach, as you already have all the data there.

A: Check below link you will get perfact answer for your question.
SQL Server: How to get all child records given a parent id in a self referencing table

redpajama_set_name: RedPajamaStackExchange


text:
Q: SignedXml.LoadXML((XmlElement)nodeList[0]) throwing "Malformed element SignedInfo/Reference" I am having trouble when reading SignedInfo from XML of a signed document, when calling
SignedXml signedXml;
Directory.SetCurrentDirectory(TmpDir);
XmlDocument xmlDoc = new XmlDocument();

foreach(Relationship signature in signs)
{
   if(_InMemoryData.ContainsKey(signature.FilePath) || File.Exists(signature.FilePath))
    {
        using(Stream xmlStream = LoadDataItem(signature.FilePath))
        {
            xmlDoc.Load(xmlStream);
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
            if(nodeList.Count == 1)
            {
                signedXml = new SignedXml(xmlDoc);
                signedXml.LoadXml((XmlElement)nodeList[0]); //throws

on line signedXml.LoadXml((XmlElement)nodeList[0]);  it is throwing exception with message "System.Security.Cryptography.CryptographicException: Malformed element SignedInfo/Reference".
The only odd thing about this XML that it have 145 recipients. However other software manages to read this without any issues, so I don't think this is an issue.
Searching for exception with "Malformed element..." mostly suggests that element's Id value has numbers in it and that is not allowed. Checked other similar XML files and they all do have numbers in them, so that should not be the case.

A: After some setting up and debuging system libraries I found out where it throws the excpetion and apperantly by default it only allow 100 recipients. To change that, I needed to add a new registry key named "SignedXmlMaxReferencesPerSignedInfo" with DWord value to be greater than 145 in my case to "Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\Security" and it started working.


text:
Q: c - in_addr_t variable as paramether of connect I have a variable of in_addr_t type and I would like to use connect() with the given ip. I'm therefore needing a (struct sockaddr *) variable as parameter for the connect(). How to insert use the in_addr_t variable instead?
in_addr_t var; // Given variable, not actually declared here ofc

int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in *srvraddr = malloc(sizeof(struct sockaddr_in));
memset((void *) srvraddr, 0, sizeof(struct sockaddr_in));
srvraddr->sin_family = AF_INET;
srvraddr->sin_port = htons(PORT_A); // Big - little endian arch compatibility

srvraddr->sin_addr.s_addr = var; // Somehow assign var here? <<<<<

connect(sockfd, (struct sockaddr *) srvraddr, sizeof(struct sockaddr_in));

Whatever I try to do connect always returns me -1.
Using perror I get the following error: Connection refused.

A:
How to insert use the in_addr_t variable instead?

You cannot use an in_addr_t with connect() instead of a struct sockaddr_in.  connect() accepts varying address structure types, but not arbitrary ones.  The correct structure type for an IPv4 address is the struct sockaddr_in that you're already using.  You need to store an appropriate representation of the remote host address into that.
Evidently, you already have an in_addr_t that you assert represents the remote address, but are uncertain how to use it:

in_addr_t var; // Given variable, not actually declared here ofc

[...]
srvraddr->sin_addr.s_addr = var; // Somehow assign var here? <<<<<

What you present is already exactly what POSIX expects you to do, however.  POSIX requires that the sin_addr member of a struct sockaddr_in be a structure having at minimum a s_addr member of type in_addr_t.  Supposing that the in_addr_t you have is in fact a correct representation of the machine address to which you want to connect, assigning that value to sin_addr.s_addr of your address structure is just right.  In principle, there could be more members of that struct, but in practice, implementations that want to be interoperable will not require you to set any other members.  Most don't have other members at all.
Do note, however, that just because connect() receives the address structure via a pointer does not mean you need to use dynamic allocation.  It would be a bit more idiomatic to do this:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in srvraddr = { 0 };

srvraddr.sin_family = AF_INET;
srvraddr.sin_port = htons(PORT_A);
srvraddr.sin_addr.s_addr = var;

connect(sockfd, (struct sockaddr *) &srvraddr, sizeof(srvraddr));

Among other things, that saves you having to free the memory afterward.

Whatever I try to do connect always returns me -1. Using perror I get the following error: Connection refused.

As far as I can see, the code you've presented is fine.  You may want to check how you are obtaining the in_addr_t value in the first place, and to verify the port number you are using.  On the other hand, do not overlook the possibility that the problem is at the remote host: perhaps the port you are trying to connect to is just not open (to you).

A: This is my way of using connect() to get a connection to "example.com" on port 80:
#include <stdio.h>
#include <netdb.h>
#include <unistd.h>

int main(void)
{
  int sockfd;

  if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
    fprintf(stderr, "socket");
    return 0;
  }

  char domain[] = "example.com";
  struct hostent *he;
  he = gethostbyname (domain);
  if (!he)
  {
    switch (h_errno)
    {
    case HOST_NOT_FOUND:
      fputs ("The host was not found.\n", stderr);
      break;
    case NO_ADDRESS:
      fputs ("The name is valid but it has no address.\n", stderr);
      break;
    case NO_RECOVERY:
      fputs ("A non-recoverable name server error occurred.\n", stderr);
      break;
    case TRY_AGAIN:
      fputs ("The name server is temporarily unavailable.", stderr);
      break;
    }
    return 1;
  }
  if (he->h_length < 4)
    return 1;

  struct sockaddr_in srvraddr;
  srvraddr.sin_len = sizeof(srvraddr);
  srvraddr.sin_family = AF_INET;
  srvraddr.sin_port = htons(80);

  srvraddr.sin_addr = * (struct in_addr *) he->h_addr_list[0];

  if (connect(sockfd, (struct sockaddr*)&srvraddr, srvraddr.sin_len) == -1) {
    fprintf(stderr,"connect() failed\n");
    return 1;
  }

  // Use conection here...

  close(sockfd);
  return 0;
}


text:
Q: How to resolve "unused variable" compiler warnings? How can I resolve the warnings below?
FGlobal FctVoid gtmnts
  PARMLIST((TESPAP, p_var, mantissa, sign),
    hspacbTp  TESPAP  ....
  )
  #ifdef ASNFAM1
  {
   (void)TESPAP;
   ...
  }

unused parameter 'TESPAP'

A: this is direct way.

*

*use --Wunused-value with gcc this will suppress all warnings for unused value in source code.

*As Sourav mentioned in comment try adding -DASNFAM1 while compiling if you want to conditionally compile it.

*add #ifdef ASNFAM1 at all occurrences.

I will recommend third option as it is fail proof.
but sometimes we need quick hack so give other 2 a try.
Quick suggestion:- try not to ignore/suppress compiler warnings as they are there for a reason.


text:
Q: Vue - Accessing slot children classes in render function I have a component that has a default slot, and in a render function i'm trying to wrap each item in the slot inside a div in order to control the layout better.
I need to grab one of the slot elements classes (if it exists) to add it to the wrapper element, but the VNode element does not have elm or $el available when the function is running, it's still undefined.
Parent component template:
<Parent>
   child 1

child 2

   <Child>child 3</Child>
</Parent>

Expected rendered result:
<Parent>
   <Wrapper>
      child 1
   </Wrapper>
   <Wrapper class="push">

child 2

   </Wrapper>
   <Wrapper>
      <Child>child 3</Child>
   </Wrapper>
</Parent>

For now, this is my render function which properly wraps each element, but it's not finding the class in the slot children, it seems like it's not accessible !
render(createElement) {
    const childs = [];
    this.$slots.default.forEach(item => {
      if (item.tag) {
        console.log(item.elm, item.componentInstance); // both returns undefined
        childs.push(createElement("Wrapper", [item]));
      }
    });

    return createElement(this.tag, { class: this.classes }, childs);
  }

So, how can I access the slot element's classes in the render function ?

A: You could use the data.staticClass attribute:

Vue.component("Child", {
  template: `

      <slot />

  `
})
Vue.component("Wrapper", {
  template: `

    <slot />

  `
})
Vue.component("Parent", {
  data() {
    return {
      tag: 'div'
    }
  },
  render(createElement) {
    const children = [];
    this.$slots.default.forEach(item => {
      if (item.tag) {
        let wrapperClasses = null
        if (item?.data?.staticClass) {
          // extracting the static class
          wrapperClasses = item.data.staticClass

          // "null"ing the static class on the passed in item
          item.data.staticClass = null
        }
        children.push(createElement(
          "Wrapper", {
            class: wrapperClasses
          }, [item]
        ));
      }
    });
    return createElement(this.tag, children);
  }
})
new Vue({
  el: "#app",
  template: `

      <Parent>
        child 1

child 2

        <Child>child 3</Child>
      </Parent>

  `
})
.push {
  color: red;
}

.pull {
  color: green;
}

*

*You can check the classes in the console.


text:
Q: How to remove space between logos in navbar? I have a menu where I have some links and logos. You can see that below.

I want 03 logos to close each other. You can see spaces between logos. I don't want to much space between logos.How Can I just remove gap/space between these logos. Help me out.
My HTML Code:

        <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

Home

Jobs

Career Advice

Skill Check

About Us

Login

Registration

Logout

MY CSS:

.cp-nav-2 .navbar-collapse .navbar-nav .menu-item {
  font-family: "Roboto", sans-serif;
  font-weight: 400;
  font-size: 1.5rem;
  margin-right: 30px;
  color: #6f7484;
}

.cp-nav-2 .navbar-collapse .navbar-nav .menu-item a:hover {
  color: #246df8;
}

.cp-nav-2 .navbar-collapse .navbar-nav .menu-item.post-job {
  margin-left: auto;
  margin-right: 0;
}

.cp-nav-2 .navbar-collapse .navbar-nav .menu-item.post-job a {
  background: #246df8;
  color: #ffffff;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
  border-radius: 3px;
  padding: 11px 20px;
}

.cp-nav-2 .navbar-collapse .navbar-nav .menu-item.post-job a i {
  font-size: 1.2rem;
  margin-right: 10px;
}

A: True to the prior. You either use inline CSS like
style="height:20px;position: relative;padding: 0;"

or you add a CSS class.
An easy fix in terms of CSS either inline or scripted could be to adjust the position from one item to the next one with something like this line below:
position:relative;right:-6px;

You have to play with the pixels to adjust as needed.
I hope this helps

A: Your CSS is all over the place, i would delete all the classes from your HTML and delete all your css and start again, to get you started if you go off this
* {
  padding: 0;
  margin: 0;
}
ul {
  display: flex;
  text-decoration: none;
  width: 100%;
  background-color: lightgrey;
  justify-content: flex-end;
}
li {
  flex-direction: row;
  list-style: none;
  padding: 1rem;
}
a {
  text-decoration: none;
  color: #333;
}

in your css add a class class="img-fluid" and then you can just change the properties from there, you don't need to do style="height:20px;position: relative;padding: 0;" in your HTML as it will start to get very messy, just do your css in your style.css file


text:
Q: Behavior of method overloading with varargs I have two overloaded methods with varargs int and long. When I run a test passing integer it seems to prefer the varargs long method. Whereas, if I make the methods static and run with an integer it seems to prefer the varargs int method. What's going on here?
void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varagrs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varagrs(1);
    staticvarargs(1);
}

Output:
Inside long varargs
1
Inside static int varargs
1
EDIT: I should've chosen better method names. There was a typo varargs, varagrs. Thanks zhong.j.yu for pointing that out.
Corrected code and expected behavior:
void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varargs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varargs(1);
    staticvarargs(1);
}

Output:
Inside int varargs
1
Inside static int varargs
1

A: It's a typo
void varagrs(long... l){
         ^^

That's why it's nice to have an IDE with spell checking (e.g. IntelliJ)
After fixing the typo, the compiler chooses (int...) over (long...) because int is a subtype of long (4.10.1), so the 1st method is more specific (15.12.2.5). Note though int[] is not a subtype of long[] (4.10.3).


text:
Q: JdbcBatchItemWriter - Incorrect Syntax near the Keyword 'ON' I'm running the following query to insert a record into my SQL Server database from my Spring application using JdbcBatchItemWriter
"INSERT INTO USER (username, address) VALUES (:username,:address) ON DUPLICATE KEY UPDATE username = username"

But am getting the following exception
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [{my_query_above}]; nested exception is java.sql.SQLException: Incorrect syntax near the keyword 'ON'.

The query runs fine without the ON condition. Any idea why this is failing?
UPDATE
here's the write config
@Bean
public ItemWriter<User> userWriter(DataSource dataSource) throws SQLException {
    JdbcBatchItemWriter<User> userWriter = new JdbcBatchItemWriter<User>();
    userWriter.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<StagingProcess>());
    userWriter.setSql(QueryUtil.QUERY_INSERT_PROCESS);
    userWriter.setDataSource(sqlServerDataSource());
    return userWriter;
}

@Primary
@Bean(name="sqlserverDS")
public static DataSource sqlServerDataSource() throws SQLException {
    final DriverManagerDataSource sqlServerDataSource = new DriverManagerDataSource();      sqlServerDataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
    sqlServerDataSource.setUrl("jdbc:jtds:sqlserver://myHost:8080/myDB");
    sqlServerDataSource.setUsername("user");
    sqlServerDataSource.setPassword("password");
    return sqlServerDataSource;
}

More of the stacktrace
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [{my_query_above}]; nested exception is java.sql.SQLException: Incorrect syntax near the keyword 'ON'.
     at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:662) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:950) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterBatchUpdateUtils.executeBatchUpdateWithNamedParameters(NamedParameterBatchUpdateUtils.java:40) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.batchUpdate(NamedParameterJdbcTemplate.java:335) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.batch.item.database.JdbcBatchItemWriter.write(JdbcBatchItemWriter.java:181) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProcessor.writeItems(SimpleChunkProcessor.java:175) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProcessor.doWrite(SimpleChunkProcessor.java:151) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProcessor.write(SimpleChunkProcessor.java:274) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:199) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_101]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_101]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_101]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_101]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) [spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) [spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at com.sun.proxy.$Proxy75.run(Unknown Source) [na:na]

A: SQL Server doesn't support "ON DUPLICATE KEY UPDATE". Look at Does SQL Server Offer Anything Like MySQL's ON DUPLICATE KEY UPDATE for the SQL Server recommended SQL.


text:
Q: Automatic population of an excel sheet I am looking to make a form in which you can pull down a menu and have fields populate based on your selection. On my excel workbook I have Sheet 1 which is the menu and Sheet 2 which has the data.
Sheet 1 is laid out as such
Item Code   Description    Wholesale Price     Retail Price

Sheet 2 is:
00001       Beans           0.45                0.67

I have setup a drop down list in A1 (Item Code) to reference the item code range on Sheet 2 but what I want to happen after I select the item code is for the rest of the information to populate. I have come close using VLOOKUP but I just don't seem to be able to nail it down.
Any suggestions?

A: In Sheet1:
B2 =VLOOKUP(A2,Sheet2!$A$1:$D$10,2,FALSE)
C2 =VLOOKUP(A2,Sheet2!$A$1:$D$10,3,FALSE)
D2 =VLOOKUP(A2,Sheet2!$A$1:$D$10,4,FALSE)

Where:

*

*Sheet2!$A$1:$D$10 is your reference table in Sheet2

*In Sheet1 I assume you have a header row (hence A2, B2, C2, D2)

A: Sheet 1:

Formula:
=VLOOKUP($A2,Sheet2!$A:$D,2,FALSE)

Where

*

*A2 is the range of the Item Code

*Sheet2!$A:$D is the 4 columns to look in for data

*2, 3 and 4 are the columns (within the above 4) of your desired data.

*FALSE requires it to be an exact match

Sheet 2:

Result in sheet 1:

Note: I've formatted the A columns as text to preserve the leading zeros, hence the little green triangles in the cell corners.


text:
Q: Using PHP and SQL on Mac Just finished installing MySQL on my Macbook in order to do my web dev homework assignment. I'm running my web pages using the mac webserver at Macintosh HD/Library/WebServer/Documents/. When I try to execute my php file from the terminal with the following code to create a table in a database I get the error also below.
Code Executed from the terminal using "php fileName.php":
<?php
    $mysqli = new mysqli(localhost, root, ****, lab7);

    $query = "CREATE TABLE products (ID int primary key)";

    $mysqli->query($query);

    $mysqli->close();
?>

Error:
Warning: mysqli::__construct(): (HY000/2002): No such file or directory in /Library/WebServer/Documents/week7/Lab7/CreateTableTest.php on line 2

Warning: mysqli::query(): Couldn't fetch mysqli in /Library/WebServer/Documents/week7/Lab7/CreateTableTest.php on line 6

Warning: mysqli::close(): Couldn't fetch mysqli in /Library/WebServer/Documents/week7/Lab7/CreateTableTest.php on line 8

A: Looks like it's due to a sha2 authentication method in MySQL 8 that php does not recognized. See the link below and thank you all for the help.
Link


text:
Q: React js Сохранение формы при перезагрузке страницы Подскажите нубу, как можно сделать, что бы при перезагрузке страницы данные в форме сохранялись, т.е. мы вбиаем их в поля, нажимаем кнопку(обработчик шлёт запрос на сервер) (если надо, то добавлю, прошу заранее не надо ругаться, мол не добавил то се). Потом появляется список данных, перезагружаем страницу, форма чистая, но в get запросе данные остаются.
Как можно выбрать данные из get запроса и поставить обратно в форму?
Или можно как-то проще.. Пробывал split, получается абракадабра.

class PersonForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {sex: 'female', firstName: '', lastname: '', email: '', phone: ''};
    this.onInputChange = this.onInputChange.bind(this);
  }

  onInputChange(event) {
    const name = event.target.name;
    this.setState({[name]: value});
  }

  render() {
    return (
      <form>

        First Name: <input name="firstName" type="text"
                             value={this.state.firstName} onChange={this.onInputChange}/>

         Last Name: <input name="lastName" type="text"
                             value={this.state.lastName} onChange={this.onInputChange}/>

         Email: <input name="email" type="email"
                             value={this.state.email} onChange={this.onInputChange}/>

         Phone: <input name="phone" type="tel"
                             value={this.state.phone} onChange={this.onInputChange}/>

         Sex: <select name="sex" value={this.state.sex} onChange={this.onInputChange}>
            <option value="male">Male</option>
            <option value="female">Female</option>
          </select>

        <input type="button" value="submit" ></input>
      </form>
    );
  }
}

ReactDOM.render(<PersonForm />,  document.getElementById('root'));

UPD.
@Klimenkomud Вы правы, я не совсем правильно изложил свою мысль, и так у меня есть форма с n-числом полей, все поля разные, пользователь заполняет их, нажимает на кнопку, на экране остаётся эта заполненная форма и отображаются результаты поиска (данные из формы перебираются в get запрос) в результате get запрос выглядит примерно так : "..... /search-car?date_from=&date_to @ ....." .И тут пользователь решает обновить страницу. При обновлении он видит следующие: все поля в форме которые он заполнял стали пустыми. Вот я и пытаюсь забрать данные из get запроса, и положить их обратно в форму.

A: Если вы всё-же хотите получить данные из get параметров, то есть несколько вариантов. Если вы используете react-router, то эти данные можно получить из this.props.location.query.имя_гет_параметра_из_урла Если же на чистом js - можете использовать вот такую функцию:
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

И потом использовать её в конструкторе, определяя state компонента:
constructor(props) {
  super(props)
  this.state = {sex: getParameterByName('sex') || 'female', ...etc}
}

Таким образом, в форму попадут данные из get параметров, либо дефолтные.
P.S. Всё-же, дополните ваш вопрос конкретной целью данных "махинаций", возможно вам нужно совсем не это!
P.P.S Источник, откуда взята функция: Тыць


text:
Q: Couldn't establish a connection with HttpClient C# and TLS 1.x I am using Asp.net c#. I have an external API url, which does respond to specific url with TLS 1.2/1.1 enabled. I want to consume that API from my Web API. I have written following code to access the same.
    public async Task<bool> Post(string oauth_signature, string oauth_consumer_key, string oauth_timestamp, string oauth_nonce, CheckKYCRequestModel payload)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

        string url = "https://recycle.icicipruamc.com/Distributorsvcs/InvestorService.svc/JSON/CheckKYC?oauth_signature=" + oauth_signature +
            "&oauth_consumer_key=" + oauth_consumer_key + "&oauth_timestamp=" + oauth_timestamp + "&oauth_nonce=" + oauth_nonce + "";

        var jsonData = JsonConvert.SerializeObject(payload);

        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpClient client = new HttpClient();
        var response = await client.PostAsync(url, content);
        return true;
    }

But I am unable to establish a connection and it is throwing "Could not reach to the server" error.
I tried doing the same thing from Fiddler and it is working perfectly, but doesn't work with HttpClient, even though the client IP address is same and TLS is enabled in both cases.

What am I doing wrong ?


text:
Q: AMPL Cplex error: QP Hessian is not positive semi-definite I'm currently trying to solve an AMPL model, that runs for me using minos, with cplex and integral variables.
Most of the problems I've solved (i think). Helped myself with a "ratio trick" from here: http://lpsolve.sourceforge.net/5.5/ratio.htm, yet right now I get "QP Hessian is not positive semi-definite." error from one of my constraints.
I kinda know what the error means, yet I am not sure why it is showing for this constraint :/
#S
set SOURCE;
#D
set HALFPROD;
#K
set HALFPRODU;
#P
set PROD;

param surmax {SOURCE} >= 0;
param prodmin {PROD} >= 0;
param prodprofit {PROD} >= 0;
param convSDmax >= 0;
param convDKmax >= 0;
param convSD {SOURCE, HALFPROD} >= 0;
param convDK {HALFPROD, HALFPRODU} >= 0;
param convDP {HALFPROD, PROD} >= 0;
param convKP {HALFPRODU, PROD} >= 0;

var xs {SOURCE} >= 0, integer;
var xu {HALFPROD} >= 0, integer;
var xpd {PROD, HALFPROD} >= 0, integer;
var xpk {PROD, HALFPRODU} >= 0, integer;
var isKUsed binary;

var quantityD {j in HALFPROD} = sum {i in SOURCE} convSD[i,j] * xs[i];
var costSur = sum {i in SOURCE} xs[i]*12;

var quantityK {k in HALFPRODU} = (sum {j in HALFPROD} xu[j] * convDK[j,k]) * isKUsed;
var costK = isKUsed * 13000;

var quantityProdD {l in PROD} = sum {j in HALFPROD} xpd[l,j] * convDP[j,l];
var quantityProdK {l in PROD} = sum {k in HALFPRODU} xpk[l,k] * convKP[k,l];
var quantityProd {l in PROD} = quantityProdD[l] + quantityProdK[l];

var profitProd = sum {l in PROD} prodprofit[l] * quantityProd[l];
var balance = profitProd - costSur - costUwod;

subject to OgrSurMax {i in SOURCE}: xs[i] <= surmax[i];
subject to OgrconvSDMax: (sum {i in SOURCE} xs[i]) <= convSDmax;
subject to OgrconvDKMax: (sum {j in HALFPROD} xu[j]) <= convDKmax;
subject to OgrProdMin {l in PROD}: quantityProd[l] >= prodmin[l];
subject to OgrHALFPRODXPD {j in HALFPROD}: (sum {l in PROD} xpd[l,j]) + xu[j] - quantityD[j] <= 0;
#------------------TRAITOR!
subject to OgrHALFPRODXPK {k in HALFPRODU}: (sum {l in PROD} xpk[l,k]) - quantityK[k] <= 0;
#--------------------------

maximize balanceMax: balance;

This is my model.
"conv" stands for conversion:

*

*S->D and D->K are ratios "how much of D I get from converting S?"

*D->P and K->P are binary matrices that says whether D or K can be converted to P

Main actors in this model are xpd and xpk - they say how much PROD was aquired from converting HALFPROD or HALFPRODU. Because of multiple conversions I got to keep track of D's amount - number of D's used for D->K and D->P has to be less or equal than D's from S->D. This works, yet for some reason the same (even easier) constraint is not working :/
Any clues as to what may be an issue or how to fix it?

UPDATE:
Based on Erwin Kalvelagens answer I've tried to linearize it. Couldn't find a simple way for linearizing it apart from bigM method.
I've changed my quantityD part to this:
param quantityKMAX = 490860;
var quantityK {k in HALFPRODU} >= 0;
s.t. ogrK1 {k in HALFPRODU}: quantityK[k] <= quantityKMAX * isKUsed;
s.t. ogrK2 {k in HALFPRODU}: quantityK[k] <= (sum {j in HALFPROD} xu[j] * convDK[j,k]);
s.t. ogrK3 {k in HALFPRODU}: quantityK[k] <= (sum {j in HALFPROD} xu[j] * convDK[j,k]) - quantityKMAX * (1 - isKUsed);

quantityKMAX is a maximum quantity acquired from conversion (when converting max possible number of D to the "most giving" K), but I've actually tried with arbitrally big number, that is for sure bigger than any possible value for quantityK.
Works!

A: Cplex can only handle certain classes of quadratic constraints (in general -- with some exceptions -- things must stay convex). In your definition of variable quantityK you introduce a quadratic expression that Cplex cannot handle.
One simple approach is just to solve the problem twice: once with isKUsed=0 and once with with isKUsed=1. Then just pick the best solution.
Otherwise you can linearize things. Multiplication of a binary variable times a continuous (or integer) non-negative variable is not very hard to linearize.


text:
Q: `amb` operator as macro or procedure? In this page there is a comment after the post that gives a very short implementation of amb as a procedure:
(define (amb-backtrack)
  (error "no solution found"))

(define (amb . args)
  (call/cc (lambda (return)
             (let ((backtrack amb-backtrack))
               (map (lambda (x)
                      (call/cc (lambda (k)
                                 (set! amb-backtrack k)
                                 (return x))))
                    args)
               (backtrack 'fail)))))

But I usually see amb implemented as a macro -- in the schemers.org FAQ, and also in Dorai Sitaram's book:
(define amb-fail '*)

(define initialize-amb-fail
  (lambda ()
    (set! amb-fail
      (lambda ()
        (error "amb tree exhausted")))))

(initialize-amb-fail)

(define-macro amb
  (lambda alts...
    `(let ((+prev-amb-fail amb-fail))
       (call/cc
        (lambda (+sk)

          ,@(map (lambda (alt)
                   `(call/cc
                     (lambda (+fk)
                       (set! amb-fail
                         (lambda ()
                           (set! amb-fail +prev-amb-fail)
                           (+fk 'fail)))
                       (+sk ,alt))))
                 alts...)

          (+prev-amb-fail))))))

So -- the macro version is longer, and a little harder to understand. I could not see any advantages of it over the procedure version, and of course I would rather use a procedure than a macro. Is there anything I missed?

A: The difference is that a procedure call always evaluates all the arguments.
(amb 1 (very-expensive-computation))

will, with the procedure version of amb, perform the very-expensive-computation, then yield 1. If yielding 1 suffices for all further computation, then you've wasted a lot of time on a computation whose result value is never used. Even worse things happen, as @Eli Barzilay mentions in a comment, when amb is used to model an infinite non-determinism such as generating all natural numbers.
The macro version avoids this and its behavior is therefore closer to that of non-deterministic programming languages such as Prolog.


text:
Q: Excel Problem with a complicated situation Here is the data:

Speed ranking
Weight ranking
Speed earnings
Weight earnings

10
1
0

2
2
200

1
3
250

4
4
100

16
5
0

12
6
0

5
7
50

11
8
0

3
9
150

6
10
0

13
11
0

8
12
0

14
13
0

15
14
0

7
15
0

9
16
0

Assuming that the top 5 earners get:

*

*250 for the 1st place

*200 for the 2nd place

*150 for the 3rd place

*100 for the 4th place

*50 for the 5th place

Here is what I want:
If the value in cell C2 is 0, then the person has not yet earned anything in the speed ranking. In that case, the formula should return a value in D2 depending on the weight ranking in column B, as follows:

*

*If B2 is 1, then D2 should be 250

*If B2 is 2, then D2 should be 200

*If B2 is 3, then D2 should be 150

*If B2 is 4, then D2 should be 100

*If B2 is 5, then D2 should be 50

*Otherwise, D2 should be 0.

If the value in cell C2 is greater than 0, then the person has already earned something in the speed ranking. In that case, the formula should return a value in D2= 0 and  depending on the weight ranking in column B, the formula must return a value of the gain for the next person on the weight ranking , let's say for example D3 , as follows:

*

*If B2 is 1, then the person has already earned the maximum amount and should not earn anything more. Therefore, D3 should be 0.

*If B2 is 2, then D3 should be the amount corresponding to the 1st place in the weight ranking, i.e., 250.

*If B2 is 3, then D3 should be the amount corresponding to the 2nd place in the weight ranking, i.e., 200.

*If B2 is 4, then D3 should be the amount corresponding to the 3rd place in the weight ranking, i.e., 150.

*If B2 is 5, then D3 should be the amount corresponding to the 4th place in the weight ranking, i.e., 100.

*If B2 is 6, then D3 should be the amount corresponding to the 5th place in the weight ranking, i.e., 50.

*Otherwise, D3 should be 0.

Here an example of what i want to have as a result :

A: So, had some fun with this, used extra columns but does work:

Must be a method to reduce the two extra columns needed. But have to go shopping :)  But I will come back to this as it seems challenging.


text:
Q: Simulation of a continous Markov chain in Matlab? Can anyone help me with the code to simulate a continuous time Markov chain? I could not figure out how to write code for a continuous time Markov chain. I would appreciate any help. Thank you in advance.

A: The standard way to simulate a time-homogeneous CTMC is to convert it to the associated "jump chain", which is a DTMC, with associated holding times. To do this, you consider  a DTMC with jump probabilities $p_{ij}=-q_{ij}/q_{ii}$, where $Q$ is the generator matrix, and $p_{ii}=0$. Then you sample the holding time at $i$ as an exponential random variable with rate $-q_{ii}$.
As for simulating the DTMC, that is basically just a matter of sampling from a discrete distribution many times.
In the time-inhomogeneous case, in general you have to take a step size $h$ (which might itself depend on time) and say that you stay at $i$ with probability $1+hq_{ii}$ and go to $j$ with probability $hq_{ij}$. In the time-homogeneous case, this approach wastes samples (because when $h$ is small, most time steps are not jumps) and unnecessarily discretizes the holding time distribution.


text:
Q: Using distinct() with a vector of column names I have a question using distinct() from dplyr on a tibble/data.frame. From the documentation it is clear that you can use it by naming explicitely the column names. I have a data frame with >100 columns and want to use the funtion just on a subset. My intuition said I put the column names in a vector and use it as an argument for distinct. But distinct uses only the first vector element
Example on iris:
data(iris)
library(dplyr)

exclude.columns <- c('Species', 'Sepal.Width')
distinct_(iris, exclude.columns)

This is different from
exclude.columns <- c('Sepal.Width', 'Species')
distinct_(iris, exclude.columns)

I think distinct is not made for this operation. Another option would be to subset the data.frame then use distinct and join again with the excluded columns. But my question is if there is another option using just one function?

A: As suggested in my comment, you could also try:
data(iris)
library(dplyr)

exclude.columns <- c('Species', 'Sepal.Width')

distinct(iris, !!! syms(exclude.columns))

Output (first 10 rows):
   Sepal.Width    Species
1          3.5     setosa
2          3.0     setosa
3          3.2     setosa
4          3.1     setosa
5          3.6     setosa
6          3.9     setosa
7          3.4     setosa
8          2.9     setosa
9          3.7     setosa
10         4.0     setosa

However, that was suggested more than 2 years ago. A more proper usage of latest dplyr functionalities would be:
distinct(iris, across(all_of(exclude.columns)))

It is not entirely clear to me whether you would like to keep only the exclude.columns or actually exclude them; if the latter then you just put minus in front i.e. distinct(iris, across(-all_of(exclude.columns))).

A: Your objective sounds unclear. Are you trying to get all distinct rows across all columns except $Species and $Sepal.Width? If so, that doesn't make sense.
Let's say two rows are the same in all other variables except for $Sepal.Width. Using distinct() in the way you described would throw out the second row because it was not distinct from the first. Except that it was in the column you ignored.
You need to rethink your objective and whether it makes sense.
If you are just worried about duplicate rows, then
data %>%
  distinct(across(everything()))

will do the trick.


text:
Q: How to deploy child module without also deploying parent module? I have a project with a parent aggregator module and 3 children modules.
I don't know if this is a bug for me or just how Maven works, but I am currently unable to deploy one of my children modules without also deploying the respective parent. When I try to import the child module on another project of mine, Maven throws an error saying it can't resolve the parent. If I deploy both to my Nexus, it works perfectly. Do I always have to deploy both?

A: Yes.
You always need the parent POM as well.

A: When Maven need to "use" a module, it needs to resolve it.
If this module has ancestors it needs to access to every ones to resolve it.
OR you will face somethings like :
Could not resolve dependencies for project org.projectB:childA-Consumer:jar:0.1.0:
Failed to collect dependencies at org.projectA:childA:jar:0.1.0:
Failed to read artifact descriptor for org.projectA:childA:jar:0.1.0:
Could not find artifact org.projectA:parent:pom:0.1.0

Solution 1 : Deploy the parent
The  common way is to deploy the parent, so this way when you consume your module maven will be able to find ancestors and so resolve your module's pom.
But lot of users seems to consider this as not so satisfying. (There are many question about that on stackoverflow ...)
Solution 2 : Parent != Aggregator
Most of the time in multi-module project, the aggregator pom  is also the parent pom but this is 2 different concepts.

*

*parent : is about sharing configuration with inheritance.

*aggregator : is about building several modules at same time.

(more details about aggregator vs parent differences)
So, you can have an aggregator with several children and each child has no parent.
This way you don't have to deploy your aggregator.
Drawback you can not use inheritance to share config between modules.
Note that this is not a drawback for everyones, some consider that using inheritance and so parent is not good idea.
Solution 3 : Use Maven Flatten Plugin
Currently poms contains 2 kind of information :

*

*how to build the artifact,

*how to consume it (e.g. dependencies).

Maven 5 will maybe clarify this and so you could have a different pom in your released artifacts and in your source code.
Using Maven 3, there is a plugin which aims to do that : flatten-maven-plugin
It aims to generate a pom.xml consumers oriented.
Among others, parent relationship is resolved, flattened and removed.
This way, you can use parents to share configuration between modules (with inheritance) and not deploy your aggregator and/or parents .
Drawback, you could maybe face issues with some other maven plug-in interaction ?
Some tips you need to know if you wan to use flatten-maven-plugin :

*

*flatten cleangoal is no more useful.

*how to fix url, scm url, scm connection and scm developerConnection resolution.


text:
Q: Transferring Data from User Form to Worksheet I have a userform, to input employee name, with checkboxes for trainings.

When a user inputs an employee name that value should be populated in L which is merged with M.
For any checkboxes that are checked I would like to return "x" into the appropriate columns for those trainings.
Note that there is another data set one row below this one with same headings but for Journeymen not Foreman (this is why my code below refers to AZ2 which captures last row of the upper data set and I plan to do the same for the bottom data set).
Data Set Example:

My code is not working even for just the employee name.
Private Sub Submit_Click()
    Set act = ThisWorkbook.ActiveSheet
    bot_row = act.Range("AZ2")
    act.Range("L" & bot_row & ":AB" & bot_row).Insert Shift:=xlShiftDown
    act.Range("L" & bot_row & ":M" & bot_row).Value = EmpNameTextBox.Text
End Sub

Edit: Working code
Private Sub Submit_Click()
    Dim act As Worksheet
    Set act = ThisWorkbook.ActiveSheet
    bot_row = act.Range("AZ2")

    act.Range("L" & bot_row & ":AB" & bot_row).Insert Shift:=xlShiftDown
    act.Range("L9:AB9").Copy
    act.Range("L" & bot_row & ":AB" & bot_row).PasteSpecial xlPasteFormats
    act.Range("L" & bot_row & ":AB" & bot_row).PasteSpecial xlPasteFormulas
    Range("P" & bot_row & ":AB" & bot_row).ClearContents
    Range("L" & bot_row) = EmpName.Value
    Range("P" & bot_row) = EmpPhone.ValueDim cBox As Control
    For Each cBox In Me.Controls
      If TypeOf cBox Is msforms.CheckBox Then
         'potential test msgbox
         'MsgBox "Box " & cBox.Caption & " has a click value = " & cBox.Value
            If cBox.Value Then
            If cBox.Caption = "Competent" Then
                Range("Q" & bot_row).Value = "x"
            ElseIf cBox.Caption = "OSHA 30hr" Then
                Range("R" & bot_row).Value = "x"
            ElseIf cBox.Caption = "OSHA 10hr" Then
                Range("S" & bot_row).Value = "x"
            ElseIf cBox.Caption = "CPR" Then
               Range("T" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Hand Signal" Then
               Range("U" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Rigging" Then
               Range("V" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Asbestos" Then
               Range("W" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Certa Torch" Then
               Range("X" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Scaffold" Then
               Range("Y" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Fork/Lull" Then
               Range("Z" & bot_row).Value = "x"
            ElseIf cBox.Caption = "Manlift" Then
               Range("AA" & bot_row).Value = "x"
            ElseIf cBox.Caption = "ATV" Then
               Range("AB" & bot_row).Value = "x"
            End If
         End If

      End If
    Next

    Unload Me
End Sub

A: This would probably work. I would recommend you include this in your code at end. I would also suggest using something more dynamic with columns. Naming them would be easy and ensures you could make easy updates without too much modification of VBA code.
 Dim cBox As Control
    For Each cBox In Me.Controls
      If TypeOf cBox Is msforms.CheckBox Then
         'potential test msgbox
         'MsgBox "Box " & cBox.Caption & " has a click value = " & cBox.Value
         If cBox.Value Then
            If cBox.Caption = "CPR" Then
               Range("T" & bot_row).Value = "X"
            ElseIf cBox.Caption = "Hand Signal" Then
               Range("U" & bot_row).Value = "X"

            'etc.
            End If
         End If

      End If
    Next


text:
Q: I am having issues in updating my document in ibm cloudant db I want to add a new object to my existing document. So I am fetching the past details first and putting it inside the insert statement but it is getting stored as an array of objects when i only want key value pairs.
router.post("/insertApprovers", (req, res) => {
  console.log("inside insertApprovers");

  let id = req.body.data.id;
  let approvers = JSON.parse(req.body.data.approv);
  db.find({ selector: { _id: id } }, async function(err, result) {
    if (err) return console.log(err.message);
    console.log("Find completed: " + JSON.stringify(result.docs));
    let restData = result.docs[0];
    await db.insert(
      {
        _id: id,
        restData,
        approvers: approvers,
        _rev: result.docs[0]._rev
      },
      function(err, data) {
        if (err) return console.log(err.message);
        console.log("Insert completed: " + data);
      }
    );
  });
});

The image shows how my data is getting stored after updation:

A: This might work:
router.post("/insertApprovers", (req, res) => {
  console.log("inside insertApprovers");

  let id = req.body.data.id;
  let approvers = JSON.parse(req.body.data.approv);
  db.find({ selector: { _id: id } }, async function(err, result) {
    if (err) return console.log(err.message);
    console.log("Find completed: " + JSON.stringify(result.docs));
    let restData = result.docs[0];
    restData.approvers = approvers;
    await db.insert(restData),
      function(err, data) {
        if (err) return console.log(err.message);
        console.log("Insert completed: " + data);
      }
    );
  });
});


text:
Q: Start search after 2 character typed in Chosen drop down In Chosen drop down plugin, a search is started after 2 characters are typed in chosen drop down.
I need the search to not start until after inputing at least two characters in the search box.
Can any one suggest how to do this?

A: I did a small change to start to search after the third character, is not the best option but works, in the chosen JS in the AbstractChosen.prototype.winnow_results function after the line     searchText = this.get_search_text(); add the following code: if (searchText != "" && searchText.length < 3) return;. Remember to change the < 3 by your own size.
Hope this help you
See part of the code below:
AbstractChosen.prototype.winnow_results = function() {
  var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
  this.no_results_clear();
  results = 0;
  searchText = this.get_search_text();
  if (searchText != "" && searchText.length < 3) return;
  escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");

A: I know this post it's old but i had to face this problem just now and wanted to share my result. I wrapped everything in a function extendedSearch and set it as a callback while chosen is emitting the chosen:showing_dropdown event.
My problem was that i need the search to show the results after the 2nd character typed in search and must filter out certain strings from the results.
Bellow you'll find a demo which shows results on the 3rd character typed in, and will keep visible only those results that end with letter "E".

$(function() {
  /**
   * By default the results are hidden when clicking a dropdown.
   * {
   *      toggleResults: false, // a function(searchValue) that returns a boolean
   *      filterResults: false, // a function(dropDownValue, selectValue) that returns a boolean
   *  }
   * @param options
   */
  const extendedSearch = (options = {}) => {

    const defaultOptions = {
      toggleResults: false,
      filterResults: false,
    };

    options = { ...{},
      ...defaultOptions,
      ...options
    };

    /**
     * Main element
     */
    return (evt, params) => {

      let originalElement = $(evt.currentTarget);
      let searchInput = params.chosen.search_field;

      const customSearch = (options = {}) => {

        let defaultOptions = {
          originalElement: null,
          searchInput: null
        };

        options = { ...{},
          ...defaultOptions,
          ...options
        };

        if (!(options.originalElement instanceof jQuery) || !options.originalElement) {
          throw new Error('Custom Search: originalElement is invalid.');
        }
        if (!(options.searchInput instanceof jQuery) || !options.searchInput) {
          throw new Error('Custom Search: searchInput is invalid.');
        }

        let res = options.searchInput
          .parent()
          .next('.chosen-results');

        res.hide();

        if (typeof options.toggleResults !== 'function') {
          options.toggleResults = (value) => true;
        }
        if (options.filterResults && typeof options.filterResults !== 'function') {
          options.filterResults = (shownText = '', selectValue = '') => true;
        }

        /**
         * Search Input Element
         */
        return (e) => {

          let elem = $(e.currentTarget);
          let value = elem.val() || '';

          if (value.length && options.toggleResults(value) === true) {

            res.show();

            if (options.filterResults) {

              let children = res.children();
              let active = 0;

              $.each(children, (idx, item) => {

                let elItem = $(item);
                let elemIdx = elItem.attr('data-option-array-index');
                let shownText = elItem.text();
                let selectValue = options.originalElement.find('option:eq(' + elemIdx + ')').attr('value') || '';

                if (options.filterResults(shownText, selectValue) === true) {
                  active++;
                  elItem.show();
                } else {
                  active--;
                  elItem.hide();
                }

              });

              if (active >= 0) {
                res.show();
              } else {
                res.hide();
              }

            }

          } else {
            res.hide();
          }

        };

      };

      options = {
        ...{},
        ...options,
        ...{
          originalElement,
          searchInput
        }
      };

      let searchInstance = customSearch(options);

      searchInput
        .off('keyup', searchInstance)
        .on('keyup', searchInstance)

    }

  };

  /** This is the final code */
  const inputValidator = (value) => {
    console.log('input', value);
    return $.trim(value).length > 2;
  };
  const textResultsValidator = (dropDownValue, selectValue) => {
    if ($.trim(dropDownValue).substr(-1, 1) === 'E') {
      console.log('results shown', dropDownValue, '|', selectValue);
      return true;
    }
    return false;
  };

  $(".chosen-select")
    .chosen()
    .on('chosen:showing_dropdown', extendedSearch({
      toggleResults: inputValidator,
      filterResults: textResultsValidator
    }));

});
@import url("https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<select class="chosen-select">
  <option value="">Pick something</option>
  <option value="APPLE">APPLE</option>
  <option value="APPLE JUICE">APPLE JUICE</option>
  <option value="BANANA">BANANA</option>
  <option value="ANANAS">ANANAS</option>
  <option value="ORANGE">ORANGE</option>
  <option value="ORANGES">ORANGES</option>
  <option value="STRAWBERRY">STRAYBERRY</option>
</select>


text:
Q: How to submit apache beam dataflow job to GCP through java application I have a dataflow job which is written in apache beam with java. I am able run the dataflow job in GCP through this steps.

*

*Created dataflow template from my code. Then uploading template in cloud storage.

*Directly creating job from template option available in GCP->Dataflow->jobs
This flow is working fine.
I want to do same step through java app. means, I have one api when someone sends request to that api, I want to start this dataflow job through the template which I have already stored in storage.

I could see rest api is available to implement this approach. as below,
POST /v1b3/projects/project_id/locations/loc/templates:launch?gcsPath=template-location

But I didn't find any reference or samples for this. I tried the below approach
In my springboot project I added this dependency
<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-dataflow -->
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-dataflow</artifactId>
            <version>v1b3-rev20210825-1.32.1</version>
        </dependency>

and added below code in controller
public static void createJob() throws IOException {
        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("myCertKey.json")).createScoped(
            java.util.Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
        try{
            Dataflow dataflow = new Dataflow.Builder(new LowLevelHttpRequest(), new JacksonFactory(),
            credential).setApplicationName("my-job").build();           --- this gives error

            //RuntimeEnvironment
            RuntimeEnvironment env = new RuntimeEnvironment();
            env.setBypassTempDirValidation(false);
            //all my env configs added

            //parameters
            HashMap<String,String> params = new HashMap<>();
            params.put("bigtableEmulatorPort", "-1");
            params.put("gcsPath", "gs://bucket//my.json");
            // all other params

            LaunchTemplateParameters content = new LaunchTemplateParameters();
            content.setJobName("Test-job");
            content.setEnvironment(env);
            content.setParameters(params);

            dataflow.projects().locations().templates().launch("project-id", "location", content);
        }catch (Exception e){
            log.info("error occured", e);
        }
    }

This gives {"id":null,"message":"'boolean com.google.api.client.http.HttpTransport.isMtls()'"}
error in this line itself
Dataflow dataflow = new Dataflow.Builder(new LowLevelHttpRequest(), new JacksonFactory(),
            credential).setApplicationName("my-job").build();

this is bcs, this dataflow builder expects HttpTransport as 1st argument but I passed LowLevelHttpRequest()
I am not sure is this the correct way to implement this. Can any one suggest any ideas on this? how to implement this? any examples or reference ?
Thanks a lot :)


text:
Q: Label Change in a loop  public partial class Balloon : Form
    {
        public Balloon()
        {
            InitializeComponent();
            TopMost = true;
            Rectangle r = Screen.PrimaryScreen.WorkingArea;
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width - 1, Screen.PrimaryScreen.WorkingArea.Height - this.Height - 8);

            InstallStart2();
        }

        private async void InstallStart2()
        {

            if (Dot35 == "Yes")
            {
                this.Titel.Text = "The Knowhow Installer is installing:";
                this.Action.Text = "Microsoft .Net Framework 2 & 3";
                if (File.Exists(root + Installfolder + "dotnetfx35.exe"))
                {
                    Process process = Process.Start(root + Installfolder + "dotnetfx35.exe", "/q /norestart");

                    while (!process.HasExited) ;

                    bool installFinished1 = false;
                    int k = -1;
                    string[] dots = new string[] { "Microsoft .Net Framework 2 & 3.", "Microsoft .Net Framework 2 & 3..", "Microsoft .Net Framework 2 & 3..." };

                    while (!installFinished1)
                    {
                        Action.Text = dots[++k % 3];
                        await Task.Delay(TimeSpan.FromSeconds(1.0));
                    }

                    process.WaitForExit();
                }
                else
                {
                    this.TopMost = false;
                    int num = (int)MessageBox.Show("dotnetfx35.exe not found", "Error");
                }
            }
            await Task.Delay(TimeSpan.FromSeconds(2.0));

            if (Dot45 == "Yes")
            {
                this.Titel.Text = "The Knowhow Installer is installing:";
                this.Action.Text = "Microsoft .Net Framework 4.5";
                if (File.Exists(root + Installfolder + "dotnetFx45.exe"))
                {
                    Process process = Process.Start(root + Installfolder + "dotnetFX45.exe", "/q");

                    bool installFinished = false;
                    int k = -1;
                    string[] dots = new string[] { "Microsoft .Net Framework 4.5.", "Microsoft .Net Framework 4.5..", "Microsoft .Net Framework 4.5..." };

                    while (!installFinished)
                    {
                        Action.Text = dots[++k % 3];
                        await Task.Delay(TimeSpan.FromSeconds(1.0));
                    }

                    while (!process.HasExited) ;

                }
                else
                {
                    this.TopMost = false;
                    int num = (int)MessageBox.Show("dotnetFx45.exe not found", "Error");
                }
            }

            await Task.Delay(TimeSpan.FromSeconds(2.0));

            this.Action.Text = "Done";

            new SoundPlayer(root + otherfolder + "Done.wav").Play();
            await Task.Delay(TimeSpan.FromSeconds(5.0));

            Environment.CurrentDirectory = dir;
            this.Close();
            new InstallDone().Show();

        }

    }

This is a part of the code and it works for the first installation, but i can not find out where to put bool installFinished1 = true; to make it go to the next. Now it just stays at Microsoft .Net Framework 4.5... (it change from 1 to 3 dots in a loop)

A: You can do something like:
Action.Text = "Installing.";
Process process = Process.Start(root + Installfolder + "dotnetFX45.exe", "/q");
while(!process.WaitForExit(1000)){
   Action.Text += ".";
}

But, if you're doing this in an event handler in a windows forms application, this won't work as you expect. You'll be blocking the UI thread and so it never gets a chance to re-paint and show the updated text. In that case, you should use a BackgroundWorker, with this in the DoWork:
Process process = Process.Start(root + Installfolder + "dotnetFX45.exe", "/q");
while(!process.WaitForExit(1000)){
   worker.ReportProgress(0.5);
}

And then update the Text property by adding .s in the ProgressChanged.

A: Use the RxNet, sample code
var interval = Observable.Interval(TimeSpan.FromMilliseconds(1000));
interval.Subscribe(
    () => Action.Text += ".",
    () => Action.Text = "Completed");

A: If it have to be await then this is simplest way:
bool installFinished = false;
int k = -1;
string[] dots = new string[] { "Installing.", "Installing..", "Installing..." };

while (!installFinished)
{
    Action.Text = dots[++k % 3];
    await Task.Delay(TimeSpan.FromSeconds(1.0));
}
Action.Text = "Finished";

When you finish install, set:
installFinished = true;

Above loop will stop, and Action.Text being set to Finished.
Other way, you can use timer.
Edit:
Base on your updated code:
using System.Threading;

bool installFinished = false;

void Install_net45()
{
    Process process = Process.Start(root + Installfolder + "dotnetFX45.exe", "/q");

    while (!process.WaitForExit(1000))
    {
    }
    installFinished = true;
    // Clean up
}

private async void InstallStart2()
{
    if (Dot45 == "Yes")
    {
        this.Titel.Text = "The Knowhow Installer is installing:";
        this.Action.Text = "Microsoft .Net Framework 4.5";
        if (File.Exists(root + Installfolder + "dotnetFx45.exe"))
        {

            installFinished = false;

            Thread t = new Thread(Install_net45);
            t.Start();

            int k = -1;
            string[] dots = new string[] { "Installing.", "Installing..", "Installing..." };

            while (!installFinished)
            {
                Action.Text = dots[++k % 3];
                await Task.Delay(TimeSpan.FromSeconds(1.0));
            }
            Action.Text = "Finished";
            MessageBox.Show("Test");
        }
        else
        {
            this.TopMost = false;
            int num = (int)MessageBox.Show("dotnetFx45.exe not found", "Error");
        }
    }
}


text:
Q: Getting undefined error while processing array I have 2 arrays like below:
$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]
$scope.selected = [{ val:12} , { val:13} ] //based on checkbox  selection

Now i just want to add selected value to Statistics array and remove those which doesnt exist in selected but ignoring 1st record of statistics.
Expected output
$scope.Stat.Statistics ={[ val:10]} , {[ val:12]} , {[ val:13]}

Code:
for (var i = 0; i < selected.length; i++) {
    for (var j = 1; j <= $scope.Stat.Statistics.length; j++) {
        //ignore 1st record for comparision
        if (selected[i].val != $scope.Stat.Statistics[j].val) {
            $scope.Stat.Statistics.splice(j, 1);
            $scope.Stat.Statistics[j].push(selected[i]);
        }
    }
}

Update:In case of same value in Statistics and selected  i would like to keep statistics value.

Error:$scope.Stat.Statistics[j] is undefined

A: $scope.Stat.Statistics ={[ val:10]} , {[ val:11]} , {[ val:13]} ,{[ val:14]}

This is not valid Javascript. If you want an array, you should be defining it like:
$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]

var Statistics = [{
  val: 10
}, {
  val: 11
}, {
  val: 13
}, {
  val: 14
}];

var selected = [{
  val: 12
}, {
  val: 13
}];

var found = selected;
Statistics.map(function(statistic) {
  selected.map(function(selectedItem) {
    if(selectedItem.val === statistic.val) {
      found.push(selectedItem);
    }
  });
});

console.log(found);

Of course, I've factored out the Angular element out of it, but this same logic should work.

A: You could take the first element of $scope.Stat.Statistics, you want to keep and concat $scope.selected to the first element.

var $scope = { Stat: {} };

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];
$scope.Stat.Statistics = [$scope.Stat.Statistics[0]].concat($scope.selected);

console.log($scope.Stat.Statistics);

Edit: keeping common items with same val and append the rest to the array.

var $scope = { Stat: {} },
    hash = {},
    i;

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13, extra: 42 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];

$scope.selected.forEach(function (a) {
    hash[a.val] = a;
});

i = $scope.Stat.Statistics.length;
while (i--) {
    if (hash[$scope.Stat.Statistics[i].val]) {
        delete hash[$scope.Stat.Statistics[i].val];
        continue;
    }
    if (i === 0) {
        continue;
    }
    $scope.Stat.Statistics.splice(i, 1);
}
Object.keys(hash).forEach(function (k) {
    $scope.Stat.Statistics.push(hash[k]);
});

console.log($scope.Stat.Statistics);


text:
Q: Two Separate getTime() Calls Return Same Value at Different Times I am making an app that saves when the user enters a location and exits. I have to separate Date objects for this. When I print out the values, they return the same exact time although they are saved at a different time. Any ideas what may be causing this?
My checkLocation() method:
private void checkLocation() {
            float[] distance = new float[2];
            for(int i = 1; i <= AssetLoader.getTotalLocations(); i++) {
                float mItemLat = AssetLoader.getItemLatitude(String.valueOf(i));
                float mItemLong = AssetLoader.getItemLongitude(String.valueOf(i));

                Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(),
                        mItemLat, mItemLong, distance);

                if(distance[0] > 55){
                    Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + "55", Toast.LENGTH_LONG).show();
                    if(startDate != null) {
                        stopDate = calendar.getTime();
                        Log.e("STOP DATE", "SAVED");
                        saveTimeDifference(startDate, stopDate, String.valueOf(i));
                    }
                } else {
                    Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + "55", Toast.LENGTH_LONG).show();
                    if(startDate == null) {
                        startDate = calendar.getTime();
                        Log.e("START DATE", "SAVED");
                    }
                }
            }
        }

Where time difference and other stuff gets calculated:
public static void saveTimeDifference(Date startDate, Date endDate, String id) {
        //TODO: FIX THIS

        //milliseconds
        long difference = endDate.getTime() - startDate.getTime();
        AssetLoader.setItemTimeDifference(id, difference);

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : "+ endDate);
        System.out.println("difference : " + difference);

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = difference / daysInMilli;
        difference = difference % daysInMilli;

        long elapsedHours = difference / hoursInMilli;
        difference = difference % hoursInMilli;

        long elapsedMinutes = difference / minutesInMilli;
        difference = difference % minutesInMilli;

        long elapsedSeconds = difference / secondsInMilli;

        Log.e("saveTimeDifference()", elapsedDays + " days, " + elapsedHours + " hours, " + elapsedMinutes + " minutes, " + elapsedSeconds + " seconds");

        AssetLoader.setItemDetails(AssetLoader.getItemName(String.valueOf(id)), AssetLoader.getItemDetails(AssetLoader.getItemName(String.valueOf(id))) + "\nStart Date: " + startDate + " Stop Date: " + startDate);

    }

Please note that the current time is being accessed at different times. It seems to save it wrong or return the wrong time when getTime() is called on the GregorianCalendar object.
Thanks for any suggestions!

A: The accepted Answer by Andreas is correct.
java.time
If you are doing more date-time work, consider using the new java.time framework which supplants the troublesome old date-time classes.
UTC
To get the current moment on the timeline in UTC with a resolution up to nanoseconds, use Instant.
Instant now = Instant.now();

Immutable objects
The classes in java.time use the Immutable Objects pattern. Each instance's values never change (never "mutate"). So when you want to know the current moment again, call Instant.now again to create another instance of Instant.
Resolution
In Java 8 that current moment is captured with a resolution up to milliseconds, rather than the class' capability of handling nanoseconds. This limitation is due to the use of a legacy implementation of Clock. In Java 9 a new implementation of Clock captures the current moment in up to the full nanosecond resolution depending on your computer's hardware clock.
Zoned
While it is generally best to store date-time values in UTC, for presentation you may want to display the values in a time zone expected by the user.
To adjust that Instant into a particular wall-clock time, apply a time zone (ZoneId). Specify a proper time zone name, never the 3-4 letter abbreviations like EST or IST.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( now , zoneId );

Elapsed
To track an elapsed span of time in terms of days-hours-minutes-seconds, use the Duration class. As a textual representation, this class parses and generates Strings using standard ISO 8601 formats such as PT1H30M for one and a half hours.
Duration duration = Duration.between( startInstant , stopInstant );
String output = duration.toString();

You can get the total number of nanoseconds or seconds or minutes or hours or days in this span of time.
Oddly, the Duration class in Java 8 lacks methods to conveniently interrogate for the days part, hours part, minutes part, and seconds part. Java 9 brings such methods.
For spans of time in years-months-days, use the Period class.

A: calendar.getTime() returns a java.util.Date object for the time currently stored in the Calendar object.
When a Calendar is initially obtained by calling Calendar.getInstance() (or other means), it has the "current time".
It will still have that same time 5 hours later. It is not a "live" time, so multiple calls to calendar.getTime() will get the same value.
If you want to capture the current time, just call new Date():
Date startDate = new Date();
// do work
Date stopDate = new Date();
long difference = endDate.getTime() - startDate.getTime();
System.out.println("Work took " + difference + "ms");


text:
Q: Having unstable layout in App using phonegap & jquery mobile after returning from webview in iphone Hi Can some one help me out to fix my issue. I am using jquery mobile with cordova to build ios App. When i trigger an external
link from my App and return back to App having unstable layout. Can someone tell why the issue is. Thanks in advance.


text:
Q: prevent drop inside a child element when drag & dropping with JS I've created a simple drag and drop setup, 2 divs that allow a user to drag a child div between the two. It works fine unless a 'child div' is dropped directly inside another. I've been trying to wrap my head around it for hours and there must be a simple solution i am missing.
You can see a (not quite) working demo here
https://preview.c9.io/teemoash/fantasyleague/gamething/pete.html?_c9_id=livepreview4&_c9_host=https%3A%2F%2Fide.c9.io
any help is greatly appreciated
Thanks!
The html is very simple. ( note that i have tried returning false on onDrop and onDragOver events)

SQUAD

Jeff

 4
Kills

2
Deaths

 12
GPM

Geoff

 7
Kills

0
Deaths

 14
GPM

Jeph

 1
Kills

9
Deaths

 24
GPM

My Team

My Team Scores

and the js looks like this;

A: The problem is that the drop is tied to the event, but the way you have it it should just be tied to the element like this:
function drop(ev, el) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  el.appendChild(document.getElementById(data));
}

Then change your drop(event) to drop(event, this) in your two ondrop events. Take a look at the snippet in Full Page mode to see that it works.

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev, el) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  el.appendChild(document.getElementById(data));
}
* {
  margin: 0;
  box-sizing: border-box;
}
#squad {
  width: 40vw;
  height: 90vh;
  overflow-y: scroll;
  border-radius: 10px;
  margin-left: 5vw;
  margin-top: 5vh;
  background-color: red;
  float: left;
}
h1 {
  text-align: center;
}
#myTeam {
  float: left;
  height: 60vh;
  width: 40vw;
  border-radius: 10px;
  background-color: red;
  margin-left: 10vw;
  margin-top: 5vh;
}
#scores {
  width: 40vw;
  height: 25vh;
  margin-top: 5vh;
  margin-left: 10vw;
  background-color: red;
  border-radius: 10px;
  float: left;
}
.champion {
  width: 90%;
  height: 15vh;
  margin: 1%;
  padding: 2%;
  border: 1px black solid;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
}
.champion h1 {
  float: left;
}
.attributes {
  margin-left: 10%;
  float: left;
}
.number {
  float: left;
  text-align: center;
  margin-left: 10px;
}
#div1,
#div2 {
  width: 90%;
  height: 15vh;
  margin: 1%;
  border: 1px black solid;
  border-radius: 10px;
}

SQUAD

Jeff

 4

Kills

2

Deaths

 12

GPM

Geoff

 7

Kills

0

Deaths

 14

GPM

Jeph

 1

Kills

9

Deaths

 24

GPM

My Team

My Team Scores


text:
Q: Uninstall android application with out user interaction I am developing android system application. Directly Uninstall another application without user interaction.
I have wrote peace of code ,
private void UninsallApp() {
    Uri packageURI = Uri.parse("package:"+"com.example.shortcutcreation");
    Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
    startActivity(uninstallIntent);
}

but before uninstall app dialog box is coming like

Could you please help me...

A: I got solution for this question.
I have cracked code AOSP framework level(android.content.pm) and signed as a ploatform apk ...
Finally app is silently uninstalling...
or
String cmd = "sh /system/bin/pm uninstall " + packageName;
    try {Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
        outputStream.writeBytes(cmd+"\n");
        outputStream.flush();
        outputStream.writeBytes("exit\n");
        outputStream.flush();
        su.waitFor();

    } catch (IOException e) {

        throw new RuntimeException(e);

    } catch (InterruptedException e) {

        throw new RuntimeException(e);
    }


text:
Q: Show that If $T$ and $S$ are Isometric Transformations, so is $TS$ I know that - $T$ is Isometic $ \iff\left\| Tv \right\| = \left\| v \right\|$
So my proof is as such:
$\left\| TS(v) \right\| = \left\| T\circ S(v) \right\| = \left\| T(S(v)) \right\| = \left\| S(v) \right\| = \left\| v \right\|$
With the last two steps using the iff statement above.
Is my proof correct? can I use that iff statement for that proof?
(Hopefully I translated the words well, I dont study Algebra in English)

A: $\left\| TS(v) \right\| = \left\| T\circ S(v) \right\| = \left\| T(S(v)) \right\| = \left\| S(v) \right\| = \left\| v \right\|$


text:
Q: Is it a coffeescript bug? Destructuring and Existential Operator following coffeescript code:
{ baz } = @foo.bar?

produces:
var baz;
baz = (this.foo.bar != null).baz;

but I expect:
var ref, baz;
if ((ref = this.foo.bar) != null) {
  baz = ref.baz;
}

Is it a bug or an expected behavior?

A: I think you've confused the unary ? operator with the binary ?. operator.
The right-hand side of this expression:
baz = @foo.bar?.baz

...uses the binary ?. operator. As you know, it returns the value of the subsequent property if it exists and null otherwise (and short-circuits evaluation of further properties).
On the other hand, the RHS of this expression:
{ baz } = @foo.bar?

...uses the unary ? operator. It returns false if its operand (the preceding expression) is null or undefined, and true otherwise.
This is a really easy mistake to make; you can see someone ask the same question in this CoffeeScript issue. Compounding the problem, the CoffeeScript docs don't even give these two operators different names. They call ? the "existential operator" and ?. the "accessor variant of the existential operator."


text:
Q: Why isn't the a-frame click event working? I'm trying to figure out why my console isn't recording my log statements in my click event handlers. Any help would be greatly appreciated.
Here's my JS Fiddle. https://jsfiddle.net/tznezkqo/
I'm using A-Frame version 5.0
Here's my HTML
 <!-- Player -->
  <a-entity camera universal-controls="movementControls: checkpoint" checkpoint-controls="mode: animate"
            position="0 1.764 0">
    <a-entity cursor="fuse: true; fuseTimeout: 500" position="0 0 -1"
              geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03;" material="color: #CCC; shader: flat;">
    </a-entity>
  </a-entity>

  <a-entity id="box" cursor-listener geometry="primitive: box" material="color: blue" position="-2 2.2 -1.5"></a-entity>

and my JS
$(document).ready(function() {

  AFRAME.registerComponent('cursor-listener', {
    init: function () {
      this.el.addEventListener('click', function (evt) {
        console.log('I was clicked at: ', evt.detail.intersection.point);
      });
    }
  });

  AFRAME.registerComponent('collider-check', {
    dependencies: ['raycaster'],
    init: function () {
      this.el.addEventListener('raycaster-intersected', function () {
        console.log('Player hit something!');
      });
    }
  });

});

A: I believe you'll have to make sure the component is registered before the elements are used.
here's a modified version of your example: https://jsfiddle.net/pj3m4obt/2/
<script>
AFRAME.registerComponent('cursor-listener', {
    init: function () {
         this.el.addEventListener('click', function (evt) {
        console.log('I was clicked at: ', evt.detail.intersection.point);
      });
    }
  });
</script>
<body>
...
<a-entity id="box" cursor-listener geometry="primitive: box" material="color: blue" position="-2 2.2 -1.5"></a-entity>


text:
Q: Sphinx extended match mode I'm using a sphinx bundle (timewasted SphinxSearchBundle) in a symfony 2 app (https://github.com/timewasted/Search-SphinxsearchBundle) (based on the PHP API)
it works great as long as I don't try to use the SPH_MATCH_EXTENDED.
Here's a code sample
$sphinxSearch = $this->get('search.sphinxsearch.search');
$sphinxSearch->setMatchMode(SPH_MATCH_EXTENDED);
$searchResults = $sphinxSearch->search("@typemesure_id 2", $index);

But the result is always empty, and it seems that my field (@typemesure_id) is considered as a word :
  'words' =>
    array
      'typemesure_id' =>
        array
          'docs' => string '0' (length=1)
          'hits' => string '0' (length=1)
      2 =>
        array
          'docs' => string '4169' (length=4)
          'hits' => string '5714' (length=4)

Does anyone konws whats wrong in my request ?
Can anyone post an exemple of working extended query working with this bundle?
My goal is to get a condition like "@(user1,user2,user3) 15"
Thanks for your help
Notes:
the SPH_MATCH_ALL & SPH_MATCH_ANY are working fine.
The setFilter() method is also working

A: Looking at the function defition...
public function search($query, array $indexes, array $options = array(), $escapeQuery = true)

It will automaticlly escape the query, so the @ will be getting escaped. Need to pass false as fourth param


text:
Q: Shouldn't the first verb in "she died before I was born" be in the past perfect? Quote from English book:

Sadly, I never got to meet her because she died before I was born.

I think it should be: Sadly, I never got to meet her because she "had" died before I was born.
I think it should be in past perfect because the death took place before the birth and both events are in the past.
Why was the past perfect not used here?

A: An action or state prior to another in a narrative sequence in the past tense is not automatically cast in the past perfect, especially with subordinating conjunctions that order a sequence by themselves, like after, before, once, until. If some action/state occurs between the two events, or if the completion of the prior event is topical, or even if the intervening time is itself significant, writers will frequently choose the past perfect. If one of these conditions is not met, then the verbs will usually remain in the past tense.
Compare these two sentences:

Ong's works were not fully recognized until he left Los Angeles for New York in 1994, where he won recognition from Robert Brustein, the artistic director of the American Repertory Theater…  — Miles Xian Liu, Asian American Playwrights: A Bio-bibliographical Critical Sourcebook, 2002.
It was not until he had left school, home, and Manchester that he began to change and grow. — AW Jones, Herbert Hamilton Kelly SSM, 1860-1950, diss., Univ. Nottingham, 1971.

The first sentence establishes a simple narrative sequence: the topic is the recognition the playwright received in New York after he moved there. Neither the move itself nor his former address is significant. The move bears no relationship to his recognition. It merely happened after the move.
In the second sentence, the author infers that Kelly's personal development was limited by his earlier life in Manchester.   His departure is topical, i.e., the act of leaving home, family, and birthplace facilitated this development. Thus the use of the past perfect.
If someone dies before some other event takes place, it can simply be a matter of "this happened, then that happened," both events narrated in the past tense:

Dorothy Wrinch died before I went to Moscow; she never knew about my conversation there with Nikolai Vasilevitch Belov, Academician, past president of the International Union of Crystallography, Honorary member of the Mineralogical Societies of the USSR, USA, Great Britain, and France, Hero of Socialist Labor, … — Marjorie Senechal, I Died for Beauty: Dorothy Wrinch and the Cultures of Science, 2012.
I never knew my father's parents, they died before I was born. I never knew my mother's father, he died before I was born. But I really knew my grandmother. I spent as much time as I could with her. My grandmother was a rich old lady living in Brooklyn—or so we thought (about being rich I mean). She always bought us ice cream… — Helaine Krob, The Road Rises Up, 2002.

In both these sentences, neither the death nor any event in the intervening time is topical. In the first sentence, it's the conversation with Belov; in the second, the memories of the author's grandmother.
In this sentence, however, the author narrates the death of a half-sister whom he only knew from scant family lore. He also wonders if she ever existed:

Now, I knew that my mom had been married before she met my dad, but I was raised to believe that her little girl had died before I was born—as an infant or toddler. I don't imagine that I'll ever know whether the certificate is in error or whether I had a "half-sister" whom I never saw.  – Jim Walker, Before I Go: My First Fifty-Six Trips Around the Sun, 2003, 20.

Because this unsatisfied curiosity is topical, the author chose the past perfect.
In this sentence, the author wonders about a long dead relative and recalls family stories about him. The death is in the past perfect and the lack of personal knowlege and family lore are narrated in the past tense.

At some point I voiced this idea and my father said, "No, they belonged to my Grandad." My own grandfather had died before I was born so I never saw his face nor heard his voice. My parents often spoke of him and repeated remarks he had made.  — B. Marie Mollohan, The Banks of the Holly, 2005, 1.

Since your example is a single sentence crafted as an illustration in a textbook, i.e., not "real" language with a context, it is impossible to say whether, were a context supplied, it would be more appropriate in the past or past perfect. The examples given here, however, sould give you some idea of which context goes with which tense: narrative sequence, past; topicality, past perfect.


text:
Q: MySQL error: Lock wait timeout exceeded; try restarting transaction We have a script that runs at 5:15am and retrieves data from 36 remote sites. A separate instance of the script runs for each site, so all 36 run at the same time. The data ranges from 400K to 1MB.
When the data comes in from the remote site, the script tries to delete rows for the same date and site id in our MySQL database and then insert the new data. We frequently get this error:

Lock wait timeout exceeded; try restarting transaction mysql

when it tries to delete the old rows. Sometimes the script just stops responding with no error message.
Does the error mean that it can't delete or insert the data because the table is locked?
How can we fix this?
Is there a way to have the delete/insert SQL queue up and wait for the table to become unlocked?
We have many other scripts that insert data from all 36 sites, but we are only having this error with 2 of our scripts. These 2 scripts happen to bring back far more data than any other script.

A: This isn't exactly the answer I was hoping for, but I have a workaround. When PHP tries to delete/insert the data into MySQL, it checks the return value to see if there were any errors. If it finds the lock wait error, it will retry for up to 10 minutes to insert the data. Since this change was made it appears to have fixed the issue. BTW, we use PDO for everything.


text:
Q: JQuery Validate - Confirm email form validation I have a quiz, and i need to add some validation to a confirm email address field, basically it just has to match the email address given in the above field. I am using the following javascript, can i add something in here which will make sure the emails match?
if ($('#mtQuiz').length > 0) {
    $('#myQuiz').validate({
        errorElement: "em",
        errorContainer: $("#warning"),
        rules: {
            'entry[first_name]':            'required',
            'entry[last_name]':     'required',
            'entry[email]': {
                required: true,
                email: true
            },
            'entry[confirm_email]': {
                required: true,
                email: true
            }
        },
        messages: {
            'entry[first_name]':    'Please enter first name',
            'entry[last_name]': 'Please enter last name',
            'entry[email]': {
                required: ' Please enter a valid email address',
                minlength: 'Not a valid email address'
            },
            'entry[confirm_email]': {
                required: ' Please make sure email matches above',
                minlength: 'Does not match above email address'
            }
                      }
    });
}

A: if ($('#mtQuiz').length > 0) { // <- unnecessary and superfluous
    $('#myQuiz').validate({
        // options, etc.
    });
}

You're using jQuery so you don't need to check for the existence of #myQuiz with if ($('#mtQuiz').length > 0).  If the #myQuiz element doesn't exist, jQuery will simply ignore it without any errors.
This is all you need to do...
$('#myQuiz').validate({  // initialize the plugin
    // options, etc.
});

To match the value of another field, simply use the equalTo rule.  While using the equalTo rule, there is no need to duplicate any of the other rules since equalTo will always force the value to match the primary field's value which already followed its rules.
$('#myQuiz').validate({
    // options, etc.,
    rules: {
        'entry[first_name]': 'required',
        'entry[last_name]': 'required',
        'entry[email]': {
            required: true,
            email: true
        },
        'entry[confirm_email]': {
            //required: true,  // <- redundant, not needed with 'equalTo'
            //email: true      // <- redundant, not needed with 'equalTo'
            equalTo: '[name="entry[email]"]' // <- any valid jQuery selector
        }
    },
    // other options, etc.
});

DEMO:  http://jsfiddle.net/JCY2E/

A: Have a look to equalTo method.
$('#myQuiz').validate({
  ...
  rules: {
    ...
    'entry[confirm_email]': {
      equalTo: "entry[email]"
    }
  }
});


text:
Q: CFWheels - How to highight which posts a user has commented on? I have a basic query to get all 'posts' in my database table 'posts'. Users who are logged in can comment on these posts. However, I want to be able to highlight (when viewing all posts) which ones the user has commented on before.
My query at the moment looks like this:
<cfset posts = model("post").findAll(

            select = "

                posts.postID,
                postTitle,
                postPoints,
                postAuthority,
                postCreated,
                postDescription,

                postCommentCount,
                postUpVoteCount,
                postDownVoteCount,

                users.userID,
                userName,

                categories.categoryID,
                categoryTitle,
                categoryToken",

            include     = "user,category",
            order       = "postPoints DESC",
            page        = params.page,
            perPage     = params.pageQuantity

        ) />

I get all posts and join the user who created the post along with the category info etc.
How can I modify this, so that if the user is logged in, they'll be able to see which posts they've already commented on? The amount of comments the user has made isn't that important, just if the user has commented at all.
I'd prefer not to run a query on every post to check this. Ideally, it'd be good to join the count in with this query.
In addition to this, I have 3 queries in the posts model:
 <cfset property(name="postUpVoteCount", sql="SELECT COUNT(*) FROM votes WHERE votes.postID = posts.postID AND votes.voteType = 1") />
        <cfset property(name="postDownVoteCount", sql="SELECT COUNT(*) FROM votes WHERE votes.postID = posts.postID AND votes.voteType = 0") />
        <cfset property(name="postCommentCount", sql="SELECT COUNT(*) FROM comments WHERE comments.postID = posts.postID AND comments.commentRemoved = 0") />

Could I utilise that in my query?
Any ideas?
Thanks,
Mikey.


text:
Q: Retrieving PCDATA with pugixml and xpath I spent the last week reading and re-reading the pugixml documentation and I can find no method of retrieving the PCDATA with xpath.
Please explain would I pull the text from title:
<title>Hello!</title>

Edit: corrected CData to PCData

A:
Please explain would I pull the text from title:
<title>Hello!</title>

One XPath expression that selects this text node is:
/*/head/title/text()

If just the string value is wanted (and not the text node), use:
string(/*/head/title)