text:
Q: jQuery on("submit") does not bind to elements loaded with ajax because it is inside another form I have a table of items.
The first column of each row contains a checkbox input as part of a form.
The user can click on these checkboxes and then click submit to do bulk actions such as delete items.
I have setup (using jquery) a situation whereby on clicking the 'Add data' link in a row column, a DIFFERENT form is loaded into a third column in which a user can enter item data.
What i then want to do is use ajax to submit this second form. To do this I am using the following code:
$(document).on('submit',".add_form",function(event)
{

    event.preventDefault();

    var serial=$(this).serialize();

    var domain=$('[name=domain]').val();

       $.ajax({
     url:"portfolio/transactions/"+domain+"/",
     type:"post",
     data: {data:serial},
     success: function(dat){
$('#transactions_div').html(dat);
     }
   });

});

This however does NOT work, and I believe this is because html does not allow forms within forms. My assumption is that jQuery follows such standards and is getting confused when a second form is loaded into a div which is contained within another set of  tags.
Given this, is what I want to do simply not possible?
THanks

A: Try this:
$(document).on('submit', ".add_form", function (event) {

    event.preventDefault();
    var serial = $(this).serializeArray();
    var domain = $('[name=domain]').val();

    $.ajax({
        url: "portfolio/transactions/" + domain + "/",
        type: "POST",
        data: serial,
        success: function (data) {
            $('#transactions_div').html(data);
        }
    });
});

A: HTML
<form class="add_form">
    <form class="secondForm">
        <input type="checkbox" />
    </form>
    <input name="domain" type="text" />
    <!-- Replace the submit-Button with a normal button -->
    <input type="button" value="Send" id="send"/>
</form>

JS
$(document).on('click', "#send", function () {

    var serial = $(".add_form").serialize();
    var domain = $('[name=domain]').val();

    $.ajax({
        url: "portfolio/transactions/" + domain + "/",
        type: "post",
        data: serial, // serial instead of {data : serial}
        success: function (dat) {
            $('#transactions_div').html(dat);
        }
    });
});


text:
Q: How to call function indirectly in Kotlin Assume I have a mutableMap:
val MM = mutableMapOf()

Now I define a function as a method for it:
MM["testF"] = fun () {
  println("WOW")
}

Now I want to call it in another place:
val MMTF = MM["testF"] as Function<*>
MMTF() <-- NOT WORKING

Any help will be appreciated.

A: This code will print bar
fun main() {
    val map = mutableMapOf<String, () -> Any>()
    map["foo"] = {
        println("bar")
    }
    run(map["foo"]!!)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Windows XCOPY fail when invoked via Perl system call via psexec? I'm using psexec to launch a Perl program on remote Windows machines. The program makes a system call to xcopy.This works fine when run directly (locally) on the machines, but when run remotely via psexec, the xcopy fails with the following message:

File creation error - Incorrect function.

(Depending on the user, the message may instead be "Access denied.")
Note that $! gives the following diagnostic:

Bad file descriptor at syscall.pl.
  perl exited on REMOTE with error code 9.

It does not seem to make a difference whether xcopy is invoked via system() or backticks.
I should point out that the "from" folder is a ClearCase dynamic view (M drive).
Oddly enough, the xcopy seems to work correctly when called directly from psexec.
Here are some other oddities:

*

*The xcopy doesn't always fail. Certain files just seem to be "cursed". The read-only attribute appears not to be a factor.

*Once a copy succeeds (e.g., via Windows Explorer), the curse is lifted, and that particular file will no longer cause xcopy errors.

*The problem does not seem to be with the destination folder. Once the curse is lifted, the file can be xcopy'd to a new destination.
Following is a portion of the test Perl script I used to narrow down the problem (folder names have been genericized).
Note that, for each "my $cmd" tested, I commented out the previous one, and added a status comment.
# ClearCase directory M:\STUFF\ABC contains ABC.tst, ABC.zip and several nonempty subfolders

# Directory copy, D drive to D drive
#my $cmd = "xcopy D:\\temp\\src D:\\temp\\dest /e /i /y";
# works

# Directory copy, M drive to D drive
#my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest /e /i /k /y";
# fails with "File creation error - Incorrect function" or "Access denied"

# File copy (.tst), M drive to D drive (trailing backslash)
#my $cmd = "xcopy M:\\STUFF\\ABC\\ABC.tst D:\\temp\\dest\\";
# works!

# Directory copy, M drive to D drive (trailing backslash)
#my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest\\ /e /i /k /y";
# copies the .tst file, but fails on the .zip (yes, the .tst file is now getting copied)

# Directory copy, M drive to D drive (same as above but without trailing backslash)
#my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest /e /i /k /y";
# copies the .tst file, but fails on the .zip

# File copy (.zip), M drive to D drive
#my $cmd = "xcopy M:\\STUFF\\ABC\\ABC.zip D:\\temp\\dest";
# fails

# File copy (.zip), M drive to D drive (trailing backslash)
#my $cmd = "xcopy M:\\STUFF\\ABC\\ABC.zip D:\\temp\\dest\\";
# fails

# After manually (Windows Explorer) copying the .zip file to the dest folder and deleting it
# Directory copy, M drive to D drive with /c (continue after failure)
#my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest /c /i /e";
# copies the .tst and .zip file (!), but fails on all other files (folders were successfully created)

# After manually copying the Folder1 folder to the dest folder and then deleting it
#my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest /c /i /e";
# copies the .tst and .zip file and the contents of Folder1(!), but fails on all other files

# Different dest:
my $cmd = "xcopy M:\\STUFF\\ABC D:\\temp\\dest1 /c /i /e";
# Same results as immediately above

print "Executing system command: $cmd ...\n";
system ($cmd);
#print(`$cmd 2>&1`); #same

A: I suggest that instead of using the xcopy command, you do the copying using Perl itself. There's a module File::Copy::Recursive that's pretty simple to use. It's not part of the standard Perl distribution, so you have to install it using cpan.
If you don't want to use non-native modules, you can try using File::Find to find the files in a directory, then combine that with File::Copy.
Found two examples on Perl Monks. One using the combination and the other using File::Copy::Recursive
Yes, this isn't answering your question directly, but you should try to avoid using system commands when possible. When you interact with the system shell and command processor (especially when ClearCase hacks with the file system), you can end up with a lot of unintentional interactions that can cause something to work in some situations, but not others.
To figure out the issue you're having with a system call, you'll have to assume the error could be in ClearCase, the cmd.exe shell, the xcopy command, or Perl. By not using the system command, you've simplified your problem, and many times actually speed up the process.

A: Try redirecting INPUT from the null device to see if your xcopy works.  I don't know why, I encountered this problem a long time ago and somehow (possibly via web search) figured this out.
It would look something like this:
xcopy /args $source $target <nul:;
(Backticks around entire command not showing up)
JKE

A: Have you tried system with a list of arguments?
my @args= qw(M:\STUFF\ABC D:\temp\dest1 /c /i /e);
warn "Executing 'xcopy @args' ...\n";
system xcopy => @args;

A: File::Copy::Recursive may solve your problem.
This way you have a more controled way of copying files. You could wrap this call to an eval block and apply some kind of retry logic there?
Maybe a "dummy update" on the problematic file help? Change the attribute/timestamp of the file or rename it to something else and rename it back...

A: If you look at how ClearCase manages read/write access for Vob and views, you will see that there is a difference between:

*

*reading the content of a directory (need r-x)

*reading a file within a directory (need just '--x' on the directory + "r--" on the file)

So depending on which user is behind the process launching the xcopy, you can have trouble reading/accessing certain directories/files.
And you need to make sure that use has set the CLEARCASE_PRIMARY_GROUP to the right value (ie a group listed as primary group of the vob, or one of its secondary group), in order to access the Vob (but if its protections are lax enough, everyone can access it anyway).
All that applies for a dynamic view, and would apply only for the update of a snapshot view (once the update is completed, you get files copied locally, and which can be read by any process).


text:
Q: Malloc pointer being freed was not allocated error when calling initWithBitmapData When I create a CIImage by calling this routine I get the malloc error in the title.  When I call initWithBitmapData directly (not within the createCIUimageFromData routine) then it works fine.
I have seen references to possible bugs in iOS that might be related, but I can't tell for sure and I certainly suspect my code more than Apple's!
My guess is somehow my additional redirection is screwing things up, but it's cleaner to have the separate routine than to embed the code wherever I need it.
Thank you.
Fails:
- (CIImage *) createCIimageFromData : (unsigned char *)pData   width : (int32_t)width height : (int32_t)height
{

    /*
     Once we have the raw data, we convert it into a CIImage.
     The following code does the required work.
     */
    NSLog(@"entering createciimage\n");
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();

    NSData *_pixelsData = [NSData dataWithBytesNoCopy:pData length:(sizeof(unsigned char)*width*height) freeWhenDone:YES ];
    CIImage *_dataCIImage = [[CIImage alloc] initWithBitmapData:_pixelsData bytesPerRow:(width*sizeof(unsigned char)) size:CGSizeMake(width,height) format:kCIFormatR8 colorSpace:colorSpaceRef];

    CGColorSpaceRelease(colorSpaceRef);

    /*
     newImage is the final image
     Do remember to release the allocated parts.
     */
    NSLog(@"done ciimage\n");
    return _dataCIImage;
}

Works:
void prepData(unsigned char *pData,  // source-destination
                           int strideSrc, // stride
                           int width,
                           int height,
                           double amount,
                           int deltaLimit,
                           id owner)
{

   //[owner createCIimageFromData:pData width:width height:height];  // <-- commented out
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();

    NSData *_pixelsData = [NSData dataWithBytesNoCopy:pData length:(sizeof(unsigned char)*width*height) freeWhenDone:YES ];
    CIImage *_dataCIImage = [[CIImage alloc] initWithBitmapData:_pixelsData bytesPerRow:(width*sizeof(unsigned char)) size:CGSizeMake(width,height) format:kCIFormatR8 colorSpace:colorSpaceRef];

    CGColorSpaceRelease(colorSpaceRef);

// . . .
}

A: Evidently the problem is caused when the NSData object attempts to free the data. To avoid the problem, use freeWhenDone:NO and then free the data after you're done with the CIImage.


text:
Q: Get HiddenField in JQuery inside Repeater I have a Repeater control, and I need to access a HiddenField inside. I can't use:
<%= Control.ID.ClientID %>

And I can't use the class or cssclass attributes either?
So my question is rather simple, how can I access my HiddenField control inside my repeater?
My scenario is that I populate a multiselectable dropdown, and I need to know in an update function which elements I have selected, for this I use the HiddenField to store the Id's. Then in code behind I can access the HiddenField values and make a propor databind.

A: HiddenField control elements are rendered to inputs of type hidden, so, albeit not thoroughly understanding your vague scenario with limited application, you can access them in jQuery with a selector like so:
$("input[type=hidden]")

Depending on your situation you might want to constrain that selector yet more.
However, this is focusing on your inclusion of the jquery tag, though your example seems to want to use inline ASP.NET script to use managed code. Please clarify your intentions and ultimate goal.

A: You can use the class selector
Put a class over the hidden field.
And on change event of multiselectable find the appropriate hidden field and set it's value.
Edit-1
I will suggest you to put a class say ddl over the multiselectable dropdown.
Bind jquery on change method on this multiselect.
Using jquery parent and prev selectors you can set the values in the hidden field.
Exmaple
     $(".ddl").change( function(){
        $(this).parent().next().find("input:hidden").val($(".ddl").val());
    });

This is just for and idea of my approach.
Edit 2
Here is a good example of how to use css-class over a hidden field.

Jquery Hidden Field

A: I found a solution which in fact is pretty easy :)
I used the ClientIDMode property on the HiddenField inside the repeater:
<asp:HiddenField ID="HiddenField_Pladser" runat="server" Value="Selected" ClientIDMode="Static" />

