text:
Q: How to count the length of concatenated strings from one column based on an ID in another? I have the following function
set.seed(1984)
test <- function(paths){
  x <- matrix(rep(NA, paths*3), ncol = 3,
              dimnames = list(c(), c("Cookie", "Site", "Count")))
  for(i in 1:paths){
    x[i, 1] <- round(sqrt(rnorm(1,50,100)^2))
    n <- function(){sample(1:10, size = 1)}
    draws <- function(){sample(LETTERS[1:5], n(), replace = T)}
    x[i, 2] <- paste(draws(), collapse = '-')
    }
  return(x)
}

Which produces output like
Cookie      Site                  Count
[1,] "91"   "B-D-E-A"             NA
[2,] "37"   "E-A-D"               NA
[3,] "108"  "B"                   NA
[4,] "93"   "D-A-D"               NA
[5,] "157"  "E-C"                 NA
[6,] "52"   "B-C-D-A-C-C-B-A-B-E" NA

For each of the unique cookie IDs in the Cookie column I'd like to

*

*concatenate each of its Site strings together (Cookie contains repeat values)

*get that concatenation's length

*drop that TOTAL length as the Count value for that Cookie ID (so, there may be repeats)

Any ideas?

A: This will group your matrix by the Cookie and return the total number of characters in the Site column (which is equal to the length of the concantenation.
test.df <- test(91)
library(dplyr)
test.df %>%
  as.data.frame(., stringsAsFactors = FALSE) %>%
  group_by(Cookie) %>%
  mutate(Count = sum(nchar(Site)))

If you want the Count to exclude the character -, just replace Site with gsub("-", "", Site, fixed = TRUE).

A: With data.table, we can do
library(data.table)
dt <- as.data.table(test(91))[, Count := as.character(sum(nchar(gsub("-", "", Site)))) ,
                    by = Cookie][]

dt[, Full_path := gsub("-", ", ", toString(Site)), by = Cookie]
head(dt)
#   Cookie          Site Count                    Full_path
#1:    258             A     1                            A
#2:     26     D-D-E-E-C    10 D, D, E, E, C, E, E, A, C, A
#3:     43         D-D-A     3                      D, D, A
#4:    171 C-C-E-A-B-D-E     7          C, C, E, A, B, D, E
#5:     57       A-D-D-C     4                   A, D, D, C
#6:    156           A-D     2                         A, D

If we need full-dashes
dt[, Full_path := paste(Site, collapse="-"), by = Cookie]


text:
Q: Infinite loop while trying to make a simple vending machine program I am trying to make a simple vending machine program this is my first time writing an independent program in python on my own.
I am not posting the whole code in the program unless requested. My issue is that the program will keep displaying infinite messages, basically an infinite loop.
I will post a small portion of the program here, again if needed I can post the full program.
def vending_process(item):
    balance=20
    vending_items={'Haribo':20 , 'Hershey':21, 'Lays':22, 'Cheetos':23, 'Pepsi':24, 'Dew':25, 'Rockstar':26, 'Monster': 27, 'Starbucks':28, 'Nescafe':29}
    item=int(input("Choose your item from the vending machine! Choose -1 to abort: "))
    if item==-1:
        exit(0)
    else:
      while item!=-1:
        if item not in vending_items.values():
           print("No such entry!")
           continue
        elif item in vending_items.values():
             if item==20:
               balance=balance-1.5
               print('You bought Haribo for 1.50! your balance is {}'.format(balance))

My issue ere is that the Print message will keep repeating itself. I want it to print back the "Choose your item from the vending machine!" and repeat the process while still updating the balance.

A: Some suggestions: I have added comments in the code where necessary. This may be improved upon, but a few points: no need to pass item as it is asked for through user input, use return for exit, no need to run elif or similar conditionals as the routine will leave via return before it reaches the rest of the code:
def vending_process(): # no need to pass 'item' as this is an inpt
    balance=20
    vending_items={'Haribo':20 , 'Hershey':21, 'Lays':22, 'Cheetos':23, 'Pepsi':24, 'Dew':25, 'Rockstar':26, 'Monster': 27, 'Starbucks':28, 'Nescafe':29}

    while balance > 0: # continue process till balance drops below 0
        item=int(input("Choose your item from the vending machine! Choose -1 to abort: "))
        if item==-1:
            return -1 # exit (return preferable)
        if item not in vending_items.values():
            print("No such entry!")
            return -2 # invalid item
        if item == 20:
            balance -= 1.5
            print('You bought Haribo for 1.50! your balance is {}'.format(balance))

vending_process()

This produces
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 18.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 17.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 15.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 14.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 12.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 11.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 9.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 8.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 6.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 5.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 3.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 2.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 0.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is -1.0

Next steps would be to add handling other items, maybe then passing the balance and the items dict to the function to handle increasingly general cases.

A: Try this:
while item!=-1:
        item = input('Choose your item from the vending machine: ')
        item = int(item)
        if item == -1:
           break
        elif item not in vending_items.values():
           print("No such entry!")
           continue
        elif item in vending_items.values():
             if item==20:
               balance=balance-1.5
               print('You bought Haribo for 1.50! your balance is {}'.format(balance))

Just initialize the value of item to anything other than -1 before the while loop and you're good to go.
The issue is that the value of item never changes in your while loop that you have written. Ideally, you should take user input inside the while loop which will allow for the input to be changing each time you run the loop.
Also a small suggestion - try adding some code to check if the balance goes lower than 0. All the best for your endeavors.

A: def vending_process(item):
    balance=20
    vending_items={'Haribo':20 , 'Hershey':21, 'Lays':22, 'Cheetos':23, 'Pepsi':24, 'Dew':25, 'Rockstar':26, 'Monster': 27, 'Starbucks':28, 'Nescafe':29}
    item = 0
    while item != -1:
        item=int(input("Choose your item from the vending machine! Choose -1 to abort: "))
        if item not in vending_items.values():
           print("No such entry!")
        elif item in vending_items.values():
             if item==20:
                 balance=balance-1.5
                 print('You bought Haribo for 1.50! your balance is {}'.format(balance))

A: Without a broader look at your code. I cannot see the reason for the while item != -1 being used right after you checked that item!=-1which is the reason for your infinite loop.
As I understand you want the user to select an item until they decide to quit. That should be something like:
def vending_process(item):
    balance=20
    vending_items={'Haribo':20 , 'Hershey':21, 'Lays':22, 'Cheetos':23, 'Pepsi':24, 'Dew':25, 'Rockstar':26, 'Monster': 27, 'Starbucks':28, 'Nescafe':29}
    item = 0 #Just to get it started
    while item!=-1:
        item=int(input("Choose your item from the vending machine! Choose -1 to abort: "))
        if item==-1:
            exit(0)
        elif item not in vending_items.values():
           print("No such entry!")
           continue
        elif item in vending_items.values():
             if item==20:
               balance=balance-1.5
               print('You bought Haribo for 1.50! your balance is {}'.format(balance))

redpajama_set_name: RedPajamaStackExchange


text:
Q: sh - Build string containing paths I'm building a small shell script for finding cat/man pages on a wide range of unix systems... in bash, I could build all possible paths by doing this:
# default search paths
default=$(echo /usr/{share, local, dpkg, XR11}/man/{man, cat}{1..8})

for path in $default
do
  ...
done

Unfortunately, I'm forced to use sh... I could build the paths with loops, but this would look really ugly... is there a neater/shorter way?

A: On my Linux system, "man -w" prints the location of the nroff source file instead of its contents. That way you use man's internal search to find the files - just like a user on the command line.
See "man man" for more information.

A: This isn't terrible:
for dir in share local pdkg XR11; do
  for type in man cat; do
    for n in 1 2 3 4 5 6 7 8; do
      path="/usr/${dir}/man/${type}$n"
      # ...
    done
  done
done

or even, though it's not DRY, this is explicit and readable
prefixes="
    /usr/share/man/man /usr/share/man/cat
    /usr/local/man/man /usr/local/man/cat
    /usr/pdkg/man/man  /usr/pdkg/man/cat
    /usr/XR11/man/man  /usr/XR11/man/cat
"
for prefix in $prefixes; do
  for n in 1 2 3 4 5 6 7 8; do
    path="${prefix}$n"
    # ...
  done
done

A: you can use find
find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d \( -name "man[0-9]" -o -name "cat[0-9]" -o -name "cat" -o -name "man" \)

A: Given Bourne shell, I'd probably use:
for path in `ls -d /usr/*/man/[mc]a[tn][1-8]`
do
    if [ -d $path ]
    then ...
    fi
done

This only leads you astray if somebody malicious creates a directory /usr/spoof/man/man3, or /usr/share/man/mat1 or /usr/dpkg/man/can2, which is unlikely enough that I'd not worry about it.

A: You can use find:
find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d -regex '.*/man/\(cat\|man\)[1-8]$'

On my system, I have a bunch of localized man pages that would get excluded by the above, so  you could do this:
find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d -regex '.*/\(cat\|man\)[1-8]$'


text:
Q: vb doens't excute all batch commands, just a few First I'm new at VB. So don't go hard on me :P
I want to run a batch file silently and after that a batch the normal way.
And this must run when the file is being opened so not via cmd.
I already tried something but it doesn't pause:
My *.vbs for the normal batch:
set shell=CreateObject("Shell.Application")
shell.ShellExecute "C:\Apps\SV\Test.bat", 1, True

I don't have a .vbs for my silent batch(yet).
My Test.bat:
http://pastebin.com/u95WjzWF
The batch echo's a picture and then pause.
But when I run my VB script it shows for a sec and disappears.
I think VB didn't executed the pause command in the batch.
So what is the script to do this?

A: I got the answer.
In my batch the pause command is like this:
pause>swap

That doesn't work but when I do it like this:
pause >swap

Then it works and the batch pauses.
Thanks @Kayasax @aphoria @foxdrive


text:
Q: iMac display wakes up even when no one is using it I have my iMac set to set the display to sleep after 15 minutes. I notice at night that, even when no one is touching the computer, the display will come on for a while and then to go back to sleep after it's usually set time (10 minutes).
Is there any way to find out what's waking it up? Or even better, to force it to keep the display asleep?

A: Try this in your Terminal:
syslog |grep -i "Wake reason"

Then you'll get something like:
Sat Sep 08 09:28:12 MacBookPro kernel[0] : Wake reason = OHC1
Mon Sep 10 21:14:54 MacBookPro kernel[0] : Wake reason = PWRB
...

Depending on the text after the =-sign, you have the reason why your Mac went to sleep. And it can have multiple causes:

*

*OHC: some USB device. If you see OHC1 or OHC2, it's very likely a USB keyboard or mouse has woken up your iMac.

*EHC: USB interface too, but if you see this, it will likely be a wireless device.

*USB: another USB device (drive, printer,...)

*PWRB: If your powerbutton gets pressed (very unlikely)

*RTC: a scheduled wake-up (energy saver, backups, iCal events,...)

I hope your item is in this list :)

A: Applications folder -> Utilities folder -> "Console" application will show you logs.
Maybe you see something like USB wake up
Do you have some bluetooth HID like keyboard mouse ?
found at http://forums.macrumors.com/archive/index.php/t-428248.html


