text:
Q: confused about what my service method should return I have 2 domain classes: User and Role. 1 User can have 1 or more Roles.
public class User implements Serializable {
   private String username;
   private String password;
   private boolean lockFlag;
   private List<Role> rolesList;
   // getters and setters
}

public class Role implements Serializable {
   private int roleId;
   private String description;
   // getters and setters
}

In my service layer I have a method to login a user into the system. This method receives 3 arguments: String username, String password, int roleId and it throws an exception UserServiceException if an error occurs.
public void login(String username, String password, int roleId) throws UserServiceException;

The service method retrieve the User domain class along with associated Roles:
User user = userDAO.getUserById(username);

The service method retrieve the Role domain class:
Role role = roleDAO.getRoleById(roleId);

The service method perform no. of checks. Assuming all checks are passed, service method needs to tell its caller that the login was successful and send the user object and the role object. That's where I am confused how to send them. I have come up with some options:

OPTION 1:
Change the service method signature to return object of User domain class:
public User login(String username, String password, int roleId) throws UserServiceException;

Change the User domain class to add one more property currentRole which is of Role class type:
public class User implements Serializable {
   private String username;
   private String password;
   private boolean lockFlag;
   private List<Role> rolesList;
   private Role currentRole;
   // getters and setters
}

In my service method set the currentRole property of user object to the role object before sending the user object:
user.setCurrentRole(role);
return user;

OPTION 2:
Instead of changing the User domain class, create a DTO which resembles the User domain class + one more property currentRole which is of Role class type:
public class UserModelDTO implements Serializable {
   private String username;
   private String password;
   private boolean lockFlag;
   private List<Role> rolesList;
   private Role currentRole;
   // getters and setters
}

Change the service method signature to return object of UserModelDTO class:
public UserModelDTO login(String username, String password, int roleId) throws UserServiceException;

In my service method create an object of UserModelDTO class and send it:
UserModelDTO userModelDTO = new UserModelDTO();
userModelDTO.setUsername(user.getUsername());
userModelDTO.setPassword(user.getPassword());
userModelDTO.setLockFlag(user.getLockFlag());
userModelDTO.setRolesList(user.getRolesList());
userModelDTO.setCurrentRole(role);
return userModelDTO;

OPTION 3:
Create a DTO which has 1 property user of User class type and 1 property role of Role class type:
public class UserRoleModelDTO implements Serializable {
   private User user;
   private Role role;
   // getters and setters
}

Change the service method signature to return object of UserRoleModelDTO class:
public UserRoleModelDTO login(String username, String password, int roleId) throws UserServiceException;

In my service method create an object of UserRoleModelDTO class and send it:
UserRoleModelDTO userRoleModelDTO = new UserRoleModelDTO();
userRoleModelDTO.setUser(user);
userRoleModelDTO.setRole(role);
return userRoleModelDTO;

OPTION 4:
Change the service method signature to return a Map:
public Map login(String username, String password, int roleId) throws UserServiceException;

In my service method create a Map and send it:
Map map = new HashMap();
map.put("USER_DOMAIN", user);
map.put("ROLE_DOMAIN", role);
return map;

OPTION 5:
No link to domain classes.
Create a RoleModelDTO which resembles the Role class type.
Create a UserModelDTO which resembles the User class type.
In UserModelDTO, the property rolesList will refer to List of RoleModelDTO type.
In UserModelDTO, add one more property currentRole which is of RoleModelDTO class type:
public class RoleModelDTO implements Serializable {
   private int roleId;
   private String description;
   // getters and setters
}

public class UserModelDTO implements Serializable {
   private String username;
   private String password;
   private boolean lockFlag;
   private List<RoleModelDTO> rolesList;
   private RoleModelDTO currentRole;
   // getters and setters
}

Change the service method signature to return object of UserModelDTO class:
public UserModelDTO login(String username, String password, int roleId) throws UserServiceException;

In my service method create an object of UserModelDTO class and send it:
RoleModelDTO roleModelDTO = new RoleModelDTO();
roleModelDTO.setRoleId(role.getRoleId());
roleModelDTO.setDescription(role.getDescription());

List<RoleModelDTO> roleModelDTOList = new ArrayList<RoleModelDTO>();
for (Role role1 : user.getRolesList()) {
    RoleModelDTO roleModelDTO1 = new RoleModelDTO();
    roleModelDTO1.setRoleId(role1.getRoleId());
    roleModelDTO1.setDescription(role1.getDescription());
    roleModelDTOList.add(roleModelDTO1);
}

UserModelDTO userModelDTO = new UserModelDTO();
userModelDTO.setUsername(user.getUsername());
userModelDTO.setPassword(user.getPassword());
userModelDTO.setLockFlag(user.getLockFlag());
userModelDTO.setRolesList(roleModelDTOList);
userModelDTO.setCurrentRole(roleModelDTO);
return userModelDTO;

Which of the option should I go with? Is there any other option which makes the most sense? If yes please do share.
Some questions:
Does 1 service method should always return 1 domain class? In case of wanting to return more than 1 domain class, should we build a relationship between them?
Regarding Option 1, does it make sense to change a domain class to include something your caller (controller) need?
Regarding Options 2, 3 &4, does it make sense to return anything other than a domain class from the service method?
Which options might be breaking a design pattern?
UPDATE 1
I thought about another option which I have added as 5th option. This option sends a DTO but that DTO has no link to Domain model classes. Interesting concept.
Please reply about my question. I am in kind of a limbo and need some experienced developers guidelines to move me forward.
Thanks