The ClientID value is set to the value of the ID property. Then it's easy in the JQuery script to access the value:
$("#HiddenField_Pladser").val();

And from the code behind I know the ItemIndex from the repeater, which makes it easy to create a data collection whit this code:
var data = from RepeaterItem item in rpPladser.Items
                   let hidden = ((HiddenField)item.FindControl("HiddenField_Pladser"))
                   select new
                              {
                                  selected = hidden.Value
                              };

Please leve a comment if this implementation have flaws or somehow is bad.


text:
Q: Purpose of Eclipselink 2.6.0 query - SELECT ID FROM TBL WHERE ID=? Has anyone got an idea why JPA Provider - Eclipselink (using version 2.6.0) generates query like:
SELECT ID FROM OPERATION WHERE (ID = ?);

or
SELECT ID FROM SUBSCRIPTION WHERE (ID = ?);

Why it needs to get ID providing an ID...
Maybe 1st or 2nd level Cache synchronization?
Maybe my queries are inaccurate...
In my queries I never ask directly this to execute - I use JPQL and never ask for ID giving some ID.
I have quite complex model and queries so I see no point in providing full code (or only if U really insist but I dont think it will help a lot).
Using Oracle 12c DB.

A: We have encountered the same issue with our Java application using EclipseLink 2.5.2. Specifically, we saw it whenever we inserted a new entity that had a M:1 relationship with another entity. A simplified use case would be:
A a = new A(); // the new entity
B b = lookupB(); // get existing entity from database
a.setB(b); // set M:1 relationship
em.persist(a); // save

In this case, we would always see a query for B (i.e., SELECT ID FROM B WHERE ID = @). After some research, we traced it down to the existence checking that EclipseLink performs before merging records.
We found that annotating the entity class for B with @ExistenceChecking(ExistenceType.ASSUME_EXISTENCE) prevented EclipseLink from running the query.
For a further discussion of this, see this related post.


text:
Q: How to make Tab bar transparent in native base android?
I want to make the tab bar transparent. I have tried changing its backgroundcolor to that of the screen put it still shows pushed out of the screen.
....

    *<Tabs
                tabBarUnderlineStyle={{backgroundColor: 'transparent'}}
                tabBarActiveTextColor={'white'}>
                <Tab heading="LOGIN">
                  <Tab1 {...props} />
                </Tab>
                <Tab heading="SIGNUP">
                  <Tab2 {...props} />
                </Tab>
              </Tabs>**
....


text:
Q: Faster alternatives to .Distinct() I'm making a video game where performance is critical.
I'm using the .Distinct() extension method to get unique value from a List.
Is there a faster way to do so? (even if it means having many more lines of code)

A: Does it have to be a List?
Would it be possible to switch from List, to HashSet? HashSet prevents objects from being inserted into the list more than once in the first place, so the Distinct is already done.

A: .Distinct is an O(n) call.
You can't get any faster than that.
However, you should make sure that your GetHashCode (and, to a lesser extent, Equals) is as fast as possible.
Depending on your scenario, you may be able to replace the List<T> with a HashSet<T>, which will prevent duplicates from being inserted in the first place.  (yet has O(1) insertion)
However, Always profile your code before jumping to conclusions about what needs to be faster.

A: If you can do the distinct in place, you can do it very quickly and with zero allocations by first using Array.Sort and then:
 TSource oldV = source[0];
 int pos = 1;
 for (int i = 1; i < source.Count; i++)
 {
     var newV = source[i];
     source[pos] = newV;
     if (!eqComparer.Equals(newV, oldV))
     {
        pos++;
     }
     oldV = newV;
 }
 //pos now == the new size of the array

You will then have to keep track of the now smaller size of the array, or use Array.resize (But that will allocate a new array)
Alternatively if you do this same approach with a List<T> you can call RemoveRange at the end to resize it without allocating. This ends up being significantly quicker.
Other posters are probably correct though that you can achieve this goal some other way, such as using a hashset in the first place, or keeping parallel collections where one contains only the distinct elements all the time. Offsetting small costs on insert/remove so that no time at all is required to get the distinct set.


text:
Q: Request for helping converting odd data frame in R I have some data that I've received from a company I work with but have no idea how to approach converting it to a wide data format that I can use for analysis. The data frame is 15,800,000 rows and only 5 variables. The 4th and 5th variables, however, are the name and response to one of the (~90) variables I have to work with. To make things more complicated, the questions were asked more than once, so have multiple responses.
Where there is more than 1 possible response, however, the responses knock over onto the next line (see below).
      id       date answer_instance                         pdl_variable_name answer_option
1  25839 2014-02-01               4                      discretspend (25228)            14
2  25839 2014-02-05              11                    legal_services (25495)          [99]
3  25839 2014-12-07               6                     comppen_company (706)          [97]
4  25837 2014-12-15               2               Affluence_V2_P_2014 (34264)             8
5  25837 2015-01-20               5      study_qualification_children (35100)          [98]
6  25837 2015-08-05               4                      overall_debt (27281)          [99]
7  25837 2015-09-03               3                 benefits_received (25465)          [98]
8  25834 2015-09-13               5                     privpen_company (707)          [96]
9  25834 2015-11-12               3            pocket_money_frequency (27076)            10
10 25835 2016-01-18               4               unemployment_status (21922)             6
11 25835 2016-02-05               8                    legal_services (25495)          [99]
12 25822 2016-02-11               3           assets_total_investable (26413)             3
13 25822 2016-03-03               2      disability_benefits_received (25055)          [99]
14 25822 2018-04-01               1               insurance_held_2018 (58085)            [1
15    4]
16 25811 2018-04-13               1                      insurance_held (615)            [1
17     4         11             20]
18 25811 2018-04-26               2                 profile_work_stat (25617)             5

Ideally, I'd like to convert this to a long/wide format that I can use for analysis.

A: If we ignore the format of the data for the multiple answers, you can dcast your data like this:
library(data.table)
dt <- data.table(df)
dt.wide <- dcast(
  formula =  date +  answer_instance ~ pdl_variable_name,
  data = dt,
  value.var = "answer_option"
)

For the multiple options your need to ask for the data in the format that you can read into a data.frame if you want to use R.
Having single cell on multiple lines is not the best way to exchange the data. If that is the only way you can ask to wrap values in quotes.
As your file is relatively big I recommend to use data.table which has fast fread function.