text:
Q: Prevent automatic Timestamp change in SQL Server statement If table has a Timestamp column it's changed every time an UPDATE statement is executed.
We have the following scenario: the Timestamp is used for optimistic concurrency (detection of change) in Linq 2 SQL. This works fine.
But sometimes we want to update a record outside of Linq 2 SQL, executing direct SQL code. We do this and then ChangeConflictException occurs during subsequent modifications through Linq 2 SQL, because the Timestamp is changed by that direct statement.
So the questions is as follows: is there any workaround to keep the optimistic concurrency in Linq 2 SQL, but also allow direct modification without raising ChangeConflictException?


text:
Q: Unable to activate solution in another machine I have a solution that has custom site columns and content types. When I try to activate this on the production box is does not allow me to do so and whenever I try to activate, it gives me an error which says -

A duplicate field name "XXXXXXXXXXX" was found.

Although there is no such field with this id in my solution. It is really difficult to troubleshoot. Please help.


text:
Q: jQuery onclick function won't fire on nested divs I've got a web-page that features two buttons at the top which are meant to sort some data later in the page.  For some reason I can't get the nested #byFilter to accept an onclick(function())
Javascript
$(document).ready(function() {

            $('.filter').click(function() {
                console.log('I\'ve gotten');

            });

            $('#byName').click(function(e) {
                e.stopPropagation();
                console.log('this far');

            });

            //just some stuff with geolocation
            getLocation().done(function() {

                getStuff(origin);

            });
        });

HTML

                Name

                Distance

So when I load the page and click on the divs, all I get is "I've gotten"
I don't remember any extra step required to attach a click listener to a nested div like this, but I can't seem to get this to work.  I fear I'm missing something quite trivial.

A: Remove the pound(#) signs in the id attributes themselves. Pound is only used in a selector as a short-hand to refer to an id attribute

$(document).ready(function() {

  $('.filter').click(function() {
    console.log('I\'ve gotten');

  });

  $('#byName').click(function(e) {
    e.stopPropagation();
    console.log('this far');

  });

});

  Name

  Distance


text:
Q: how to run the quartz scheduler as soon as I started the server in JBOSS5.1.1 Currently I have added the quartz-1.8.6 and quartz-jboss-1.8.6 jars and quartz-    service.xml file in jboss5.1.1 and i have added the quartz1.8.6 related jar files in the EAR application and I have return the code as follows:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
InitialContext ctx = new InitialContext();
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = new JobDetail("job1", "group1", SimpleJob.class);
CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1", "group1", "0/5 * * * * ?");
sched.addJob(job, true);
Date ft = sched.scheduleJob(trigger);
try
{
 Thread.activeCount();
catch (Exception e)
 {
}
sched.start();
}
catch (Exception exc){
exc.printStackTrace();
}
.....
}

but this code is running successfully once i logged in the link ...but i needed it to run the crontask once the server started


text:
Q: Spring Boot is not creating tables automatically I'm facing an error when Spring Boot try to insert data in a table. I'm using H2 and Spring Boot 2.5.0. It's seems that Spring is not creating the table.
Here is my entity
@Entity(name = "Users")
@Table(name = "users")
public class UserEntity implements Serializable {

    // Serial

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String surname;

    private String email;

    // Getters and setters

}

And my repository
public interface UserRepository extends JpaRepository<UserEntity, Integer> {

}

I have added to my pom.xml h2 and spring-boot-starter-data-jpa.
When I start the server in debug mode I got this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/PATH/target/classes/data.sql]: INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Tabla "USERS" no encontrada
Table "USERS" not found; SQL statement:
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com') [42102-200]

This is my data.sql
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com');
INSERT INTO users (id, name, surname, email) VALUES (2, 'Melanie', 'Bell', 'melanie.bell51@example.com');
INSERT INTO users (id, name, surname, email) VALUES (3, 'Diane', 'Ruiz', 'diane.ruiz24@example.com');

I try some configuration in properties file but I wasn't able to fix the error.
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver

I can see the query to insert data but it's not generating query to create the table so I think that the problem is there.
Thanks in advance.

A: The SQL Script DataSource Initialization feature has been redesigned in Spring Boot 2.5.

By default, data.sql scripts are now run before Hibernate is
initialized. This aligns the behavior of basic script-based
initialization with that of Flyway and Liquibase. If you want to use
data.sql to populate a schema created by Hibernate, set
spring.jpa.defer-datasource-initialization to true. While mixing
database initialization technologies is not recommended, this will
also allow you to use a schema.sql script to build upon a
Hibernate-created schema before it's populated via data.sql.

Reference
Spring Boot 2.5 Release Notes

A: If you are working on a maven project, spring.jpa.defer-datasource-initialization=true should be added in both src/main/resources/application.properties(for Spring Boot Application to run properly) and src/test/resources/application.properties (for mvn clean install to execute successfully).
PS: I am using Spring boot 3.0.2

A: Make sure adding dependence of h2 database here both dependence for
gradle
enter code here
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'

maven  dependence
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop change to update it mean when rerun application or project your previous data in database will not lose.


text:
Q: jquery prevent reload form on submit I want to upload files using javascript/jquery/ajax and in my case, I have to prevent the reload on form submitting on upload.
Also, I want to add a delete button, such that, when file is uploaded, the delete button can delete this and same is the scenario, that to prevent the page refresh/reload on form submitting.
Hence, I've three buttons in a single form, UPLOAD, DELETE, NEXT and in my case, only next allows to submit the form by refreshing/action of form. And obviously, when file is just selected and the user directly hits the next button, it first uploads and then take his action.
HTML:
    <form name="myform" method="post" id="FORM2" enctype="multipart/form-data">
// OTHER VALUES OF FORM
                    <input type="file" name="FileUpload-1" id="FileUpload-1"  class="file_upload" />

                    <input type="submit" value="Upload" id="upload" class="submitUpload" />
                    <input type="submit" value="Delete" id="delete" class="submitDelete" />

<input type="submit" name="" id="FORMSUBMIT">
</form>

JS:
  $(".submitUpload").click(function(){ console.log('UPLOAD');
        action = "upload.php";
         $("#FORM").on('submit',function(){
          var options={
           url     : action,
           success : onsuccess
          };
        $(this).ajaxSubmit(options);
         return false;
         });
     }
     return false;

    });

     $(".submitDelete").click(function(){ console.log('DELETE');
        return false;
    });
 $('.FORMSUBMIT').click(function () {
         //CUSTOM HANDLING
      });

A: To Directly answer your question:
$("#FORM").on('submit',function(evt){
    evt.preventDefault();
});

This piece of code will prevent the normal form submitting.
My advice is to transform the Update and Delete buttons from type=submit to type=button. Like this:
<input type="button" value="Delete" id="Delete" class="submitDelete" />

This will prevent the form to be submitted when delete or update are pressed...
I wrote a jsfiddle for you:
https://jsfiddle.net/yL35bh10/

A: I recently prototyped a page needing image file upload.  I found a package on GitHub that was easy to use and should provide the majority of the functionality you're needing.
https://github.com/blueimp/jQuery-File-Upload
My only question to you:  Once a file is uploaded to the server, how are you going to know what to delete?


text:
Q: How to programmatically differentiate between iphone 4 and iphone 4S? I am working on app which needs to check the iphone model, but I'm not able to find any solution.  I will be thank full for any suggestion.

A: This is much simpler one. SIMPLE ENOUGH FOR JUST COPY & PASTE
Also, I've included matching model name for machine name.
//MARK: Required import
#import <sys/utsname.h>

+ (NSString*)deviceModelName {

    struct utsname systemInfo;
    uname(&systemInfo);

    NSString *machineName = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];

    //MARK: More official list is at
    //http://theiphonewiki.com/wiki/Models
    //MARK: You may just return machineName. Following is for convenience

    NSDictionary *commonNamesDictionary =
    @{
      @"i386":     @"iPhone Simulator",
   @"x86_64":   @"iPad Simulator",

   @"iPhone1,1":    @"iPhone",
   @"iPhone1,2":    @"iPhone 3G",
   @"iPhone2,1":    @"iPhone 3GS",
   @"iPhone3,1":    @"iPhone 4",
   @"iPhone3,2":    @"iPhone 4(Rev A)",
   @"iPhone3,3":    @"iPhone 4(CDMA)",
   @"iPhone4,1":    @"iPhone 4S",
   @"iPhone5,1":    @"iPhone 5(GSM)",
   @"iPhone5,2":    @"iPhone 5(GSM+CDMA)",
   @"iPhone5,3":    @"iPhone 5c(GSM)",
   @"iPhone5,4":    @"iPhone 5c(GSM+CDMA)",
   @"iPhone6,1":    @"iPhone 5s(GSM)",
   @"iPhone6,2":    @"iPhone 5s(GSM+CDMA)",

   @"iPhone7,1":    @"iPhone 6+ (GSM+CDMA)",
   @"iPhone7,2":    @"iPhone 6 (GSM+CDMA)",

   @"iPhone8,1":    @"iPhone 6S (GSM+CDMA)",
   @"iPhone8,2":    @"iPhone 6S+ (GSM+CDMA)",

   @"iPad1,1":  @"iPad",
   @"iPad2,1":  @"iPad 2(WiFi)",
   @"iPad2,2":  @"iPad 2(GSM)",
   @"iPad2,3":  @"iPad 2(CDMA)",
   @"iPad2,4":  @"iPad 2(WiFi Rev A)",
   @"iPad2,5":  @"iPad Mini 1G (WiFi)",
   @"iPad2,6":  @"iPad Mini 1G (GSM)",
   @"iPad2,7":  @"iPad Mini 1G (GSM+CDMA)",
   @"iPad3,1":  @"iPad 3(WiFi)",
   @"iPad3,2":  @"iPad 3(GSM+CDMA)",
   @"iPad3,3":  @"iPad 3(GSM)",
   @"iPad3,4":  @"iPad 4(WiFi)",
   @"iPad3,5":  @"iPad 4(GSM)",
   @"iPad3,6":  @"iPad 4(GSM+CDMA)",

   @"iPad4,1":  @"iPad Air(WiFi)",
   @"iPad4,2":  @"iPad Air(GSM)",
   @"iPad4,3":  @"iPad Air(GSM+CDMA)",

   @"iPad5,3":  @"iPad Air 2 (WiFi)",
   @"iPad5,4":  @"iPad Air 2 (GSM+CDMA)",

   @"iPad4,4":  @"iPad Mini 2G (WiFi)",
   @"iPad4,5":  @"iPad Mini 2G (GSM)",
   @"iPad4,6":  @"iPad Mini 2G (GSM+CDMA)",

   @"iPad4,7":  @"iPad Mini 3G (WiFi)",
   @"iPad4,8":  @"iPad Mini 3G (GSM)",
   @"iPad4,9":  @"iPad Mini 3G (GSM+CDMA)",

   @"iPod1,1":  @"iPod 1st Gen",
   @"iPod2,1":  @"iPod 2nd Gen",
   @"iPod3,1":  @"iPod 3rd Gen",
   @"iPod4,1":  @"iPod 4th Gen",
   @"iPod5,1":  @"iPod 5th Gen",
   @"iPod7,1":  @"iPod 6th Gen",
    };

    NSString *deviceName = commonNamesDictionary[machineName];

    if (deviceName == nil) {
        deviceName = machineName;
    }

    return deviceName;
}