text:
Q: High load of resources by software RAID1 in Debian 6 I have a server with Debian 6 and software RAID1. There is a problem: every few seconds the jbd2/md2-8 process loads all the HDD IO. It was detected by iotop. And for the md2_raid1 process 99% of IO displays.
The flush-9:2 process every few seconds loads 99% of CPU in top.
What can I do to optimize this system? Can transition to hardware RAID help in this situation?
This is cat /proc/mdstat
Personalities : [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md3 : active raid1 sda4[0] sdb4[1]
      1822442815 blocks super 1.2 [2/2] [UU]

md2 : active raid1 sda3[0] sdb3[1]
      1073740664 blocks super 1.2 [2/2] [UU]

md1 : active raid1 sda2[0] sdb2[1]
      524276 blocks super 1.2 [2/2] [UU]

md0 : active raid1 sda1[0] sdb1[1]
      33553336 blocks super 1.2 [2/2] [UU]

unused devices: <none>

A: next time this happens, run the following command "cat /proc/mdstat" then paste the output here

A: Your software raid is taking all the CPU cycles in order to run the RAID.  Getting a hardware RAID can help.  Keep in mind that if you want to take full advantage of a RAID controller you will need to ensure it has a BBU (battery back up) in order to enable the cache and write-back mode.
Depending on what is important to you, you could turn on RAID 0 (striping) and get even better performance out of your system, but even a regular RAID hardware controller will help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I run sub-minute cron jobs? I would like to run a cron job every Wednesday at 10:31:10, but I just learned that crontab cannot run sub-minute jobs, so the closest I can get is 10:31 a.m. with the below code:
31 10 * * WED /file/to/run.py

Is it possible to hack around this, or are there other alternatives to cron that could do the job?

A: The easiest solution is to sleep for 10 seconds:
# .----------------- minute (0 - 59)
# |   .------------- hour (0 - 23)
# |   |  .---------- day of month (1 - 31)
# |   |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |   |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |   |  |  |  |
# *   *  *  *  *     command to be executed
  31 10  *  *  3     sleep 10 && /file/to/run.py

A: You can't. Cron has a 60 sec granularity.
You can though build a SH script that sleeps for ten seconds and then does X, set your cron job to run a script at 10:31 AM on a wednesday that then sleeps for 10 seconds, then do x.


text:
Q: Saving an array of custom objects that each contain an array of custom objects, best method? I am having difficulty deciding which is the best method for saving my app data.
It is a recipe app.
I have an array of category class objects that contains an NSString variable for the category title and an NSMutable Array of Recipe class objects (which contains 3 NSString variables).
here is a semi-visual representation of my app model:
Array of Categories contains:

*

*Category Object 1-->contains string title and  mutable array of Recipe Objects

*Category Object 2-->contains string title and mutable array of Recipe Objects

...
etc.
Users are able to create new recipes and the recipe object is stored within a selected category object.
On app load x amount of categories are created (depending on value of a numberOfCategories int). and of course upon relaunch I want to restore the recipes to their appropriate category objects.
Hopefully that wasn't too confusing--I was going the NSUserDefaults way and doing the NSCoding thing to encode/decode my custom objects but found it confusing because I have an array of custom objects that contains an array of custom objects.
I am open to the idea if it is the best route of converting my project to use Core Data--but that also seemed overly complicated for the simplicity of my app (pre-populating my SQLite database with categories, etc etc).
Let me know if you need further clarification.

A: Use CoreData.  Sounds like you will need at least two separate entities and establish a relationship between them (Recipe and RecipeObject).  NSUserdefaults is great for storing small amounts of data that needs to be persisted, but not really good for your use case.
Also, check out MagicalRecord and MOGenerator.  Both of these open source libraries make working with CD much more fun and productive.

A: I would suggest you serialize your object as XML which is a good method to store hierarchical data.


text:
Q: Check if JSON object is empty I want to check if an object has any data in it inside of cities, so basically it would show true for data for this:
JSON
{"cities":[{"id":0,"client_id":"1","storename":"test","notes":"test","rejected":"on","offer":"test","time":1394457477525}]}

and false for this:
{"cities":[]}

Currently my code is incorrect as its not checking inside of cities just if its empty or not, is there any way I can adapt my code for it to work?
JavaScript
 if (jQuery.isEmptyObject(JsonData) == false) {
      $('#upload').show();
      alert("There is data");
 } else {
      $('#upload').hide();
      alert("There is no data");
 }

A: Assuming JsonData is a valid JSON
if (JsonData.cities.length > 0) {
   alert("there is data");
}
else {
   alert("there is no data");
}

if JsonData is a string you need instead to parse it before as a JSON structure, using JSON.parse(JsonData) : see MDN for further reference

Note:
If you're not sure to always have JsonData or JsonData.cities available, you may create a fence for properties lookup (as suggested on ajaxian) in this way
if (((JsonData || 0).cities || 0).length > 0) {
   alert("there is data");
}
else {
   alert("there is no data");
}

A: check for cities.length its an array.


text:
Q: Wrapping uneditable Singleton classes I have SingletonA and SingletonB, classes in an obfuscated jarfile. They do not implement the same interface nor are they children of the same superclass, but they do have similar characteristics, which the original programmers missed.
I want to be able to pass them as arguments to a method like this:
public void method(SingletonObject singleton) {
    //do stuff with singleton
}

However, the only thing I can think of that would work is this:
    public void method(Object singleton) {
        if(singleton instanceof SingletonA) {
           SingletonA singletonA = (SingletonA) singleton;
            // do stuff with singletonA
        }
        else if(singleton instanceof SingletonB) {
            SingletonB singletonB = (SingletonB) singleton;
           //do exact same stuff with singletonB
        }
        else {
            return;
        }
    }

Since the bottom example is terrible, what can I do to make it look more like the top.

A: If you know that a certain method exists for these 2 different classes, then you can use reflection
  public void method(Object singleton) {
        Class<?> clazz = singleton.getClass();
        Method m;
        try {
            m = clazz.getDeclaredMethod("someCommonMethod");
            //m.setAccessible(true);
            m.invoke(singleton);
        } catch (Exception e) {
            e.printStackTrace();
        }
  }

A: Composition also could be an option:
class SingletonObject{
     SingletonA a;
     SingletonB b;

    SingletonObject(SingletonA a, SingletonB b){
         if(a==null && b==null){
            throw InvalidArgumentException();
         }
       this.a = a;
       this.b =b
    }

    public void callCommonMethod(){
         if(a!=null){
            a.callCommonMethod();
         }else{
           b.callCommonMethod()
         }
    }
}

so you composed singleton objects in one class where anyone can used it without know how is behind them


text:
Q: Rails: storing arrays in DB vs. setting up relationship Setting: There are two models with the following attributes.

*

*Person: name, age, work_experience, available_dates

*WorkExperience: job_title, starting_date, ending_date

Then, I can do the following
Person
  has_many work_experiences

WorkExperience
  belongs_to Person

Q1: Should available_dates be an attribute (array of dates) or a child (e.g. Person has_many available_dates)?
Q2: Can Person have work_experiences field that's just an array of objects instead of an individual table in DB?

A: TL;DR: As in all design questions, I think the answer is "it depends."
On Q1:
I've done both ways before. If I were making this decision, I would consider the following:

*

*Do I see myself adding more information to available_dates in a very near future? For example, it could be location, timezone, commute distance, and so on that would make this data into "availability" in general. In that
case, I'd rather create separate objects with association.

*Do I see myself reusing these dates in some other place in my code? Then I'd rather make them into separate objects and persist.

On Q2:
I don't think it'd be good for your sanity. DB has simple datatypes and are not designed to retain object models.

A: On Q1 I would go with an association instead of an array as it provides more flexibility. So a child, as you call it is what I would do.
On Q2 I would also go with a separate WorkExperience Model as it also provides more flexibility and room for growth. Also the array might get a bit messy as a Person starts gathering work experiences and querying for information might get more complicated than it needs to be with an array. With a separate model Active Record will give you a lot of tools you can use to dig into a person's work experiences.
Hope that helps.


text:
Q: Finding cumulative second max per group in R I have a dataset where I would like to create a new variable that is the cumulative second largest value of another variable, and I would like to perform this function per group.
Let's say I create the following example data frame:
(df1 <- data.frame(patient = rep(1:5, each=8), visit = rep(1:2,each=4,5), trial = rep(1:4,10), var1 = sample(1:50,20,replace=TRUE)))

This is pretend data that represents 5 patients who each had 2 study visits, and each visit had 4 trials with a measurement taken (var1).
> head(df1,n=20)
   patient visit trial var1
1        1     1     1   25
2        1     1     2   23
3        1     1     3   48
4        1     1     4   37
5        1     2     1   41
6        1     2     2   45
7        1     2     3    8
8        1     2     4    9
9        2     1     1   26
10       2     1     2   14
11       2     1     3   41
12       2     1     4   35
13       2     2     1   37
14       2     2     2   30
15       2     2     3   14
16       2     2     4   28
17       3     1     1   34
18       3     1     2   19
19       3     1     3   28
20       3     1     4   10

I would like to create a new variable, cum2ndmax, that is the cumulative 2nd largest value of var1 and I would like to group this variable by patient # and visit #.
I figured out how to calculate the cumulative 2nd max number like so:
df1$cum2ndmax <- sapply(seq_along(df1$var1),function(x){sort(df1$var1[seq(x)],decreasing=TRUE)[2]})
df1

However, this calculates the cumulative 2nd max across the whole dataset, not for each group. I have attempted to calculate this variable using grouped data like so after installing and loading package dplyr:
library(dplyr)
df2 <- df1 %>%
        group_by(patient,visit) %>%
        mutate(cum2ndmax = sapply(seq_along(df1$var1),function(x){sort(df1$var1[seq(x)],decreasing=TRUE)[2]}))

But I get an error: Error: Problem with mutate() input cum2ndmax. x Input cum2ndmax can't be recycled to size 4.
Ideally, my result would look something like this:
patient visit   trial   var1    cum2ndmax
1   1   1   25  NA
1   1   2   23  23
1   1   3   48  25
1   1   4   37  37
1   2   1   41  NA
1   2   2   45  41
1   2   3   8   41
1   2   4   9   41
2   1   1   26  NA
2   1   2   14  14
2   1   3   41  26
2   1   4   35  35
…   …   …   …   …

Any help in getting this to work in R would be much appreciated! Thank you!

A: One dplyr and purrr option could be:
df1 %>%
 group_by(patient, visit) %>%
 mutate(cum_second_max = map_dbl(.x = seq_along(var1),
                                 ~ ifelse(.x == 1, NA, var1[dense_rank(-var1[1:.x]) == 2])))

   patient visit trial  var1 cum_second_max
     <int> <int> <int> <int>          <dbl>
 1       1     1     1    25             NA
 2       1     1     2    23             23
 3       1     1     3    48             25
 4       1     1     4    37             37
 5       1     2     1    41             NA
 6       1     2     2    45             41
 7       1     2     3     8             41
 8       1     2     4     9             41
 9       2     1     1    26             NA
10       2     1     2    14             14
11       2     1     3    41             26
12       2     1     4    35             35
13       2     2     1    37             NA
14       2     2     2    30             30
15       2     2     3    14             30
16       2     2     4    28             30
17       3     1     1    34             NA
18       3     1     2    19             19
19       3     1     3    28             28
20       3     1     4    10             28

A: Here is an Rcpp solution.
cum_second_max is a modification of cummax which keeps track of the second maximum.
library(tidyverse)

Rcpp::cppFunction("
NumericVector cum_second_max(NumericVector x) {
  double max_value = R_NegInf, max_value2 = NA_REAL;
  NumericVector result(x.length());

  for (int i = 0 ; i < x.length() ; ++i) {
    if (x[i] > max_value) {
      max_value2 = max_value;
      max_value = x[i];
    }
    else if (x[i] < max_value && x[i] > max_value2) {
      max_value2 = x[i];
    }
    result[i] = isinf(max_value2) ? NA_REAL : max_value2;
  }
  return result;
}
")

df1 %>%
  group_by(patient, visit) %>%
  mutate(
    c2max = cum_second_max(var1)
  )
#> # A tibble: 20 x 5
#> # Groups:   patient, visit [5]
#>    patient visit trial  var1 c2max
#>      <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1       1     1     1    25    NA
#>  2       1     1     2    23    23
#>  3       1     1     3    48    25
#>  4       1     1     4    37    37
#>  5       1     2     1    41    NA
#>  6       1     2     2    45    41
#>  7       1     2     3     8    41
#>  8       1     2     4     9    41
#>  9       2     1     1    26    NA
#> 10       2     1     2    14    14
#> 11       2     1     3    41    26
#> 12       2     1     4    35    35
#> 13       2     2     1    37    NA
#> 14       2     2     2    30    30
#> 15       2     2     3    14    30
#> 16       2     2     4    28    30
#> 17       3     1     1    34    NA
#> 18       3     1     2    19    19
#> 19       3     1     3    28    28
#> 20       3     1     4    10    28

A: Thanks so much everyone! I really appreciate it and could not have solved this without your help! In the end, I ended up using a similar approach suggested by tmfmnk since I was already using dplyr. I found an interesting result with the code suggested by tmkmnk where for some reason it gave me a column of values that just repeated the first row's number. With a small tweak to change dense_rank to order, I got exactly what I wanted like this:
df1 %>%
 group_by(patient, visit) %>%
 mutate(cum_second_max = map_dbl(.x = seq_along(var1),
                                 ~ ifelse(.x == 1, NA, var1[order(-var1[1:.x])[2])))


text:
Q: "enum class" emulation or solid alternative for MSVC 10.0 I'm looking for a hacky kind of solution to the following problem:
GCC 4.4+ accepts the following c++0x code:
enum class my_enum
{
    value1,
    value2
};

Which allows the use like this:
my_enum e = my_enum::value1;

with all the bells and whistles this brings. I would like to make this code compatible with MSVC 2010, to the effect that the usage syntax does not change. I already pondered on this before here, and the accepted answer works, but the need for the two different names fo the enum and the enum values is killing the compatibility of the two approaches. This makes it of course unusable to replace the C++0x code as is. I wondered if some #undef and #define trickery could work around this, allowing me to use enum class-like syntax (perhaps without the strict type safety etc.), but at least the same syntax. Thanks!

A: Do not use this solution.  See the accepted answer by Howard for a better solution.  I'm leaving this post here because Howard's answer refers to it.
If you need to be able to compile your code with a compiler that doesn't yet support a new, not yet standard or not yet widely implemented language feature, it's best to avoid using that language feature in your code.
That said, as a hack workaround, you can wrap the enum in a struct and use a pair of implicit conversions:
struct my_enum {
    enum type {
        value1,
        value2
    };

    my_enum(type v) : value_(v) { }

    operator type() const { return value_; }

private:

    type value_;
};

A: I just discovered a problem with James' good hack (which I have heretofore been using), and a fix to the problem.  I discovered the problem when I tried to define a stream operator for my_enum.
#include <iostream>

struct my_enum {
    enum type {
        value1,
        value2
    };

    my_enum(type v) : value_(v) { }

    operator type() const { return value_; }

private:

    type value_;
};

std::ostream&
operator<<(std::ostream& os, my_enum v)
{
    return os << "streaming my_enum";
}

int main()
{
    std::cout << my_enum::value1 << '\n';
}

The output is:
0

The problem is my_enum::value1 has different type than my_enum.  Here's a hack to James' hack that I came up with.
struct my_enum
{
    static const my_enum value1;
    static const my_enum value2;

    explicit my_enum(int v) : value_(v) { }

    // explicit // if you have it!
       operator int() const { return value_; }

private:

    int value_;
};

my_enum const my_enum::value1(0);
my_enum const my_enum::value2(1);

Notes:

*

*Unless otherwise specified by an enum-base, the underlying type of a scoped enumeration is int.

*Explicit conversions to and from the underlying integral type are allowed.  But implicit conversions are not.  Do your best.

*This hack is more of a pita than James' because of the need to enumerate the values twice.  I'm hoping compilers without scoped enum support rapidly become extinct!

A: I have been fighting for a whole day to find a truly optimal solution, but there doesn't seem to be one. I need my enum that is

*

*Not implicitly convertible to an integral type

*Usable in a switch statement

*Usable as non-type template parameter

In have come up with the following code, built upon Howard Hinnant's solution:
struct DataType
{
    struct integral {
        enum type { None, Single, Double, Int };
    };

    typedef typename integral::type integral_type;

    explicit DataType(integral_type v) : val(v) {}
    integral_type integral_value() const { return val; }

    bool operator==(const DataType& s) const { return val == s.val; }
    bool operator!=(const DataType& s) const { return val != s.val; }

    static const DataType None;
    static const DataType Single;
    static const DataType Double;
    static const DataType Int;

private:
    integral_type val;
};

In the .cpp file:
const DataType DataType::None   (DataType::integral::None);
const DataType DataType::Single (DataType::integral::Single);
const DataType DataType::Double (DataType::integral::Double);
const DataType DataType::Int    (DataType::integral::Int);

As non-type template parameter:
template <DataType::integral_type>
struct DataTypeTraits;

template <>
struct DataTypeTraits<DataType::integral::Single>
{
    enum { size = 4 };
};

In a switch:
size_t get_size(DataType type)
{
    switch (type.integral_value()) {
        case DataType::integral::Single:  return DataTypeTraits<DataType::integral::Single>::size;
        case DataType::integral::Double:  return DataTypeTraits<DataType::integral::Double>::size;
        case DataType::integral::Int:     return DataTypeTraits<DataType::integral::Int>::size;
        default:                          throw  std::logic_error("Unknown data type.");
    }
}

Not particularly great, but that's as good as it gets, I guess...


text:
Q: facing an issue with mysql server I was facing an issue while opening the mysql server in ubuntu 8.04 LTS.
the problem is as shown below:
$ mysql -u root -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)


text:
Q: Magento2 Improper Breadcrumb On Product Detail Page I'm using a custom theme for Magento2.2.4 & also used Magento Migration tool.
On product detail page, currently, breadcrumb format is (please visit on below link).
e.g- http://nimb.ws/V8paZS
But the right format should be:-
e.g- http://nimb.ws/ARX7YG


text:
Q: VBA look up/find value matching a date variable and return the date next to it I can't seem to solve what seems to be a minor issue. I basically need to open another file, match the datetime stored in a variable with a date in the opened file, then return the datetime four cells to the right.
I've used both of these formulas but neither seem to work:
[Variables]
Dim TDate As Date
TDate = ThisWorkbook.Worksheets("Static Data").Range("B1").value
Filename = "<filename>"
Workbooks.Open Filename:=Filename, UpdateLinks:=False

[Formula 1]
rundate = WorksheetFunction.VLookup(CDate(TDate), ActiveWorkbook.Sheet("Dates").Range("B:F"), 4, False).value

[Formula 2]
Dim TDate As Date
TDate = ThisWorkbook.Worksheets("Static Data").Range("B1").value

rundate = ActiveWorkbook.Sheet("Dates").Cells.Find(Format(TDate, "d-mmm-yy"), ActiveWorkbook.Sheet("Dates").Range("B1"), xlValues, xlPart, xlByRows, xlNext, False, False).value
runtime = rundate.Offset(0, 4).value

What am I missing here?

A: The worksheet's VLOOKUP function returns a value, not a cell reference that you need to get the Range.Value property from.
TDate is already a date but you can also use the raw long integer value.
You need a Worksheets collection, not a Sheet.
rundate = WorksheetFunction.VLookup(CLng(TDate), ActiveWorkbook.Worksheets("Dates").Range("B:F"), 4, False)


text:
Q: Properties and env always null I have a hard time loading properties from my properties file. I'm trying to load a property into my configuration class which is listed below.
package dk.fitfit.budget.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    @Autowired
    private Environment env;

    @Value("${snot:test}")
    private String snot;

    public ApplicationConfig() {
        logger.info("Application config loaded!");  // Displays as expected
        logger.info("snot: {}", snot);              // snot: null
        logger.info("env: {}", env);                // env: null
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

If I change the name of the file (application.properties) or "@PropertySource("classpath:application.properties")" I get an error about the file not being present. So clearly it's being loaded (to some extend anyway).
I was at least expecting to see the default string "test" injected into the variable snot. But not even that is done. I'm not able to autowire Environment either... not sure if there is a relation.
The content of my application.properties is as below.
snot=snog

My application.properties file is placed in src/main/resources/.
Anyone got a clue about what I'm doing wrong?

A: The purpose of a constructor is to initialize a class instance. You have to construct and initialize the class instance before Spring can do anything to it. As such, you cannot expect the env and snot fields to have anything other than the default null value within the constructor.

A: Spring (and all dependency-injection tools) can't inject fields before the instance is created with new, which is one reason why constructor injection should be preferred to field injection. Generally, you can use @Value on constructor parameters, but there are certain issues with @Configuration classes that make constructor injection impractical.
However, there's a solution meant for exactly this situation: @PostConstruct. This method will be called after the DI framework has done all its magic to the bean:
@PostConstruct
public void log() {
    logger.info("Application config loaded!");  // Displays as expected
    logger.info("snot: {}", snot);              // snot: null
    logger.info("env: {}", env);                // env: null
}


text:
Q: what kind of web service (REST or SOAP) is more efficient to be called from a mobile application I have to develop a mobile application, and i want to know if there is a web service framework
which make developing easier and offers scalability, security and faster in parsing messages.

A: In terms of performance and network transport, Web Service is probably the least efficient way to go due to the size of SOAP and the complex XML parsing.  If you are open to use AMF, in my experience it is the most efficient implementation.  There are numerous server-side supports including Java, .NET, php, ruby, etc.
You may check the performance comparisons of different technologies via this blog, and iOS implementation of AMF can be found here.
In brief, here are my takes on numerous client-server communications:
Web Services (SOAP)

*

*Pros: Strongly-typed, verbose, support complex data type, support in many server platforms.  Most client would have some kind of built-in support

*Cons: Extremely bulky in size which is bad for network transport, and complex XML structure would eat into application performance.

Restful XML

*

*Pros: Easy to understand, smaller size XML compared to SOAP  if designed correctly

*Cons: Not strongly-typed.  You have to write your own XML parser to parse data to your strongly-typed objects.  XML parsing in general is slow and inefficient.

JSON

*

*Pros: Easy to understand, more compact structure.

*Cons: Not strongly-typed.  Cannot support referenced data.  For example, if you return ten children who reference the same parent in their properties, you would end up having ten copies of the same parent.

AMF

*

*Pros: Binary data format, strongly-typed, small network footprint and extremely fast serialization and deserialization

*Cons: Not as widely known.


text:
Q: Invariant Violation: Element type is invalid I am trying to clean up my styles by using a StyleSheet, but I can't seem to get it to work. I believe the error (seen below) is caused when I attempt to create a StyleSheet (const styles =  EStyleSheet.create.
Note I am using react-native-extended-stylesheet  However this is not the problem. This also happens with react-native's stylesheet.
This a picture of the error:
This this my code:
import React, { Component } from "react";

import {
  View,
  Text,
  Button,
  Image,
  StyleSheet,
  TextInput,
  KeyboardAvoidingView,
  TouchableOpacity
} from "react-native";

export default class Login extends Component {
  render() {
    return (
      <View style={styles.wrapper}>
        <Text>Login screen </Text>

        <KeyboardAvoidingView behavior="padding" style={styles.loginContainer}>

          <TextInput
          placeholder="username or email"
          placeholderTextColor='whitesmoke'
          style={styles.input}
          />

          <TextInput
          placeholder="password"
          secureTextEntry
          placeholderTextColor='whitesmoke'
          style={styles.input}
          />

          <TouchableOpacity style={styles.loginbutton} onPress={() => this.props.navigation.navigate("Grades")}>
            <Text style={{
              textAlign: 'center',
              color: "whitesmoke",
              fontWeight: '700',
            }}>
            Login
            </Text>
          </TouchableOpacity>

        </KeyboardAvoidingView>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  loginContainer: {
    paddingHorizontal: 9,
    backgroundColor: "red"
  },

  input: {
      paddingHorizontal: 10,
      marginBottom: 10,
      color: '#f1c40f', //sunflower color
      backgroundColor: '#3498db',
    },

 logo: {
    width: 231,
    height: 231
  },

  wrapper: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  }

});

Here is my app.js.
import React from "react";
import { Font } from "expo";

import { Root } from "./app/router";
import { FontError } from "./app/components/fontError";

export default class App extends React.Component {
  state = {
    fontLoaded: false
  };
  async componentDidMount() {
    await Font.loadAsync({
      Arial: require("./app/resources/Arial.ttf")
    });
    this.setState({ fontLoaded: true });
  }
  render() {
    if (!this.state.fontLoaded) return <FontError/>;
    return <Root />;
  }
  // ...
}

My root component is router.js, I am using react-navigation.
import React, { Component } from "react";
import { createStackNavigator } from "react-navigation";

import {
  Login,
  Grades,
} from "./screens";

export const Root = createStackNavigator({
  Login: {screen: Login},
  Grades: {screen: Grades},

});

Feel free to ask me to append any additional information.
Thanks for your help in advance.

A: To fix my error I just re-cloned the repo and added back in all the code I wrote.
Thankfully I didn't push this error to the master branch.
This fixed the error.
*note in the process I got rid off react-native-extended-stylesheet, so it might have been cause of error.


text:
Q: Custom counter printed correctly in situ, but not in nameref references The journal that I'm submitting to has a LaTeX template (yay!), but the template suggests manually labeling supplemental figures. Since I'm too lazy to do that, I thought I would make a new counter and a new command that would keep track of it for me. However, in references to those supplemental figures, the counter shows up as 0.
As a minimal example,
\documentclass[10pt,letterpaper]{article}

\newcounter{SFig}
\newcommand{\figsupp}[2]{\refstepcounter{SFig} \paragraph*{S\theSFig\ Fig.}\label{#1} {\bf #2}}

\usepackage{hyperref}

\begin{document}
\section{Journal Article}
Lorem Ipsum  (\nameref{Supp:Supp1}).  Dolor sic amet (\nameref{Supp:Supp2}).

\section{Supplemental Information}
\figsupp{Supp:Supp1}{ I did some extra stuff}
\figsupp{Supp:Supp2} {I did even more extra stuff}

\end{document}

gives all 0s in the references, even though the output in the supplemental section is just fine.

A: The \label is using the wrong information here -- I suggest to create the \@currentlabel and \@currentlabelname content directly and apply \label afterwards then.
\documentclass[10pt,letterpaper]{article}

\usepackage{hyperref}

\newcounter{SFig}
\makeatletter
\newcommand{\figsupp}[2]{%
  \begingroup
  \refstepcounter{SFig}%
  \paragraph*{S\theSFig\ Fig.} {\bfseries{#2}}\phantomsection
  \protected@edef\@currentlabel{\theSFig}
  \protected@edef\@currentlabelname{S\theSFig\ Fig.}
  \label{#1}
  \endgroup
}
\makeatother

\begin{document}
\section{Journal Article}
Lorem Ipsum  (\nameref{Supp:Supp1}).  Dolor sic amet (\nameref{Supp:Supp2}).

\clearpage
\section{Supplemental Information}
\figsupp{Supp:Supp1}{I did some extra stuff}
\figsupp{Supp:Supp2}{I did even more extra stuff}

\end{document}


text:
Q: Connecting to a KVM guest OS in Ubuntu I am lost on this. Basically I am trying to set up a Ubuntu Server 10.10 as a virtual machine by using KVM. Everything went smoothly and I can even sudo-apt get packages from the guest OS.
Now, because of my limited networking & administrating experience, I cannot find out how I can connect to the VMed Ubuntu Server from the host OS. When I did ifconfig the only address that I saw started with 127.0.x.x which means there is no IP for outside communication.
How can I do so? I tried to ping/telnet but apparently, there is no proper IP for that.
The reason for me to do this, is to transfer some of the application into the VM server and run some tests on it.
I googled it out but apparently, I cannot find any useful guide.
Thanks in advance.
P/S: The host OS is ubuntu 10.10 desktop edition

A: Are you using bridged networking?  This is usually the easiest way to set up networking in KVM under Linux.  I would assume one reason you might be able to have network connectivity on the guest VM without having set up its IP explicitly is that it's getting a valid IP from a DHCP server, either through NAT from the host OS or from a DHCP server on your network. However, usually you choose network interfaces during install (using virt-install, KVM, etc) to make available to the guest.  How did you install the guest OS?
To find its IP, you would need to run ifconfig on the guest, not the host.  If you get an IP on the same subnet as your host OS's IP, you can connect to it using that IP -- in that case treat it like it's any other computer on the network.
UPDATE:
Per my comment below, to set up bridged networking, on the host OS edit the /etc/network/interfaces file to look like the following:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
        address 192.168.0.10           #change these 5 lines
        network 192.168.0.0            #to match your IP/network info
        netmask 255.255.255.0          #
        broadcast 192.168.0.255        #
        gateway 192.168.0.1            #
        bridge_ports eth0
        bridge_stp off
        bridge_fd 0
        bridge_maxwait 0

if you use DHCP to get your IP, set the br0 section to look like this instead of the last part above:
auto br0
iface br0 inet dhcp
        bridge_ports eth0
        bridge_stp off
        bridge_fd 0
        bridge_maxwait 0

You can set the network when you install the guest using libvirt:
sudo virt-install --vnc -n vm1 -r 1024 --vcpus=1 \
--os-type=linux --os-variant=ubuntulucid  --hvm --accelerate \
--network=bridge:br0 -c ~/isos/ubuntu_lucid_amd64.iso \
-f ~/vms/vm1ubuntu.vm -s 50

This would install an Ubuntu Lucid guest named 'vm1' from an iso file, giving it 1 vCPU, 1024MB of RAM,  and a 50GB qcow2 disk image file.
If you've installed your guest with this or another method, you can run sudo virsh dumpxml vm1 > vm1.xml to dump information about that guest, edit the file to change a setting, and use sudo virsh create vm1.xml to recreate the guest with the new settings (you'll need to run sudo virsh destroy and sudo virsh undefine in between or use some other method to stop and remove the guest in its current format before re-creating).


text:
Q: Kosaraju's Algorithm for finding SCCs but keep track of edge between SCCs? I currently have a working implementation of Kosaraji's algorithm that, given a directed graph with no weights, will print the SCCs in a graph.
I would like to adapt it so it will also state where the edges between the SCCs are.
Here is the code:
from collections import defaultdict

#---- Definitions ----#

#Graph
Graph = {}

#Transpose of Graph
Transpose_Graph = {}

#Visited Nodes for Graph
Visited_Nodes_Graph = {}

#Visited Nodes for Transpose Graph
Visited_Nodes_Transpose_Graph = {}

#Stack to process
Stack = []

#---- Definitions ----#

#Based on the number of verticies, create a dictionary where every vertex is the key, and the value are the edges from it to another vertex.
def Generate_Empty_Graphs(Number_of_Verticies):
    for Vertex in range(1, Number_of_Verticies+1):
        Graph[Vertex] = []
        Transpose_Graph[Vertex] = []
        Visited_Nodes_Graph[Vertex] = False
        Visited_Nodes_Transpose_Graph[Vertex] = False

#Populate Graph with edges
def Populate_Graphs(Head, Tail):
    Graph[Head].append(Tail)
    Transpose_Graph[Tail].append(Head)

#Run DFS on given Graph, at provided position.
#This is used for DFS #2 (
def Run_DFS(Vertex, Given_Graph, SCC_List):
    Visited_Nodes_Transpose_Graph[Vertex] = True
    SCC_List.append(Vertex)
    for Adjacent_Vertex in Transpose_Graph[Vertex]:
        if(Visited_Nodes_Transpose_Graph[Adjacent_Vertex] == False):
            Run_DFS(Adjacent_Vertex, Transpose_Graph[Adjacent_Vertex], SCC_List)
        #TODO something here to log it...
    return SCC_List

#Process Stack and run DFS
#This is used for DFS #1
def Populate_Stack(Vertex, Given_Graph):
    Visited_Nodes_Graph[Vertex] = True
    for Adjacent_Vertex in Given_Graph[Vertex]:
        if (Visited_Nodes_Graph[Adjacent_Vertex] == False):
            Populate_Stack(Adjacent_Vertex, Given_Graph)
    Stack.append(Vertex)

def Detect_SCCs(Given_Graph, Number_Of_Verticies):
    for Vertex in range(1, Number_Of_Verticies+1):
        if(Visited_Nodes_Graph[Vertex] == False):
            Populate_Stack(Vertex, Given_Graph)

    SCC = []
    while(len(Stack) != 0):
        Current_Vertex = Stack.pop()
        if(Visited_Nodes_Transpose_Graph[Current_Vertex] == False):
            SCC = Run_DFS(Current_Vertex, Transpose_Graph, [])
            print(SCC)

Number_Of_Verticies = 9
Generate_Empty_Graphs(Number_Of_Verticies)

Populate_Graphs(1, 2)
Populate_Graphs(2, 3)
Populate_Graphs(3, 1)
Populate_Graphs(3, 4)
Populate_Graphs(3, 7)
Populate_Graphs(4, 6)
Populate_Graphs(6, 5)
Populate_Graphs(5, 4)
Populate_Graphs(7, 8)
Populate_Graphs(8, 9)
Populate_Graphs(9, 7)

Detect_SCCs(Graph, Number_Of_Verticies)

For the given graph:
{1,2,3} -> {8,7,9}
{1,2,3} -> {4,5,6}
Meaning, there is an edge between {1,2,3} and {8,7,9}. There is also an edge between: {1,2,3} -> {4,5,6}
However, there is NO edge between {8,7,9} and {4,5,6}
The goal is to keep track of these, to determine the largest amount of SCCs possible to touch starting from any given vertex. How could I modify this code to produce this as a graph?

A: One thing can be done that, you can assign each node a component id.
For your example, lets say,
[1, 3, 2] => component id 1
[7, 9, 8] => component id 2
[4, 5, 6] => component id 3

Then create another graph (SCC_GRAPH) using this component id. To generate this graph, you can traverse the original graph once and for each edge (u,v) if their component id is different then create an edge in
SCC_GRAPH with component_id(u) -> component_id(v).
For this example,
1 -> 2
1 -> 3

Then for a given node, get the component id of this node. Then find number of node reachable in SCC_GRAPH starting from the component id of the given node.


text:
Q: deleting duplicates tail recursively in OCaml I tried to write my own solution for this exercise by iterating through a list with a empty complst list where all non duplicates are inserted into and then get returned.
I know it is a over complicated approach after looking up the solution but would still like to understand why the pattern matching does not work as intended:
let compress list =
  let rec aux complst lst =
    match lst with
    | [] -> complst
    | a :: (b :: c) -> if a = b then aux complst (b::c) else aux (a::complst) (b::c)
    | x -> x
  in aux [] list;;
val comp : 'a list -> 'a list = <fun>

Regardless of the input, the output is always a list with only the last element:
 compress [1;1;2;2;3];;
- : int list = [3]

 compress [1;2;3];;
- : int list = [3]

A: Pattern matching
Your pattern-matching matches against three patterns:

*

*The empty list: []

*The list with at least two elements: a :: (b :: c)

*A catch-all, which must by process of elimination be a list with a single element.

Consider what happens when we evaluate your example:
compress [1; 1; 2; 2; 3]
aux [] [1; 1; 2; 2; 3]
aux [] [1; 2; 2; 3]
aux [1] [2; 2; 3]
aux [1] [2; 3]
aux [2; 1] [3]
[3]

Oops, as soon as it hit lst being [3] it just returned it.
Let's rewrite your function to handle that single element list by adding to complst.
let compress lst =
  let rec aux complst lst =
    match lst with
    | [] -> complst
    | [x] -> aux (x::complst) []
    | a :: (b :: c) ->
      if a = b then aux complst (b::c)
      else aux (a::complst) (b::c)
  in
  aux [] list

Now:
compress [1; 1; 2; 2; 3]
aux [] [1; 1; 2; 2; 3]
aux [] [1; 2; 2; 3]
aux [1] [2; 2; 3]
aux [1] [2; 3]
aux [2; 1] [3]
aux [3; 2; 1] []
[3; 2; 1]

Clean up and reversing the resulting list
Of course, there are also ways to clean up your code a bit using a conditional guard and _ for values you don't need to bind names to. You probably also want to reverse your accumulator.
let compress lst =
  let rec aux complst lst =
    match lst with
    | [] -> List.rev complst
    | [x] -> aux (x::complst) []
    | a :: (b :: _ as tl) when a = b -> aux complst tl
    | a :: (_ :: _ as tl) -> aux (a::complst) tl
  in
  aux [] lst

Fold
When you see this pattern of iterating over a list one element at a time and accumulating a new value, you can usually map that pretty well to List.fold_left.
let compress lst =
  List.(
    fold_left
      (fun i x ->
         match i with
         | (x'::_) when x = x' -> i
         | _ -> x::i)
      [] lst
    |> rev
  )

Because List.fold_left can only be aware of one element at a time on the list, the function we pass as its first argument can't be aware of the next element in the list. But it is aware of the accumulator or "init" value. In this case that's another list, and we can pattern match out that list.
If it's not empty and the first element is equal to the current element we're looking at, don't add it to the result list. Otherwise, do add it. This also handles the first element case where the accumulator is empty.
Kudos on creating a tail-recursive solution to this problem!

A: The problem with your code here is mainly the last part, which corresponds to when you have the last element in your list so here  [3], and you return that list with this single element.
What you need to do instead is append it to complst like this :
let compress list =
  let rec aux complst lst =
    match lst with
    | [] -> complst
    | a :: (b :: c ) -> if a=b then aux complst (b::c) else  aux (a::complst) (b::c)
    | x::e -> x::complst
  in aux [] list;;
val comp : 'a list -> 'a list = <fun>

Now you can check with the given example :
compress [1;1;2;2;3];;
- : int list = [3; 2; 1]

Hope it helps you understand your mistake better.
Note regarding comments:
you should keep the [] case, because although it can only happen in one scenario, it is still a valid input meaning it must be kept!.


text:
Q: $|\mathbb{N}|\neq|\mathbb{N}^\mathbb{N}|$ by using the Cantor's diagonal argument A General question about a proof:
While I was reading to proof of $|\mathbb{N}|\neq|\mathbb{N}^\mathbb{N}|$ by using the Cantor's diagonal argument, I saw that they defined $h\in \mathbb{N}^\mathbb{N}$ to be $h(x)=(f(x))(x)+1$ when $f : \mathbb{N}\to \mathbb{N}^\mathbb{N}$ but I can't understand what does $(f(x))(x)$ means?

A: Since $f:\mathbb{N}\to\mathbb{N}^{\mathbb{N}}$, for any $x\in\mathbb{N}$, $f(x)$ is an element of $\mathbb{N}^\mathbb{N}$.  That is, $f(x)$ is itself a function $\mathbb{N}\to\mathbb{N}$, and you can evaluate it at any element of $\mathbb{N}$.  So $(f(x))(x)$ is the function $f(x)$ evaluated at the input $x$, which gives an output in $\mathbb{N}$.


text:
Q: length of continuously differentiable curves I saw that the length of a continuously differentiable curve $\gamma$ in $\mathbb{R}^n$ with $\gamma(t) \neq 0$ is defined as $\int_a^b |\gamma^{'}(t)|dt$, as can be found here https://en.wikipedia.org/wiki/Curve#Lengths_of_curves .
I dont understand why does it really define length as we want it to be?
I hoped someone could explain the idea behind the definition and give some intuition.

A: Let $\gamma$ be the curve in question and partition $[a,b]$ as $a = t_0,...,t_k = b$. To determine $L(\gamma)$ the length of the curve $\gamma$ you approximate its length by the sum of the lengths of the $k$ different line segments joining $\gamma(t_i)$ and $\gamma(t_{i+1})$ with $i=0,...,k-1$.
With this in mind let

*

*$l(t)$ be the length of the curve from $\gamma(a)$ to $\gamma(a+t)$. In particular $l(a) = 0$ and $l(b) = L(\gamma).$

*$\Delta_i t = t_{i+1}-t_i$ be a small change in the variable $t$

*$\Delta_i l = l(t_{i+1})-l(t_i)$ the length of the curve $\gamma$ between $\gamma(t_{i+1})$ and $\gamma(t_i)$

*$\Delta_i \gamma = \gamma(t_{i+1})- \gamma(t_i)$ so that $\vert \Delta_i \gamma \vert $ is the length of the line segment joining $\gamma(t_i)$ and $\gamma(t_{i+1})$.

Intuitively as the partition gets finer and finer we have
$$ \Delta_i l \approx \vert \Delta_i \gamma \vert $$
Now multiply by $1 = \frac{\Delta_i t}{\Delta_i t}$ on the right hand side and sum over all the $i$ to find
$$ \sum_i \Delta_i l \approx \sum_{i} \left\vert \frac{\Delta_i \gamma}{\Delta_i t} \right\vert\Delta_i{t}.$$
On the left you find $l(b) = L(\gamma)$ and the right side intuitively converges to the $\int_a^b \vert \gamma'(t)\vert dt$ when the partition gets finer and finer.
To make this into a rigorous proof all you need to do is to show that
$$ \frac{dl}{dt} = \vert \gamma'(t)\vert$$
since you'll have
$$ L(\gamma) = l(b) - l(a) = \int_{a}^b \frac{dl}{dt} dt = \int_a^b \vert \gamma'(t)\vert dt.$$


text:
Q: How do you keep Xcode project source files in sync with your file system directories? I'm new to XCode and I find the file management a huge pain.  In most IDEs, you can simply have the project source tree reference a directory structure on disk.  This makes it easy to add new files to your project - you simply put them on disk, and they will get compiled automatically.
With XCode, it appears I have to both create the file and separately add it to the project (or be forced to manipulate the filesystem through the UI).  But this means that sharing the .xcodeproj through source control is fraught with problems - often, we'll get merge conflicts on the xcodeproj file - and when we don't, we often get linker errors, because during the merge some of the files that were listed in the project get excised.  So I have to go and re-add them to the project file until I can get it to compile, and then re-check in the project file.
I'm sure I must be missing something here.  I tried using 'reference folders' but the code in them doesn't seem to get compiled.  It seems insane to build an IDE that forces everyone to modify a single shared file whenever adding or removing files to a project.

A: Other answers notwithstanding, this is absolutely a departure from other IDEs, and a major nuisance. There's no good solution I know of.
The one trick I use a lot to make it a little more bearable — especially with resource directories with lots of files in them — is:

*

*select a directory in the project tree,

*hit the delete key,

*choose "Remove References Only", then

*drag the directory into the project to re-add it.

This clobbers any manual reordering of files, but it does at least make syncing an O(1) operation, instead of being O(n) in the number of files changed.

A: I'm intrigued which IDEs you're using that automatically compile everything in a directory, as no IDE I've ever used does that (at least for C++).  I think it's pretty standard to have a project file containing a list of all the files.  Often you may want to only include certain files for different targets, have per-file compiler settings, etc.
Anyway, given that that's how it does work, you really shouldn't have too many problems from merge conflicts.  The best advice would be commit early and often so that you don't get out of step with other people's changes.  Merely adding files to the project shouldn't result in a conflict unless they happen to be added at exactly the same point in the project tree.  We've been using Xcode in our team for years and we very rarely get conflicts: only if someone has restructured the project.
Fortunately, because the Xcode file format is text, it's generally quite easy to resolve conflicts when they occur, unlike the Bad Old Days of Codewarrior with it's binary format.


text:
Q: How many bytes in a map in MATLAB? I have a map called res_Map, containing a set of arrays of varying size. I want to find the total memory used to store res_Map.
As you can see below, it looks as if res_Map takes up almost no memory at all, whereas the individual elements in res_Map do.
res_1 = res_Map(1);
>> whos
  Name              Size             Bytes  Class             Attributes

  res_1           118x100            94400  double
  res_Map          11x1                112  containers.Map

Does anyone know how I can find the actual memory used to store res_Map? I can't find any info about this in the documentation.

A: The containers.Map object is a Matlab object like any other.  Under the hood these are implemented as a Matlab structures with some additional access controls and function mappings.
You can force Matlab to show you the raw structure using the struct command.  This throws a warning, as it is usually not recommended.  However, the structure view of the class shows the complete contents, and is accurately reflected in a whos call.
Some example code is below:
%Initialize map and add some content
res_Map = containers.Map;
for ix = 1:1000
    res_Map(sprintf('%05d',ix)) = ix;
end

%Look at the memory used by the map
disp('Raw who:  always 112 Bytes for Map')
whos('res_Map')

%Force the map into a structure, and look at the contained memory
mapContents = struct(res_Map);
disp('Look at the size of the map contents, reflect true size')
whos('res_Map','mapContents')

%Add additional contents and check again.
for ix = 1001:2000
    res_Map(sprintf('%05d',ix)) = ix;
end
mapContents = struct(res_Map);
disp('Look at the size of the map contents, reflect true size')
whos('res_Map','mapContents')

The result of the above script (after removing the warning messages) is shown below:
Raw who:  always 112 Bytes for Map
Name            Size            Bytes  Class             Attributes
res_Map      1000x1               112  containers.Map

Look at the size of the map contents, reflect true size
Name                Size             Bytes  Class             Attributes
mapContents         1x1             243621  struct
res_Map          1000x1                112  containers.Map

Look at the size of the map contents, reflect true size
Name                Size             Bytes  Class             Attributes
mapContents         1x1             485621  struct
res_Map          2000x1                112  containers.Map

A: There is a script to do this for any struct over at matlab central, which I believe will also work for a map.
To implement it yourself, you need to recurse over the content of the map and subsequently over all the fields in the structs or cells it may contain to determine the sizes.


text:
Q: Shopware 5 development setup for windows 10 I've been trying to get a Shopware 5 development setup up and running on my Win 10 PC, for the last few days, but without success.
I've tried with vagrant, docker or plain old Xampp, but I've never been able to get to the DemoShop page.
Either I keep on getting PHP errors during the Shopware setup, or I won't reach the server ever.
(get error on missing or outdated library, another one, one more, then a PHP syntax error in the shopware/recovery/instals files)
I've followed 4-5 different tutorials by now and I was wandering if there are Shopware developers here, that maybe could help with / suggest an easy-to-install setup.
I'm mostly trying to get this up and running on my pc, to learn this environment, because in a month or so, I'll start working for a new company, and I wanted to get ahead.
Thank you very much, if you have any questions I'll be happy to answer.

A: There are different docker setups for shopware. The most straighforward, out of the box solution is dockware, which also supports Shopware 5 and has been reported to work on Windows.
You can pull from dockerhub or use docker-compose to do so.
This is my docker-compose.yml based on the dockware documentation. I only tested on Ubuntu so far.
version: "3"

services:
    shopware:
        image: dockware/dev:5.6.9
        container_name: shopware
        ports:
            - "80:80"
            - "22:22"
            # Admin Watcher Port
            - "8888:8888"
            # Storefront Watcher Port
            - "9999:9999"
        environment:
            - PHP_VERSION=7.4
            - XDEBUG_ENABLED=1
        volumes:
            - "db_volume:/var/lib/mysql"
            - "shop_volume:/var/www/html"
volumes:
    db_volume:
        driver: local
    shop_volume:
        driver: local


text:
Q: Hibernate Validator 3.1.0.GA ignoring ValidationMessages.properties (test project included) I have a problem with Hibernate Validator 3.1.0.GA not looking up custom validation messages in the property file ValidationMessages.properties.
To illustrate the problem, I created a small example project, which you can get through git:
git clone https://bitbucket.org/sstein/validation-example.git

After you got the source tree, you can test the problem by running the unit tests I created using:
mvn test

There are 3 test cases and validateDescriptionTest(com.example.MyClassTest) is failing with:

expected:<[Description must be between 1 and 10 characters long.]> but was:<[{descriptionMsg}]>

I also added a test case verifying that the resource bundle is accessible by unit tests and this works.
Does anyone know why this one is failing?
PS: I completely rewrote my initial question adding the example so that you can try on your own.

A: The final location of ValidationMessages.properties shuold be in WEB-INF/classes. How it gets there depends on the build system you are using and how you configure it. In NetBeans IDE, when I create a web application, I can just put ValidationMessages.properties into the default Java package.
In case you are using Maven as a build tool, put the properties into the /src/main/resources directory, this way Maven will copy it into WEB-INF/classes.
To make sure that the properties file is in place, open the .war file as a ZIP and just take a look. Another way to tell is just by checking if JSF picks up the validator messages inside.
For JSR-303 messages like @Size, the above properties key should be correct.

A: So the solution is simple and was found by Hardy Ferentschik of Hibernate:
In Hibernate Validator 3.1.0.GA, the bundle must be called ValidatorMessages.properties and NOT ValidationMessages.properties.


text:
Q: Is this possible to speed up datachannel processing using webworkers I have this code from a well known chat bot AI.
//main thread:

const worker = new Worker('worker.js');

worker.onmessage = event => {
  console.log(`Received message from worker: ${event.data}`);
};

const peerConnection = new RTCPeerConnection();

const dataChannel = peerConnection.createDataChannel('myDataChannel');

dataChannel.onmessage = event => {
  console.log(`Received message from data channel: ${event.data}`);
};

worker.postMessage({ type: 'dataChannel', dataChannel });

//web worker

self.onmessage = event => {
  if (event.data.type === 'dataChannel') {
    const dataChannel = event.data.dataChannel;
    dataChannel.onopen = () => {
      dataChannel.send('Hello, main thread!');
    };
  }

};

Appart from signaling and other things related to the connection I was wondering if this code might work, in a sense that if I send or receive messages it won't be blocked by the main thread? I can't really see a first glance what would be the real improvement here as the endpoint is the main thread and will be treated synchronously but maybe there are some?!


text:
Q: Google Analytics - Not tracking in IE I have a site URL: <removed after answering>
and it is mapped to show as app on facebook:
I'm able to track engagements on the apps.facebook url and direct URL on all browsers except IE. I have tried different solutions from people on the internet but none seem to work.
You can have a look at he source of the page to look at analytics settings. Am I doing something wrong?

A: Solved the issue. With help from: www.savio.no/blogg/a/104/how-to-track-facebook-iframes-with-google-analytics, i tried the solution for asp.net and it worked. Apparently it looks like cookies were not being set as expected.


text:
Q: 'I couldn't agree more.' (Is this sentence 'past tense' or 'present tense'?
'I couldn't agree more.'

Is this sentence 'past tense' or 'present tense' We need 'context'?

A: The tense of a clause is the tense of its finite verb.  In this case, the finite verb is the modal "could".  ("Agree" here is a bare infinitive and so has no tense.)
Morphologically (and for some purposes grammatically), "could" is the past tense of "can".  However, some people prefer to think of "can" and "could" as separate modal verbs (and therefore as not having tense in any meaningful sense).  Obviously, semantically, "could" by no means refers exclusively to past time, and it probably doesn't do so here.  Its meaning here is probably conditional (couldn't agree more = "would not be able to agree more"), although it could also be past ("yesterday, when we discussed this, you'll recall that I couldn't agree more" = wasn't able to agree more), but the past-time interpretation is less likely.
Still, overall, I would say that, if forced to state what tense this modal is, I'd say it's the past tense.
Note: I agree that the speaker is probably referring to present time, but tense and time are not the same thing.  Tense is grammatical, time is semantic.  "I am going to see him tomorrow" is present tense; "I fly next Thursday" is also present tense. In "If I knew, I would tell you", "knew" is past tense, but refers to a hypothetical present rather than the past.

A: The modal verb could is the politer relation of can, especially in requests, e.g. "Could you open the window, please?" "Could you lend me a hand?"
In "I couldn't agree more", couldn't is used as an intensifier, it means "absolutely" or "totally" as in I totally agree with you. I agree so much so, it would be impossible to express this agreement more completely.
It's unusual–not impossible–just unusual, to use can in "I cannot agree more".
Without any context, we can surmise that the speaker is referring to the present. But without context, it's quite possible the speaker is referring to a past situation or a previous discussion.


text:
Q: 301 Redirection on nginx server (thousands of 404 errors) we have an issue with the website (using Magento, on nginx) as it has ~5k URLs returning a 404 error. Most of these are product pages.
We need to make a 301 redirects for all these URLs, e.g.:
redirect from www.example.com/category1/product.html to www.example.com/product.html.
What would be the best way to do that? Should we do this manualy for every page or is there a better way?
I would appreciate your help,

A: Nginx's url matching is able to do that, but for an entirely Magento solution, one could add an additional url lookup tool to the Magento error page. Put this in the '404 Not Found 1' CMS page:
{{block type="core/template" template="redirect/process.phtml"}}

Then create a redirect/process.phtml directory and file in your theme's template directory. Also add a list.csv file in the redirect directory, containing urls like:
/old/category1/url,/new/url

Process.phtml would have something like:
$F = fopen(__DIR__.'/list.csv','r');
if ($F) while (($_ = fgetcsv($F))) {
  if ($_[0] == $_SERVER['REQUEST_URI']) {
    Mage::app()->getResponse()
    ->setRedirect($_[1], 301)
    ->sendResponse();
    return;
  }
}
fclose($F);

I assumed here that the contents of that CSV file are extremely large and not work I'd want to on every url lookup, or are changing faster than I'd want to keep updating Magento's internal redirect databasee. Example of that: https://gielberkers.com/how-to-programmatically-create-url-rewrites-in-magento-enterprise/


text:
Q: Change Label for Telephone on Checkout Page I would like to know where can I edit the label for the form under "Billing Information" One page Checkout?

A: To change label "Telephone" only on billing, you can edit below file.
app/design/frontend/[THEME_PACKAGE]/[THEME]/template/checkout/onepage/billing.phtml

To change label "Telephone" on checkout page, you can use below file.
app/locale/en_US/Mage_Checkout.csv

Try using template path hints to checkout the file path if you are not using default Magento OnePageCheckout.


text:
Q: select element after insert jquery javascript I have a little problem which is the following:
I have a button which allows to generate html code, example:
               $( "#addBlockArray" ).click(function() {

       let idunique =  Math.floor(Math.random() * 100000);

           let array =
           '\
           <divSpecialSelected class="selectedbloccss"  id= ' + idunique + '> edit\

 \

\

\
           #	\
           First	\
           Last	\
           Handle	\

\

\

\

\
           1	\
           Mark	\
           Otto	\
           @mdo	\

\

\
           2	\
           Jacob	\
           Thornton	\
           @fat	\

\

\
           3	\
           Larry the Bird	\
           @twitter	\

\

\

\
     </divSpecialSelected>\
           '

           $( "#blocArray" ).append( array);

     });

However, when this code is generated, I am unable to use selectors to do actions on it
$("divSpecialSelected").on('click', function () { // that dont work, he dont find this selector
console.log("aaa");
document.getElementById(this.id).addEventListener('mousedown', mouseDown, false);
localStorage.setItem('id', this.id);
window.addEventListener('mouseup', mouseUp, false);

});
I think because it is not in the DOM loaded at the start. But how could I get around this problem?


text:
Q: first-child in jQuery doesn't seem to be finding the right element I'm using this jQuery code
$('div:first-child').text('change me');

And this HTML in the body section:

test1

test2

test3

test4

I thought this would just replace "test1", but it seems to replace everything such that all I see on the page is "change me".
Have I misunderstood what first-child does (I assumed this jQuery code would replace the first child element, which is the test1 of strong, of the first div it finds)? Or is my code wrong?
Thanks

A: You need to use the div element selector then a child selector with the :first-child selector
$('div > :first-child').text('change me');

Your code is searching for a div element which is the first child of its parent element, instead of finding the first child within the div element
Demo: Fiddle

A: :first-child selects all elements that are the first child of their parent. Try this:
$('div strong:first-child').text('change me');

Here's a fiddle.


text:
Q: Mostrar texto que fica escondido ao mudar de linha Tenho o problema com o css do meu checkbox.
Código do checkbox:

.funkyradio div {
  clear: both;
  overflow: hidden;
}

.funkyradio label {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #D1D3D4;
  font-weight: normal;
}

.funkyradio input[type="radio"]:empty,
.funkyradio input[type="checkbox"]:empty {
  display: none;
}

.funkyradio input[type="radio"]:empty ~ label,
.funkyradio input[type="checkbox"]:empty ~ label {
  position: relative;
  line-height: 2.5em;
  text-indent: 3.25em;
  margin-top: 2em;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

.funkyradio input[type="radio"]:empty ~ label:before,
.funkyradio input[type="checkbox"]:empty ~ label:before {
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  content: '';
  width: 2.5em;
  background: #D1D3D4;
  border-radius: 3px 0 0 3px;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label {
  color: #888;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label:before,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #C2C2C2;
}

.funkyradio input[type="radio"]:checked ~ label,
.funkyradio input[type="checkbox"]:checked ~ label {
  color: #777;
}

.funkyradio input[type="radio"]:checked ~ label:before,
.funkyradio input[type="checkbox"]:checked ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #333;
  background-color: #ccc;
}

.funkyradio input[type="radio"]:focus ~ label:before,
.funkyradio input[type="checkbox"]:focus ~ label:before {
  box-shadow: 0 0 0 3px #999;
}

.funkyradio-success input[type="radio"]:checked ~ label:before,
.funkyradio-success input[type="checkbox"]:checked ~ label:before {
  color: #fff;
  background-color: #5cb85c;
}

.clearfix:after {
 content: "";
 display: block;
 clear: both;
 visibility: hidden;
 height: 0;
}

.form_wrapper .input_field, .form_wrapper .textarea_field {
 position:relative;
}
.form_wrapper .input_field > span, .form_wrapper .textarea_field > span {
 position:absolute;
 left:0;
 top:0;
 color:#333;
 height:100%;
 border-right:1px solid #ccc;
 text-align:center;
 width:30px;
}
.form_wrapper .textarea_field > span {
 border-bottom:1px solid #ccc;
 max-height:35px;
}
.form_wrapper .input_field > span > i, .form_wrapper .textarea_field > span > i {
 padding-top:12px;
}

.col_half {
 width:40%;
 float:left;
}

Humor/Comportamento/Personalidade

<input type="checkbox" name="Euforia" id="Euforia1" Value="Sim" ' . ( ($row["Euforia"]=='Sim') ? 'checked' : '' ) .' readonly="true">
Sente Euforia (Alegria Patológica Desproporcional à Circunstância)

Mas ao visualizar esconde uma parte do texto, uma vez que muda de linha.
Como posso resolver este problema, nos casos que mudam de linha?

A: Vc colocou bottom:0 no pseudo elemento, por isso ele "estica" até o final do container pai, cobrindo parte do texto que está abaixo quando quebra a  linha.
Uma das forma simples de resolver é tirar o bottom:0 e colocar um height fixo em PX, ou EM (EMs seria mais indicado)

Além disso para centralizar o ✔ no box, coloque display: flex no pseudo elemento e coloque align-items: center
Segue o código da imagem acima

.funkyradio div {
  clear: both;
  overflow: hidden;
}

.funkyradio label {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #D1D3D4;
  font-weight: normal;
}

.funkyradio input[type="radio"]:empty,
.funkyradio input[type="checkbox"]:empty {
  display: none;
}

.funkyradio input[type="radio"]:empty ~ label,
.funkyradio input[type="checkbox"]:empty ~ label {
  position: relative;
  line-height: 2.5em;
  text-indent: 3.25em;
  margin-top: 2em;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.funkyradio input[type="radio"]:empty ~ label:before,
.funkyradio input[type="checkbox"]:empty ~ label:before {
  position: absolute;
  display: block;
  top: 0;
  /* bottom: 0; */
  height: 19px;
  display: flex;
  align-items: center;
  left: 0;
  content: '';
  width: 2.5em;
  background: #D1D3D4;
  border-radius: 3px 0 0 3px;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label {
  color: #888;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label:before,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #C2C2C2;
}

.funkyradio input[type="radio"]:checked ~ label,
.funkyradio input[type="checkbox"]:checked ~ label {
  color: #777;
}

.funkyradio input[type="radio"]:checked ~ label:before,
.funkyradio input[type="checkbox"]:checked ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #333;
  background-color: #ccc;
}

.funkyradio input[type="radio"]:focus ~ label:before,
.funkyradio input[type="checkbox"]:focus ~ label:before {
  box-shadow: 0 0 0 3px #999;
}

.funkyradio-success input[type="radio"]:checked ~ label:before,
.funkyradio-success input[type="checkbox"]:checked ~ label:before {
  color: #fff;
  background-color: #5cb85c;
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  height: 0;
}

.form_wrapper .input_field,
.form_wrapper .textarea_field {
  position: relative;
}

.form_wrapper .input_field > span,
.form_wrapper .textarea_field > span {
  position: absolute;
  left: 0;
  top: 0;
  color: #333;
  height: 100%;
  border-right: 1px solid #ccc;
  text-align: center;
  width: 30px;
}

.form_wrapper .textarea_field > span {
  border-bottom: 1px solid #ccc;
  max-height: 35px;
}

.form_wrapper .input_field > span > i,
.form_wrapper .textarea_field > span > i {
  padding-top: 12px;
}

.col_half {
  width: 40%;
  float: left;
}

    Humor/Comportamento/Personalidade

          <input type="checkbox" name="Euforia" id="Euforia1" Value="Sim" ' . ( ($row["Euforia"]==' Sim') ? 'checked' : '' ) .' readonly="true">
          Sente Euforia (Alegria Patológica Desproporcional à Circunstância)

A: Troque a propriedade text-indent: 3.25em; por padding-left: 3.25em; na label.
O text-indent só vai indentar a primeira linha do texto, ou seja, se houver quebra de linha, da segunda linha em diante do texto não sofrerá indentação.

Talvez outros ajustes sejam necessários (no line-height do texto e
  ajustes no checkbox), mas como a dúvida era apenas sobre o texto da
  label, o padding-left já resolve.

Veja:

.funkyradio div {
  clear: both;
  overflow: hidden;
}

.funkyradio label {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #D1D3D4;
  font-weight: normal;
}

.funkyradio input[type="radio"]:empty,
.funkyradio input[type="checkbox"]:empty {
  display: none;
}

.funkyradio input[type="radio"]:empty ~ label,
.funkyradio input[type="checkbox"]:empty ~ label {
  position: relative;
  line-height: 2.5em;
  /*text-indent: 3.25em;*/
  padding-left: 3.25em;
  margin-top: 2em;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

.funkyradio input[type="radio"]:empty ~ label:before,
.funkyradio input[type="checkbox"]:empty ~ label:before {
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  content: '';
  width: 2.5em;
  background: #D1D3D4;
  border-radius: 3px 0 0 3px;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label {
  color: #888;
}

.funkyradio input[type="radio"]:hover:not(:checked) ~ label:before,
.funkyradio input[type="checkbox"]:hover:not(:checked) ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #C2C2C2;
}

.funkyradio input[type="radio"]:checked ~ label,
.funkyradio input[type="checkbox"]:checked ~ label {
  color: #777;
}

.funkyradio input[type="radio"]:checked ~ label:before,
.funkyradio input[type="checkbox"]:checked ~ label:before {
  content: '\2714';
  text-indent: .9em;
  color: #333;
  background-color: #ccc;
}

.funkyradio input[type="radio"]:focus ~ label:before,
.funkyradio input[type="checkbox"]:focus ~ label:before {
  box-shadow: 0 0 0 3px #999;
}

.funkyradio-success input[type="radio"]:checked ~ label:before,
.funkyradio-success input[type="checkbox"]:checked ~ label:before {
  color: #fff;
  background-color: #5cb85c;
}

.clearfix:after {
 content: "";
 display: block;
 clear: both;
 visibility: hidden;
 height: 0;
}

.form_wrapper .input_field, .form_wrapper .textarea_field {
 position:relative;
}
.form_wrapper .input_field > span, .form_wrapper .textarea_field > span {
 position:absolute;
 left:0;
 top:0;
 color:#333;
 height:100%;
 border-right:1px solid #ccc;
 text-align:center;
 width:30px;
}
.form_wrapper .textarea_field > span {
 border-bottom:1px solid #ccc;
 max-height:35px;
}
.form_wrapper .input_field > span > i, .form_wrapper .textarea_field > span > i {
 padding-top:12px;
}

.col_half {
 width:40%;
 float:left;
}
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Humor/Comportamento/Personalidade

<input type="checkbox" name="Euforia" id="Euforia1" Value="Sim" ' . ( ($row["Euforia"]=='Sim') ? 'checked' : '' ) .' readonly="true">
Sente Euforia (Alegria Patológica Desproporcional à Circunstância)


text:
Q: How do I distinguish between $t$ and $u$ channel? Here are two fermion-fermion scattering Feynman diagrams for $L_{int} = -g\phi\bar\psi\psi$:

I'm just wondering how can we define and distinguish between $t$ and $u$ channels. On the Wikipedia page, $t$ and $u$ are defined the other way around.
Also, because the outgoing particles are fermions, do I need to take care of the antisymmetric property? Is there a phase difference between these channels?

A: In cases where $(1,2)$ or $(3,4)$ are pairs of identical particles, you can't distinguish t- from u-uchannel scattering. You must include both (and any interference) when computing your amplitude.  However, if a conservation law prohibits or suppresses a transformation between one of your inputs and one of your outputs, you can choose to describe your interaction as "all t-channel" and say that the corresponding u-channel process is forbidden.
For example, elastic electron-electron scattering includes both t- and u-channel terms. However, in electron-positron scattering, the momentum transfer in the u-channel would also need to carry two units of charge. So in $e^-e^+\to e^-e^+$, the u-channel is strongly suppressed/forbidden.


text:
Q: Adding a solid stroke to Text I am trying to add a thick solid stroke to some Text in React Native. I've added a snippet with the desired CSS.
I've tried directly applying the CSS via styled-components but I get an error stating that my value is unable to be parsed.
const Title = styled.Text`
  text-shadow: 2px 2px 0px  #000, -2px -2px 0px  #000, 2px -2px 0px  #000, -2px 2px 0px  #000;
`;

I have tried using textShadow but this does not apply a solid stroke. This prop relies on a width and height prop for an offset.
Here's a snack for example - https://snack.expo.io/@hannigan/ba7574

h1 {
  text-shadow: 2px 2px 0px  #000, -2px -2px 0px  #000, 2px -2px 0px  #000, -2px 2px 0px  #000;
  color: white;
  font-family: 'Arial';
}

Hello World

A: I couldn't find a way to do this with react native's css but I found a way to do a stoke in the text with react-native-svg
<Svg height="60" width="200">
  <Text
    fill="none"
    stroke="purple"
    fontSize="20"
    fontWeight="bold"
    x="100"
    y="20"
    textAnchor="middle"
  >
    STROKED TEXT
  </Text>
</Svg>

Edit
I know this answer isn't the perfect one, but so far is the only answer I found to do this, but unfortunately it isn't good for dynamic text.

A: So this works for me, are you sure that it won't work for you in dynamic height?
Edit: I might have now found what you were talking about. I am checking if I can update the snack to work for dynamic views.
Edit2: Alright, made it work. You just need to make the first text non-absolute.
https://snack.expo.io/Bk8ifP!4I
Edit3: As mentioned by Vencovsky it might break if you need to use flex around it. You can hack it with a onLayout like in this Snack: https://snack.expo.io/HJ!PRUKNL
basically you save the height of the text and then use it for height and margin on other views. It hacky, but I have used it in other settings and works fine.

export default class App extends React.Component {

  render() {

       const myText = 'Hello World. This is my very long text, that can be a few lines height'

    return (
      <View style={styles.container}>

      <View>

        <Text style={[styles.paragraph]}>{myText}</Text>
        <Text style={[styles.paragraph, styles.abs, {textShadowOffset: {width: -2, height: -2}}]}>{myText}</Text>
        <Text style={[styles.paragraph, styles.abs, {textShadowOffset: {width: -2, height: 2}}]}>{myText}</Text>
        <Text style={[styles.paragraph, styles.abs, {textShadowOffset: {width: 2, height: -2}}]}>{myText}</Text>

      </View>

       <Text> 'Here another text' </Text>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8
  },
  paragraph: { fontSize: 50, color: '#FFF', textShadowColor: 'black', textShadowRadius: 1, textShadowOffset: {
          width: 2,
          height: 2
        }},
  abs: {
     position: 'absolute',
      top: 0, left: 0, right: 0, bottom: 0
    }
});


text:
Q: netsh "Error: 87 The parameter is incorrect" when using hostnameport I am using the following netsh command successfully:
netsh http add sslcert ipport=127.0.0.1:9000 appid={7B8DB713-2C51-41B5-AE6F-6DAA07833DBE} certhash=69fed34fdf164e7feac5e17823b94d0f30ab05c5

but when I change the "ipport=..." to "hostnameport" it doesn't work:
netsh http add sslcert hostnameport=localhost:9000 appid={7B8DB713-2C51-41B5-AE6F-6DAA07833DBE} certhash=69fed34fdf164e7feac5e17823b94d0f30ab05c5

I get the following error:
    SSL Certificate add failed, Error: 87
    The parameter is incorrect.
This is the ONLY THING I've changed in the command.  I am still running as administrator, same exact command prompt.  Why am I getting this error?

A: The problem is a bug in the netsh command.  When using "hostnameport" you must also add the "certstorename=MY" parameter.  This is the default value for certstorename, and it is explicitly documented as optional.  So my new command is:
netsh http add sslcert hostnameport=localhost:9000 appid={7B8DB713-2C51-41B5-AE6F-6DAA07833DBE} certhash=69fed34fdf164e7feac5e17823b94d0f30ab05c5 certstorename=MY


text:
Q: Python Scrapy unicode comparing string Turkish characters I researched many times this problem but i could not find clear answer. Please help me how can i compare two unicode strings. I want to get date from this format "17 Ağustos 2017" or "11 Eylül 2017" and I try to convert to this format "17-08-2017" , "11-9-2017" . But when i get the month string it returns

"Ağustos" > "A\xc4\x9fustos" ,"Eylül" > "Eyl\xfcl"

    months = ['Ocak', '\xc5\x9eubat', 'Mart', 'Nisan',
               'May\xc4\xb1s', 'Haziran', 'Temmuz',
              'A\xc4\x9fustos', 'Eyl\xfcl', 'Ekim',
                'Kas\xc4\xb1m', 'Aral\xc4\xb1k'
             ]

                month= valuesDetails[indexDate].split(" ")

                if int(months.index(month[1])+1 < 10): # month
                    month[-2]= "0"+str(months.index(month[1])+1)
                else:
                    month[-2]= str(months.index(month[1])+1)
                if int(month[0]) < 10: # day
                    mont[0] = "0"+month[0]

                item['date'] = month[0]+"-"+month[1]+"-"+month[2]

A: A simpler way of doing this is to use Python's datetime & locale libraries given we know Turkish's locale code, tr_TR, and some datetime masking.
#coding:utf8
from datetime import datetime
import locale

# Datetime is aware of locale,
# change locale to Turkish
locale.setlocale(locale.LC_TIME, "tr_TR")

dates = ['17 Ağustos 2017','11 Eylül 2017']

for date in dates:
    # Make `date` str a datetime object
    # using a datetime mask
    dt = datetime.strptime(date, '%d %B %Y')
    # Convert `dt` datetime object to
    # str in preferred format using a
    # datetime mask
    dt_str = dt.strftime('%d-%m-%Y')
    # Walla!
    print(dt_str)

Output:
17-08-2017
11-09-2017

A: Without changing the locale, you could create a global dictionary of the respective months and replace the Turkish month with the corresponding English month:
#coding:utf8
from datetime import datetime

MONTHS = {
    'Ocak': 'January',
    'Şubat': 'February',
    'Mart': 'March',
    'Nisan': 'April',
    'Mayıs': 'May',
    'Haziran': 'June',
    'Temmuz': 'July',
    'Ağustos': 'August',
    'Eylül': 'September',
    'Ekim': 'October',
    'Kasım': 'November',
    'Aralık': 'Decemeber'
}

def format_date(date):
    # Iterate through months and grab
    # respective turkish and english
    # month
    for tr_month, eng_month in MONTHS.items():
        # Replace turkish month (if found)
        # with english month
        if tr_month in date:
            print("'%s' > %s" % (tr_month, repr(tr_month)))
            date = date.replace(tr_month, eng_month)
            break
    # Convert date to datetime object and
    # back into the preferred format
    return datetime.strptime(date,'%d %B %Y').strftime('%d-%m-%Y')

for date in ['17 Ağustos 2017','11 Eylül 2017']:
    print(format_date(date))

Output:
'Ağustos' > 'A\xc4\x9fustos'
17-08-2017
'Eylül' > 'Eyl\xc3\xbcl'
11-09-2017

I'm assuming I got the months correct but I don't know Turkish so you might want to double check that.


text:
Q: If I change tabs and come back, my GIF freezes for a while (p5.js) Code for Catbus game
Whenever I try to run it, it works fine, but when I change to another tab and back, the gif freezes for the same amount of time I was in the other tab. I'm trying to be able to run both the background AND the gif. So, do y'all know anything that may fix the gif?
(Code is as follows)
let img;
let img2;
var bgImg;
var x1 = 0;
var x2;

var scrollSpeed = 4;

var screen = 0;
var y = -20;
var x = 200;
var speed = 2;
var score = 0;

let bing

function preload() {
  bgImg = loadImage("backgwound.png");

  bing=loadSound('catbus theme song.mp3')

}

function setup() {
  createCanvas(1000, 1000);

  img = loadImage("backgwound.png");

  img2 = loadImage("catgif.gif");

  x2 = width;

bing.loop()

}

function draw() {
  if (screen == 0) {
    startScreen();
  } else if (screen == 1) {
    gameOn();
  } else if (screen == 2) {
    endScreen();
  }

  let time = frameCount;

  image(img, 0 - time, 0);

  image(bgImg, x1, 2, width, height);
  image(bgImg, x2, 2, width, height);

  x1 -= scrollSpeed;
  x2 -= scrollSpeed;

  if (x1 <= -width) {
    x1 = width;
  }
  if (x2 <= -width) {
    x2 = width;
  }

  scale(0.4, 0.4);
  translate(300, 1855);

  image(img2, 0, 0);
}

function startScreen() {
  background(96, 157, 255);
  fill(255);
  textAlign(CENTER);
  text("CAT BUS BIZARRE ADVENTURE", width / 2, height / 2);
  text("click any key to START", width / 2, height / 2 + 20);
  reset();
}

function gameOn() {
  background(0);
  text("SCORE = " + score, 30, 20);
  ellipse(x, y, 20, 20);
  rectMode(CENTER);
  rect(mouseX, height - 10, 50, 30);
  y += speed;
  if (y > height) {
    screen = 2;
  }
  if (y > height - 10 && x > mouseX - 20 && x < mouseX + 20) {
    y = -20;
    speed += 0.5;
    score += 1;
  }
  if (y == -20) {
    pickRandom();
  }
}

function pickRandom() {
  x = random(20, width - 20);
}

function endScreen() {
  background(150);
  textAlign(CENTER);
  text("GAME OVER", width / 2, height / 2);
  text("SCORE = " + score, width / 2, height / 2 + 20);
  text("click space to play again", width / 2, height / 2 + 40);
}

function mousePressed() {
  if (screen == 0) {
    screen = 1;
  } else if (screen == 2) {
    screen = 0;
  }
}

function reset() {
  score = 0;
  speed = 2;
  y = -20;
}

A: I wasn't able to find the route cause of the issue but I found a potential workaround, and it might even benefit you later when adding the ability for the cat to jump.
Rather than using loadImage I'm using createImg - here's a link to the docs.
  let cat = {
    x: 50,
    y: 730
  }

  ...
  // in setup()

  catGif = createImg("catgif.gif");
  catGif.position(cat.x, cat.y);
  catGif.size(200, 100);

If you get stuck, I've implemented the changes in this p5.js sketch to point you in the right direction.
Then later on, in your draw() method you can dynamically set the position of the cat based on some velocity, I'd recommend taking a look at this post as it should help you understand forces and how they can be applied to your game.

A: The problem here is actually a bug in p5.js. The code in _animateGif that gets the current time is oddly buggy (sometimes it gets a time in the past). I don't understand why the authors of that code decided to use pInst._lastFrameTime + pInst.deltaTime instead of just using pInst.millis().


text:
Q: Django and pytest, multiple databases, use only one database I have 2 databases in my project:
DATABASES = {
    'default': env.db('DEFAULT_DATABASE_URL'),
    'second': env.db('SECOND_DATABASE_URL'),
}

When I had only one database, then all tests that required access to the database passed fine, but when I connected the second one, then all tests began to fail with an error - django.db.utils.IntegrityError: duplicate key value violates unique constraint.
As I understand it, the test runs twice for each database and crashes because of this. Is there some way to tell pytest to only take one database for tests?
Example of one test:
@pytest.mark.django_db
def test_complaint_reasons(client: APIClient):
    reasons_count = 12
    Profile.create_batch(reasons_count)

    client.force_login(Factory())
    response = client.get(reverse('url'))
    assert response.status_code == status.HTTP_200_OK
    assert len(response.data) == reasons_count
    jsonschema.validate(response.data, ProfileComplaintReasonsSchema)

A: Use this mark instead:
@pytest.mark.django_db(databases=['default', 'second'])
But be careful with this because it's still experimental.


text:
Q: libvorbis complains "more samples than frame size" I am trying to figure out what's wrong with my command to encode into theora+vorbis. I am able to demonstrate the issue with minimum code as following:
encoding audio followed by video works ok:
ffmpeg -filter_complex "smptehdbars=size=1280x720:rate=30000/1001[v];sine=beep_factor=2[a]" -map [a] -map [v] -vcodec libtheora -acodec libvorbis -t 3 -f ogg map-audio-video.ogg -y

however video followed by audio does not work (swapped order of -map):
ffmpeg -filter_complex "smptehdbars=size=1280x720:rate=30000/1001[v];sine=beep_factor=2[a]" -map [v] -map [a] -vcodec libtheora -acodec libvorbis -t 3 -f ogg map-video-audio.ogg -y

and fails with the following error:
ffmpeg version 4.4-full_build-www.gyan.dev Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 10.2.0 (Rev6, Built by MSYS2 project)
Stream mapping:
  smptehdbars -> Stream #0:0 (libtheora)
  sine -> Stream #0:1 (libvorbis)
Press [q] to stop, [?] for help
[libvorbis @ 000001f846602fc0] more samples than frame size
Audio encoding failed
Conversion failed!

Any idea why the standard order video, audio breaks on samples vs. frame size?

A: Use -f lavfi to indicate that the following inputs are filters. Because you have two distinct inputs use two -f lavfi.
ffmpeg -y -f lavfi -i "smptehdbars=size=1280x720:rate=30000/1001" -f lavfi -i "sine=beep_factor=2" -c:v libtheora -c:a libvorbis -t 3 output.ogg


text:
Q: Save id from  into a variable I have a piece of code in which I can select a user from the database.
<html>
<form method="post">
Vak:<select name="gebruiker">
<?php
$resultaat = mysqli_query($mysql,"SELECT * FROM gebruikers ORDER BY gebruikersnaam") or die("De query op de database is mislukt!");
while ($rij = mysqli_fetch_assoc($resultaat)){
    echo "<option value=\"{$rij['id']}\">{$rij['gebruikersnaam']} {$rij['voorletters']} {$rij['achternaam']} {$rij['rol']} {$rij['actief']} {$rij['vak']}</option>";
}
?>
</select><br>
</form>
</html>

Now I want to save the ID of the selected user into the variable '$id', but only the ID. I want to use this variable in the following query (at WHERE).
<?php
 mysqli_query($mysql,"UPDATE gebruikers SET gebruikersnaam =
'$gebruikersnaam', wachtwoord ='$wachtwoord',voorletters ='$voorletters',
achternaam ='$achternaam', rol='$rol',actief='$actief',vak='$vak' WHERE
id = '$id'")
or die("De updatequery op de database is mislukt!");
?>

I know I can save all the data from the selected user with
<?php
$gebruiker = mysqli_real_escape_string($mysql,$_POST['gebruiker']);
?>

but I only need the ID from the user.
Does someone know how I can do this?
Thanks in advance


text:
Q: jQuery dataTable : How to know width applied to each column I'm creating two tables, one for normal rows (table1), and another for total row(s) (-table2).
I would like to have the width for table1 automatic , and apply same widths to table2.
I tried to get the widths of table1 in table 2 drawCallback and apply the same :
"fnDrawCallback": function (oSettings) {
  var i=0;
  jQuery('#table1 tbody tr:last td').each(function () {
    jQuery('#table2 tbody tr td:eq(' + i + ')').width(jQuery(this).width());
    i++;
  });
}

But sometimes, the width of table1 last row is returned as 0.
So, is there any way, that I can query the data table1 object, and get the width applied for it?

A: dataTables set the width of the <th> elements, not <tbody> <td>'s. If you are not adding inline CSS to your headers (and basically that should never be necessary) the easiest is simply to copy dataTables injected style attribute, which contains the calculated widths "width: 63px;" etc :
drawCallback: function() {
   jQuery('#table1 thead th').each(function(i,th) {
      jQuery('#table2 thead th:eq('+i+')')
         .attr('style', jQuery(th).attr('style'))
   })
}

demo -> http://jsfiddle.net/51jLt8og/


text:
Q: Update ng-class in ng-repeat using ng-click How can I update the ng-class when I click the ng-click in ng-repeat?
HTML

  <button ng-class="{'red':color==true,'blue':color==false}" ng-click="changeColor(x.color)">
    Change Color
  </button>

Script
$scope.changeColor = function(c){
  if(c){
    $scope.color = true;
  }else{
    $scope.color = false;
  }
}

I already tried this but it doesnt work.
UPDATE
I want to change only the color of the button clicked.

A: The problem with your code is that for all the elements in the collection, you're using the same flag, i.e. $scope.color. When this flag changes, it changes all the buttons' color.
To mitigate that, one way is to have an array which contains the value true and false at the specified indices and use that array to decide the class assignment in the template.

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  $scope.y = [{
    color: 'r'
  }, {
    color: ''
  }];

  $scope.classes = [];

  $scope.changeColor = function(c, i) {
    if (c) {
      $scope.classes[i] = true;
    } else {
      $scope.classes[i] = false;
    }
  }

});
.red {
  color: red;
}

.blue {
  color: blue;
}

    <button ng-class="{'red':classes[$index],'blue':classes[$index] !== undefined && !classes[$index]}" ng-click="changeColor(x.color, $index)">
    Change Color
  </button>

A: You should maintain color property on element rather than using global (single) color property for styling effect. I'd say pass whole entity x to change color method and toggle color property when user clicks on it.
HTML

  <button ng-class="{'red':color,'blue':!color}" ng-click="changeColor(x)">
    Change Color
  </button>

OR

  <button ng-class="color ? 'red: 'blue'" ng-click="changeColor(x)">
    Change Color
  </button>

Code
$scope.changeColor = function(c){
   c.color = !c.color;
}


text:
Q: Best way to refresh the thumbnail/base url of Google Photos/Google Drive API Google suggests to retrieve the base url again when needed after 60 minutes after the origin query because the url's expire.
So far, so good. But what if I'm developing a photo gallery and I'm displaying 5000 or them in a grid? Should I query the API again and again? They use a maximum page size of 100 (instead pf 1000 for google drive), so we're starting many requests if that's true.
I'm already caching the photos locally, but when the user scrolls to another section, the url will be expired after one hour.
What is the best solution for that?

A: Google has a batch request for that use case :
https://developers.google.com/photos/library/reference/rest/v1/mediaItems/batchGet
Anyway the maximum number of items you can request per call is 50, so you should anyway queue some of those requests.
Personally I made it automatic in my code. When the baseUrl i'm loading gives me a 403, it automatically get the mediaitem updated object and retry.
Also you should not cache base urls or generally mediaobjects within different app launches (assuming you're writing an app). You should retain only the mediaItem id and reload it or the entire collection when needed.


text:
Q: Does a section having no zero locus divisor imply that it is nowhere vanishing? Let $X$ be a normal variety over a field $k$, $L$ is a line bundle on it, and $s$ is a global section of $L$. If the Weil divisor associated to $s$ equals zero. Then can I conclude that $s$ is nonvanishing everwhere?
Equivalently, let $A$ be a integrally closed finitely generated $k$-algebra, and $s\in A$, if $s$ is not a unit, then can I conclude that there exits a prime idea $p$, such that

*

*dim($A_p$)=1

*the valuation of $s$ corresponding to $p$ is non-zero.

If it is not true in general, what extra conditions should I impose on the variety $X$?

A: Yes, a normal domain equals the intersection of its localizations at height one primes inside its fraction field. Hartshorne ("Algebraic Geometry", Prop. II 6.3A) gives the reference: Matsumura "Commutative Algebra", Th. 38, p. 124. We apply this to $s$ and $1/s$.