A: The major problem in data presented by OP seems to be single record spilling over next-line. Hence, once rows are arranged properly it will be pretty easy to convert data in any form for analysis.
Positive look-ahead ^(?=.*]) on ] and Negative look-ahead (?!.*\\[) on [ has been used to decide if a row is partial and is 2nd part of previous row.
The space and ( has of pdl_variable_name column has been changed to _( so that it can be read as single column using read.table
library(tidyverse)
library(splitstackshape)

# Read from text file linewise
df_line <- data.frame(fileText = readLines("Answer.txt"), stringsAsFactors = FALSE)

tidy_text <- df_line %>% mutate(rn = row_number()) %>%  # To merge partial row
  mutate(rn = ifelse(grepl("^(?=.*])(?!.*\\[)",df$fileText, perl = TRUE),lag(rn), rn)) %>%  #doesnot contain [ but contains ]
  group_by(rn) %>%
  summarise(fileText = paste0(trimws(fileText), collapse=" ")) %>%
  ungroup() %>%
  mutate(fileText = gsub("\\s(\\()", "_\\1", fileText)) %>%
  mutate(fileText = gsub("\\[|]", "\\'", fileText))  # [1 4] is changed to '1 4'

  # Concatenate rows prepared above separated by '\n' so that it read as dataframe
  tidy_data <- read.table(text = paste0(trimws(tidy_text$fileText), collapse="\n"), header = TRUE, stringsAsFactors = FALSE)

  #Use cSplit to split answers in multiple columns
  tidy_data  <- tidy_data %>%
    mutate(pdl_variable_name = gsub("_(\\()", " \\1", pdl_variable_name)) %>%
    cSplit("answer_option", sep=" ")

Result:
 tidy_data
 #       id       date answer_instance                    pdl_variable_name answer_option_1 answer_option_2 answer_option_3 answer_option_4
 # 1: 25839 2014-02-01               4                 discretspend (25228)              14              NA              NA              NA
 # 2: 25839 2014-02-05              11               legal_services (25495)              99              NA              NA              NA
 # 3: 25839 2014-12-07               6                comppen_company (706)              97              NA              NA              NA
 # 4: 25837 2014-12-15               2          Affluence_V2_P_2014 (34264)               8              NA              NA              NA
 # 5: 25837 2015-01-20               5 study_qualification_children (35100)              98              NA              NA              NA
 # 6: 25837 2015-08-05               4                 overall_debt (27281)              99              NA              NA              NA
 # 7: 25837 2015-09-03               3            benefits_received (25465)              98              NA              NA              NA
 # 8: 25834 2015-09-13               5                privpen_company (707)              96              NA              NA              NA
 # 9: 25834 2015-11-12               3       pocket_money_frequency (27076)              10              NA              NA              NA
 # 10: 25835 2016-01-18               4          unemployment_status (21922)               6              NA              NA              NA
 # 11: 25835 2016-02-05               8               legal_services (25495)              99              NA              NA              NA
 # 12: 25822 2016-02-11               3      assets_total_investable (26413)               3              NA              NA              NA
 # 13: 25822 2016-03-03               2 disability_benefits_received (25055)              99              NA              NA              NA
 # 14: 25822 2018-04-01               1          insurance_held_2018 (58085)               1               4              NA              NA
 # 15: 25811 2018-04-13               1                 insurance_held (615)               1               4              11              20
 # 16: 25811 2018-04-26               2            profile_work_stat (25617)               5              NA              NA              NA

Raw data:
Contents of answer.txt as provided by OP:
   id       date answer_instance                         pdl_variable_name answer_option
25839 2014-02-01               4                      discretspend (25228)            14
25839 2014-02-05              11                    legal_services (25495)          [99]
25839 2014-12-07               6                     comppen_company (706)          [97]
25837 2014-12-15               2               Affluence_V2_P_2014 (34264)             8
25837 2015-01-20               5      study_qualification_children (35100)          [98]
25837 2015-08-05               4                      overall_debt (27281)          [99]
25837 2015-09-03               3                 benefits_received (25465)          [98]
25834 2015-09-13               5                     privpen_company (707)          [96]
25834 2015-11-12               3            pocket_money_frequency (27076)            10
25835 2016-01-18               4               unemployment_status (21922)             6
25835 2016-02-05               8                    legal_services (25495)          [99]
25822 2016-02-11               3           assets_total_investable (26413)             3
25822 2016-03-03               2      disability_benefits_received (25055)          [99]
25822 2018-04-01               1               insurance_held_2018 (58085)            [1
4]
25811 2018-04-13               1                      insurance_held (615)            [1
4         11             20]
25811 2018-04-26               2                 profile_work_stat (25617)             5

A: library(readr)
library(tidyverse)
library(splitstackshape)

#read file
txt <- read_lines(file = "file_path/test.txt")

#identify continuation of previous row and add it to the previous row
idx <- which(grepl('\\]\\s+$', txt))
txt <- gsub("^\\d+\\s+", "", txt)    #remove row number from each row
txt[idx-1] <- paste(txt[idx-1], trimws(txt[idx]))
txt <- txt[-c(1,idx)]

#add a separator ";" to identify different columns in each row
txt <- gsub("(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+\\s+\\S+)\\s+(.*)", "\\1;\\2;\\3;\\4;\\5", txt)

#prepare data for analysis
df <- as.data.frame(txt) %>%
  cSplit("txt", sep = ";") %>%
  `colnames<-`(c("id", "date", "answer_instance", "pdl_variable_name", "answer_option")) %>%
  mutate(answer_option = gsub("\\[|\\]|(\\s{2})+", "", answer_option)) %>%
  separate_rows("answer_option", sep=" ")
df

Output is:
      id       date answer_instance                    pdl_variable_name answer_option
1  25839 2014-02-01               4                 discretspend (25228)            14
2  25839 2014-02-05              11               legal_services (25495)            99
3  25839 2014-12-07               6                comppen_company (706)            97
4  25837 2014-12-15               2          Affluence_V2_P_2014 (34264)             8
5  25837 2015-01-20               5 study_qualification_children (35100)            98
6  25837 2015-08-05               4                 overall_debt (27281)            99
7  25837 2015-09-03               3            benefits_received (25465)            98
8  25834 2015-09-13               5                privpen_company (707)            96
9  25834 2015-11-12               3       pocket_money_frequency (27076)            10
10 25835 2016-01-18               4          unemployment_status (21922)             6
11 25835 2016-02-05               8               legal_services (25495)            99
12 25822 2016-02-11               3      assets_total_investable (26413)             3
13 25822 2016-03-03               2 disability_benefits_received (25055)            99
14 25822 2018-04-01               1          insurance_held_2018 (58085)             1
15 25822 2018-04-01               1          insurance_held_2018 (58085)             4
16 25811 2018-04-13               1                 insurance_held (615)             1
17 25811 2018-04-13               1                 insurance_held (615)             4
18 25811 2018-04-13               1                 insurance_held (615)            11
19 25811 2018-04-13               1                 insurance_held (615)            20
20 25811 2018-04-26               2            profile_work_stat (25617)             5

Sample data:
      id       date answer_instance                         pdl_variable_name answer_option
1  25839 2014-02-01               4                      discretspend (25228)            14
2  25839 2014-02-05              11                    legal_services (25495)          [99]
3  25839 2014-12-07               6                     comppen_company (706)          [97]
4  25837 2014-12-15               2               Affluence_V2_P_2014 (34264)             8
5  25837 2015-01-20               5      study_qualification_children (35100)          [98]
6  25837 2015-08-05               4                      overall_debt (27281)          [99]
7  25837 2015-09-03               3                 benefits_received (25465)          [98]
8  25834 2015-09-13               5                     privpen_company (707)          [96]
9  25834 2015-11-12               3            pocket_money_frequency (27076)            10
10 25835 2016-01-18               4               unemployment_status (21922)             6
11 25835 2016-02-05               8                    legal_services (25495)          [99]
12 25822 2016-02-11               3           assets_total_investable (26413)             3
13 25822 2016-03-03               2      disability_benefits_received (25055)          [99]
14 25822 2018-04-01               1               insurance_held_2018 (58085)            [1
15    4]
16 25811 2018-04-13               1                      insurance_held (615)            [1
17     4         11             20]
18 25811 2018-04-26               2                 profile_work_stat (25617)             5

in test.txt


text:
Q: How can I use Flex in JSP project How can I use flex in my Java EE project and what new can I do with Flex as I'm unable to run flex application in Netbeans after installing Plugin and add SDK as well

A: I suggest you to read the following tutorial and duplicate its exercises if you are completely beginner: http://media.techtarget.com/tss/static/articles/content/Flex/Flex_Chapter20.pdf

A: Flex ultimately gets compiled to a SWF file. If you have seen some Flash animation on a webpage, click view source, thats how it would look like. JSP will generate the html with the SWF file embedded in it. There are free IDEs for flex like flashdevelop.
You can also develop flex apps using plain text editor and flex sdk just like java.


text:
Q: no viable alternative at input I have a small interrogation concerning my grammar.
I want to parse strings, like the following :
 "(ICOM LIKE '%bridge%' or ICOM LIKE '%Munich%')"

I ended up with the following grammar (a bit more complex than needed I know) :
// Aiming at parsing a complete BQS formed Query
grammar Logic;

options {
    output=AST;
}

tokens {
  NOT_LIKE;
}

/*------------------------------------------------------------------
 * PARSER RULES
 *------------------------------------------------------------------*/
 // precedence order is (low to high): or, and, not, [comp_op, geo_op, rel_geo_op, like, not like, exists], ()
 parse
    : expression EOF -> expression
    ; // ommit the EOF token

 expression
    : query
    ;

 query
    : term (OR^ term)*    // make `or` the root
    ;

 term
    : factor (AND^ factor)*
    ;

 factor
  :  (notexp -> notexp) ( NOT LIKE e=notexp  -> ^(NOT_LIKE $factor $e))?
  ;

 notexp
  :  NOT^ like
  |  like
  ;

 like // this one has to be completed (a lot)
    : atom (LIKE^ atom)*
    ;

 atom
    : ID
    | | '(' expression ')' -> expression
    ;

/*------------------------------------------------------------------
 * LEXER RULES
 *------------------------------------------------------------------*/
// GENERAL OPERATORS:
//NOTLIKE   :   'notlike' | 'NOTLIKE'; // whitespaces have been removed
LIKE    :   'like' | 'LIKE';

OR          :   'or' | 'OR';
AND         :   'and' | 'AND';
NOT         :   'not' | 'NOT';

//ELEMENTS
CONSTANT_EXPRESSION : DATE | NUMBER | QUOTED_STRING;
ID          :   (CHARACTER|DIGIT)+;

WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+    { $channel = HIDDEN; } ;

fragment DATE       :   '\'' YEAR '/' MONTH '/' DAY (' ' HOUR ':' MINUTE ':' SECOND)? '\'';

fragment QUOTED_STRING :    '\'' (CHARACTER)+ '\'' ;

//UNITS
fragment CHARACTER :    ('a'..'z' | 'A'..'Z'|'.'|'\''|'%'); // FIXME: Careful, should be all ASCII
fragment DIGIT  :   '0'..'9' ;
fragment DIGIT_SEQ  :(DIGIT)+;
fragment DEL    :   SPACE ',' SPACE ; //Delimiter + may be space behind
fragment NUMBER :   (SIGN)? DIGIT_SEQ ('.' (DIGIT_SEQ)?)?; // should be given in decimal degrees, North is 0 and direction is clockwise, range is 0 to 360
fragment SIGN   :   '+' | '-';
fragment YEAR   :   DIGIT DIGIT DIGIT DIGIT;
fragment MONTH  :   DIGIT DIGIT;
fragment DAY    :   DIGIT DIGIT;
fragment HOUR   :   DIGIT DIGIT;
fragment MINUTE :   DIGIT DIGIT;
fragment SECOND :   DIGIT (DIGIT)? ('.' (DIGIT)+)?;

fragment SPACE : (' ')?;// used to increase compatibility

Thing is, I have this message when creating the AST :
line 1:11 no viable alternative at input ''%bridge%''
line 1:35 no viable alternative at input ''%Munich%''

The generated tree is though correct (as far as I'm concerned at least):

So, could anyone give me a hint about what's wrong in there ? I think character contains all extra characters needed to correclty parse this expression. . .
Thanks !
As usual, some Java code to quickly test the grammar :
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
  public static void main(String[] args) throws Exception {

    // the expression
    String src = "(ICOM LIKE '%bridge%' or ICOM LIKE '%Munich%')";

    // create a lexer & parser
    //LogicLexer lexer = new LogicLexer(new ANTLRStringStream(src));
    //LogicParser parser = new LogicParser(new CommonTokenStream(lexer));

    LogicLexer lexer = new LogicLexer(new ANTLRStringStream(src));
    LogicParser parser = new LogicParser(new CommonTokenStream(lexer));

    // invoke the entry point of the parser (the parse() method) and get the AST
    CommonTree tree = (CommonTree)parser.parse().getTree();

    // print the DOT representation of the AST
    DOTTreeGenerator gen = new DOTTreeGenerator();
    StringTemplate st = gen.toDOT(tree);
    System.out.println(st);
  }
}

A: I see 3 issues:
1
Your atom rule matches epsilon (nothing):
atom
 : ID
 | | '(' expression ')' -> expression
 ;

(note the "nothingness" inside | |)
causing your grammar to be ambiguous. I guess it should be:
atom
 : ID
 | '(' expression ')' -> expression
 ;

2
Your fragment CHARACTER matches a single quote while this single quote also denotes the end of the fragment QUOTED_STRING.
I guess CHARACTER should be this instead:
fragment CHARACTER : ('a'..'z' | 'A'..'Z' | '.' | '%');

3
Nowhere in your parser rule you match the token CONSTANT_EXPRESSION, so the AST you posted could never have been created by a parser generated from the grammar you posted. I presume you'd want to match it in the atom rule like this:
atom
 : ID
 | CONSTANT_EXPRESSION
 | '(' expression ')' -> expression
 ;

With the changes outlined above, I get the following AST without any errors being printed to the console:


text:
Q: Why "for line in file:" can only use once? I have a simple question which I stock in it !
for line1 in file:
    print(line1)
for line2 in file:
    print(line2)
for line3 in file:
    print(line3)
I expect this to work three times, but only "for line1 in file:" work.

A: Because the file is read as part of iterating over the lines. You'll need to reopen the file each time, or read the whole file into a list of lines (via file.readlines() perhaps) and iterate over that, if memory limits permit.
Any open file has a "read pointer" that tracks what's been read, which advances with each line consumed. The loops as written will each consume the whole file.


text:
Q: JQuery display first 3 items and hide the rest of the results, Show all results when show more is clicked not working I have the following code where after 3rd item I want to hide the extra items until the user clicks "Show More". When Show More is clicked "Show Less" will replace the Show More and when Show Less is clicked with will again go back to display only 3 items and display "show more". Currently its adding show more for every items and not hiding the extra items.
Here is my code and Fiddle
//SHOW ONLY 2 RESULT INITIALLY ANS HIDE the REST UNTIL USER CLICKS  SHOW MORE and when SHOW LESS is clicked display show more with the 3 items.
$("div.item-b").has("div:nth-child(5)").append('
Show More
');
$("div.item-b").click(function () {
    var $this = $(this), $cards = $(this).closest('.item-b');
    $cards.toggleClass('open');
    $this.text($cards.hasClass('open') ? 'Show less' : 'Show more')
});

A: i updated your fiddle - i added a counter to each element as a id

http://jsfiddle.net/n7305445/52/
hope it helps ;)

A: Check out my JSFiddle. Hopefully this can help:
The basic idea is to add your "Show More" and "Show Less" divs within the list of items and then hide the "Show Less" div. These could be links or buttons also, but I decided to use divs. Use what fits your needs.
HTML

Stuff inside 1

Stuff inside 2

Stuff inside 3

Stuff inside 4

Stuff inside 5

Show More

Show Less

So next, you want to hide all the divs after the 3rd one in your list, excluding the show more/less divs, so in CSS you could do:
CSS
/* Hide the show more/less divs */
.show {
    display: none;
    color: blue;
}

.show:hover {
    cursor: pointer;
}

/* Hide 4th div and all the ones after it */
.item-b div:nth-child(n+4) {
    display: none;
}

And then in your JS, you will want to apply two click handlers (you could refactor it into one click handler if you wanted to), one for the .show.more div and one for the .show.less div. This will toggle the back and forth.
Let me know if you need further clarification.
$(document).ready(function() {
    var threshold = 3;

    if ($("div.item-b").children().not(".show").length > threshold) {
        $(".show.more").css("display", "block");
    }

    $(".show.more").on("click", function() {
        $(this).parent().children().not(".show").css("display", "block");
        $(this).parent().find(".show.less").css("display", "block");
        $(this).hide();
    });

    $(".show.less").on("click", function() {
        $(this).parent().children(":nth-child(n+" + (threshold + 1) + ")").not(".show").hide();
        $(this).parent().find(".show.more").css("display", "block");
        $(this).hide();
    });

});


text:
Q: providing free in-app purchases to select people I have an app that is being funded through a donation website that includes rewards. Some of the rewards I want to do is a free set of in-app purchases. Is this possible on google play? Can I manually do discount codes, or is there a systematic way to do it?
Any other ideas?
Thanks!

A: The only thing I have found is to e-mail the APK for the game itself and manage the details in a database, and change the numbers. I'll mark this is the accepted answer, but if someone comes up with something else, I'll happily change it.

A: You can implement give-away coupons with redeemable codes for your in-app products using the new in-app promotions Play Store feature:
http://developer.android.com/google/play/billing/billing_promotions.html
You can create up to 500 promo codes for a month and send them to your supporters.


text:
Q: Is the ~ character special at the start of a filename? If I create a file named ~abc.tmp and then try to use Command Prompt's character completion feature (usually TAB), it doesn't behave the same way as normal characters:

*

*If I type ~ and press TAB, it "completes" the file name incorrectly to ~"~abc.tmp".

*If I type ~a and press TAB, it fails to complete the file name.

Is there something special about the ~ character that I'm not aware of?
(I know that the 8.3 variants of long file names contain a ~ at the end, but I'm talking about ~ at the start.)

A: The tilde prefix on a temporary item is commonly created by Microsoft applications.

Windows Desktop applications, such as Write, and multiple document interface (MDI) applications, such as Excel, create temporary files to handle necessary user editing.

https://support.microsoft.com/en-us/help/92635/windows-temporary-files


text:
Q: How to correctly display data from two related models in Django ListView I have two models as below:
class Loo(models.Model):
    loo_type = models.CharField(max_length=3, default="LOO"...)
    loo_from = models.ForeignKey(Harr, on_delete=models.CASCADE, ...)
    loo_fac = models.DecimalField(max_digits=7, decimal_places=.....)

class Woo(models.Model):
    woo_item = models.AutoField(primary_key=True, ...)
    woo_loo = models.ForeignKey(Loo, on_delete=models.CASCADE, ...)
    woo_dt = models.DateField(null=True, ...)
    woo_rate = models.DecimalField(max_digits=7, decimal_places=.....)

I am trying to display data from the models using the following listview:
class WhoLooView(ListView):
    template_name = "who_loo_list.html"
    context_object_name = 'wholoos'
    model = Loo

    def get_context_data(self, **kwargs):
        context = super(WhoLooView, self).get_context_data(**kwargs)
        context.update({
            'woo_item_list': Woo.objects.order_by('-woo_dt'),
        })
        return context

    def get_queryset(self):
        return Loo.objects.order_by('loo_from')

Note that there can be more than one "woo_item" per instance of Loo (id), so in the listview there will be occasions when for the same Loo id it will have two instances of Woo/s, and thus need to be displayed separately (preferably in two distinct rows).
What I have tried so far creates extra (adjacent) columns for each Loo id and whichever Loo/s have a single instance of Woo, are shown in the normal fashion as expected.
How does one take care of such a situation. Can we have a nested row for cases where there are more than one instance of Woo?
Edit
What I have tried (based on your code sample):
{% for obj in wholoos %} <!-- wholoos : context object name -->
    {{ obj.loo_type }}
    {% for item in obj.woo_set.all %}
        {{ item.woo_dt }}
    {% endfor %}
{% endfor %}

But now I am not getting anything from the second model Woo.
Edit 2
I am getting the same result as earlier with my original code. Check the image below:

If you notice (in the image above), objects # 31 and 34 have one each of child objects (sub-objects). # 32 and 33 have two each. I want them to be in separate rows and not columns. The reason is, in case there are a number of items for each parent item (which my DB design makes it imperative to be), I would end up with an enormous number of extra columns for the sub-objects (and that too without any column header).

A: you can loop the instances of Loo as shown, in your templates, don't have to override the get_context_data.
{% for obj in object_list %}
{{ obj.loo_type }}
{% for item in obj.woo_set.all %}
{{ item.woo_dt }}
{% endfor %}{% endfor %}


text:
Q: Quote all fields in CSV output @out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w")
CSV::Writer.generate(@out) do |csv|
  csv << ["01", "02", "test"]
end
@out.close

When i run above code it stores the values in CSV as
01, 02. test
I want them to store as
"01", "02", "test"

A: Change
CSV::Writer.generate(@out)do |csv|

to
CSV::Writer.generate(@out, {:force_quotes=>true}) do |csv|

A: So why not double quote them?
@out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w")
CSV::Writer.generate(@out) do |csv|
  csv << ['"01"', '"02"', '"test"']
end
@out.close


text:
Q: Autofit does size rows correctly on cells with Wrapped-Text PRELUDE: THIS IS NOT A DUPLICATE, There is a similar question asked HERE, but their solution does not work for my problem. (Their solution is applied in the code below)
I am trying to have the height of the entire row autofit the cell with the largest block of text.
MY CODE (snippet):
               With my_xl_workbook.Sheets(1).Range(rng)
                    .WrapText = True
                    .Merge
                    .value = DegreesInformationArray(j, i)
                    .Borders.LineStyle = 1
                    .Borders.Weight = 4
                    .EntireRow.AutoFit
               End With

MY SPREADSHEET OUTPUT:

WHAT I EXPECTED THE SPREADSHEET OUTPUT TO BE:

I have also, tried changing the order that the attributes are set in with no success.
Any tips, suggestions, or name calling are welcome. :)
(edit: inserted correct image)

A: Here's one solution:
Sub fitheight()
  Dim h, ma
  h = 0
  For Each c In Selection
    With c
      ma = .MergeArea.Address
      If InStr(ma, .Address) = 1 Then
        .UnMerge
        .EntireRow.AutoFit
        If .Height > h Then
          h = .Height
        End If
        ActiveSheet.Range(ma).Merge
        .RowHeight = h
      End If
    End With
  Next
End Sub

How it works
The procedure assumes you're auto-setting the height based on a selection.  It could be easily adapted to operate on a range.
It uses two variables:

*

*h to hold the maximum height

*ma to hold the range of each cell's merge area

It iterates through each cell in the selection, where it:

*

*Loads the merge area in the ma variable.

*Tests if the merged area begins with the cell's address.  Note that a Selection will iterate through merged cells more than once.  For example, if cells C3 and D3 were merged, Selection would iterate through both C3 and D3.  We're interested in only the first merged cell, which we can do using the Instr test.

*Unmerges the cell.

*Autofits the row to the cell's height.

*Tests the height against the h variable.  If greater, it sets h to the new height.

*Re-merges the cell using the ma variable.

*Sets the row height to h, which at this point is the largest height so far.


text:
Q: Map object key to value type in class generic I have the following code:
interface Person {
    name: string;
    age: number;
}

class Store<T, K extends keyof T> {
    constructor(private obj: T) { }

    get(key: K): T[typeof key] {
        return this.obj[key];
    }
}

const person: Person = {
    name: 'John',
    age: 99
};

const store = new Store(person);
const value = store.get('name');

value type shows:
const value = store.get('name');
   // ^^^^^ value: string | number

How to infer the value type of an object given its key as an argument in a class method?
I want value to be properly typed as string in this case. How to achieve this?
Typescript playground

A: The get function itself needs to be generic so it can use the type of the argument. This allows it return a specific key from T like T[K].
And the K generic on the class now no longer makes sense. keyof T would be the same thing anywhere in that class, so you can remove it completely.
Put another way Store as a class doesn't think any one key is special, so it doesn't need a generic for that. But the get method needs to get one specific key, so the type system needs to know which specific key, so you need a generic there.
class Store<T> {
    constructor(private obj: T) { }

    get<K extends keyof T>(key: K): T[K] {
        return this.obj[key];
    }
}

Playground


text:
Q: How to avoid adding timezone when subtract tow time in php My php timezone is Asia/Dhaka (UTC+6)
Let I have two time
$a = 11:00:00;
$b = 09:00:00;
$sub = $a-$b; //it should return 02:00:00. But it adding the timezone and returns 08:00:00 (02:00:00 + 06:00:00)

How to avoid to adding the timezone time from this output?

A: try using the php DateTime
$a = '11:00:00';
$b = '09:00:00';

$start_date = new DateTime($a);
$since_start = $start_date->diff(new DateTime($b));
echo "{$since_start->h}:{$since_start->i}:{$since_start->s}";


text:
Q: How do I separate OpenLayers methods from my own, while using inheritance? I am working on a GIS API, that uses OpenLayers. I initialize the map lke this:
xgis.map = OpenLayers.Class(OpenLayers.Map, {
    var mapOptions = {};
    mapOptions.allOverlays = false;
    /*
        more mapOptions here
    */
    OpenLayers.Map.prototype.initialize.apply(this, ['map', mapOptions]);
});

Of course, I do this because I want to create my own methods, like this one, for example.
xgis.map.prototype.zoom(action) {
    switch(action) {
        case 'in:
            this.zoomIn();    // Uses the OpenLayers zoomIn method
            break;
        case 'out:
            this.zoomOut();    // Uses the OpenLayers zoomOut method
            break;
};

The problem is this 'zoom' method I created is not recognized as a function (I get: number is not a function), because OpenLayers has a 'zoom' numeric value where it stores the zoom.
Is there a way to use inheritance and access the parent's methods like this?
this.parent.zoomIn()

This would definitely fix the 'zoom' name problem.

A: You are writing bad, it must be:
xgis.map.prototype.zoom = function(action) { ... }

Anyway, it is better you follow the Ol code conventions. To create subclasses you must create methods inside  class definition, something like:
xgis.map = OpenLayers.Class(OpenLayers.Map, {
    someAttribute: 'someValue'.
    someMethod: function() {
        ...
    }

    CLASS_NAME: 'your_class_name'
});

You can find a custom control code at: http://acanimal.github.io/Openlayers-Cookbook/recipes/ch08/crossControl.js
Which is part of the samples of the OpenLayers Cookbook. See more samples at http://acanimal.github.io/Openlayers-Cookbook/ the sample "chapter8-custom control".


text:
Q: Is it possible to specify a skip date/period in Data Factory schedule trigger/ tumbling window trigger? My requirement is to skip the run of a trigger if it is the first day of the month
Similarly run a trigger if it is Monday or 1st day of the month
Can we achieve it at trigger level or we have to write custom logic (If conditon/ Case activity)  in ADF to kick it off and exit gracefully by sending an email rather than running other activities ( like precedence contraints in SSIS)

A: I recommend Logic Apps for this kind of operation. Its more user friendly and is separate from ADF, so you can change the trigger rules without changing the pipeline. Here is a very similar question where I outline this approach. You would just need to modify the date processing rules in the Logic App to match your scenario.

A: You can implement the first ask by playing with the schedule object . Read here .
This should work .
{"weekDays":["tuesday", "wednesday", "thursday", "friday","saturday","sunday"]}
For the second part where you have the OR condition I doubt if we can implement that using one trigger  , but I think we can create two triggers like .
TRG1
 "schedule":{"weekDays":["monday"]}

TRG2

"schedule": {  "monthDays": [1]  }

HTH

A: I managed to handle this using a master/child pipeline stuff.
I am triggering a master pipeline every time whenever I need to run a particular schedule - I am then setting various variables like "dayOfMonth" , "hourOfDay", "dayOfWeek" etc etc and then using those variables in "If"/ "case" activities to trigger respective child pipelines using "Execute Pipeline" activities.


text:
Q: How to erase element with a reverse iterator from a `std::set`? Facing issue with deletion of last element in set :
#include <bits/stdc++.h>
using namespace std;
int main()
{
set < pair <int,int > > a;
a.insert(make_pair(2,3));
auto it = a.rbegin();
a.erase(it.base()); // for deleting last element in set
cout << a.size() << endl;
return 0;
}

Getting the runtime issue, Also have tried with auto, Iterator and Const iterator, it's not working.Is there any other way to erase an element from a set ?
Edit :  How can I delete a Particular element based on iterator reference ?
if i do like :

auto it=a.begin();
a.erase(it); Here it = reference to the element for deletion
it doesn't work.Any other way to delete based on iterator reference ?

A:
Is there any other way to erase an element from a set ?

a.erase(std::prev(std::end(a)));

Can you tell me,whats problem with my code ?

itr.base() where itr == a.begin() is equivalent to a.end(). See: http://en.cppreference.com/w/cpp/iterator/reverse_iterator/base
Erasing a past-the-end iterator is undefined behavior.


text:
Q: Invalidation from Mutations in React Query I am uploading an image in the backend using react-query useMutation. Everything is working correctly, but onSuccess in useMutation when invalidateQueries is called it's inValidating the useQuery before the POST request gets executed successfully on the backend. So I have to refresh the page for new images.
enter image description here
  const { data: usermedia,} = useQuery(["usermedia"],() => {
    return getInfo("http://127.0.0.1:8000/usermedia/").then((t) => t.json());},
  );

  const mutation = useMutation(
    (body) => postMedia("http://127.0.0.1:8000/usermedia/", body),
    {
      onSuccess:(data,) => {
         console.log("Got response from backend successfull", data);
         client.invalidateQueries("usermedia")

      },
      onError(error) {
         console.log("Got error from backend", error);},
    }
  );

I am was expecting to InValidate query when the POST got completed in the backend OR after inValidating useQuery it got triggered after 1 sec.

A: You might want to try and return the invalidatequeries call as demonstrated here https://tkdodo.eu/blog/mastering-mutations-in-react-query
{
  //  will wait for query invalidation to finish
  onSuccess: () => {
    return queryClient.invalidateQueries(['posts', id, 'comments'])
  }
}
{
  //  fire and forget - will not wait
  onSuccess: () => {
    queryClient.invalidateQueries(['posts', id, 'comments'])
  }
}


text:
Q: "MongooseError('The `uri` parameter to `openUri()` must be a ' +" error appears even though variable is a string I want to simply connect my db via mongoose onto my localhost. However, I receive this error:
C:\Users\przyb\Desktop\JWT\node_modules\mongoose\lib\connection.js:520
    throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
    ^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

This confuses me as the variable being passed is definitely a string. Here is my file tree:
JWT
|
model --- User.js
node_modules
public
routes --- .env.js, auth.js
views
index.js
package.json
package-lock.json

index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv").config();

//Imported routes
const authRoute = require('./routes/auth');

//Connect to db
mongoose.connect(
    process.env.DB_CONNECT,
    {useNewUrlParser:true},
    () => console.log("connected to db")
);

//Middleware
app.use(express.json());

//Route Middlewares
app.use('/api/User', authRoute);

app.listen(3000, () => console.log("All good"));

.env.js
DB_CONNECT = "mongodb+srv://USERNAME:PASSWORD@cluster0-wu2im.mongodb.net/test?retryWrites=true&w=majority";

Stackoverflow said I have too much code for this question so I cannot show you the auth.js & User.js.

A: This issue was resolved by:

*

*Rename file .env.js to .env.

*Put .env file at root of projects.

A: This issue was resolved by:

*

*Rename your .env.js file to only .env

*Put .env file at root directory of project.Same directory where your package.json file is located.

*If this issue arrises when you deploy it such as on Heroku. On heroku it looks up for environmental variables which are declared in heroku. So just follow:

*Go to your dashboard and in your selected app go to settings tab.

*Go to Config vars and click reveal vars.

*Just add your .env variables there in key and value pair.

*Eg. Put DB_CONNECT in Key and mongodb+srv://USERNAME:PASSWORD@cluster0-wu2im.mongodb.net/test?retryWrites=true&w=majority in Value.
That's it. You will be able to deploy your app including your .env variables.


text:
Q: Large .img file processing in R (GIS) I am working with U.S. National Landcover Dataset (NLCD) to classify habitat type at more than 150 sites across the northeast U.S. The dataset is very large (15GB) so I cannot upload it here, but it comes in .img format at 30m resolution.
 I have GPS coordinates for the center point of all the sites. I would like to be able to extract the proportion of landcover classes in a 1 square kilometer around the point. My questions are:
1)  How do I upload .img files into r?
2)  How do I extract the information from around the GPS coordinates as proportions of the different habitat classes?
Has anyone worked with this dataset in r before? If so I could really use the help.
Cheers,
Israel

A: Use the raster package which can process the files from disk, only reading in chunks at a time.
the raster package has an extract function with a buffer argument. set your buffer to the appropriate value (1000 if your map units are metres and you want a km radius)

A: Thanks to mnel. I have gotten the basic idea to work (code below). Now if anyone could give me a pointer on how to calculate the proportion of each category for every coordinate. The extract function gives me matrices of values for each set of coordinates. Is there a way to summarize this data?
#load in map and locality data
NLCD<-raster ('NLCD2006/NLCD2006.img')
sites<-read.csv('sites.csv', header=T)
#crop site data to just latitude and longitude
sites<-sites[,4:5]
#convert lat/lon to appropirate projection
str (sites)
coordinates(sites)  <-  c("Longitude",  "Latitude")
proj4string(sites)  <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")
sites_transformed<-spTransform(sites, CRS("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"))

#plot the map
plot (NLCD)
#add the converted x y points
points (sites_transformed, pch=16, col="red", cex=.75)
#extract values to poionts
Landcover<-extract (NLCD, sites_transformed, buffer=1000)


text:
Q: How to get month from Material design Datepicker Android kotlin I have a datepicker from material design, its opening well in the app.
Now how can i get for example the selected month from the datepicker.
Initialize the datepicker:
val datePicker = MaterialDatePicker.Builder.datePicker()
    .setTitleText("Kies een datum")
    .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
    .build()

On button hit the calendar opens:
fun pickDate() {
    binding.DatepickerButton.setOnClickListener {

        datePicker.show(activity?.supportFragmentManager!!, datePicker.toString())

    }
}

so it shows, but i cannot get the data from it.

A: For Java 8, you can use Date/Time API
binding.DatepickerButton.addOnPositiveButtonClickListener {
    var dateFormatter = DateTimeFormatter.ofPattern("MM", Locale.getDefault())
    val month = dateFormatter.format(
                Instant.ofEpochMilli(it)
                    .atZone(ZoneId.systemDefault()).toLocalDate()
            )
}

Otherwise, you can use SimpleDateFormatter
 binding.DatepickerButton.addOnPositiveButtonClickListener {
     val calendar = Calendar.getInstance()
     val simpleDateFormatter = SimpleDateFormat("MM", Locale.getDefault())
     calendar.time = Date(it)
     val month = simpleDateFormatter.format(calendar.time)
 }

A: Try this click positive button click listener. after getting the date you can extract a month from it.
 binding.DatepickerButton.addOnPositiveButtonClickListener {
     val (startOfRange, endOfRange) = it   // in case date range operation
     val date = it //  single select date
     String dateString = DateFormat.format("dd/MM/yyyy", new Date(date)).toString();
 }


text:
Q: useState hook not updating when adding a variable fetched through ternary operator I have a variable x whose value I am calculating using a ternary operator. When I try to update this value inside useEffect it does not update it. I understand that setState is async operation and probably it is reading a stale value but is there a way to handle this situation?
const [x,setX] = useState();

let val  =data.result. > 900 ? 100 / 5 : data.totalResults / 5
setX(val);

A: Read the value when the value of x is updated. Like the following
useEffect(() => {
  console.log(x)
},[x])


text:
Q: How to send data over the URL to the Home Controller using ajax in Spring MVC? I am trying to send data using ajax over the url to my home controller but I am getting a 404 error.
1.You can send multiple authors or genres Ids by selecting from a list got from the show add book.
2.You can send a Author by entering his details and adding a author
3.You can send a Genre by entering the details and adding a new the genre
4.You can select one publisher either from the list or my entering the details and creating a new publisher.
The above code works.
There is only a problem with receiving the data at the controller.
I can seed the data I entered on the link in the console error.
Ajax code:
$.ajax({
    type: "POST",
    url: "addBook/"+authorName+"/"+genreName+"/"+bookTitle+"/"+publisherName+"/"+publisherAddress+"/"+publisherPhone+"/"+author+"/"+genre+"/"+publisherId
}).done(function( msg ) {
    $('#result').html(msg + "<br/>");
});

Home controller code:
@RequestMapping(value = "/addBook/{authorName}/{genreName}/{bookTitle}/{publisherName}/{publisherAddress}/{publisherPhone}/{author}/{genre}/{publisherid}", method = { RequestMethod.GET,RequestMethod.POST})
public @ResponseBody String addBook(@PathVariable (value="authorName") String authorName,@PathVariable(value="genreName") String genreName,@PathVariable(value="bookTitle") String bookTitle ,@PathVariable(value="publisherName") String publisherName ,@PathVariable(value="publisherAddress") String publisherAddress ,@PathVariable(value="publisherPhone") String publisherPhone ,@PathVariable(value="author[]") String authorIds[] ,@PathVariable(value="genre[]") String[] genreIds ,@PathVariable(value="publisherid") String publisherId , Locale locale, Model model) {
//Add Book code
}

Thanks in advance

A:
function statusFun()
{

    var x = document.getElementById("statusDropdown");
    alert(x.options[x.selectedIndex].value);

    var client = x.options[x.selectedIndex].value;
    var htm = $.ajax({
    type: "POST",
    url: "categorylist.php",
    data: "client="+client,
    async: false
    }).responseText;

    if(htm)
    {
        alert(htm);
        $("#catid").html(htm);
        return true;
        // Uncomment the following line in your application
        //return true;
    }
    else
    {
        alert("test1");
        $("#clientdetails").html("no result found");

        return false;
    }
}


text:
Q: How to add SPFx webpart to page in SharePoint online sub-sites? I have created the SPFx web part for custom development in SharePoint online modern site.
I have created multiple subsites under one site collection. I need to add the SPFx web part to all sub-sites.
I have tried to save a template of one site but it doesn't allow me to save the site as a template. It has thrown me the below error,

Sorry, this site can't be saved as a template. It contains apps that
don't work in templates: spfx-demo-client-side-solution

I have tried another way. I have created a site to add all necessary lists, libraries, and pages. I have successfully saved the template for that site. I have created many subsites using that custom template.
Now, I need to add my SPFx web part to the sites that were created using a template.
For that, I need to add the SPFx app to all subsite's Site Contents and add the SPFx web part to all subsite's Site Pages. Can I achieve that with PowerShell or do I need to prefer some alternative way?
Can anyone help me with the same?
Thanks in Advance.


text:
Q: How to upload >250 mb size using php ,ajax post in cakephp application? I am using jax post method to upload data from php to server using cakephp application, upto 250 mb is uploading and I am using nginx server. Greater than 250 mb throwing post error. Is there any other way to upload large file sizes.
I have done all changes in php.ini file: max_execution_time, upload_max_filesize, post_max_size, max_input_time. Still the issue remains same. This issue is related to ajax post method. How to solve this?


text:
Q: Getting invalid json from facebook on fetching email I am getting invalid json when using graphrequest to fetch email. Here is my code
    LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                    GraphRequest request =GraphRequest.newMeRequest(loginResult.getAccessToken(),new GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            // TODO Auto-generated method stub
                             Log.v("LoginActivity", response.toString());

                        }
                    });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields","email");
                    request.setParameters(parameters);
                    request.executeAsync();
}