A: Update a list of devices:
In future will be updated with iPad 4.
+  (NSString*)deviceModelName {
/*
 @"i386"      on the simulator
 @"x86_64"    on the simulator
 @"iPod1,1"   on iPod Touch
 @"iPod2,1"   on iPod Touch Second Generation
 @"iPod3,1"   on iPod Touch Third Generation
 @"iPod4,1"   on iPod Touch Fourth Generation
 @"iPod5,1"   on iPod Touch Fourth Generation
 @"iPhone1,1" on iPhone
 @"iPhone1,2" on iPhone 3G
 @"iPhone2,1" on iPhone 3GS
 @"iPad1,1"   on iPad
 @"iPad2,1"   on iPad 2
 @"iPad2,5"   on iPad mini 1
 @"iPad3,1"   on iPad 3
 @"iPhone3,1" on iPhone 4
 @"iPhone4,1" on iPhone 4S
 @"iPhone5,1" on iPhone 5
 */

struct utsname systemInfo;

uname(&systemInfo);

NSString *modelName = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];

if([modelName isEqualToString:@"i386"] || [modelName isEqualToString:@"x86_64"]) {
    modelName = @"iPhone Simulator";
}
else if([modelName isEqualToString:@"iPhone1,1"]) {
    modelName = @"iPhone";
}
else if([modelName isEqualToString:@"iPhone1,2"]) {
    modelName = @"iPhone 3G";
}
else if([modelName isEqualToString:@"iPhone2,1"]) {
    modelName = @"iPhone 3GS";
}
else if([modelName isEqualToString:@"iPhone3,1"]) {
    modelName = @"iPhone 4";
}
else if([modelName isEqualToString:@"iPhone4,1"]) {
    modelName = @"iPhone 4S";
}
else if([modelName isEqualToString:@"iPhone5,1"]) {
    modelName = @"iPhone 5";
}
else if([modelName isEqualToString:@"iPod1,1"]) {
    modelName = @"iPod 1st Gen";
}
else if([modelName isEqualToString:@"iPod2,1"]) {
    modelName = @"iPod 2nd Gen";
}
else if([modelName isEqualToString:@"iPod3,1"]) {
    modelName = @"iPod 3rd Gen";
}
else if([modelName isEqualToString:@"iPod4,1"]) {
    modelName = @"iPod 4th Gen";
}
else if([modelName isEqualToString:@"iPod5,1"]) {
    modelName = @"iPod 5th Gen";
}
else if([modelName isEqualToString:@"iPad1,1"]) {
    modelName = @"iPad";
}
else if([modelName isEqualToString:@"iPad2,1"]) {
    modelName = @"iPad 2(WiFi)";
}
else if([modelName isEqualToString:@"iPad2,2"]) {
    modelName = @"iPad 2(GSM)";
}
else if([modelName isEqualToString:@"iPad2,3"]) {
    modelName = @"iPad 2(CDMA)";
}
else if([modelName isEqualToString:@"iPad2,4"]) {
    modelName = @"iPad 2(WiFi + New Chip)";
}
else if([modelName isEqualToString:@"iPad2,5"]) {
    modelName = @"iPad mini (WiFi)";
}
else if([modelName isEqualToString:@"iPad2,6"]) {
    modelName = @"iPad mini (GSM)";
}
else if([modelName isEqualToString:@"iPad3,1"]) {
    modelName = @"iPad 3(WiFi)";
}
else if([modelName isEqualToString:@"iPad3,2"]) {
    modelName = @"iPad 3(GSM)";
}
else if([modelName isEqualToString:@"iPad3,3"]) {
    modelName = @"iPad 3(CDMA)";
}

return modelName;

}

A: For my purposes I've written a tiny library that abstracts away the underlying C calls and presents an Objective-C interface.
NSLog(@"Big model number: %d", deviceDetails.bigModel);
//Big model number: 4

NSLog(@"Small model number: %d", deviceDetails.smallModel);
//Small model number: 1

if (deviceDetails.model == GBDeviceModeliPhone4S) {
    NSLog(@"It's a 4S");
}
//It's a 4S

if (deviceDetails.family != GBDeviceFamilyiPad) {
    NSLog(@"It's not an iPad");
}
//It's not an iPad

NSLog(@"systemInfo string: %@", [GBDeviceInfo rawSystemInfoString]);
//systemInfo string: iPhone4,1

It's on github: GBDeviceInfo

A: Use this code. This is a full list of any actual iDevice and the Model number, the list can be updated easily by checking http://theiphonewiki.com/wiki/Models .
#import <sys/utsname.h>

struct utsname systemInfo;
uname(&systemInfo);

NSString *modelName = [NSString stringWithCString:systemInfo.machine
                                         encoding:NSUTF8StringEncoding];

NSString *machinename = [NSString stringWithCString:systemInfo.machine
                                           encoding:NSUTF8StringEncoding];

NSString *modelnumber = @"?";

//Simulator
if([modelName isEqualToString:@"i386"] || [modelName isEqualToString:@"x86_64"]) {
    modelName = @"iPhone Simulator";
}

//iPhone
else if([modelName isEqualToString:@"iPhone1,1"]) {
    modelName = @"iPhone";
    modelnumber = @"A1203";
}
else if([modelName isEqualToString:@"iPhone1,2"]) {
    modelName = @"iPhone 3G";
    modelnumber = @"A1241/A1324";
}
else if([modelName isEqualToString:@"iPhone2,1"]) {
    modelName = @"iPhone 3GS";
    modelnumber = @"A1303/A1325";
}
else if([modelName isEqualToString:@"iPhone3,1"]) {
    modelName = @"iPhone 4 (GSM)";
    modelnumber = @"A1332";
}
else if([modelName isEqualToString:@"iPhone3,2"]) {
    modelName = @"iPhone 4 GSM Rev A";
    modelnumber = @"?";
}
else if([modelName isEqualToString:@"iPhone3,3"]) {
    modelName = @"iPhone 4 (CDMA)";
    modelnumber = @"A1349";
}
else if([modelName isEqualToString:@"iPhone4,1"]) {
    modelName = @"iPhone 4S";
    modelnumber = @"A1387/A1431";
}
else if([modelName isEqualToString:@"iPhone5,1"]) {
    modelName = @"iPhone 5 (GSM)";
    modelnumber = @"A1428";
}
else if([modelName isEqualToString:@"iPhone5,2"]) {
    modelName = @"iPhone 5 (GSM+CDMA)";
    modelnumber = @"A1429/A1442";
}

//iPod touch
else if([modelName isEqualToString:@"iPod1,1"]) {
    modelName = @"iPod touch 1G";
    modelnumber = @"A1213";
}
else if([modelName isEqualToString:@"iPod2,1"]) {
    modelName = @"iPod touch 2G";
    modelnumber = @"A1288";
}
else if([modelName isEqualToString:@"iPod3,1"]) {
    modelName = @"iPod touch 3G";
    modelnumber = @"A1318";
}
else if([modelName isEqualToString:@"iPod4,1"]) {
    modelName = @"iPod touch 4G";
    modelnumber = @"A1367";
}
else if([modelName isEqualToString:@"iPod5,1"]) {
    modelName = @"iPod touch 5G";
    modelnumber = @"A1421";
}

//iPad
else if([modelName isEqualToString:@"iPad1,1"]) {
    modelName = @"iPad 1G";
    modelnumber = @"A1219/A1337";
}
else if([modelName isEqualToString:@"iPad2,1"]) {
    modelName = @"iPad 2 (WiFi)";
    modelnumber = @"A1395";
}
else if([modelName isEqualToString:@"iPad2,2"]) {
    modelName = @"iPad 2 (GSM)";
    modelnumber = @"A1396";
}
else if([modelName isEqualToString:@"iPad2,3"]) {
    modelName = @"iPad 2 (CDMA)";
    modelnumber = @"A1397";
}
else if([modelName isEqualToString:@"iPad2,4"]) {
    modelName = @"iPad 2 (WiFi + Rev A)";
    modelnumber = @"A1395";
}
else if([modelName isEqualToString:@"iPad3,1"]) {
    modelName = @"iPad 3 (WiFi)";
    modelnumber = @"A1416";
}
else if([modelName isEqualToString:@"iPad3,2"]) {
    modelName = @"iPad 3 (GSM+CDMA)";
    modelnumber = @"A1403";
}
else if([modelName isEqualToString:@"iPad3,3"]) {
    modelName = @"iPad 3 (GSM)";
    modelnumber = @"A1430";
}
else if([modelName isEqualToString:@"iPad3,4"]) {
    modelName = @"iPad 4 (WiFi)";
    modelnumber = @"A1458";
}
else if([modelName isEqualToString:@"iPad3,5"]) {
    modelName = @"iPad 4 (GSM)";
    modelnumber = @"A1459";
}
else if([modelName isEqualToString:@"iPad3,6"]) {
    modelName = @"iPad 4 (GSM+CDMA)";
    modelnumber = @"A1460";
}

//iPad mini
else if([modelName isEqualToString:@"iPad2,5"]) {
    modelName = @"iPad mini (WiFi)";
    modelnumber = @"A1432";
}
else if([modelName isEqualToString:@"iPad2,6"]) {
    modelName = @"iPad mini (GSM)";
    modelnumber = @"A1454";
}
else if([modelName isEqualToString:@"iPad2,7"]) {
    modelName = @"iPad mini (GSM+CDMA)";
    modelnumber = @"A1455";
}

//Apple TV, just for funn:)
else if([modelName isEqualToString:@"AppleTV2,1"]) {
    modelName = @"Apple TV 2G";
    modelnumber = @"A1378";
}
else if([modelName isEqualToString:@"AppleTV3,1"]) {
    modelName = @"Apple TV 3G";
    modelnumber = @"A1427";
}
else if([modelName isEqualToString:@"AppleTV3,2"]) {
    modelName = @"Apple TV 3G (Rev A)";
    modelnumber = @"A1469";
}

NSLog(@"Device model: %@/ %@",modelName,modelnumber);

This could be the output: Device model: iPhone 4 GSM/ iPhone3,1

A: Try using following : you will get all the detail informations of the Device...
NSLog(@"uniqueIdentifier: %@", [[UIDevice currentDevice] uniqueIdentifier]);
NSLog(@"name: %@", [[UIDevice currentDevice] name]);
NSLog(@"systemName: %@", [[UIDevice currentDevice] systemName]);
NSLog(@"systemVersion: %@", [[UIDevice currentDevice] systemVersion]);
NSLog(@"model: %@", [[UIDevice currentDevice] model]);
NSLog(@"localizedModel: %@", [[UIDevice currentDevice] localizedModel]);

If above does not work for you then use github project
EDIT :
Whether you are on an iPhone or a iPod Touch:
UIDevice *device = [UIDevice currentDevice];
NSString *systemName = [device systemName];

To detect the version of the OS:
UIDevice *device = [UIDevice currentDevice];
NSString *systemVersion = [device systemVersion];

For Reference:
how do I detect whether I have iPhone 2G,3G,3GS