Json response i am getting from facebook  is as follows :
{Response:  responseCode: 200, graphObject: {"id":"1592747474311684","email":"nanowebtech87@gmail.com"}, error: null}

How to solve this.

A: Please try this,
public void onCompleted(JSONObject object, GraphResponse response) {
                        // TODO Auto-generated method stub
                        try {
                            System.out.println("object :  " + object.toString());
                            String id=object.getString("id");
                            System.out.println("id"+ id);
                            String name=object.getString("name");
                            System.out.println("name"+ name);
                            String email=object.getString("email");
                            System.out.println("email"+ email);
                            String gender=object.getString("gender");
                            System.out.println("gender"+ gender);
                            String birthday=object.getString("birthday");
                            System.out.println("birthday"+ birthday);
                            //do something with the data here
                        } catch (JSONException e) {
                            e.printStackTrace(); //something's seriously wrong here
                        }

                    }


text:
Q: how to dynamically change model query in controller in laravel 5.2? This is my code
    $showid=3;
    $screenid='1';

    $seatdata=Screen1::all();

    $showtimedata=Showtime::where('showid',$showid)->get();
    $count =Showtime::where('showid',$showid)->count();

Now $showid and $screenid will be changing dynamically, there is no problem with showid it's working well,
but whenever screen id changes then the model name written in the line below should change
    $seatdata=Screen1::all();