A: However if you are running application on simulator, you will never get device name as "iPhone 6" of "iPhone6+" or anything like that. I am currently using Xcode Version 6.2 (6C131e) in which I have successfully checked device type even on simulator using few macros. Those are
// ******************* DEVICE INDENTIFICATION MACROS *****************//
#define IS_IPAD             (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE           (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE4          (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 480.0f)
#define IS_IPHONE5          (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_IPHONE6          (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0)
#define IS_IPHONE6PLUS      (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0)
#define IS_RETINA           ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0))

A: Here is a common method of retriving the device model.  There are no NS methods for this, so you gotta use c
#include <sys/types.h>
#include <sys/sysctl.h>

- (NSString *)machine {
    NSString *machine;
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *name = malloc(size);
    sysctlbyname("hw.machine", name, &size, NULL, 0);
    machine = [NSString stringWithUTF8String:name];
    free(name);
    return machine;
}


text:
Q: iPhone: capturing back button event Greetings,
I have the following code for capturing the back button's event:
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStylePlain target:self action:@selector(doLogout:)]];

And here is my doLogout:
-(void) doLogout:(id)sender{
    NSLog(@"hi");
}

Everything compiles and runs fine, and the back button text is changed to "Logout".
The only problem is that my doLogout function is never called!!!
What can I do? I've been stuck on this for an hour now... ;(
Many thanks in advance,

A: The official doc:
When this item is the back item of the navigation bar—when it is the next item below the top item—it may be represented as a back button on the navigation bar. Use this property to specify the back button. The target and action of the back bar button item you set should be nil. The default value is a bar button item displaying the navigation item's title.

A: Instead of trying to catch "back button event" why no just just try overriding UIViewController viewDidUnload?

A: Instead of setting backBarButtonItem on the top view controller, what you could do is set the leftBarButtonItem on the child view controller.  This can be any arbitrary bar button item and all action messages should be delivered as normal. Because this takes place of the back button, you have to make sure you manually pop the child controller in one of the action methods.


text:
Q: Trying to access MariaDB databse through phpmyadmin hosted within a docker container I am trying to set up a basic LAMP stack using docker-compose but am unable to connect to the mariadb database using phpmyadmin when the containers are run.
To try and resolve the issue I stripped back my docker-compose.yaml file to:
version: '3.2'

services:
   db:
      image: mariadb
      container_name: appsDB
      restart: always
      ports:
       - '6603:3306'
      environment:
        MYSQL_ROOT_PASSWORD: secret

   app:
      depends_on:
       - db
      image: phpmyadmin/phpmyadmin
      container_name: phpmyadmin
      restart: always
      ports:
       - '8080:80'
      environment:
        PMA_HOST: db

When I run the containers I can navigate to the phpmyadmin page but when I enter the root/secret username/password I get an error:
 Cannot log in to the MySQL server

 mysqli::real_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known

To make sure it is not an issue with my computer I also ran docker-compose up with the database image changed to mysql and keeping every other detail the same. There was no issue then: phpmyadmin worked fine and I could log into normally with the same root/secret credentials used in the previous image.
Can anyone advise me why mariadb behaves this why and is there any way I can access it via phpmyadmin in a docker container?
EDIT
Following advice to check the connection between the containers it seems the mariadb container database is failing to start. The result from the docker logs is:
2020-07-01  9:32:22 0 [Warning] 'default-authentication-plugin' is MySQL 5.6 / 5.7 compatible option. To be implemented in later versions.
2020-07-01  9:32:22 0 [Note] mysqld (mysqld 10.4.8-MariaDB-1:10.4.8+maria~bionic) starting as process 1 ...
2020-07-01  9:32:22 0 [Note] InnoDB: Using Linux native AIO
2020-07-01  9:32:22 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2020-07-01  9:32:22 0 [Note] InnoDB: Uses event mutexes
2020-07-01  9:32:22 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2020-07-01  9:32:22 0 [Note] InnoDB: Number of pools: 1
2020-07-01  9:32:22 0 [Note] InnoDB: Using SSE2 crc32 instructions
2020-07-01  9:32:22 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
2020-07-01  9:32:22 0 [Note] InnoDB: Initializing buffer pool, total size = 256M, instances = 1, chunk size = 128M
2020-07-01  9:32:22 0 [Note] InnoDB: Completed initialization of buffer pool
2020-07-01  9:32:22 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2020-07-01  9:32:22 0 [ERROR] InnoDB: Invalid flags 0x4800 in ./ibdata1
2020-07-01  9:32:22 0 [ERROR] InnoDB: Plugin initialization aborted with error Data structure corruption
2020-07-01  9:32:23 0 [Note] InnoDB: Starting shutdown...
2020-07-01  9:32:23 0 [ERROR] Plugin 'InnoDB' init function returned error.
2020-07-01  9:32:23 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2020-07-01  9:32:23 0 [Note] Plugin 'FEEDBACK' is disabled.
2020-07-01  9:32:23 0 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2020-07-01  9:32:23 0 [ERROR] Unknown/unsupported storage engine: InnoDB
2020-07-01  9:32:23 0 [ERROR] Aborting

Can anyone advise how I can go about resolving this within docker?
FURTHER EDIT
Just to keep up to date I have found I can start the database container from the CLI with no issues - Database starts and ready to connect:
docker run --name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -d mariadb

A: Are you perhaps working with an outdated version of your images/containers? Your docker-compose.yml works fine for me (my Docker version is 19.03.8, not that I think that should matter).
I'd first try forcing it to recreate the whole stack, docker-compose up --force-recreate. I noted that you refer to this file as docker-compose.yaml but the correct default extension should be .yml; if you once created it with a .yml file (or by specifying the file name directly to docker-compose), it's conceivable to me that Docker would silently (or at least un-noticeably) fail to rebuild the new file, so double-check the file names as well.
If that doesn't work, I'd suggest getting in to the shell of the phpMyAdmin container and trying some networking commands to see if you can connect directly; for instance install the mariadb-client package and try mysql -u root -h db -p.


text:
Q: How to pass object array in url if I have an object like this
value =  [
    {
        "service_id": "5cebd21f28ea9000459a654a"
    },
    {
        "service_id": "5cebbde328ea9000459a6518"
    }
]

how can i pass it through  the url  http://example.com/services/value
i am using the messenger platform and i want to pass my array of objects so that i can receive it and then be able to use it after i have received a response

A: Convert your object to a string using JSON.stringify() and pass the value as a string.


text:
Q: How to downgrade this piece of code from .net 4.0 to 3.5? I've been really loving this extension method in my .NET 4.0 code:
public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

Now, I'd really like to use it in my .net 3.5 project, but it's missing the Contains method.  How can I cleanly downgrade this extension method without complicating things too much?

A: Contains is an extension on IEnumerable introduced in 3.5 as part of LINQ.  This code will compile under 3.5.
If it's not then make sure you have included
using System.Linq

A: I agree with James Gaunt, this should run under 3.5 as is.
Perhaps you have neglected to add the using System.Linq; and using System.Collections.Generic; declarations at the top of your code?
I get caught by that all the time.


text:
Q: Where is the Insert mode command Control-Shift-U documented in Vim? In Insert mode C-S-U (control-shift-u) acts (almost) exactly like C-V u. However, I'm not finding where this mapping/function is documented. Aside, is i_CTRL-S-U how this keycombo would be represented in Vim's help pages and <C-S-U> in a :map command?
I'm using VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Jul 26 2017 20:13:43).

A: C-S-U is not a Vim function: it is for inserting Unicode characters based on their HEX values.
Because it is a functionality of the OS, it is not in the Vim documentation (it's like C-S-V for pasting text, which is a function of the terminal and also not documented in Vim).


text:
Q: How can I improve the smoothness of my NDSolve solution? This will, unfortunately, be a broader question than I prefer, but I do have a concrete example.
I simulate many oscillatory systems with NDSolve. For short simulation times, the result is generally excellent. For longer times, the oscillations get jagged and visibly not-smooth. I find the array of options in NDSolve regarding accuracy, maximum step size, and maximum step count very confusing.
The NDSolve shown below is inferior to a 4th order Runge-Kutta (from Matlab). (For the interested, these equations describe the oscillation of an optomechanical oscillator driven by a laser.) The RK step size is 3.57e-10 (see the picture generated below the code). Yet when I set MaxStepSize in the NDSolve to 3e-10, still the NDSolve solution is jagged when viewed in the same window (and destroys features such as the alternating peak heights). Clearly the sampling rate is too low.
I have done my best to review the NDSolve options in the help; is there some other option that I have failed to tune correctly? (I also have a working Runge-Kutta in Mathematica, but as it employs loops, it is far too slow to use for longer simulations times.)
(1) How can improve the smoothness of this simulation, specifically? (2) Generally, which option does it seem I have overlooked and may save me this grief next time around? I can tolerate slow calculation, but not poor fidelity. Thanks very much.
m = 5*10^-11;
b = 1.4*10^-6;
k = 57559.5;

ringEqn = m r''[t] + b r'[t] + k r[t] == 1.02*10^-8 (Abs[A[t]])^2;

NW = 182.1;
DeltaW[t_] = 1.42*10^7 - 1.483*10^19 r[t];
ampEqn = A'[t] + A[t] (2.58*10^7 - I DeltaW[t]) == 3.74*10^8 I;

myInits = {r[0] == 0, r'[0] == 0, A[0] == 0};

myVars = {A, r};

OMOsol = NDSolve[{{ringEqn, ampEqn}, myInits},
  myVars, {t, 0, .000036}, MaxStepSize -> 3*10^-10,
  MaxStepFraction -> .0000001]

amp = Evaluate[A[t] /. OMOsol];
Plot[(Abs[amp])^2, {t, 0, m/b},
   PlotRange -> {{.9*10^-5, 1*10^-5}, {0, 60}},
   Frame -> True]

Above: Mathematica--plot of (Abs[amp])^2 with above NDsolve

Above: Matlab--plot of (Abs[amp])^2 using 4th order Runge-Kutta with step size h=3.57e-10

A: Just increase PlotPoints in Plot.  I tried 400 and got a nice result.  BTW, it seems to run fine, and much faster, without MaxStepSize -> 3*10^-10, MaxStepFraction -> .0000001.
OMOsol = NDSolve[{{ringEqn, ampEqn}, myInits}, myVars, {t, 0, .000036}]

Plot[(Abs[amp])^2, {t, 0, m/b}, PlotRange -> {{.9*10^-5, 1*10^-5}, {0, 60}},
  Frame -> True, PlotPoints -> 400]

A: From Easy way to plot ODE solutions from NDSolve?, one might use ListLinePlot on the InterpolatingFunction:
ListLinePlot[
 {A["Grid"], Abs@A["ValuesOnGrid"]^2} /. First@OMOsol // Transpose // Interpolation,
 PlotRange -> {{.9*10^-5, 1*10^-5}, {0, 60}}, Frame -> True]

Since the plot range is a small portion, it may be worth selecting a subset of the solution:
range = {.9*10^-5, 1*10^-5};
grid = Flatten[A["Grid"] /. OMOsol];
mask = UnitStep[# - .9*10^-5] UnitStep[1*10^-5 - #] &@grid // SparseArray;
dom = Span @@ Flatten@Clip[
    mask["NonzeroPositions"][[{1, -1}]] + {-1, 1}, {1, Length@grid}]
(*  14461 ;; 16054  *)

ListLinePlot[
 ({A["Grid"], Abs@A["ValuesOnGrid"]^2} /. First@OMOsol)[[All, dom]] //
    Transpose // Interpolation,
 PlotRange -> {{.9*10^-5, 1*10^-5}, {0, 60}}, Frame -> True]

One can see the steps easily using Mesh, as in Matlab. Like @ChrisK, I omitted MaxStepSize -> 3*10^-10, MaxStepFraction -> .0000001.  This is one way to see if the step size needs manual adjustment.
ListLinePlot[
 ({A["Grid"], Abs@A["ValuesOnGrid"]^2} /. First@OMOsol)[[All, dom]] //
    Transpose // Interpolation,
 Mesh -> All, MeshStyle -> {PointSize[Small], Red},
 PlotRange -> {{.9*10^-5, 1*10^-5}, {0, 60}}, Frame -> True]


text:
Q: Analyzing Sensor Data stored in cassandra and draw graphs I'm collecting data from different sensors and write them to a Cassandra database.
The Sensor-ID accts as a partition key, the timestamp of the sensors data as clustering column. Additionally a value of the sensor is stored.
Each sensor collects something about 30000 to 60000 values a day.
The simplest thing I wane do is draw a graph showing this data. This is not a problem for a few hours but when showing a week or even a longer range, all the data has to be loaded into the backend (a rails application) for further processing. This isn't really fast with my test dataset and won't be faster in production I think.
So my question is, how to speed this up. I thought about pre-processing the data directly in the database but it seems, that Cassandra isn't able to do such things.
For a graph with a width of 1000px it isn't interesting to draw ten thousands of points - so it would be interesting to gather only relevant, pre-aggregated data from the database.
For example, when showing the data for a whole day in a graph with a width of 1000px, it would be enough to take 1000 average values (this would be an average clustered by 86seconds - 60*60*24 / 1000).
Is this a good approach? Or are there other techniques fasten this up? How would I handle this with database? Create a second Table and store some average values? But the resolution of the graph may change...
Other approaches would be drawing mean values by day, week, month and so on. Maybe vor this a second table could do a good job!

A: Cassandra is all about letting you write and read your data quickly. Think of it as just a data store. It can't (really) do any processing on that data.
If you want to do operations on it, then you are going to need to put the data into something else. Storm is quite popular for building computation clusters for processing data from Cassandra, but without knowing exactly the scale you need to operate at, then that may be overkill.
Another option which might suit you is to aggregate data on the way in, or perhaps in nightly jobs. This is how OLAP is often done with other technologies. This can work if you know in advance what you need to aggregate. You could build your sets into hourly, daily, whatever, then pull a smaller amount of data into Rails for graphing (and possibly aggregate it even further to exactly meet the desired graph requirements).

A: For the purposes of storing, aggregating, and graphing your sensor data, you might consider RRDtool which does basically everything you describe.  Its main limitation is it does not store raw data, but instead stores aggregated, interpolated values.  (If you need the raw data, you can still use Cassandra for that.)

A: AndySavage is onto something here when it comes to precomputing aggregate values. This does require you to understand in advance the sorts of metrics you'd like to see from the sensor values generally.
You correctly identify the limitation of a graph in informing the viewer. Questions you need to ask really fall into areas such as:

*

*When you aggregate are you interested in the mean, median, spread of the values?

*What's the biggest aggregation that you're interested in?

*What's the goal of the data visualisation - is it really necessary to be looking at a whole year of data?

*Are outliers the important part of the dataset?

Each of these questions will lead you down a different path with visualisation and the application itself too.
Once you know what you're wanting to do, an ETL process harnessing some form of analytical processing will be needed. This is where the Hadoop world would be useful investigating.
Regarding your decision to use Cassandra as your timeseries historian, how is that working for you? I'm looking at technical solutions for a similar requirement at the moment and it's one of the options on the table.


text:
Q: Увеличение ширины формы Как можно увеличить ширину select формы? Прописывал inline стили, но не сработало.

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />

        <form action="/get_data" method="POST" class="form-inline">
            <select id='sel' name='sel' class="selectpicker sel" multiple data-live-search="true" style="width: 100%;">
                    <option value= "val">val</option>
            </select>
            <button type="submit" class="btn btn-primary mb-2">Select</button>
        </form>

A: Как вариант (думаю, что не очень хороший, но быстрый) можно поменять стиль этого select'a в стилях bootstrap, либо сделать !important стиль для него. Пример:
.bootstrap-select:not([class*="col-"]):not([class*="form-control"]):not(.input-group-btn) {
  width: 600px !important;
 }


text:
Q: Quantum group Uq(sl(2)) I'm looking at motivating the standard deformation of $U(\mathfrak{sl}(2))$.  As an algebra $U(\mathfrak{sl}(2))$ is generated by $X,Y$ and $H$ and subject to the relations $[X,Y] = H$, $[H,X] = 2X$ and $[H,Y] = -2Y$.  From $q$-analysis I have that an integer $n$ is deformed according to $[n] = \frac{q^{n}-q^{-n}}{q-q^{-1}}$.
This seems to motivate, at least partially, the means of deforming $U(\mathfrak{sl}(2))$.  That is, set $[X,Y] = [H] = \frac{q^{H}-q^{-H}}{q-q^{-1}}$ and then set $K = q^{H}$ and $K^{-1} = q^{-H}$.  But what motivates the relations $KX = q^{2}XK$ and $KY = q^{-2}YK$?

A: Since $K=q^H$, the relation $KX=q^2XK$ is really $$q^HX=q^2Xq^H.$$ Now $\frac{d}{dq}q^H=Hq^{-1}q^H$ so differentiating with respect to $q$ the previous equality we get $$Hq^{-1}q^HX=2qXq^H+q^2XHq^{-1}q^H.$$ If we now let $q=1$, this becomes $HX=2X+XH$, which becomes, after rearranging terms, $$[H,X]=2X$$ which is the classical commutation relation.
We thus see that the relations defining the exponential are a deformation which infinitessimally, at $q=1$, gives the usual enveloping algebra.
(All of this can be put in a context where it actually makes sense...)

A: Hi Ryan,
You can prove that if $a,b$ are some elements in an algebra such that $[a,b]=\lambda b$ for $\lambda$ a scalar, then (in a context where this expression makes sense) $q^a b q^{-a}=q^{\lambda} b$: rewrite the relation as
$$ab=b(a+\lambda)$$
then
$$a^nb=b(a+\lambda)^n$$
therefore
$$q^ab=\sum \frac{\log(q)^na^n}{n!}b=b\sum \frac{\log(q)^n(a+\lambda)^n}{n!}= bq^{(a+\lambda)}=q^{\lambda}bq^a$$
since $\lambda$ commutes with everything.
Therefore it's in fact not a deformation but the same relation with $q^H$ instead of $H$.
In my opinion, what is more miraculous is the existence of a non-trivial deformation of the Hopf structure. Although it does not leads to explicit formulas, the conceptual explanation for that comes from the Kohno-Drinfeld theorem, or more generally from the Etingof-Kazhdan quantization functor.

A: Allow me the excuse to mention a cute way of constructing Uq(sl2) as a q-analogue. Presumably this is ahistorical, since I suspect that initially Uq(sl2) was constructed first over the formal disc, then later it was realised that it was definable over $\mathbb{Q}(q)$.
Anyhow, let S be a finite set. Consider a vector space with basis $\{[I]\mid I\subset S\}$. Define operators e,f,h on this vector space by
$$e[I]=\sum_{i\notin I}[I\cup\{i\}]$$
$$f[I]=\sum_{i\in I}[I\setminus \{i\}]$$
$$h[I]=(2|I|-|S|)[I].$$
You can check that this is a representation of sl2 (it's just a tensor power of the standard represenation in disguise).
Now q-analogise! How? Well we should replace the idea of a subset of a set with that of a subspace of a vector space (of course working over the finite field with q elements).
Let V be a finite dimensional vector space over $\mathbb{F}_q$. We should consider the space of all complex-valued functions on the Grassmannian Gr(V) of all subspaces of V. Well actually we'd really like something of dimension 2^n, so we should consider only those functions invariant under the action of a Borel subgroup.
Let F be the space of pairs (W,W') with $W\subset W'$ two subspaces of V satifying dim(W')=dim(W)+1. There are two obvious maps $p_1,p_2:F\to Gr(V)$.
Now we can define two operators on our space of functions on Gr(V), namely $E=(p_2)_!(p_1)^!$ and $F=(p_1)_!(p_2)^!$. Here p! is pullback of functions and p! means sum the function over the fibre. These are almost the generators of the quantum group we're after, to make the formulae match up nicely, we need to modify the definition of p! by multiplying it by a factor of q-d/2 where d is the dimension of the fibre summed over (a Tate twist).
Now you have two operators E and F, and when you compute their commutator, you naturally find another operator K such that $$EF-FE=\frac{K-K^{-1}}{q^{1/2}-q^{-1/2}}.$$
Computing KE=qEK and qKF=FK is now easy.
But even better, this approach gives more than just the product structure on the quantum group. You can also get the coproduct. I will be brief since I haven't checked all powers that q that appear. I haven't thought about obtaining the antipode.
Consider a short exact sequence of vector spaces 0-->V'-->V-->V''-->0. Given functions f' on Gr(V') and f'' on Gr(V''), one can define a function on Gr(V) by
$$(f'\otimes f'')(X)=f'(X\cap V')f''(X/(X\cap V')).$$
There is a reasonable chance this needs correction by a power of q. The point however is that this defines an isomorphism between Borel-equivariant functions on Gr(V) and the tensor product of Borel-equivariant functions on Gr(V') with Borel-equivariant functions on Gr(V''). (If you drop Borel-equivariant, then you're still getting a map, you're just not deforming a representation of sl2).
I leave it as an exercise to the interested reader to use this to deduce the coproduct formulae in Uq(sl2).


text:
Q: How observes nested properties in Ember.Array Suppose I have a model Stock that has several StockPartition (its a property called partitions, its an Array).
The Stock model has a property usedAmount that should change when any of all partition.amount changes, and, of course, be updated when a partition is added/removed.
Example :
stock.get('usedAmount') -> 0
stock.get('partitions') -> [Class, Class, Class]
stock.get('partitions')[0].set('amount', 12)
stock.get('usedAmount') -> I want here to return 12
stock.get('partitions')[1].set('amount', 12)
stock.get('usedAmount') -> I want here 24

How could Stock observes each partitions.amount?
I can write a function addPartition that looks like this :
addPartition: function(partition) {
  partition.addObserver('amount', function() {
    this.get('owner').notifyPropertyChange('usedAmount');
  });
}

But I hope there is a better solution.

A: I would make usage of the powerful computed properties. Also you can make usage of the helpful methods available on  Ember.Enumerable's, see http://jsfiddle.net/pangratz666/BxyY4/:
App.partitionsController = Ember.ArrayProxy.create({
    content: [],

    addPartition: function(amount) {
        this.pushObject(Ember.Object.create({
            amount: amount
        }));
    },

    usedAmount: function() {
        // reduce by adding all 'amount' values, start with initial value 0
        return this.reduce(function(previousValue, item) {
            return previousValue + item.get('amount');
        }, 0);
    }.property('@each.amount')
});

The reduce is documented in the docs.


text:
Q: Google app engine: which solves the race condition? Transactions or compare-and-set? On the Google App Engine with Python, I am looking for solutions to the race condition problem, i.e., multiple users are trying to increment a certain counter at the same time. I found two of them: the increment_counter() described in transactions and the bump_counter() in compare-and-set.
My questions: 1) Do both of them completely solve the race condition problem? 2) If so, which one is better?
In addition, could some body elaborate more about each of them, because I can't see how the codes solve the problem. For examples, 1) during the increment_counter() transaction, if another user updates the counter, the transaction would fail?  2) similarly, during the bump_counter() in compare-and-set, if another user updates the counter, the client.cas() would fail?

A: *

*Yes they both can eliminate race conditions.

*The first is using datastore, the second memcache. So they can not be compared. Memcache is volatile and can be purged at any time - you should not use it for storing permanent data. So in this regard datastore transactions are better. Also, transactions can assure atomicity on a set of entities, while compare_and_set assures atomicity only on one memcache value.

*Transactions do not do blocking. If they detect collision they fail and you need to roll it back and repeat again yourself.

*Ditto for memcache: you need to repeat the procedure yourself.


text:
Q: how can I use FB comments plugin in one page with different users I have a profile page that displays users profile by sending different Id param to it. I added FB comment plugin to it, but the comments show with all users I cannot display the plugin with each user separately.

A: you need a unique url for every profile
use this code  if you want to use HTML 5 & your programing lang is php
<div class="fb-comments" data-href="http://example.com/?unique=<?php echo $user_id ?>" data-num-posts="2" data-width="470">

visit here for more infos
https://developers.facebook.com/docs/reference/plugins/comments/


text: Q: Why does every document in doc center go to the drop off library I currently have 1 rule setup for my content organizer. I'm curious as to why when I upload a document that follows the rule it always uploads to both the document center and the doc library that the rule is based on. Based on my understanding of the drop off library the documents should only go there if more than one rule applies to a specific document. Does anyone have an explanation? Thanks!


text:
Q: Find intersection of two dictionaries, and alter object attributes at intersection There are two objects, an apple and an orchard, each with their own initial attributes given below:
class apple:
    def __init__(self, apple_id, orchard_id):
        self.apple_id = apple_id
        self.orchard_id = orchard_id
        self.found = false

class orchard:
    def __init__(self, id):
        self.id = id
        self.picked_apples = []

Sets of these objects are stored in their own respective dictionaries. Each dictionary is sorted based on their orchard id, which can be thought of as representing where the apple was picked:
apple_dict = {"1": apple(1,1), apple(3,1), "2": apple(5,2), "3": apple(2,3), apple(4,3), apple(6,3), apple(7,3)}

orchard_dict = {"1": orchard(1), "2": orchard(2), "3": orchard(3)}

The goal is to match each apple to the orchard it was picked from, and change the apple.found attribute to true once the operation is complete. Additionally, we want to add the apple object to its respective orchards' list, orchard.picked_apples. Comparing the dictionaries is simple enough. However, the trouble I'm having is with altering the attribute of the apple objects once dictionaries are compared, as well as adding the apple objects to the orchard's list. Any ideas how this could be done?

A: You can compare orchard ids with apple.orchard_id like this and update picked_apples list when corresponding orchard is found:
class apple:
    def __init__(self, apple_id, orchard_id):
        self.apple_id = apple_id
        self.orchard_id = orchard_id
        self.found = False

    def __str__(self):
        return f"apple_id: {self.apple_id}, oid: {self.orchard_id}"

class orchard:
    def __init__(self, id):
        self.id = id
        self.picked_apples = []
    def __str__(self):
        return ",".join(self.picked_apples)

apple_dict = {"1": (apple(1,1), apple(3,1)), "2": (apple(5,2),), "3": (apple(2,3), apple(4,3), apple(6,3), apple(7,3))}
orchard_dict = {"1": orchard(1), "2": orchard(2), "3": orchard(3)}

for apples in apple_dict.values():
    for a in apples:
        if str(a.orchard_id) in orchard_dict:
            a.found = True
            orchard_dict.get(str(a.orchard_id)).picked_apples.append(str(a))

for o in orchard_dict.values():
    print(o)

Result:
apple_id: 1, oid: 1,apple_id: 3, oid: 1
apple_id: 5, oid: 2
apple_id: 2, oid: 3,apple_id: 4, oid: 3,apple_id: 6, oid: 3,apple_id: 7, oid: 3


text:
Q: Returning the latest version of a document in elasticsearch I am in need of some help with returning only the latest version of the documents that I have indexed in elasticsearch.
My documents have a field called version(for internal system versioning) and I index a new document every time there is an update made and increment the version field for the new document
How would I query the index so that it only returns the the latest version out of n amount, where "id": n"
EDIT
The documents that are being versioned have an id with .n version number appended at the end and I want to return the latest version of each of these within an index using the version field

A: So each time a new document is added the version field increments by 1 right.
Then version with maximum value would be the latest version. You can use max aggregation to get that.
{
    "aggs" : {
        "latest" : { "max" : { "field" : "version" } }
    }
}

A: I figured out a work around. I had to add a bool isLatestVersion Property onto my object and I do a query that filters on that.


text:
Q: How to check if a cell in DataGridView exist? I have a static method that check the sum of an given column. I am using it on event RowsAdded  but I got the following error:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.

Here is my code, please tell me where I am wrong
public static decimal datagSum(DataGridView dgv, string colName)
{
    int i = dgv.RowCount - 1, j = 0;
    decimal dgvSum = 0;
    decimal k = 0;
    while (j < i)
    {
        if (dgv.Rows[(i - 1)].Cells.Count > 3)
        {

            if (decimal.TryParse(dgv.Rows[(i - 1)].Cells[colName].Value.ToString(), out k))
            {
                dgvSum += k;
            }
            j++;

        }
    }
    return dgvSum;
}

A: Code Snippet
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
   {
       if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
       {
           dataGridView1.Rows[e.RowIndex].ErrorText =
               "Company Name must not be empty";
           e.Cancel = true;
       }
   }


text:
Q: Java.net.SocketException: Permission denied: connect I have two PCs in one network that I want to connect. One of them should send a notification to the other via TCP. One the one PC I have a "server" (Python script) socket which waits for the "client"(Jar file) to send a specific String and then it gives me a notification. This works perfectly fine when I'm trying it out one one PC. But when I want to do the intended action the "client" PC's .jar gives me an error that the connection is refused. Do I have to open a specific port on the other PC or what else could cause trouble? One PC runs Fedora the other Windows 8
"Server Code"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 5005))
s.listen(1)

try:
    while True:
        komm, addr = s.accept()
        while True:
            data = komm.recv(1024)
            if data == "$":
                noty()
            if not data:
                komm.close()
                break
finally:
    s.close()

"Client" Code
public static void main(String[] args) throws Exception {
Socket socket = new Socket("192.168.178.25", 5005);
OutputStream out = socket.getOutputStream();
String dat = "$";
    out.write(dat.getBytes());
socket.close();
}

A: if its permission denied then something is blocking your connection with the computer. i would try to open a port and see if that works. if you want an example of java sockets you can take a look at my SUPER Tic-Tac-Toe Multiplayer it uses java sockets to send strings to the clients as a way to represent what actions the clients should take.

A: Your server is probably binding to the wrong interface,
calling
s.bind(("", 5005))

Without setting an interface will allow the program to pick what ip address / interface it will connect to.
Since your client is trying to connect to ("192.168.178.25", 5005); you may want to put an IP address into the bind call to prevent the server picking the wrong ip interface.
Example:
s.bind(("192.168.178.25", 5005))


text:
Q: How to refresh a url and load a new image I'm trying to use timer to refresh an image from the internet.
This is my code:
public class ProjectActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    BannerActivity ba = new BannerActivity(this);
    LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout);
    layout.addView(ba);
}

public class BannerActivity extends ImageButton implements OnClickListener{
    URL url = null;
    public BannerActivity(Context context) {
        super(context);
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300));
        loadimage();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                loadimage();
            }
            }, 5000, 1000);
    }

    private void loadimage(){
        try {
            url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStream content = null;
        try {
            content = (InputStream)url.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Drawable d = Drawable.createFromStream(content , "src");
        setBackgroundDrawable(d);

        setOnClickListener(this);
    }

The error that I'm getting is this:
CalledFromWrongThreadException: Only the original thread that created a view
hierarchy can touch its views.

I'm new to this and not sure what it means or how to fix it.

A: You are tying to Change a UI form a non UI thread which is not possible in Android. Instaed od calling this method  setBackgroundDrawable(d); inside the run method of your Timer, surround it within a runonUiThread().
contextObj.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            setBackgroundDrawable(d);
        }
    });