If say $screenid=2 then the code should become like
    $seatdata=Screen2::all();

If say $screenid=3 then the code should become like
   $seatdata=Screen3::all();

Note I have already created models Screen1, Screen2, & Screen3
I tried doing this but it didn't work
   $showid=3;
    $screenid='1';
    $screen='Screen'.$screenid;

    $seatdata=$screen::all();

    $showtimedata=Showtime::where('showid',$showid)->get();
    $count =Showtime::where('showid',$showid)->count();

This gives me error that
    FatalErrorException in SeatlayoutController.php line 27:Class 'Screen1' not found

Help is appreciated.

A: Try specify full namespace in your class, for example
$screen='App\Screen'.$screenid;


text:
Q: Dialyzer emits Type specification is a subtype of the success typing for multiple functions with same name I have the following two functions and I am receiving this dialyzer warning on them:
"Type specification 'Elixir.MyModule':calculate(arg1::'Elixir.String':t(),arg2::'Elixir.CustomType':t(),arg3::'Elixir.String':t()) -> 'ok' | 'error'; calculate(arg1::'Elixir.String':t(),arg2::'Elixir.CustomType':t(),arg3::maybe_improper_list()) -> 'ok' | 'error' is a subtype of the success typing: 'Elixir.MyModule':calculate(binary(),#{'__struct__':='Elixir.CustomType', _=>_},binary() | maybe_improper_list()) -> 'error' | 'ok'"