Try to get the context of your ACtivity and then change your LoadImage() like this,
private void loadimage(){
    try {
        url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    InputStream content = null;
    try {
        content = (InputStream)url.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    final Drawable d = Drawable.createFromStream(content , "src");
    contextObj.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            setBackgroundDrawable(d);
        }
    });

    setOnClickListener(this);
}

A: Activity class is a  thread. if you try to create thread inside activity without Handler it gives ThreadException. So, add a Handler to Handle this new thread.
Thanks


text:
Q: WPF ListView with column names? I have this ListView and I'm using a DataTemplate (as you can see) for items.
How can i add column names to the ListView with this ItemTemplate definition?
I cannot use that GridViewColumn definition, because this ListView uses lazy data loading, so when there are too many rows, it fetches them on demand. GridViewColumn somehow does not function with this lazy loading.
<ListView Grid.Row="3">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid x:Name="grid" Background="Transparent" MinWidth="580" >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="220" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="70"/>
                            <ColumnDefinition Width="80"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock VerticalAlignment="Center" Grid.Column="0" Text="{Binding Path=Benutzer.Value.Code}"/>
                        <TextBlock VerticalAlignment="Center" Grid.Column="1" Text="{Binding Path=Nachname}"/>
                        <TextBlock VerticalAlignment="Center" Grid.Column="2" Text="{Binding Path=Vorname}"/>
                        <TextBlock VerticalAlignment="Center" Grid.Column="3">
                                <TextBlock.Text>
                                    <Binding Path="GeburtDate" StringFormat="{}{0:d}"/>
                                </TextBlock.Text>
                        </TextBlock>
                        <Button VerticalAlignment="Center" Grid.Column="4" Style="{StaticResource StyleEditButton}" Content="Öffnen..." Tag="{Binding}"  Click="OpenPersonButton_Click"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListView>

A: I don't think there is any point in using a ListView if, as you say, you cannot use GridView (or any other view).  I would exchange ListView for ItemsControl (or ListBox if you need a selectable item or any of the other things that ListBox offers).
If what you say is true, you could just use a stack panel to position a header row above your data rows:
<StackPanel>
  <!-- Header -->
  <StackPanel Orientation="Horizontal">
    <TextBlock Width="220" TextAlignment="Center" Text="Code" />
    <TextBlock Width="100" TextAlignment="Center" Text="Nachname" />
    <TextBlock Width="100" TextAlignment="Center" Text="Vorname" />
    <TextBlock Width="70"  TextAlignment="Center" Text="GeburtDate" />
  </StackPanel>
  <!-- Data rows -->
  <ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal" MinWidth="580">
            <TextBlock Width="220" TextAlignment="Center" Text="{Binding Path=Benutzer.Value.Code}" />
            <TextBlock Width="100" TextAlignment="Center" Text="{Binding Path=Nachname}" />
            <TextBlock Width="100" TextAlignment="Center" Text="{Binding Path=Vorname}" />
            <TextBlock Width="70"  TextAlignment="Center" Text="{Binding Path=GeburtDate, StringFormat={0:d}}" />
            <Button VerticalAlignment="Center" Grid.Column="4" Style="{StaticResource StyleEditButton}" Content="Öffnen..." Tag="{Binding}"  Click="OpenPersonButton_Click"/>
          </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</StackPanel>

Hope that helps.  You might also like to read about virtualizing panels.  That might provide the kind of laziness you're talking about.


text:
Q: Create screen session in background only if it doesn't already exist How can i create a screen in detached mode only if it doesn't exist?
This creates a screen named name in detached mode but will create duplicates
screen -dmS name command

This creates a screen only if it doesn't exist but not detached
screen -dRms name command

How do i combine both? I need to create multiple screens in a batch file so reattaching is not convenient. I want to use the batch file to "restart" screens that have died for various reasons but leave the already running ones intact.

A: I've just stumbled over this issue and solved it like this:

*

*Create a Python script which checks if a screen session exists.

*Some shell scripting

In my case, the screen session name I'm interested in is 'activity' (for my activity tracker project).
Python Script does_screen_session_exist.py
Python 3.4+; no dependencies:
#!/usr/bin/env python

"""
Check if a screen session exists.

If it does, give exit code 0.
If it doesn't, give exit code 1.
"""

import subprocess
import sys
from argparse import ArgumentParser
from typing import List

parser = ArgumentParser()
parser.add_argument("session_name")

def main(session_name: str) -> None:
    session_names = get_active_screen_sessions()
    if session_name in session_names:
        print(f"Screen session '{session_name}' exists")
        sys.exit(0)
    else:
        print(f"Screen session '{session_name}' does NOT exist")
        sys.exit(1)

def get_active_screen_sessions() -> List[str]:
    result = subprocess.run(["screen", "-ls"], stdout=subprocess.PIPE)
    output = result.stdout.decode("utf-8")
    if "No Sockets found" in output:
        return []
    assert "There is a screen on" in output

    # get lines
    lines = []
    for line in output.splitlines():
        if line.startswith("\t"):
            lines.append(line)

    # get session names
    session_names = []
    for line in lines:
        line = line.strip()
        line = line.split("\t")[0]
        line = line.split(".")[1]
        session_names.append(line)
    return session_names

if __name__ == "__main__":
    args = parser.parse_args()
    main(args.session_name)

Bash script
python does_screen_session_exist.py activity
status=$?
if [ $status = 0 ]
then
    echo 'activity' screen exists
else
    echo Start activity screen
    screen -S activity -U -d -m activity_tracker log-activity
fi

A: The easiest one-line solution is to use flock with screen:
try this:
screen -S session-name -d -m flock -n /tmp/some_lockfile sleep 100
screen -S session-name -d -m flock -n /tmp/some_lockfile sleep 100
screen -ls

it will list only one session. Hope it would help.

A: Thank you for your solution. More compact python function, if someone needs it:
async def check_screen_exists(screen_name: str):
    proc = await asyncio.create_subprocess_shell("screen -ls", stdout=asyncio.subprocess.PIPE)
    stdout,stderr = await proc.communicate()
    existed_screens = [line.split(".")[1].split("\t")[0].rstrip() for line in stdout.decode("utf-8").splitlines() if line.startswith("\t")]
    if screen_name in existed_screens:
        return True


text:
Q: Split overlapping ranges into all unique ranges I am trying to split a dynamic number of ranges with associated attributes, so that whenever 2 or more ranges overlap, the overlapping section(s) are split into unique ranges with the combination of all overlapping attributes.
datasets are of type
case class testCC(bgn_ts: java.sql.Timestamp, end_ts: java.sql.Timestamp, supply1: Int, supply2: Int)

Now data dataset1 will always have supply2 as 0 and dataset2 will always have supply 1 as 0.
                         Set1
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-13T11:45  | 2020-12-16T11:45  | 10         |  0     |
2020-12-16T11:45  | 9999-12-31T00:00  | 11         |  0     |

                         Set2
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-15T11:45  | 9999-12-31T00:00  | 0          |  12    |

This should result in
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-13T11:45  | 2020-12-15T11:45  |   10       |  0     |
2020-12-15T11:45  | 2020-12-16T11:45  |   10       |  12    |
2020-12-16T11:45  | 9999-12-31T00:00  |   11       |  12    |

Another example:
                         Set1
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-13T11:45  | 2020-12-16T11:45  | 10         |  0     |
2020-12-16T11:45  | 2020-12-17T11:45  | 12         |  0     |
2020-12-17T11:45  | 9999-12-31T00:00  | 20         |  0     |

                         Set2
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-13T11:45  | 2020-12-15T11:45  | 0          | 10     |
2020-12-15T11:45  | 2020-12-16T11:45  | 0          |  9     |
2020-12-16T11:45  | 2020-12-18T11:45  | 0          | 12     |
2020-12-18T11:45  | 9999-12-31T00:00  | 0          | 21     |

This should result in
bgn_ts            | end_ts            |  supply1   |supply2 |
2020-12-13T11:45  | 2020-12-15T11:45  | 10         | 10     |
2020-12-15T11:45  | 2020-12-16T11:45  | 10         |  9     |
2020-12-16T11:45  | 2020-12-17T11:45  | 12         | 12     |
2020-12-17T11:45  | 2020-12-18T11:45  | 20         | 12     |
2020-12-18T11:45  | 9999-12-31T00:00  | 20         | 21     |

Below is the code I tried:
implicit def ts_ordering: Ordering[Timestamp] = new Ordering[Timestamp] {
            override def compare(x: Timestamp, y: Timestamp): Int = x compareTo y
          }

set2.sortBy(_.end_ts)
.foldLeft(set1.sortBy(_.end_ts)) {
  case (result, set2_entry) =>
    result.span(!_.end_ts.after(set2_entry.bgn_ts)) match {
      case (before, remaining) =>
        val (overlap, after) = remaining.span(_.bgn_ts.before(set2_entry.end_ts))
        before ++ (
          overlap.flatMap {
            case o if o.bgn_ts.equals(set2_entry.bgn_ts) && o.end_ts.equals(set2_entry.end_ts) =>
              o.copy(supply2 = set2_entry.supply2) :: Nil
            case o if o.bgn_ts.before(set2_entry.bgn_ts) && o.end_ts.after(set2_entry.end_ts) =>
              // need to split into three here, set2 record is entirely within this record
              o.copy(end_ts = set2_entry.bgn_ts) ::
              o.copy(bgn_ts = set2_entry.bgn_ts, end_ts = set2_entry.end_ts, supply2 = set2_entry.supply2) ::
              o.copy(bgn_ts = set2_entry.end_ts) ::
              Nil
            case o if !o.bgn_ts.after(set2_entry.bgn_ts) =>
              // split into two here, set2 record overlaps after the beginning of this record
              o.copy(end_ts = set2_entry.bgn_ts) ::
              o.copy(bgn_ts = set2_entry.bgn_ts, supply2 = set2_entry.supply2) ::
              Nil
            case o =>
              // split into two here, set2 record overlaps before the end of this record
              o.copy(end_ts = set2_entry.end_ts, supply2 = set2_entry.supply2) ::
              o.copy(bgn_ts = set2_entry.end_ts) ::
              Nil
          }
        ) ++ after
    }
}

To make it easier for testing, I'm supplying the test data:
Example1
val set1 = List(
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-13 11:45:00"),
        end_ts = Timestamp.valueOf("2020-12-16 11:45:00"), supply2 = 0, supply1 = 10),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-16 11:45:00"),
        end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply2 = 0, supply1 = 11)
)

val set2 = List(
  testCC(
    bgn_ts = Timestamp.valueOf("2020-12-15 11:45:00"),
    end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply1 = 0, supply2 = 12)
)

val expected1 = List(
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-13 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-15 11:45:00.0"), supply1 = 10, supply2 = 0),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-15 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-16 11:45:00.0"), supply1 = 10, supply2 = 12),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-16 11:45:00.0"),
        end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply1 = 11, supply2 = 12)
    )

Example2
val set1 = List(
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-13 11:45:00"),
        end_ts = Timestamp.valueOf("2020-12-16 11:45:00"), supply2 = 0, supply1 = 10),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-16 11:45:00"),
        end_ts = Timestamp.valueOf("2020-12-17 11:45:00"), supply2 = 0, supply1 = 12),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-17 11:45:00"),
        end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply2 = 0, supply1 = 20)
    )

val set2 = List(
  testCC(
    bgn_ts = Timestamp.valueOf("2020-12-13 11:45:00"),
    end_ts = Timestamp.valueOf("2020-12-15 11:45:00"), supply1 = 0, supply2 = 10),
  testCC(
    bgn_ts = Timestamp.valueOf("2020-12-15 11:45:00"),
    end_ts = Timestamp.valueOf("2020-12-16 11:45:00"), supply1 = 0, supply2 = 9),
  testCC(
    bgn_ts = Timestamp.valueOf("2020-12-16 11:45:00"),
    end_ts = Timestamp.valueOf("2020-12-18 11:45:00"), supply1 = 0, supply2 = 12),
  testCC(
    bgn_ts = Timestamp.valueOf("2020-12-18 11:45:00"),
    end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply1 = 0, supply2 = 21)
)

val expected1 = List(
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-13 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-15 11:45:00.0"), supply1 = 10, supply2 = 10),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-15 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-16 11:45:00.0"), supply1 = 10, supply2 = 9),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-16 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-17 11:45:00.0"), supply1 = 12, supply2 = 12),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-17 11:45:00.0"),
        end_ts = Timestamp.valueOf("2020-12-18 11:45:00.0"), supply1 = 20, supply2 = 12),
      testCC(
        bgn_ts = Timestamp.valueOf("2020-12-18 11:45:00.0"),
        end_ts = Timestamp.valueOf("9999-12-31 00:00:00"), supply1 = 20, supply2 = 21)
    )

A: This appears to work for the 2 test examples provided.
import java.sql.Timestamp

case class TestCC(bgn_ts: Timestamp, end_ts: Timestamp
                 ,supply1: Int, supply2: Int)