Here are the functions:
@spec calculate(arg1 :: String.t, arg2 :: CustomType.t, arg3 :: String.t)
def calculate(arg1, %CustomType{} = arg2, arg3) when is_binary(arg1) and is_binary(arg3) do
  calculate(arg1, arg2, [arg3])
end

@spec calculate(arg1 :: String.t, arg2 :: CustomType.t, arg3 :: maybe_improper_list())
def calculate(arg1, %CustomType{prop1: val, prop2: val2}, arg3) when is_binary(arg1) and is_integer(val2) and is_binary(val) and is_list(arg3) do
...
end

I don't understand why I am getting this warning. I thought this is the correct way to write functions with different argument types in Elixir but given Dialyzer keeps emitting warnings, I am beginning to wonder if I am writing this code incorrectly?

defmodule CustomType do
  @type t :: %CustomType{
    prop1: String.t(),
    prop2: integer(),
    prop3: String.t(),
    prop4: boolean(),
    ...
  }
end

These are the dialyzer flags I am running with:
dialyzer: [
  flags: ~w[underspecs overspecs race_conditions error_handling unmatched_returns]a
]

Repro Sample:
defmodule MyCustomType do
    @type t :: %MyCustomType{
        prop1: String.t(),
        prop2: integer(),
        prop3: String.t()
    }

    defstruct [:prop1, :prop2, :prop3]
end

defmodule MyModule do
    @spec calculate(String.t,
                    MyCustomType.t,
                    String.t)
    :: :ok
    def calculate(arg1, %MyCustomType{} = arg2, arg3) when is_binary(arg1) and is_binary(arg3) do
        calculate(arg1, arg2, [arg3])
    end

    @spec calculate(String.t,
                    MyCustomType.t,
                    maybe_improper_list)
    :: :ok
    def calculate(arg1, %MyCustomType{prop1: val, prop2: val2}, arg3) when is_binary(arg1) and is_list(arg3) and is_binary(val) and is_integer(val2) do
        :ok
    end
end

Here are the warnings I am getting:
      Type specification 'Elixir.MyModule':calculate
          ('Elixir.String':t(),
          'Elixir.MyCustomType':t(),
          'Elixir.String':t()) ->
             'ok';
         ('Elixir.String':t(),
          'Elixir.MyCustomType':t(),
          maybe_improper_list()) ->
             'ok' is a subtype of the success typing: 'Elixir.MyModule':calculate
          (binary(),
          #{'__struct__' := 'Elixir.MyCustomType',
            'prop1' := binary(),
            'prop2' := integer(),
            _ => _},
          binary() | maybe_improper_list()) ->
             'ok'

A: First, I don't see any elixir typespec tutorials where they write the @spec with the variable names in the spec--instead all I find are tutorials with types only in the typespec:
@spec calculate(arg1 :: String.t, arg2 :: CustomType.t, arg3 :: String.t)

v.

@spec calculate(String.t, CustomType.t, String.t)

Nevertheless, the following passed dialyzer for me:
defmodule CustomType do
  @type t :: %CustomType{}
  defstruct a: nil, b: nil
end

defmodule MyModule do

  @spec calculate(arg1::String.t, arg2::CustomType.t, arg3::String.t) :: number

  #def calculate(<<arg1::binary>>, %CustomType{} = arg2, <<arg3::binary>>) do
  def calculate(arg1, %CustomType{} = arg2, arg3) when is_binary(arg1) and is_binary(arg3) do
    calculate(arg1, arg2, [arg3])
  end

  @spec calculate(String.t, CustomType.t, maybe_improper_list()) :: number

  def calculate(<<arg1::binary>>, %CustomType{} = arg2, arg3) when is_list(arg3) do
    123
  end

end

~/elixir_programs/friends$ mix dialyzer
Compiling 1 file (.ex)
warning: variable "arg1" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/friends/my_module.ex:17

warning: variable "arg2" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/friends/my_module.ex:17

Checking PLT...
[:compiler, :connection, :crypto, :db_connection, :decimal, :ecto, :elixir,
 :kernel, :logger, :poolboy, :postgrex, :stdlib]
PLT is up to date!
Starting Dialyzer
dialyzer args: [
  check_plt: false,
  init_plt: '/Users/7stud/elixir_programs/friends/_build/dev/dialyxir_erlang-20.3_elixir-1.8.2_deps-dev.plt',
  files_rec: ['/Users/7stud/elixir_programs/friends/_build/dev/lib/friends/ebin'],
  warnings: [:unknown]
]
done in 0m1.43s
done (passed successfully)

I will say that I find this syntax:
@spec calculate(String.t, CustomType.t, String.t)

much easier to read.
According to Learn You Some Erlang:

is a subtype of the success typing

This warns you that in fact, your specification is way too strict for
  what your code is expected to accept, and tells you (albeit
  indirectly) that you should either make your type specification
  looser, or validate your inputs and outputs better in your functions
  to reflect the type specification.

However, I am unable to produce your dialyzer output:
defmodule CustomType do
  @type t :: %CustomType{}
  defstruct a: nil, b: nil
end

defmodule MyModule do

  @spec calculate(arg1 :: String.t,
                  arg2 :: CustomType.t,
                  arg3 :: String.t)
  :: :ok | :error

  def calculate(arg1, %CustomType{} = arg2, arg3)
  when is_binary(arg1) and is_binary(arg3) do
    calculate(arg1, arg2, [arg3])
  end

  @spec calculate(arg1 :: String.t,
                  arg2 :: CustomType.t,
                  arg3 :: maybe_improper_list())
  :: :ok | :error

  def calculate(arg1, %CustomType{} = arg2, arg3)
  when is_binary(arg1) and is_list(arg3) do
    case arg1 do
      "hello" -> :ok
      "goodbye"  -> :error
    end
  end

end

$ mix dialyzer
Compiling 1 file (.ex)
warning: variable "arg2" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/friends/my_module.ex:19

Checking PLT...
[:compiler, :connection, :crypto, :db_connection, :decimal, :ecto, :elixir,
 :kernel, :logger, :poolboy, :postgrex, :stdlib]
PLT is up to date!
Starting Dialyzer
dialyzer args: [
  check_plt: false,
  init_plt: '/Users/7stud/elixir_programs/friends/_build/dev/dialyxir_erlang-20.3_elixir-1.8.2_deps-dev.plt',
  files_rec: ['/Users/7stud/elixir_programs/friends/_build/dev/lib/friends/ebin'],
  warnings: [:unknown]
]
done in 0m1.46s
done (passed successfully)

So, you need to post a minimal example that reproduces your dialyzer output.  I will note that arg3 has to be a binary in your first clause, so when you call calculate(arg1, arg2, [arg3]) in the first clause's body, the argument [arg3] will never be an improper list, so you can tighten that spec up to: list(binary) for the second clause.
============
Here's the code I've put together:
defmodule CustomType do
  @type t :: %CustomType {
    prop1: String.t(),
    prop2: integer(),
    prop3: String.t(),
    prop4: boolean()
  }

  defstruct prop1: nil, prop2: nil, prop3: nil, prop4: nil
end

defmodule MyModule do
  @spec calculate(arg1 :: String.t,
                  arg2 :: CustomType.t,
                  arg3 :: String.t)
  :: :ok | :error

  def calculate(arg1, %CustomType{} = arg2, arg3)
  when is_binary(arg1) and is_binary(arg3) do
    calculate(arg1, arg2, [arg3])
  end

  @spec calculate(arg1 :: String.t,
                  arg2 :: CustomType.t,
                  arg3 :: maybe_improper_list)
  :: :ok | :error

  def calculate(arg1, %CustomType{prop1: val, prop2: val2}, arg3)
  when is_binary(arg1) and is_binary(val) and is_integer(val2) and is_list(arg3) do
    case arg1 do
      "hello" -> :ok
      "goodbye"  -> :error
    end
  end

end

Running dialyzer:
~/elixir_programs/friends$ mix dialyzer
Checking PLT... [:artificery,
 :compiler, :connection, :crypto, :db_connection, :decimal,  :distillery,
 :ecto, :elixir, :kernel, :logger, :poolboy, :postgrex,  :runtime_tools,
 :stdlib] Finding suitable PLTs Looking up modules in dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt Finding applications for dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt Finding modules for dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt Checking 718 modules in dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt Adding 56 modules to dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt Starting Dialyzer dialyzer args: [
  check_plt: false,
init_plt: '/Users/7stud/elixir_programs/friends/_build/dev/dialyxir_erlang-
20.3_elixir-1.8.2_deps-dev.plt', files_rec:
['/Users/7stud/elixir_programs/friends/_build/dev/lib/friends/ebin'],
  warnings: [:unknown] ] done in 0m1.26s done (passed successfully)

With the following in mix.exs:
  def project do
    [
      app: :friends,
      version: "0.1.0",
      elixir: "~> 1.6",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      dialyzer: [
            flags: ~w[underspecs
                      overspecs
                      race_conditions
                      error_handling
                      unmatched_returns]a
      ]
    ]
  end

Here's the output:
~/elixir_programs/friends$ mix dialyzer
Checking PLT...
[:artificery, :compiler, :connection, :crypto, :db_connection, :decimal,
:distillery, :ecto, :elixir, :kernel, :logger, :poolboy, :postgrex,
:runtime_tools, :stdlib]
PLT is up to date!
Starting Dialyzer
dialyzer args: [
  check_plt: false,
  init_plt: '/Users/7stud/elixir_programs/friends/_build/dev/dialyxir_erlang-20.3_elixir-1.8.2_deps-dev.plt',
  files_rec: ['/Users/7stud/elixir_programs/friends/_build/dev/lib/friends/ebin'],
  warnings: [:underspecs, :overspecs, :race_conditions, :error_handling,
   :unmatched_returns, :unknown]
]
done in 0m1.38s
done (passed successfully)


text:
Q: Startup Items - Creating a basic one Please save me from a potential nervous breakdown!
I've been following Apples documentation (see below) on how to create a Startup Item. Currently I'm just trying to get my script to print something to the console, much less actually run my app.
Here are my two scripts, one is the startup executable, the other is the plist:
#!/bin/sh
. /etc/rc.common

# The start subroutine
StartService() {
# Insert your start command below.  For example:
echo "hey Eric we've started"
# End example.
  }

# The stop subroutine
 StopService() {
# Insert your stop command(s) below.  For example:

  echo "STOPPED ERIC"

# End example.
    }

   # The restart subroutine
     RestartService() {
    # Insert your start command below.  For example:

echo "RESTART ERIC"

    # End example.
       }

 RunService "$1"

 {
 Description     = "Software Update service";
   Provides        = ("SoftwareUpdateServer");
  Requires        = ("Network");
   Uses            = ("Network");
   OrderPreference = "Late";
    Messages =
   {
     start = "Starting Software Update service";
     stop  = "Stopping Software Update service";
     };
  }

Using terminal I tried to set the permissions as closely as possible as to how it is documented in the example in the link below. The odd thing was that the files didn't show the 'root' aspect to their ownership.
I then ran SystemStarter start theApp and nothing happens. Absolutely nothing.
Any help?
http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/StartupItems.html

A: You should not create a Startup Item any more. It's a legacy mechanism and superseded by launchd. Write a plist for launchd instead. I know this is not the help you wanted, but sadly with Apple, you need to follow the mothership...
Read this section of the same document instead.
See the document just you quoted yourself:

Note: The launchd facility is he preferred mechanism for launching daemons in Mac OS X v10.4 and higher. Unless your software requires compatibility with Mac OS X v10.3 or earlier, you should use the launchd facility instead of writing a startup item. For more information, see "Guidelines for Creating and Launching Daemons."

Note that v10.4 become available in 2005.


text:
Q: Zooming and position objects relative to mouseX in processing In this sketch, objects' positions are calculated from left to right from a fixed point. When zooming in or out, the objects will enlarge or decrease from left to right as well.
How do I calculate the offset I need to add to x so that when I zoom in or out the objects expand or shrink based on the mouse's X position (so mouseX will be the origin of zooming)?
The code for the sketch (takes a while to load because images are taken from the internet)
PImage backgroundImage;
PFont font;
int x = 0;
int xoffset = 0;
int deltax = 5;
float scale = 512/30;
float deltascale = 0.02;
ArrayList<Object> ObjectList;
//String[] objectfile;
//String[] configfile;
//int savetimer = 0;

class Object {
  String name;
  float diameter;
  String unit;
  String sprite;
  PImage img;
  int wid;
  int hei;
  int xpos;

  Object(String Oname, float Odiameter, String Ounit, String Oimg) {
    name = Oname;
    diameter = Odiameter;
    unit = Ounit;
    img = loadImage(Oimg);
    sprite = Oimg;
    //img = loadImage(Oimg);
    wid = img.width;
    hei = img.height;
  }
}

void setup() {
  size(1500, 800);
  frameRate(200);
  //objectfile = loadStrings("objects.txt");
  //configfile = loadStrings("config.ini");
  //backgroundImage = loadImage("background.png");
  //font = createFont("Franklin Gothic Book Regular.ttf", 32);
  fill(255,255,255);
  textSize(32);
  textAlign(CENTER, CENTER);
  text("Images are loading (this may take a while)",700,400);
  ObjectList = new ArrayList();
  readObjects();
  //readConfig();
  //loadOffset();
}

void addObject(String Aname, float Adiameter, String Aunit, String Aimg) {
  //if (Aimg.equals("null")) {
  //  ObjectList.add(new Object(Aname, Adiameter, Aunit, "images/"+Aname+".png"));
  //} else {
  ObjectList.add(new Object(Aname, Adiameter, Aunit, Aimg));
  //}
}

void readObjects() {
  //for (int i = 0; i < objectfile.length; i++) {
  //  String[] currentObject = split(objectfile[i], ",");
  //  addObject(currentObject[0], float(currentObject[1]), currentObject[2], currentObject[3]);
  //}
  addObject("RED", 30, "m", "https://s-media-cache-ak0.pinimg.com/736x/8f/1b/cc/8f1bcc72c81d1e9370597f7239ee476a.jpg");
  //addObject("ORANGE", 60, "m", "http://6iee.com/data/uploads/36/489075.jpg");
  addObject("YELLOW", 70, "m", "https://i.stack.imgur.com/aez1V.jpg");
  addObject("GREEN", 100, "m", "http://space-facts.com/wp-content/uploads/mars.jpg");
  addObject("PURPLE", 105, "m", "http://space-facts.com/wp-content/uploads/jupiter.png");
  addObject("PINK", 110, "m", "https://vignette1.wikia.nocookie.net/starwars/images/4/4a/Alderaan.jpg");
  addObject("BROWN", 150, "m", "https://cdn.pixabay.com/photo/2013/07/12/16/33/venus-151142_960_720.png");
  addObject("GRAY", 180, "m", "http://www.lpi.usra.edu/lpi_40th/images/1989/neptune.jpg");
  //addObject("WHITE", 200, "m", "http://www.clipartkid.com/images/19/log-in-sign-up-upload-clipart-Dpr48a-clipart.png");
  addObject("INDIGO", 300, "m", "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Sun_in_February.jpg/155px-Sun_in_February.jpg");
  addObject("SKYBLUE", 301, "m", "https://upload.wikimedia.org/wikipedia/commons/e/ea/Uranus_(Edited).jpg");
  addObject("BLUE", 1000, "m", "https://vignette2.wikia.nocookie.net/heman/images/3/36/Earth.jpg");
}

//void readConfig() {
//  for (int i = 0; i < configfile.length; i++) {
//    char slash = configfile[i].charAt(0);
//    if (slash != '/') {
//      //getting config values based on line number
//      if (i == 1) {
//        xoffset = int(configfile[i]);
//      } else if (i == 3) {
//        scale = float(configfile[i]);
//      }
//    }
//  }
//}