def mergeRanges(lst1: List[TestCC]
               ,lst2: List[TestCC]): List[TestCC] = {
  val lsts = lst1 ++ lst2
  val bMap = lsts.groupMapReduce(_.bgn_ts)(identity){
    case (a,b) => TestCC(a.bgn_ts, b.end_ts
                        ,a.supply1+b.supply1, a.supply2+b.supply2)
  }
  val eMap = lsts.groupMapReduce(_.end_ts)(identity){
    case (a,b) => TestCC(a.bgn_ts, b.end_ts
                        ,a.supply1+b.supply1, a.supply2+b.supply2)
  }
  List.unfold(bMap.keys.toList.sorted ->
              eMap.keys.toList.sorted){
    case (Nil, Nil) => None
    case (Nil,_)|(_,Nil) => throw new Error("unexpected")
    case (b::bs, e::es) =>
      if (bs.nonEmpty && bs.head.before(e))
        Some(bMap(b).copy(end_ts = bs.head) -> (bs,e::es))
      else
        Some(TestCC(b, e
                   ,bMap(b).supply1 max eMap(e).supply1
                   ,bMap(b).supply2 max eMap(e).supply2) -> (bs,es))
  }
}

The code makes a few assumptions about the input data and I'm not sure how well it will handle malformed input, but give it a try and see if it gets you closer to your goal.

2nd attempt
After thinking it over I decided that a different approach was required.
def mergeRanges(lst1: List[TestCC]
               ,lst2: List[TestCC]): List[TestCC] = {
  val lsts = lst1 ++ lst2
  val s1Map = lsts.filter(_.supply1 > 0)
                  .sortBy(_.bgn_ts)
                  .foldLeft(Map.empty[Timestamp,Int]){
                    case (mp, TestCC(b,e,s1,_)) =>
                      mp + (b -> s1) + (e -> s1)
                  }.withDefaultValue(0)
  val s1Lst = s1Map.keys.toList.sorted.reverse
  val s2Map = lsts.filter(_.supply2 > 0)
                  .sortBy(_.bgn_ts)
                  .foldLeft(Map.empty[Timestamp,Int]){
                    case (mp, TestCC(b,e,_,s2)) =>
                      mp + (b -> s2) + (e -> s2)
                  }.withDefaultValue(0)
  val s2Lst = s2Map.keys.toList.sorted.reverse
  lsts.flatMap{case TestCC(b,e,_,_) => List(b,e)}
      .distinct.sorted.sliding(2).toList
      .map{case List(ts1, ts2) =>
        TestCC(ts1, ts2
          ,s1Lst.dropWhile(_.after(ts1)).headOption.fold(0)(s1Map)
          ,s2Lst.dropWhile(_.after(ts1)).headOption.fold(0)(s2Map))
      }
}

I believe this passes all current test examples.

A: I came up with this, kind of similar to @jwvh's line of thinking. Instead of using maps, I am putting the event in a Set

case class Event(offset: Timestamp, isEnd: Boolean, supply1: Int, supply2: Int)
case class CoreData(supply1: Int, supply2: Int)

def createEventsFromSymbol(x: TestCC): List[Event] = {
    Event(x.bgn_ts, isEnd = false, x.supply1, x.supply2) ::
    Event(x.end_ts, isEnd = true, x.supply1, x.supply2) :: Nil
}
val lst = ats ++ inv

val events = lst
      .flatMap(createEventsFromSymbol)
      .sortBy(x => (x.offset, x.isEnd))

val defaultTs = Timestamp.valueOf("1970-01-01 00:00:00.0")

val (result1, _, _) =
    events.foldLeft(List.empty[InvAts], defaultTs, List.empty[CoreData]){

      case ((result, currentStart, currentSet), currentEvent) =>
        if(currentEvent.isEnd) {
          val mergedEvent =
            if(!currentStart.equals(defaultTs) && currentEvent.offset.after(currentStart)) {
              val coreData: CoreData = currentSet
                .reduce((a, b) => CoreData(a.current_supply + b.current_supply, a.available_to_sell + b.available_to_sell))

              TestCC(currentStart, currentEvent.offset, x.current_supply, x.available_to_sell) :: Nil
            }
            else {
              Nil
            }

            val new_set = currentSet
                .filterNot(x =>  x.current_supply == currentEvent.current_supply && x.available_to_sell == currentEvent.available_to_sell)

            (mergedEvent ++ result, currentEvent.offset, new_set)
        }
        else {
            val mergedEvent =
            if (!currentStart.equals(defaultTs) && !currentEvent.offset.equals(currentStart) && currentEvent.offset.after(currentStart)) {
              val x = currentSet
                .reduce((a, b) => CoreData(a.current_supply + b.current_supply, a.available_to_sell + b.available_to_sell))

              TestCC(currentStart, currentEvent.offset, x.current_supply, x.available_to_sell) :: Nil
            }
            else {
              Nil
            }

            val new_set = (CoreData(currentEvent.current_supply, currentEvent.available_to_sell) :: currentSet).distinct
            (mergedEvent ++ result, currentEvent.offset, new_set)
        }
    }


text:
Q: TypeError: unsupported operand type(s) for -: 'DatetimeArray' and 'datetime.date' I have a panda column that's in <class 'pandas._libs.tslibs.timestamps.Timestamp'> and also a variable (date_1) that's in <class 'datetime.date'>
I like to calculate the month between both as follow but got the error TypeError: unsupported operand type(s) for -: 'DatetimeArray' and 'datetime.date'
df['Duration (months)']= (date_1 - df['Date'])/np.timedelta64(1,'M')

How can I calculate the duration in months between the variable of date_1 and df['Date']?

A: try with to_datetime():
date_1=pd.to_datetime(date_1)

OR
try with pd.Timestamp():
date_1=pd.Timestamp(date_1)

Finally:
df['Duration (months)']= (date_1 - df['Date'])/np.timedelta64(1,'M')


text:
Q: Mapping Exception while serializing an object having a HashMap to JSON using Jackson I have a class that I am trying to serialize to JSON using Jackson:
class A {
    String someString;
    Map<String, Long> someMap;
}

I am serializing using the following code:
mapper.writeValueAsString(a);

where a is an instance of class A.
I am getting this exception:
com.fasterxml.jackson.databind.JsonMappingException: java.lang.Double cannot be cast to java.lang.Long (through reference chain ... java.util.HashMap)

I have tried enabling different Default Typing, but that has not helped.

A: This happens because your map contains Doubles instead of Longs. Usually that's a result of ignoring warnings or using reflection. It's fairly easy to reproduce:
A a = new A();
a.someMap = new HashMap<>();
((Map)a.someMap).put("bar", 1.0);
new ObjectMapper().writeValueAsString(a);

com.fasterxml.jackson.databind.JsonMappingException: java.lang.Double cannot be cast to java.lang.Long (through reference chain: A["someMap"]->java.util.HashMap["bar"])


text:
Q: Best place for getStoreConfig - block or model When creating a magento module i sometimes need store config values for use in a template file.  Where would be the best place for this - should I create a model or is a helper or block good enough?
I thinking in terms of best practice?

A: I would say a helper because it is accessible from everywhere. It wouldn't be hurtful to place in a block if it's only ever used in that block or it's template, although there is not much reason to create a block just for this when a helper will do.
A model should only be used to model things. As a rule of thumb I only use models for objects that might be used in a data structure, not as a convenience holder for functions.

A: Template should (whenever possible) get everything from block to keep it simple and little clogged... In the block you might call the helper for getting the config value if you think that will enhance reuse ability.


text:
Q: URL Rewriting in PHP causing problems Here is my .htaccess:
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ profile.php?user=$1 [L,QSA]
</IfModule>

here is profile.php:
if(isset($_GET['user']) && strlen($_GET['user'])>0) {
    $userreal = $_GET['user'];
    $stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?");
    $stmt->bind_param('s', $userreal);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows == 1) {
        $user = $_GET['user'];
    }
    else {
        $us = $_SESSION['username'];
        header("Location: profile/" . $us);
        exit();
    }
    $stmt->close();
}
else {
    $us = $_SESSION['username'];
    header("Location: profile/" . $us);
    exit();
}

This is my redirecting part (thought it might be helpful).
but it redirects me to:
http://localhost/PHP/Projects/HassanTech/pages/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/Hassan

when I try to access
http://localhost/PHP/Projects/HassanTech/pages/profile

I want my links:
http://localhost/PHP/Projects/HassanTech/pages/profile?user=Hassan

to
http://localhost/PHP/Projects/HassanTech/pages/profile/Hassan

My .htaccess file is in the pages folder and the profile.php is in the pages folder. Hope you can help me.

A: Change your header redirect to use ./ and you will stay in the same directory thus resolving your problem:
header("Location: ./" . $us);

A: RewriteEngine On
RewriteRule ^pages/profile/([^/]+)/?$ pages/profile.php?user=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

Did the trick for me. :]


text:
Q: DocuSign ListRecipients() not working, but other calls OK I am using the Docusign eSign API for an integration.  My integration key works fine with building and sending envelopes, and with checking envelope status (using GetEnvelope()).  But ListRecipients() doesn't work.     I have been following the documentation from here: https://developers.docusign.com/docs/esign-rest-api/how-to/get-envelope-recipients/.
My recipient-checking code is:
apiClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + authToken.access_token.ToString()); // I am suspicious of this line

var envelopesApi = new EnvelopesApi(apiClient);

foreach (var envelope in envelopes)
{
    List<SignerModel> listSigners = new List<SignerModel>();
    Recipients results = envelopesApi.ListRecipients(_apiAccountId, envelope.envelopeId.ToString());
    // Do something with it...
}

When I run this with the suspicious line in place (un-commented) I get this error message at that line:

GetSigners error: Object reference not set to an instance of an object.

When I comment it out I get the same error message at the ListRecipients() call.
This is how I am getting my access token:
                List<string> docusignScopes = new List<string> { "impersonation", "signature" };

                apiClient = new ApiClient(_restBasePath);
                authToken = apiClient.RequestJWTUserToken(
                    _clientId,
                    _impersonatedUserId,
                    _authServer,
                    privateKeyBytes, 1, docusignScopes);

Why is the listRecipients call not working?

A: I tested this code and it works just fine. Make sure to put your envelopeID in there. Try this basic code and let me know:
    var apiClient = new ApiClient(basePath);
    apiClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
    EnvelopesApi envelopesApi = new EnvelopesApi(apiClient);
    var rec = envelopesApi.ListRecipients(accountId, "4f925c10-xxxxxx-xxx-xxxx-xxxxxx");


text:
Q: Link_to href and text confusion I have document download functionality for a page. This is the code in place
%td= link_to upload.file, '#', class: " bogus btn btn-xs #{'btn-primary' if upload.published}"

The problem with this is that results in the following html:
/public/uploads/file/46/random.txt

I thought it would be as simple as changing the structure to this:
%td= link_to '#', upload.file, class: " bogus btn btn-xs #{'btn-primary' if upload.published}"

which would result in the following html:
#

This however results in the following error:
undefined method `model_name' for FileUploader:Class

A: You might what to try something like this <%= link_to "#", upload.file.url, class: " bogus btn btn-xs #{'btn-primary' if upload.published}" %>


text:
Q: Using UIKit can you wrap a uiimage? I have a game running on the iPhone 3 at 30 fps. I have subclassed UIView to create a scrolling background class. Is it possible to transform a uiimage to create the scrolling effect (wrap the image) or should I be looking at having 4 images and moving the off screen images ready to reappear on the other sides.
Thanks for any help.