void draw() {
  //image(backgroundImage, 0, 0);
  fill(0,0,0);
  rect(0, 0, 1500, 800);

  int x = 0 + xoffset;
  for ( Object drawObject : ObjectList ) {
    float dia = drawObject.diameter;
    //int drawWidthh = int(scale * dia);
    int drawWidth = int(scale * dia);
      int drawHeight = int(drawWidth * drawObject.hei / drawObject.wid);
    if (x+drawObject.img.width >= 0 && x <= 1500) {

      //checks if image is too small to be drawn

      if (drawWidth > 0 && drawHeight > 0) {
        image(drawObject.img, x, 400-(drawHeight/2),drawWidth, drawHeight);
        //calculates font size relative to object's current size
        int textSize;
        //checks if the name or diameter is longer, then uses the longer one for calculation
        fill(255,255,255);
        if (drawObject.name.length() < str(drawObject.diameter).length()) {
          textSize = int(drawWidth/str(drawObject.diameter).length());
        } else {
          textSize = int(drawWidth/drawObject.name.length());
        }
        if (textSize > 0) {
          textSize(textSize);
          float texty = 418+(drawHeight/2);
          if (texty < (418+(drawHeight/2))) {
            texty = 418;
          }
          text(drawObject.name, x+(drawWidth/2), texty);
          text(drawObject.diameter+drawObject.unit, x+(drawWidth/2), texty+textSize);
        }
      }

    }
    drawObject.xpos = x;
      x += (drawWidth*0.08 + drawWidth);
    //display deltax
    textSize(32);
    text(str(deltax), 1450, 10);
    text(str(deltascale), 1450, 50);
    //display Saved
    //if (savetimer > 0) {
    //  text("Saved", 1450, 90);
    //  //text(str(savetimer),1450,130);
    //}
    //if (savetimer > 0) {
    //  //savetimer -= 1;
    //}
    println(str(scale));
  }
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  if (e < 0) {
    scale *= (1 + deltascale);
  } else if (e > 0) {
    scale *= (1 - deltascale) ;
  }
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == LEFT) {
      xoffset += deltax;
    } else if (keyCode == RIGHT) {
      xoffset -= deltax;
    } else if (keyCode == UP) {
      deltax += 5;
    } else if (keyCode == DOWN) {
      deltax -= 5;
    }
  }
  if (key == 'r') {
    //reloadObjects();
  } else if (key == 'q') {
    deltascale += 0.02;
  } else if (key == 'a') {
    deltascale -= 0.02;
  }
  if (deltax < 0) {
    deltax = 0;
  } else if (deltascale < 0) {
    deltascale = 0;
  }
}

void keyReleased() {
  //reloadObjects();
}

void reloadObjects() {
  for ( Object reloadObject : ObjectList ) {
    float dia = reloadObject.diameter;
    //int drawWidthh = int(scale * dia);
    if (reloadObject.xpos > 0 && reloadObject.xpos+reloadObject.img.width <= 1500) {
      reloadObject.img = loadImage(reloadObject.sprite);
    }
  }
}

Use the mouse scroll wheel to zoom in and out and left and right arrow keys to navigate. Thanks !

A: You can get away with a bunch of nested transformations keeping track of coordinate spaces using pushMatrix()/popMatrix() calls.
You can follow the 2D Transformations Processing Tutorial for more details.
Here's a quick commented sketch that explains the concept:
//a position to scale from
PVector mouse = new PVector();
//a scale value
float scale = 1.0;
//drawing dimensions - this depends on your actual content
float w = 400;
float h = 400;

void setup(){
  size(400,400);
  rectMode(CENTER);
}
void draw(){
  background(255);
  //move everything to centre
  translate(width * .5, height * .5);
  //isolate coordinate space
  pushMatrix();
  //move in the opposite direction by half of the drawing size => transform from drawing centre
  translate(-w * .5,-h * .5);
  //move to where the transformation centre should be (this can be mixed with the above, but I left it on two lines so it's easier to understand)
  translate(mouse.x,mouse.y);
  //transform from set position
  scale(scale);
  //move the transformation back
  translate(-mouse.x,-mouse.y);
  //draw what you need to draw
  drawStuff();
  //return to global coordinate space
  popMatrix();

  //draw a preview of the transformation centre
  if(mousePressed){
    fill(192,0,0);
    ellipse(mouse.x-width*.5,mouse.y-height*.5,35,35);
  }
}
//just a bunch of boxes as a placeholder
void drawStuff(){
  for(int i = 0 ; i < 400; i++){
    int x = i % 20;
    int y = i / 20;
    pushMatrix();
    translate(x * 20, y * 20);
    rotate(radians(i));
    scale(sin(radians(i)) + 1.1);
    fill(i % 400);
    rect(0,0,15,15);
    popMatrix();
  }
}
//set the transformation centre
void mousePressed(){
  mouse.set(mouseX,mouseY);
}
//change scale by moving mouse on X axis
void mouseDragged(){
  scale = map(mouseX,0,width,0.25,2.0);
}

You can run a demo bellow:

//a position to scale from
var mouse;
//a scale value
var scl = 1.0;
//drawing dimensions - this depends on your actual content
var w = 400;
var h = 400;

function setup(){
  mouse = createVector(0,0);
  createCanvas(400,400);
  rectMode(CENTER);
}
function draw(){
  background(255);
  //move everything to centre
  translate(width * .5, height * .5);
  //isolate coordinate space
  push();
  //move in the opposite direction by half of the drawing size => transform from drawing centre
  translate(-w * .5,-h * .5);
  //move to where the transformation centre should be (this can be mixed with the above, but I left it on two lines so it's easier to understand)
  translate(mouse.x,mouse.y);
  //transform from set position
  scale(scl);
  //move the transformation back
  translate(-mouse.x,-mouse.y);
  //draw what you need to draw
  drawStuff();
  //return to global coordinate space
  pop();

  //draw a preview of the transformation centre
  if(mousePressed){
    fill(192,0,0);
    ellipse(mouse.x-width*.5,mouse.y-height*.5,35,35);
  }
}
//just a bunch of boxes as a placeholder
function drawStuff(){
  for(var i = 0 ; i < 400; i++){
    var x = i % 20;
    var y = i / 20;
    push();
    translate(x * 20, y * 20);
    rotate(radians(i));
    scale(sin(radians(i)) + 1.1);
    fill(i % 400);
    rect(0,0,15,15);
    pop();
  }
}
//set the transformation centre
function mousePressed(){
  mouse.set(mouseX,mouseY);
}
//change scale by moving mouse on X axis
function mouseDragged(){
  scl = map(mouseX,0,width,0.25,2.0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/p5.js"></script>


text:
Q: Enable to refresh token on a java feign client I am trying to use a request interceptor to refresh a token on a feign client.
The problem is that the interceptor is executed on the first request and its not executed on other. Her's the code of the interceptor. I am using the common instant to try to refresh the token when its expired but the code is only executed on the first request. What is the good way to do that?
public AdeptClientConfiguration(TokenService tokenService) {
    this.tokenService = tokenService;
  }

  @Lazy
  @Bean
  @Qualifier("AdeptRequestInterceptor")
  public RequestInterceptor requestInterceptor() {
    Instant instant = Instant.now();
    if (token == null || (instant.getEpochSecond()>token.getRefreshExpiresIn())) {
      token = tokenService.getAdeptAccessToken();
      token.setRefreshExpiresIn(instant.getEpochSecond() + token.getExpiresIn());
    }
    return requestTemplate -> requestTemplate.header("Authorization", "Bearer " + token.getAccessToken());
  }

This is how I inject the interceptor.
@Lazy
@FeignClient(value = "adept",  configuration = AdeptClientConfiguration.class, url = "${application.web.adeptUrl}")
public interface AdeptClient {

the method token.getAccessToken()) is returning me a new token.
Thanks for help.

A:     public RequestInterceptor requestInterceptor() {
        return requestTemplate -> requestTemplate.header("Authorization", "Bearer " + getAccessToken());
    }

    private String getAccessToken() {
        Instant instant = Instant.now();
        if (token == null || (instant.getEpochSecond()>token.getRefreshExpiresIn())) {
            token = tokenService.getAdeptAccessToken();
            token.setRefreshExpiresIn(instant.getEpochSecond() + token.getExpiresIn());
        }
        return token.getAccessToken();
    }


text:
Q: How to change timer I'm not sure how to change the timer in my program.
I want to control the timer as the program runs.
This is my code:
Timer timer = new Timer(Difficulty, new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                if(p.GameOver==0)
                {
                    if(p.s==1)
                    {
                        System.out.println("S");
                        p.moveSquare(p.SnakeHeadX,p.SnakeHeadY+p.SnakeHeadH);
                        p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
                        p.Border(p.SnakeHeadX,p.SnakeHeadY);
                        p.Colision(p.SnakeHeadX,p.SnakeHeadY);
                    }
                    if(p.d==1)
                    {
                        System.out.println("D");
                        p.moveSquare(p.SnakeHeadX+p.SnakeHeadW,p.SnakeHeadY);
                        p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
                        p.Border(p.SnakeHeadX,p.SnakeHeadY);
                        p.Colision(p.SnakeHeadX,p.SnakeHeadY);
                    }
                    if(p.a==1)
                    {
                        System.out.println("A");
                        p.moveSquare(p.SnakeHeadX - p.SnakeHeadW,p.SnakeHeadY);
                        p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
                        p.Border(p.SnakeHeadX,p.SnakeHeadY);
                        p.Colision(p.SnakeHeadX,p.SnakeHeadY);
                    }
                    if(p.w==1)
                    {
                        System.out.println("W");
                        p.moveSquare(p.SnakeHeadX,p.SnakeHeadY-p.SnakeHeadH);
                        p.eatBlueSquare(p.SnakeHeadX,p.SnakeHeadY);
                        p.Border(p.SnakeHeadX,p.SnakeHeadY);
                        p.Colision(p.SnakeHeadX,p.SnakeHeadY);
                    }

                }

            }
        });
timer.start();

If I change difficulty as the program runs there is no effect.

A: Just use timer.setDelay(Difficulty) every time you update the difficulty.
For more info about timer see this: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

A: you would have to cancel the current timer and then reinstantiate the timer with the correct value (where you would change the difficulty)


text:
Q: Is there a way to upload a deep learning model to a PostgreSQL database? I have deep learning models (tensorflow in hdf5 format), which I want to upload to a PostgreSQL database.
A single model may be up to 500 MBs, and the models need to be updated and uploaded/downloaded from the database frequently (e.g., once every 30 mins).
I'm a begineer to PostgreSQL, so any information/receipes to start with would be appreciated.

A: Storing large binary data in an relational DB is possible but unwise. Also, you have to eventually copy your model from the DB to the disk for TensorFlow to load anyway. Why not store your model directly on the disk?

A: Relation DB is a wrong tool for this. Store the link to an S3 bucket for example. Or your own private cloud if the model is private.


text:
Q: USB WiFi stick: not detected as a WLAN device (0BDA:C811 Realtek AC) I tried Ubuntu LTS and Fedora 37.

*

*On lshw, the Realtek device shows up as unclaimed.

*I can see the device using lsusb.

*I found some solution on the net about installed "linux-modules-extra" for Ubuntu but that package is not available for Ubuntu LTS.

*i found a suggestion that talks about modprobe and blacklist (also for Ubuntu) and same result.
Any more ideas? thanks


text:
Q: How to limit task executions in Camunda (without external synchronization) I have a Camunda delegate which is supposed to send mails. We want to restrict the parallel executions of tasks so that the mail server is not flooded with too many messages.
Is there any (easy) possibility to restrict that task only to, say, 25 concurrent executions without resorting to Camunda-external synchronization (which is possible but complicated)?

A: If you make the service task async in the modeler, the camunda jobexecutor will execute the delegate with a managed thread pool, so you will have a maximum of the definied executor threads sending mails. Could already be a solution for your problem.