text:
Q: OAuth2 userdetails not updating in spring security (SpringBoot) I am new to spring security and have used jhipster in which i have configured db and LDAP based authentications. Now i have integrated it with OAuth client using @enableOAuthSso. I can able to authenticate using external OAuth Idp (Okta) and it is redirecting to my application and my principle is getting updated and i can access resources through rest. But my userDetails object not getting populated.
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) {
    try {

        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());

        auth
            .ldapAuthentication()
            .ldapAuthoritiesPopulator(ldapAuthoritiesPopulator)
            .userDnPatterns("uid={0},ou=people")
            .userDetailsContextMapper(ldapUserDetailsContextMapper)
            .contextSource(getLDAPContextSource());

    } catch (Exception e) {
        throw new BeanInitializationException("Security configuration failed", e);
    }
}

I have check by going deep where its getting failed and found out the following
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        log.info("authentication is not null");
        if (authentication.getPrincipal() instanceof UserDetails) { //failing here
            log.info("principle is instance of userdetails");
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            log.info(springSecurityUser.getUsername());
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}

Its failing at the line
if(authentication.getPrincipal() instanceof UserDetails)

What is the possible and the best way to handle this to update user details object.
Update:
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
    log.info("======inside getUserWithAuthorities =================");
    log.info("current user is :::::::"+SecurityUtils.getCurrentUserLogin());
    Optional<User> optionalUser = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin());
    User user = null;
    if (optionalUser.isPresent()) {
        user = optionalUser.get();
        user.getAuthorities().size(); // eagerly load the association
    }
    return user;
}

Its trying to fetch the user from db. But the user is not present in the database

A: Similar to the LDAP tip, I would reocmmend creaing an OktaUserDetails class and casting the principal.  Then you can keep most of the authentication code the same.  The LDAP code example is below, the format of OktaUserDetails would depend on the JSON response
} else if (authentication.getPrincipal() instanceof LdapUserDetails) {
    LdapUserDetails ldapUser = (LdapUserDetails) authentication.getPrincipal();
    return ldapUser.getUsername();
}

To save information received from an Oauth2 resource, declare a PrincipalExtractor Bean in your SecurityConfiguration.  This lets you parse the response in a custom manner.  A basic example is below (source).
@Bean
public PrincipalExtractor principalExtractor(UserRepository userRepository) {
    return map -> {
        String principalId = (String) map.get("id");
        User user = userRepository.findByPrincipalId(principalId);
        if (user == null) {
            LOGGER.info("No user found, generating profile for {}", principalId);
            user = new User();
            user.setPrincipalId(principalId);
            user.setCreated(LocalDateTime.now());
            user.setEmail((String) map.get("email"));
            user.setFullName((String) map.get("name"));
            user.setPhoto((String) map.get("picture"));
            user.setLoginType(UserLoginType.GOOGLE);
            user.setLastLogin(LocalDateTime.now());
        } else {
            user.setLastLogin(LocalDateTime.now());
        }
        userRepository.save(user);
        return user;
    };
}


text:
Q: Looking for an algorithm to generate int 0- 255 when provided with an arbitrary pair of numbers between 1 - 99 (upper limit can be you your choice) This is intended to uniquely number the links between a mesh of an arbitrary number o nodes (for my needs anywhere between 1 and 50 is OK. The upper limit can be your choice as long as it is higher than 9.
Here are my requirements:
-the result must be an integer between 0 and 255
-the result must be unique in the sense that each pair of numbers shall result in a unique number (call it link ID)
-the input data is a pair of numbers between 1 and X where X can be between 1 and  100. (you can change that to any number higher than 9, the higher the number the better)
-the result must be intuitive in the sense that if I look at the input pair I should be able to guess
Here is an example:
A1 A2 A3 A4 are the nodes
The A1A2 link will be 12
A3A2 link will be 23
Algorithm: take the node indexes arrange them in an ascending order and you have your Link ID
The problem appears when I try to use the above for numbers higher than 10 because A8A10 will be 810 which is greater than 255
Note: I am fine for nodes from 1 to 9. I need solutions for more than 9 nodes

A: If you have $23$ nodes then there are $\binom{23}{2} = 253$ possible links,
assuming that any node may be linked to any other.
If you had $24$ nodes there would be $\binom{24}{2} = 276$ possible links,
so $23$ nodes is the most you can have if every pair of nodes must have
a unique integer identifier $n$ in the range $0 \leq n \leq 255$.
Number the links as follows: for nodes $A_x$ and $A_y$, let
$v = \max\{x,y\}, u = \min\{x,y\}.$
In other words, the nodes are identified as nodes number $u$ and $v$
with $1 \leq u < v \leq 23$.
Then let the link between these nodes be identified by
$$
L(u,v) = \frac12(v-1)(v-2) + u - 1.
$$
For example, if we link nodes $A_1$ and $A_2$, which are the lowest-numbered possible pair of nodes, the link is link number
$L(1,2) = \frac12(2-1)(2-2) + 1 - 1 = 0$, the lowest possible link number.
If we link nodes $A_{22}$ and $A_{23}$, which are the highest-numbered possible pair of nodes, we get link number
$L(22,23) = \frac12(23-1)(23-2) + 22 - 1 = 252$.
Some other nodes and their link numbers are:
\begin{align}
A_1    &&& A_3    & L(1,3) &= 1 \\
A_2    &&& A_3    & L(1,3) &= 2 \\
A_1    &&& A_4    & L(1,3) &= 3 \\
A_3    &&& A_4    & L(1,3) &= 5 \\
A_1    &&& A_5    & L(1,3) &= 6 \\
A_1    &&& A_{21} & L(1,21)  &= 190 \\
A_{20} &&& A_{21} & L(20,21) &= 209 \\
A_1    &&& A_{22} & L(1,22)  &= 210 \\
A_{21} &&& A_{22} & L(21,22) &= 230 \\
A_1    &&& A_{23} & L(1,23)  &= 231 \\
\end{align}
The reasoning behind this formula is that there are
$\binom{v-1}{2} = \frac12(v-1)(v-2)$ pairs of nodes where both
nodes have node numbers less than $v$, and these will get node numbers
$0$ through $\frac12(v-1)(v-2) - 1$, inclusive;
then the pair $A_1$, $A_v$ will get the next link number,
$\frac12(v-1)(v-2)$,
the pair $A_1$, $A_v$ will get link number $\frac12(v-1)(v-2) + 1$,
and so forth up to $A_{v-1}$, $A_v$,
which gets link number $\frac12(v-1)(v-2) + v - 2 = \frac12 v(v-1) - 1$.

A: For x,y in [1..10] you could map AxAy to 10M+m, where M=max(x,y) and m=min(x,y)
-This yields a number in [11..110] which is guaranteed in [0..255]
-AxAy maps to the same number as AyAx since changing order doesn't affect max or min
-Distinct unordered (x,y) pairs always map to different numbers (since they must differ in either max or min, and per the formula no distinct (max,min) pairs map to the same number)
-It's ez to compute mentally

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do E.T. and Elliott get sick and how do they recover? There's many ways to explain what happened in the movie, so I will leave that to a quote form E.T. Wikipedia article :

On Halloween, Michael and Elliott dress E.T. as a ghost so they can sneak him out of the house. Elliott and E.T. ride a bicycle to the forest, where E.T. makes a successful call home. The next morning, Elliott wakes up to find E.T. gone, and returns home to his distressed family. Michael finds E.T. dying in the forest, and takes him to Elliott, who is also dying. Mary becomes frightened when she discovers her son's illness and the dying alien, before government agents invade the house.
Scientists set up a medical facility in the house, quarantining Elliott and E.T. Their link disappears, and E.T. then appears to die while Elliott recovers. A grief-stricken Elliott is left alone with the motionless alien when he notices a dead flower, the plant E.T. had previously revived, coming back to life. E.T. reanimates and reveals that his people are returning.

I never fully understood why do they became sick and how do they recover?

A: From my observation, ET shows signs of his health diminishing right from the start of the movie.  I believe ET breaths CO2.  We have CO2 in the air - enough to sustain plant life, but not enough to sustain a creature like ET.  So as you go through the movie, ET's health diminishes until he gets put into that chamber where his body would be kept cold for preservation.  Looks like there using dry ice to keep him cold creating CO2 gas which ET was breathing.  By the time they get to the park ET has had enough time to breath CO2 to make a full recovery.

A: When growing up I'd always assumed that ET's recovery was kind of asserted, that he just found some kind of inner will or auxiliary power to come back to life (a bit like the T-800 in Terminator 2: Judgement Day).
But when I watched it the other day a more logical idea hit me:
At the start of the movie we can see that the aliens are all linked to some manner of central mechanism that makes their hearts glow. (Or they are some kind of hive entity.) So is it possible that they require this link to stay alive for extended periods? Either it has some kind of regulatory function without which they will decay, or it actually gives them some kind of vital energy. Or both.
Now immediately before ET returns to life, we see his heart glow under the lid of the container. This is something we actually haven't seen since the start of the movie. And immediately after the excited Elliott begins talking to him, he reveals that his people are coming.
So what if none of this is a coincidental cluster, but it's all related? ET could never have survived on Earth permanently without the heart pulse from his people. They received his message, returned to Earth and were continually sending out the heart pulses. Right at the point of ET's apparent death, they get close enough for him to receive one of the vital heart pulses. This is what revives him.

A: From the transcript of E.T. we know E.T. has DNA, which implies a susceptibility to human pathogens (bacteria, viruses, etc). This would then imply that E.T., presumably having no prior exposure to human pathogens, would be at an increased risk of serious infection from even a single Earth pathogen, much-less dozens he could have been exposed to that most humans with a working immune system don't have to be concerned with.
We also can see that E.T. can establish "sympathetic" bond with living creatures, such as the flower and Elliot. As E.T.'s health diminished we can watch a plant he had revived begin to wither, and finally die with E.T.'s death.
Presumably, the bond that E.T. establishes with Elliot is the same as the one established with the flower. As E.T. got sick, there was a sympathetic feedback into Elliot, which made him sick. E.T. seemed to have the ability to sever the link, which allowed Elliot to rapidly recover since he wasn't really sick.
As to how E.T. recovered, it could be that his biology allows for a dormancy period to recover from illness or that the ability he has to revive dying things could automatically heal himself if his body suffers enough damage.
Another thought is that he allowed himself to die secure in the knowledge that he had sent a call for his ship to rescue him. When the ship was within a "telepathic" range, his body revived through his healing mechanism.

A: Ive been a long time fan of this movie and have seen it roughly 100 times...and have also wondered the same thing.
No doubt there is the whole human/alien emotional link, but I think if you were to TRY to put a little more logic behind it you can consider the fact that
1) space is cold and that is where E.T. comes from.
2) He started to get sick before they tried to contact his family in the forest and found him lying in "cold" water flowing from the creek, maybe he was trying to cool off.
3) He dies and is put in a cold chamber at which point he comes back to life.
I think maybe earth was too warm for E.T.
-Just a theory.


text:
Q: How do I read a CSV line from input and initialize each value to variables of different types? (C++) Example of a line: "10,abc,2.5"
I want 10 to be set to an int, abc to be set to a Cstring, and 2.5 to be set to a float. The only header I will be using is iostream. Thanks for the help!

A: You can accomplish what you are trying to do without much effort using the std::basic_istream::getline which allows reading into the basic c-string char * type and takes an optional delimiter as its third argument. Using the ',' as the delimiter, and keeping a simple counter to determine the conversion to perform. You can parse into int, or double using the std::stoi and std::stod functions. All with nothing but the iostream header, e.g.
#include <iostream>

#define MAXFIELD 256

int main (void) {

    int cnt = 0;
    char field[MAXFIELD] = "";

    /* read each field delimited by ',' or '\n' */
    while (std::cin.getline (field, MAXFIELD, ',')) {
        if (cnt == 0) {     /* if count 0, convert to int */
            std::cout << "int    : " << std::stoi (field) << "\n";
            cnt++;  /* increment count */
        }
        else if (cnt == 1) {    /* if count 1, use string */
            std::cout << "string : " << field << "\n";
            cnt++;  /* increment count */
        }
        else {  /* if count 2, convert to double, reset count */
            std::cout << "double : " << std::stod (field) << "\n";
            cnt = 0;
        }
    }
}

(note: you should validate that the field did not exceed MAXFIELD characters by checking failbit and handling the error -- which is left to you)
Example Use/Output
$ echo "10,abc,2.5" | ./bin/iostream_cstring_csv
int    : 10
string : abc
double : 2.5

Look things over and let me know if you have further questions.


text:
Q: How to prevent XML parsing errors being written to System.err (stderr)? I am writing some unit tests that are deliberately passing bad strings to the Java DOM XML parser.
E.g.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

String message_xml = ""; // Empty string, not valid XML!!!
ByteArrayInputStream input = new ByteArrayInputStream(message_xml.getBytes());
Document doc = db.parse(input);

This is correctly throwing a SAXParseException (which is what my unit test expects).  But it is also writing a message to System.err (stderr) in the Java console:
[Fatal Error] :1:1: Premature end of file.

Is there any way to configure the XML parser to NOT write to stderr?
I'm using Java 1.6SE.

A: Install your own ErrorHandler:
db.setErrorHandler(new ErrorHandler() {
    @Override
    public void warning(SAXParseException e) throws SAXException {
        ;
    }

    @Override
    public void fatalError(SAXParseException e) throws SAXException {
        throw e;
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        throw e;
    }
});


text:
Q: Active Directory Lookup via PHP How can you do an Active Directory lookup via PHP? Without needing to recompile PHP. PHP version is 5.3
I want to find a persons display name from their user name. Web server is IIS 6 and PHP is served using FastCGI.
I get the username with:
$cred = explode('\\',$_SERVER['REMOTE_USER']);
if (count($cred) == 1) array_unshift($cred, "(no domain info - perhaps SSPIOmitDomain is On)");
list($domain, $user) = $cred;
return $user;

So how can I then find the name? e.g. DoeJ = John Doe
Edit:
Trying to lookup user, but not sure how to find the "base DN". Don't have direct access to the Active Directory server or have admin rights, so connecting anonymously.
<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("example.co.uk")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";

        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION,3);
        ldap_set_option($ldapconn, LDAP_OPT_REFERRALS,0);

        $dn = "CN=Users"; // also tried DC=example,DC=co,DC=uk
        $filter="(SAMAccountName=username)";
        $justthese = array("ou", "sn", "givenname", "mail");

        $sr=ldap_search($ldapconn, $dn, $filter, $justthese);

        $info = ldap_get_entries($ds, $sr);

        echo $info["count"]." entries returned\n";

    } else {
        echo "LDAP bind anonymous failed...";
    }
}
?>

Fails on the ldap_search: Warning: ldap_search() [function.ldap-search]: Search: Operations error

A: OK - first of all, you need the ext/ldap to communicate with your Active Directory server via the LDAP interface. Obviously this requirement is met with your PHP installation (otherwise you'd get errors about undefined functions).
The question now is: what Windows server are you coding against? From Windows Server 2003 onwards anonymous binds are disabled by default, which means that you cannot search the Active Directory tree without authenticating with an existing and authorized user first. (To enable anonymous binds please see here - but as you don't have any admin rights, you won't be able to change this)
The second problem is your base DN which actually is the location within your LDAP tree from which on a search operation will be executed. The normale base DN for the users' container should be CN=Users,DC=yourdomain,DC=yourtopleveldomain, which is for example CN=Users,DC=example,DC=local.
The filter you're using is correct actually: (SAMAccountName=username) will find the account entry for user username. To use your username variable you can do:
$filter = sprintf('(SAMAccountName=%s)', $user);

The general code flow, though, seems to be correct, too.
To summarize: you'll have to check first if your Active Directory allows anonymous binds and then you'll have to adjust your search's base DN. If no anonymous binds are allowed you'll have to use a user that is authorized to bind to the Active Directory.

A: The fisrt parameter of ldap_get_entries function is incorrect:
$info = ldap_get_entries($ldapconn, $sr);

Tested in this way and your code works now.

A: PHP has a LDAP library which you can use to query an active directory. It's not enabled by default though.
If you can use it, you can look at ldap_search()

A: Since you're using IIS than that means that you are running php on windows, that in turn means that you can enable the LDAP extension without recompiling php. That should solve most of your problems.


text:
Q: Check which index a custom object in NSArray has A really simple question here.
I know how do you check if an NSString exists in an array and I do it like this:
if ([dataArray containsObject:paymentMethodString])

But apart from checking if it exists or not I would like to find out the index of corresponding element in the array. How do you do that in Objective-C?

A: You should use
NSUInteger index = [dataArray indexOfObject:your_object];

A: NSUInteger index = [dataArray indexOfObject:paymentMethodString];

if( index != NSNotFound ) {

    //the object is present at the index
}

A: Try this:
[dataArray indexOfObject:paymentMethodString]

A: use NSArray method:
- (NSUInteger)indexOfObject:(id)anObject

like this:
NSUInteger myIndex = [dataArray indexOfObject:paymentMethodString];


text:
Q: Error during initialization of VM on fresh eclipse/Java install I've just installed the JDK 9 and eclipse-java Photon (the .rar that you can download from their webpage).

*

*Opened eclipse for the first time + Set the workspace.

*Configured some visual things.

*Created an empty project (some test package -> some test Class).

*Tried to run it (a 100% EMPTY Class, just an empty main() and that's it).

*Got this error (the 'D:\Boludeces' displayed path is not at all related with any installation of eclipse nor JDK/JRE. That's confuses me).

I'm not sure what's wrong here. I'm using Windows 7 64-bits. Software versions (both of JDK/JRE and eclipse) are 64-bits also (completely sure about that), so they should be complatible with each other.
The Run configuration is also completely untouched.
Those are my installation paths:
eclipse: D:\Boludeces ^_^\Programas\Carpetas de programas\eclipse\java-photon.
eclipse's default workspace: D:\Boludeces ^_^\Programas\Carpetas de programas\eclipse\Workspace.
JDK: C:\Program Files\Java\jdk-9.0.1.
JRE: C:\Program Files\Java\jre-9.0.1.
Some useful pictures below:
1 CLASSPATH environment variable
2 PATH environment variable
3 Other Java's environment variables
2 java -version on cmd
Do somebody has any ideas? Thanks in advance. Best regards,
Viciecal

A: Eclipse Photon will be released on June 27, 2018. There are currently only milestones pre-releases of Eclipse Photon which might be unstable.
If you have problems, you can use an Eclipse IDE package of the current release (which is currently Oxygen.1a) instead.


text:
Q: Java how to split strings at a space, after a certain number of characters (question was closed because to broad so i have tried to be more clear)
I found a many duplicate questions, but they were all in other programming languages.
I have a string and every 68 characters I want to break the string. But that will most likely cause the sentence to be broken in the middle of a word.
For example

I am a love cats and dogs but not the flees they carry. Also i thin
  k that cats are sometimes rude because they do not hug me when i wa
  nt them too. Overall though cats and dogs are both great.

Instead I would like to break these strings at the closest space before character 68. Then I can present the string in a way where they do not break the words in the middle.
Ultimately this problem could be probably be solved by a for loop checking each char 68 and below one at a time to see if they are spaces. When it finds the space it could then be cut at that char. Alternatively I could add in the words one at a time until i pass 68 characters and not add that last word. A third option would be to substring the string at the 68th character and then substring the string a second time at the lastIndexOf the space character.
However, all my ideas seem very inefficient and i was wondering if there were any already created or built-in string methods that could do this?

A: You can use WordUtils.wrap() method from Apache commons [code]:
Code:
import org.apache.commons.lang3.*;

class WrapTest {
    public static void main (String[] args)  {
        String str = "I am a love cats and dogs but not the flees they carry. Also i think that cats are sometimes rude because they do not hug me when i want them too. Overall though cats and dogs are both great.";
        str = WordUtils.wrap(str, 68);
        System.out.println(str);
    }
}

Output:
I am a love cats and dogs but not the flees they carry. Also i think
that cats are sometimes rude because they do not hug me when i want
them too. Overall though cats and dogs are both great.


text:
Q: Node package dependencies on IBM Cloud Foundry - require/module is not defined (Package not loading) I am working on an application via the toolchain tool on IBM Cloud and editing the code via the Eclipse Orion IDE. As I am not accessing this through my local cli, my understanding is that in order to so call npm install {package}, I would just need to include the package in the package.json file under dependencies and require it in my app. However, when I load the application, I get the require is not defined indicating that the package has not been installed. Moreover, the require() is being used in the app.js file with the application being launched but not from files in my public directory.
After playing around further, it seems it might have to do with the way the directory tree is being traced as the error is only thrown in subdirectories. For example, require('express') works in app.js which is in the main directory ./ but fails when it is called in test.js in ./subdirectory/test.js. I feel like I'm missing something painfully simple like configuration of endpoint or something.
I've been searching around but I can't seem to find how to get the packages loaded, preferably without using the cli. Appreciate any pointers. Thanks!
Update: After playing around further, I am also getting module is not defined error when trying to require from another file in the same directory. For example module.exports = 'str' returns this error. While trying to require('./file') returns the require is not defined. It might have to do with how node is wrapping the functions?
Update 2: Tried "start": "npm install && node app.js" in package.json but no luck. Adding a build stage which calls npm install before deployment also does not work
Update 3: After adding npm install build stage, I am able to see that the dependencies have been successfully built via the logs. However, the require is not defined error still persists.
Update 4: Trying npm install from my CLI doesn't work as well even though all packages and dependencies are present
Update 5: Running cf restage or configuring cache via cacheDirectories does not work as well
Opened a related question regarding deployment here

A: Found out my confusion was caused due to me not realizing that require() cannot be used on the client side unless via tools such as Browserify.


text:
Q: How to handle new line for matTooltip? I am trying to add new lines from a text area, but when I send the data to the API in json format folowing is the format.
{
   day: "2018-07-30"
   notes: "Enter↵New↵Lines↵in↵Textarea↵"
   time: "4"
}

as you can see in the given object "notes" property has a special character added for enter.
How to handle this json format and again populate it to matTooltip with new lines.
Expected output:
Enter
New
Lines
in
Textarea

Current Output:
Enter↵New↵Lines↵in↵Textarea↵


text:
Q: AutoMapper decoupling domain from entity and beyond I am attempting to decouple my domain from my entity and opted to use AutoMapper to accomplish some of this. Perhaps this is an open question but I am wondering how people would go about decoupling these layers from each other. For example, I have the following:
public class A //Entity
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class B //Domain
{
    public string Name { get; set; }
}

I am wondering, truly decoupling the two would mean not presenting the property Id back to the domain? Essentially, my domain object will be consumed by the UI (MVC layer) and is it "correct" for the UI to have the concept of an ID, being able to manipulate and change it?
Thanks in advance, DS.

A: You know, the domain has entities too... You want he domain decoupled from anything else (persistenec, UI etc).
The UI has its own model (mainly the view models) who is created usually from the Domain model. Here is where the deocupling take place and you can use a service/mapper for that. in your case the view mode seems to be very similar to the domain model so you an use automapper to create the view model from a domain model.

is it "correct" for the UI to have the concept of an ID, being able to manipulate and change it?

It's correct for the UI to have ANY information it needs to do its job. However, the UI shouldn't change directly the domain model. The domain changes according to use cases (usually implemented in services/command handlers) and in 99.99% of cases I don't know why you would want to change the ID of a domain entity.

A: ID is also a DDD concept known as entity identifier. If the domain entity doesn't have an identifier, your ui and application are not able to manipulate them.
For example, I want to modify the booking contact name of an order with trackingId[123]. the ui need the identifier to fetch the order. The Order domain object is then reconsititute by mapping the order persistent entity(mapping all fields but id). The last thing is store the order(map domain to entity, but id is lost), how can I decide which order persistent entity to be updated if there is no identifier in Order domain object?
So the answer to "I am wondering, truly decoupling the two would mean not presenting the property Id back to the domain?" is no.
But some ids in persistent entities are not identical in domain objects, these ids could be skipped. same order example, if the application is built based on a legacy database, and the booking contact is an individual table from order table like:
create table t_order {
    tracking_id varchar2(255) pk,
    //other fields
};

create table t_order_booking_contact {
     tracking_id varchar2(255) pk,
     name varchar2(255),
     //other fields
}

But for some reasons, the BookingContact in domain model is a value object(no id needed). In this case, the trackingId in BookingContact persistent model could be skipped, the mapper and persistent component could use trackingId in Order persistent model instead.
For me, the truly decoupling the two would mean develop the domain models as what makes handle domain logic easily and develop the persistent models as what makes persistence easily. The mapper is used to fix the difference between them.


text:
Q: How to document.querySelectorAll() only checked items I have a quick wizard that captures customer selection with both checkboxes and radio buttons (only a single instance on each wizard page so only radio or checkboxes)
I'm trying to capture only the selected radio and checkboxes
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const inputs = [];
  form.querySelectorAll("input").forEach((input) => {

    const { name, value, status } = input;
    inputs.push({ name, value });
  });
  console.log(inputs);
  form.reset();
});

here is the HTML with the 3 step wizard

    <form>

How to serve?

            <input type="radio" id="forhere" name="where" value="forhere"
         checked>
             For Here

            <input type="radio" id="togo" name="where" value="togo">
             To Go

        <button type="button" class="next-btn">Next</button>

Size?

            <input type="radio" id="small" name="size" value="small"
         checked>
             Small

            <input type="radio" id="medium" name="size" value="medium">
             Medium + 0.49c

            <input type="radio" id="large" name="size" value="large">
             Large + 0.99c

        <button type="button" class="previous-btn">Prev</button>
        <button type="button" class="next-btn">Next</button>

Anything Else:

          <input type="checkbox" id="extrahot" name="extrahot" checked>
          Extra Hot

          <input type="checkbox" id="doubleshot" name="doubleshot">
          Double Shot + $0.49c

          <input type="checkbox" id="whipped" name="whipped">
          Whipped Cream

        <button type="button" class="previous-btn">Prev</button>
        <button type="submit" class="submit-btn">Add To Order</button>

    </form>

I'm not set on this as I'm going to be adding this as a popup that I currently use only with a single selection option but need the checkboxes
Thank you

A: Return just the checked items.
form.querySelectorAll("input:checked")

A: const elements = form.querySelectorAll('input[type="checkbox"]:checked, input[type="radio"]:checked');


text:
Q: Google Button "cannot be cast to android.widget.Button" I'm trying to follow Google's instructions to import Google  Play Game Services at:
https://developers.google.com/games/services/training/signin
<!-- sign-in button -->
<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

When I import the official Google Play Button (as shown above in the XML Layout), i get this error in my log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{flash4life.gespant2015.com.flashreflex20/flash4life.gespant2015.com.flashreflex20.MainActivity}: java.lang.ClassCastException: com.google.android.gms.common.SignInButton cannot be cast to android.widget.Button
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3255)

This is the entire Error Log:
08-15 19:57:25.961 472-472/flash4life.gespant2015.com.flashreflex20 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: flash4life.gespant2015.com.flashreflex20, PID: 472
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{flash4life.gespant2015.com.flashreflex20/flash4life.gespant2015.com.flashreflex20.MainActivity}: java.lang.ClassCastException: com.google.android.gms.common.SignInButton cannot be cast to android.widget.Button
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3255)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3351)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1796)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7230)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: java.lang.ClassCastException: com.google.android.gms.common.SignInButton cannot be cast to android.widget.Button
                                                                                at flash4life.gespant2015.com.flashreflex20.MainActivity.onCreate(MainActivity.java:107)
                                                                                at android.app.Activity.performCreate(Activity.java:6877)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3208)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3351)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1796)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7230)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I assigned the Button in my Java:
signInButton = (Button) findViewById(R.id.sign-in-button);

A: SignInButton cannot be assigned to Button.
You can use it in this way:
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);

If required, you can refer:
https://developers.google.com/identity/sign-in/android/sign-in

A: While it has the word button in it, as per the SignInButton documentation, SignInButton actually extends FrameLayout.
Every View supports setting an OnClickListener so there's no reason to cast it to Button at all.

A: this is the SignInButton documentation,it is a frameLayout no a button
public final class SignInButton extends FrameLayout implements View.OnClickListener
but it has the function you can use it
void setOnClickListener(View.OnClickListener listener)
so you can do it like that
signInButton = (SignInButton ) findViewById(R.id.sign-in-button);
signInButton.setOnClickListener(new OnCLickListener)

A: SignInButton Can't assign to Button
You can use This way :(Kotlin)
        var signin = findViewById<View>(R.id.sign_in_button) as SignInButton


text:
Q: How to select features from different WFS layers? I'm trying to select features from different WFS layers but unfortunatelly it doesn't works in my code.
This is my code:
var select = new OpenLayers.Layer.Vector("Selection", {styleMap: new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"])});
var hover = new OpenLayers.Layer.Vector("Hover");

map.addLayers([hover,select]);

controles = new OpenLayers.Control.GetFeature({
    protocol: new OpenLayers.Protocol.WFS({
        url: "http://demo.opengeo.org/geoserver/wfs",
        featureType: ["states","world"]}),
    box: true,
    hover: true,
    multipleKey: "shiftKey",
    toggleKey: "ctrlKey",
});

controles.events.register("featureselected", this, function(e) {
      select.addFeatures([e.feature]);
});

controles.events.register("featureunselected", this, function(e) {
      select.removeFeatures([e.feature]);
});

controles.events.register("hoverfeature", this, function(e) {
      hover.addFeatures([e.feature]);
});

controles.events.register("outfeature", this, function(e) {
      hover.removeFeatures([e.feature]);
});

map.addControl(controles);
controles.activate();

As you can see, I've put in the featureType two layers but only the first one can be selected. What am I doing wrong?

A: The documentation and source code say featureType has the type 'String' not array
controles = new OpenLayers.Control.GetFeature({
    protocol: new OpenLayers.Protocol.WFS({
        url: "http://demo.opengeo.org/geoserver/wfs",
        featureType: "states"}),
    box: true,
    hover: true,
    multipleKey: "shiftKey",
    toggleKey: "ctrlKey",
});

It's better to create each layer in a single step and pass them to a OpenLayers.Control.SelectFeature instance.
Here the link to the official example: http://openlayers.org/dev/examples/select-feature-multilayer.html


text:
Q: Definition of $k$-times differentiable on $S$? I'm trying to come up with a good definition of being $k$-times differentiable on a subset $S$.
Here's the definitions I'm working with.
Let $f$ be a function from $X\subseteq\mathbb{R}$ to $\mathbb{R}$. Let $L\in\mathbb{R}$. If $x_0\in X$ is a limit point of $X$, we say that $f$ has derivative $L$ at $x_0$ iff $\lim_{x\to x_0}\frac{f(x)-f(x_0)}{x-x_0}=L$, i.e. iff
$$\forall\epsilon>0,\exists\delta>0,0<|x-x_0|<\delta\implies\left\lvert\frac{f(x)-f(x_0)}{x-x_0}-L\right\rvert<\epsilon.$$
If $S$ is a subset of $X$, we say that $f$ is differentiable on $S$ iff the derivative exists at $x_0$ for all $x_0\in S$ (in particular, every point of $S$ must be a limit point of $X$). We say that $f$ is differentiable iff it is differentiable on its whole domain.
Are these definitions standard so far?
Now the definition I've come upon for "$k$-times differentiable" is as follows.
Let $f$ be a function from $X\subseteq\mathbb{R}$ to $\mathbb{R}$. We say that $f$ is $1$-times differentiable iff $f$ is differentiable, and the first derivative of $f$ is the function $f^{'}:X\to\mathbb{R}$, also denoted $f^{(1)}$, defined in the obvious way. For $k\geq 1$, we say that $f$ is $(k+1)$-times differentiable iff $f$ is $k$-times differentiable and $f^{(k)}$ is differentiable, and in this case the $(k+1)$th derivative is the function $f^{(k+1)}:= (f^{(k)})': X\to\mathbb{R}$. A function is said to be infinitely differentiable iff it is $k$-times differentiable for all $k$.
Seem fine so far? But then I thought, how would I say that a function $f$ is $k$-times differentiable on some subset of its domain? Well, since we want "$f$ is $1$-times differentiable" to mean the same as "$f$ is differentiable", we might want "$f$ is $1$-times differentiable on $S$" to mean the same as "$f$ is differentiable on $S$".
How would you define "$f$ is $k$-times differentiable on $S$"?

A: Of course you can define "$f$ is differentiable on $S$" as you do. Higher derivatives are then a problem. For example, if $f'(x)$ exists for all $x \in S$, we are in general not able to define $f''(x)$ for $x \in S$ because we cannnot be sure that each $x \in S$ is a be a limit point of $S$. You could do it as follows:
Define $f$ to be $k$-times differentiable on $S$ if there exist subsets $S_i \subset X$, $0=1,\ldots,k$, such that

*

*$S = S_k \subset S_{k-1} \subset \ldots S_2 \subset S_1 \subset S_0 = X$

*Each $x \in S_{i+1} $ is a limit point of $S_i$, $i =1,\ldots, k$

*$f'(x)$ exists for all $x \in S_1$, $f''(x)$ exists for all $x \in S_2$, etc.
But honestly I do not think this concept is very useful.


text:
Q: Modifiy method called from extended class I have three classes, and I need to modify first class through the second that is extended :
my first class A :
public class A{

private String name;

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

my second class B
public abstract class B  {
 public void init() {

   A a = new A();
  a.setHost("foo");
 }
}

my third class C
public class C extends B {
// I want to use the method setName() of the a declared in class B
  b.init.a.setName("bar");//compile error, I tried several syntax I don't know how to do it

}

expected output, in my third class :
a.Getname = "bar"

A: Your code has multiple issues:
1) Variable b is never declared.
2) Variable a is private to method init, so you can't access it outside the init method.
So the solution should be like:
Class B:
public abstract class B  {

 protected static A a = new A(); // Protected to make it visible to child class
 public void init() {

  a.setHost("foo");
 }
}

Class C:
public class C extends B {
  public static void main(String[] args) {
    a.setName("bar");
    System.out.println(a.getName());  //Output = bar
  }
}

A: you can return a in the init method of B like below.
public A init() {

  A a = new A();
  a.setHost("foo");
  return a;
 }

Then  you can set the value in C like below
public class C extends B {
   public setNameinA() {
      B b = new B();
      b.init().setName("bar");
   }
}


text:
Q: Java usecase of overloaded version of Class.forName() What is the use of overloaded version of Class.forName()?
public static Class<?> forName(String name,
                       boolean initialize,
                       ClassLoader loader)
                throws ClassNotFoundException

Can anyone please give one example where it is preferred to use.
Edit:
Refer below code.
Class  clz=(Class)Class.forName("com.test.classloader.MyClass", false, Thread.currentThread().getContextClassLoader());

        MyClass mc=(MyClass) clz.newInstance();
        System.out.println(mc.TEST);
        System.out.println(mc.i);

MyClass:
public class MyClass {

static String TEST="MYCLASS";
static int  i;
static{
    i=20;
}

}

Why it prints
MYCLASS
20

A: You would use this method if you want to load the Class with a specific ClassLoader, which is passed via the loader parameter.
Also the initialize boolean will state if you want the class to be initialized or not.
Quite straightforward.

A: The intialise is whether to call the static block at that point or not.
If you use any static fields or methods, you have to call the static blocks so you don't see the behaviour.
What you can do is add a debug output in the static block and your example to see the order they are called. (Or add an exception to the static block)


text:
Q: Android ARToolKit - Changing the reference images in the NFT sample project? I've been tinkering with ARToolKit and their sample Android Studio Projects to see which one I can modify for my purpose. I opened the nftBookProj, it's the one using the pinball.jpg and then places an animated propeller plane along with a 3D axis in the origin of the image.
I noticed that the nftBookProj/nftBook/src/main/assets/DataNFT/ directory had pinball.iset, pinball.fset, and pinball.fset3 files. I then made my own image (with definite features, high resolution, high dpi and all) and then using the methods specified in this tutorial, I created my own set of reference_1.iset, reference_1.fset, reference_1.fset3 files. I then placed those 3 files in the same folder where the pinball files are.
I then checked all the activites and classes to find out the lines I have to change to make the app reference my own reference files instead of the pinball ones. It wasn't in any of the classes but I found markers.dat file under the /assets/Data/ folder and it looked like this:
# Number of markers
1

# Entries for each marker. Format is:
#
# Name of pattern file (relative to this file)
# Marker type (SINGLE)
# Marker width in millimetres (floating point number)
# Optional tokens:
#     FILTER [x]   Enable pose estimate filtering for the preceding marker
#                  x (optional) specifies the cutoff frequency. Default
#                  value is AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT, which
#                  at time of writing, equals 5.0.
# A blank line

../DataNFT/pinball
NFT
FILTER 15.0

I then changed ../DataNFT/pinball to ../DataNFT/reference_1, compiled the project, ran it on my tablet.
However, when I ran the code, it wasn't reacting to the image I made and when I checked with the pinball image, it worked. This means that I wasn't able to fully change the image it would refer to.
I then triple checked all the classes I could but I couldn't see where it indicates there that the pinball image should be used. This dead end stumps me because I no longer know where to look.
Has anyone had luck in changing the reference image in ARToolKits NFTBookProj for Android?

A: Found it. In the nftBookApplication class, it says there that if the file(s) in the assets folder get changed, you should update the assets folder, you should also update the version code in the Manifest.
If you aren't going to upload the app to the google play store, you can just update the one on the manifest AND remove the versionCode and versionName lines in the build gradle file. If you don't, the version info in the gradle file will always override the one in the manifest. Well you can also use the version codes in the gradle file if you're okay with spending a minute or two over when you have to sync it.


text:
Q: Comparing size of array in MongoDB subdocument Given a document like this
{
  _id: '1234',
  items: [{
    qty: 2,
    assigned: ['a', 'b']
  }, {
    qty: 3,
    assigned: []
  }]
}

I want to match this document because qty is greater than assigned.length. Can this be done directly with a query?

** Edit **
I was looking at the $size operator, but it only accept a number.


text:
Q: Break loop from a block in a task So i have code similar to this i want to run:
main:

  // This works
  mloop :
    print "test"
    return

  //This will not compile
  task:: mloop :
     print "test"
     return //this seems t be the problem

mloop [block]:
  while true:
    sleep --ms=100
    block.call

I want to break the infinite loop from within the block. But i also need to run the loop in a task. It will not compile and gives the error message  Can't explicitly return from within a lambda. This does not seem like it is posible with return or continue. Is there any way a similar funtionality can be implemented?

A: This is a limitation of the current iteration of the language. You would want to use break.mloop to break out of the loop:
main:
  task:: mloop:
    print "test"
    break.mloop // Read as "break out of mloop".

mloop [block]:
  while true: ...

However, this functionality isn't implemented in the compiler yet.
You have a few options to work around this:

*

*Create the lambda that is passed to the task in a function:

task_function:
  mloop:
    print "test"
    return

main:
  task:: task_function

This always works.

*Use the block's return value to signal an exit.

my_mloop [block]:
  mloop:
    if block.call: return

main:
  task:: my_mloop:
    print "test"
    true  // Signal end.

The latter has the advantage that the block's code would be inside main and could thus share variables more easily. It only works if the mloop function doesn't expect a value from the given block.


text:
Q: Graphic user interface with c# I have to create a graphic interface for a c# winform project. There is a background image and a set of small transparent pictures. The user must be able to put those little images over the backgroud, select them and move them freely (I have also to calculate distance between them but this is another step!).
I know I can do somthing like this:
Flicker free drawing using GDI+ and C#
I also found this:
http://cs-sdl.sourceforge.net/
My question is: is there a better or simplest solution to achieve this?
update
Now images are rectangular. There are no problems if images overlaps!
If small images are a problem I can switch with simple circles (DrawEllipse). The important point is that user can always click on and move them.

A: I have searched for a solution on how to remove flickering from pictureboxs, without finding something satisfying ... i ended up using some 2DVector from the XNA framework and spirits. it worked fine :)
http://www.xnadevelopment.com/ gives a good explanation for how to use it, it is explained in a game context.

A: The Windows Presentation Fo
Foundation (WPF) may be a better solution for this. It is more graphically inclined than GDI+, and is also much faster, as its powered by DirectX.

A: If you don't want flickr your best option is DirectX/XNA/OpenGL. Try to find a 2d framework with sprites for your application.

A: If you would use WPF then you should use a Canvas as your container control. To the images you have to add these event handlers in you code behind file:
private bool IsDragging = false;
private System.Windows.Point LastPosition;

private void MyImage_MouseDown(object sender, MouseButtonEventArgs e)
{
    // Get the right MyImage
    Image MyImage = sender as Image;

    // Capture the mouse
    if (!MyImage.IsMouseCaptured)
    {
        MyImage.CaptureMouse();
    }

    // Turn the drag mode on
    IsDragging = true;

    // Set the current mouse position to the last position before the mouse was moved
    LastPosition = e.GetPosition(SelectionCanvas);

    // Set this event to handled
    e.Handled = true;
}

private void MyImage_MouseUp(object sender, MouseButtonEventArgs e)
{
    // Get the right MyImage
    Image MyImage = sender as Image;

    // Release the mouse
    if (MyImage.IsMouseCaptured)
    {
        MyImage.ReleaseMouseCapture();
    }

    // Turn the drag mode off
    IsDragging = false;

    // Set this event to handled
    e.Handled = true;
}

private void MyImage_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
    // Get the right MyImage
    Image MyImage = sender as Image;
    // Move the MyImage only when the drag move mode is on
    if (IsDragging)
    {
        // Calculate the offset of the mouse movement
        double xOffset = LastPosition.X - e.GetPosition(SelectionCanvas).X;
        double yOffset = LastPosition.Y - e.GetPosition(SelectionCanvas).Y;

        // Move the MyImage
        Canvas.SetLeft(MyImage, (Canvas.GetLeft(MyImage) - xOffset >= 0.0) && (Canvas.GetLeft(MyImage) + MyImage.Width - xOffset <= SelectionCanvas.ActualWidth) ? Canvas.GetLeft(MyImage) - xOffset : Canvas.GetLeft(MyImage));
        Canvas.SetTop(MyImage, (Canvas.GetTop(MyImage) - yOffset >= 0.0) && (Canvas.GetTop(MyImage) + MyImage.Height - yOffset <= SelectionCanvas.ActualHeight) ? Canvas.GetTop(MyImage) - yOffset : Canvas.GetTop(MyImage));

        // Set the current mouse position as the last position for next mouse movement
        LastPosition = e.GetPosition(SelectionCanvas);
    }
}

I hope that helps, David.


text:
Q: print all ipaddress inside the network I'm trying to execute a way that I get each IP ADDRESS and Mac address that connected into the router(include wireless).
I manage to find out which IPs I have inside my network by using nmap:
nmap -sP 192.168.1.* >> IPs.txt
and this return :
Starting Nmap 7.40 ( https://nmap.org ) at 2017-04-27 18:31 ???? ÷?? ???????
Nmap scan report for 192.168.1.1
Host is up (0.0010s latency).
MAC Address: 2C:E4:12:EF:5B:72 (Sagemcom Broadband SAS)
Nmap scan report for 192.168.1.10
Host is up (0.074s latency).
MAC Address: 48:02:2A:06:A4:6F (B-Link Electronic Limited)
Nmap scan report for 192.168.1.11
Host is up (0.0030s latency).
MAC Address: 6E:2E:85:FF:FF:FF (Unknown)
Nmap scan report for 192.168.1.12
Host is up (0.071s latency).
MAC Address: 8C:18:D9:C8:A3:94 (Shenzhen RF Technology)
Nmap scan report for 192.168.1.13
Host is up (0.070s latency).
MAC Address: B4:43:0D:AA:3F:6C (Broadlink)
Nmap scan report for 192.168.1.16
Host is up (0.0020s latency).
MAC Address: F8:D1:11:18:74:89 (Tp-link Technologies)
Nmap scan report for 192.168.1.17
Host is up (0.056s latency).
MAC Address: 34:23:BA:4C:82:42 (Samsung Electro-mechanics(thailand))
Nmap scan report for 192.168.1.20
Host is up.
Nmap done: 256 IP addresses (8 hosts up) scanned in 8.24 seconds

I'm looking for a way to filter the content and print is like that: IP:MAC;
Thanks!

A: @Echo off&SetLocal EnableExtensions EnableDelayedExpansion
For /f "tokens=1-5" %%A in (
  'nmap -sP 192.168.1.*'
) Do If /I "%%B" equ "scan" (
  set "IP=%%E"
) Else if /I "%%A" equ "MAC" (
  Echo !IP!,%%C;
)

Sample output from your test data:
192.168.1.1,2C:E4:12:EF:5B:72;
192.168.1.10,48:02:2A:06:A4:6F;
192.168.1.11,6E:2E:85:FF:FF:FF;
192.168.1.12,8C:18:D9:C8:A3:94;
192.168.1.13,B4:43:0D:AA:3F:6C;
192.168.1.16,F8:D1:11:18:74:89;
192.168.1.17,34:23:BA:4C:82:42;


text:
Q: How to make bootstrap rows while going through a list in react and making elements This is how I am currently doing it - it is very uneloquent, and it doesn't work. I am getting
TypeError: Cannot read property '0' of undefined
at grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);

this is my code
const list = // my list of data
        var grid = [];
        list.map((element, index) => {
            if (index%4 == 0) {
                if (index<list.length-2) {
                const el = (

                //card being a component I built
                <Card key={index} name={element[0]} img={element[1]}/>
                <Card key={index+1} name={list[index+1][0]} img={list[index+1][1]}/>
                <Card key={index+2} name={list[index+2][0]} img={list[index+2][1]}/>
                <Card key={index+3} name={list[index+3][0]} img={list[index+3][1]}/>

)
                grid.push(el);
                } else {
                    let remainder = (list.length-index);
                    for (var x=0;x+=1;x<remainder) {
                        grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);
                    }
                }

            }
        })\
        return (

            {grid}

        )

The current way I am doing it is making grid then iterating through the list and adding jsx to it. The problem is that I need to make a row for bootstrap every 4 columns to make the grid, any better ideas, solutions greatly appreciated!

A: You are using index+1, index+2, index+3 which will never exist in the array, when you reach last element.
Instead calculate it in some other variable to find elements which exist.


text:
Q: Strong convexity and strong smoothness duality A function $f$ is said to be strongly convex with respect to a norm $\|\cdot\|$ at a point $y$ if $f(x) \geq f(y) + \nabla f(y)^T(x-y) + \frac{1}{2}\|x-y\|^2.$
It is said to be strongly smooth with respect to a norm $\|\cdot\|$ at a point $x$ if $f(y) \leq f(x) + \nabla f(x)^T (y-x) + \frac{1}{2} \|y-x\|^2$.
The Fenchel dual of a convex function $f: \mathbb{R}^n \to \mathbb{R} $ is defined as: $f^*(x) = \max_y x^T y - f(y)$.
Now, it's a general fact that if $f$ is strongly convex with respect to some norm $\|\cdot\|$ everywhere, then $f^*$ is strongly smooth with respect to the dual norm $\|\cdot\|^*$ everywhere.
However, I was wondering if it is also true pointwise. Specifically, if $f$ is strongly convex at its minimum $x_0$, can one say that $f^*$ is strongly smooth at 0?

A: This is true. Notice that taking the dual reverses inequalities: $f\ge g$ implies $f^*\le g^*$.
Fix $x_0$ and let $y_0=\nabla f(x_0)$. Define
$$g(x) = f(x_0) + y_0^T (x-x_0) + \frac{1}{2}\|x-x_0\|^2 \tag{1}$$
This is a convex quadratic function of $x$.  Its dual is
$$
g^*(y) = g(y_0)+x_0^T(y-y_0)+ \frac{1}{2}\|y-y_0\|^2 \tag{2}
$$
(The derivation of $(2)$ is standard; included below for completeness.)
So, strong convexity of $f$ at $x_0$, expressed as $f\ge g$, implies $f^*\le g^*$, which is the strong smoothness of $f^*$ at $y_0$. Similarly the other way around.

Proof of $(2)$
Since $\nabla g(x) = x-x_0+y_0$, it follows that $\max_x (y^T x - g(x))$ is attained when $x-x_0+y_0=y$, which implies
$$\begin{split}
g^*(y) &= y^T(y-y_0+x_0) - \left(f(x_0) + y_0^T (y-y_0) + \frac{1}{2}\|y-y_0\|^2 \right) \\
&= (y-y_0)^T(y-y_0) +y^Tx_0 - f(x_0) - \frac{1}{2}\|y-y_0\|^2 \\
&= -f(x_0) + y^Tx_0 + \frac{1}{2}\|y-y_0\|^2
\end{split}$$
Since $g^*(y_0)=-f(x_0)+y_0^Tx_0$, the latter formula can be rewritten as $(2)$.


text:
Q: Microsoft.Owin.Host.SystemWeb dll appearing in deploys I have a web application which is made up of web forms. Slowly we are converting it over to MVC.
Last week I did a deploy to a testing environment and everything works as expected.
This week I made some changes to some ASPX/code behind files and also some user controls. I did a publish/deploy to testing and I receive an error when I browse to the site through IIS.
The error is:

Could not load file or assembly 'Microsoft.Owin, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e37' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Comparing the bin folder of the last good deploy, to the broken deploy, the only difference is the broken deploy has one extra file - Microsoft.Owin.Host.SystemWeb.dll
If I remove that file the website is able to load and function correctly.
The website has many projects and references, the root project (the one I right click > publish on) does not have a reference to this Microsoft.Owin.Host.SystemWeb.dll so it must be referenced from another project.
Is there any way to fix this error without having to delete the file from the bin folder? What is causing the error?
Also both bin folders have other Owin dll files.
Microsoft.Owin.dll
Microsoft.Owin.Security.Cookies.dll
Microsoft.Owin.Security.dll
Owin.dll

A: It sounds like one of your projects use the OWIN middleware.  It also seems like someone may have tried to update the package and possibly did not do it properly.  I would right-click on the solution and click "Manage NuGet Packages" and re-install the OWIN packages.  If that does not work its likely a binding redirect issue that needs to be resolved in the web.config.  You may also want to see if there are any OWIN references even being used in the project.


text:
Q: Cocoa/Obj-c: How to fetch string from english localizable.strings irrespective of preferred localization In my application I want to show some messages at some place in english language. For that it is required that the messages should always be read from English.lproj/Localizable.strings file irrespective of the localization selected by user. I can not use NSLocalizedString method for this purpose now because it always returns the localized string. Please suggest a way to read strings from default (or development) localization resource file.

A: You're going to have to do it manually, like this:
- (NSString *)englishLocalizedStringForKey:(NSString *)key inTable:(NSString *)table {
  if (table == nil) {
    table = @"Localizable";
  }

  NSString *path = [[NSBundle mainBundle] pathForResource:table
                                                   ofType:@"strings"
                                              inDirectory:nil
                                          forLocalization:@"en"];
  if (path == nil) {
    return nil;
  }

  NSData *data = [NSData dataWithContentsOfFile:path];
  id plist = [NSPropertyListSerialization propertyListWithData:data
                                                       options:0
                                                        format:NULL
                                                         error:NULL];

  if (![plist isKindOfClass:[NSDictionary class]]) {
    return nil;
  }

  return [plist objectForKey:key];
}

So, here's what's going on.

*

*Get the name of the table (strings file) from the parameters, defaulting to @"Localizable" if you happened to pass in nil

*Find the path of {table}.strings inside the en.lproj folder

*return nil if the file doesn't exist

*read the file in as a blob of data

*attempt to decode the blob as a property list.  This works because .strings files are in the old-style plist format, so we can use this plist parser to build it into an NSDictionary for us

*if we didn't get an NSDictionary back, return nil

*return whatever the dictionary has for the request key (may return nil if the key can't be found)

The reading and deserializing bit can potentially be expensive, so I'd recommend caching the appropriate information in a property somewhere.

A: I recommend putting these special strings in their own strings table, and then only putting that table in the English localization. This way you can use NSLocalizedStringFromTable() as Benedict suggests. The localization functions will search through locales using the user's preferred search order until they find the requested file.
An advantage of this approach is that you may be able to avoid translating strings that only appear in this table.

A: Have you tried NSLocalizedStringFromTable? It lets you specify which file to use for the strings.


text:
Q: Unable to call kotlin extension function from java I know kotlin extention functions are compile as static function using fileName as class name with Kt suffix. Problem is my single String parameter function is asking for two String parameters when invoked from java code.
Extention function is in KUtils file
fun String.extractDigits(strValue: String): String {
    val str = strValue.trim { it <= ' ' }
    var digits = ""
    var chrs: Char
    for (i in 0..str.length - 1) {
        chrs = str[i]
        if (Character.isDigit(chrs)) {
            digits += chrs
        }
    }
    return digits
}

Calling java code
KUtilsKt.extractDigits("99PI_12345.jpg")

Compile Time Error Message :
Error:(206, 42) error: method extractDigits in class KUtilsKt cannot be applied   to given types;
required: String,String
found: String
reason: actual and formal argument lists differ in length
Please Help
Thanks

A: The problem is that the receiving instance is encoded as a parameter. So:
fun String.extractDigits(strValue: String): String {...}

Becomes (javap output):
public static final java.lang.String extractDigits(java.lang.String, java.lang.String);

But you're passing only a single argument to the function.
I don't quite understand why you're using an extension function here, I'd expect to see the receiving instance used instead of passing a separate value:
fun String.extractDigits(): String {
    val str = this.trim { it <= ' ' } // Using `this`, i.e. the receiving instance
    var digits = ""
    var chrs: Char
    for (i in 0..str.length - 1) {
        chrs = str[i]
        if (Character.isDigit(chrs)) {
            digits += chrs
        }
    }
    return digits
}

Then, in Java, you can call it like you tried, and in Kotlin like this:
val str = "123blah4"
println(str.extractDigits()) // prints 1234


text:
Q: Replacing a title with position fixed, with another title position fixed So I have a node.js app using express and trying to do the following:
div(class="title")
  h1(class="h1_title") example_title

My jQuery for this is as follows:
jQuery(function($) {
    function fixDiv() {
      var $cache = $('.title');
      if ($(window).scrollTop() > 140)
        $cache.css({'position': 'fixed', 'top': '10px'});
      else
        $cache.css({'position': 'relative', 'top': 'auto'});
    }
    $(window).scroll(fixDiv);
    fixDiv();
});

So when I scroll the title will become fixed at the top of the page. Got this working, however! I have another title below this, the exact same code. But I'm trying to get my title to replace the previous one and become fixed.
So As your scrolling down through content, the title is always fixed but its just being updated with the title relevant to the content your viewing.
Can anyone help, I'd really appreciate it. I can't find anything which is what i'm exactly looking for and my knowledge is limited.
Thank you!

A: I see you were asking a lot of questions about that ... I'm gonna show you an example that maybe can helps.
With an structure like this:

TITLE

TITLE

Content1

Content2

Content3

Where .title gonna be the fixed header you can use Jquery to change the value base on the h1 of the other containers.
$(window).scroll(function(){
  $('.cont').each(function(){
    var t = $(this).offset().top - 50,
        tit = $(this).find('h1').text(),
        h = $(this).height(),
        ws = $(window).scrollTop();
    if (t < ws && ws < (h+t)) {
         $('.title').html(tit);
    }
  })
})

Check this CodePen Demo

A: Here is a really basic example: http://jsfiddle.net/jgxevwa6/1/ -- I didn't try to get the spacing perfect or anything.
You have your fixed class:
.fixed {
    position: fixed;
    top: 0;
}

And then the magic. Basically any time you scroll, it cycles through each block and determines which is in the viewport by using a basic scrolling model:
(function($) {
    var utils = {
        fixTitle: function(e) {
            var top = e.currentTarget.scrollY;

            $('div').each(function() {
                var thistop = $(this).position().top;
                if(top > thistop) {
                    $('.title').removeClass('fixed');
                    $(this).find('.title').addClass('fixed');
                }
            });
        }
    };

    $(function() {
        $(window).scroll(utils.fixTitle);
    });
})(jQuery);

The javascript and CSS could be a little more accurate, but this gives you the basic gist of it.


text:
Q: Use d3 to generate markup but not manipulate the DOM? Given the following code, I can append an svg circle to a body tag.
d3.select("body")
  .append("svg")
  .append("circle")
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("r", 20);

But say I want to use d3 to just generate the markup:
<svg><circle cx="30" cy="30" r="20"/></svg>

and assign it to a javascript variable to eventually be rendered on the page. In this case I don't want d3 to directly manipulate the DOM, but I want to use its magic to generate my markup.
How do I go about this.

A: You could use a lightweight DocumentFragment to create an in-memory tree which is not part of the actual DOM tree. Because the DocumentFragment interface inherits from the Node interface you could easily wrap it in a D3 selection and do your normal D3 operations starting from the new virtual root. When finished the desired source string can be obtained from the outerHTML property of the root node, i.e. your appended <svg>.

// Create a document fragment in memory and wrap a D3 selection around it.
var doc = d3.select(document.createDocumentFragment());

// Do your normal D3 stuff.
var svg = doc.append("svg")
svg.append("circle")
  .attr("cx", 30)
  .attr("cy", 30)
  .attr("r", 20);

// 1. Obtain your source string from the outerHTML property.
var svgString = svg.node().outerHTML;
console.dir(svgString);

// 2. You can run a normal selection on the root
// This variant does not even require keeping a
// reference to the appended elements.
svgString = doc.select("svg").node().outerHTML;
console.dir(svgString);
<script src="https://d3js.org/d3.v4.js"></script>

Note: As I just realized, there is one drawback, though, since IE still does not support innerHTML or outerHTML properties for SVG content. Therefore, this approach is no viable solution if you need to support IE.


text:
Q: Empty product list on QueryProducts in Delphi XE6 TInappPurchase on Android I am developing inapp-Purchase in Delphi XE6.
Based on embarcadero documentation I create an InAppPurchase component as below:
        FInAppPurchase := TInAppPurchase.Create(self);
{$IFDEF Android}
        FInAppPurchase.ProductIDs.Add(License5And);
        FInAppPurchase.ProductIDs.Add(License10And);
        FInAppPurchase.ProductIDs.Add(License20And);
        FInAppPurchase.ProductIDs.Add(License50And);
{$ENDIF}
{$IFDEF IOS}
        FInAppPurchase.ProductIDs.Add(License5);
        FInAppPurchase.ProductIDs.Add(License10);
        FInAppPurchase.ProductIDs.Add(License20);
        FInAppPurchase.ProductIDs.Add(License50);
{$ENDIF}
        FInAppPurchase.OnSetupComplete := InAppPurchase1OnSetupComplete;
        FInAppPurchase.OnConsumeCompleted := InAppPurchase1ConsumeCompleted;
        FInAppPurchase.OnError := InAppPurchase1Error;
        FInAppPurchase.OnProductsRequestResponse := InAppPurchase1ProductsRequestResponse;
        FInAppPurchase.OnPurchaseCompleted := InAppPurchase1PurchaseCompleted;
        FInAppPurchase.OnRecordTransaction := InAppPurchase1RecordTransaction;
        FInAppPurchase.OnVerifyPayload := InAppPurchase1VerifyPayload;

{$IFDEF Android}
        FInAppPurchase.ApplicationLicenseKey := myLicenseKeyFromGoogleDeveloperConsole;
{$ENDIF}

Then in InAppPurchase1OnSetupComplete I Called the FInAppPurchase.QueryProducts then it goes into InAppPurchase1ProductsRequestResponse and products and InavlidProductIDs both are empty. I don't know what I missed. Any help will be appreciated.
I check my products in google developer console all of them are 'Active' and as Type of 'Managed'.
p.s. Code is working perfect on ios Device.

A: I lost a lot of time to understand the problem.
After I studied the source code I have understand that in Android the Events are asynchronous, you must wait the "QueryProducts" result.
In order to fix this problem I created a TTimer that wait 5 second before it read "InAppPurchase.IsProductPurchased"
(I'm sorry for bad English)

A: It seems the app should be published for alpha or beta testing.
Instead of uploading for production I need to upload it for alpha first then publish it. after that the products are shown.

A: I developed the interface with the market starting from the example CapitalITrivia in Enbarcadero. I had the same problem and I read the answer that was given here.
I tried it and actually works. But this solution did not satisfy me because it depends on a delay not justified.
I realized that in InAppPurchaseSetupComplete was called the QueryProducts function and then I performed IsProductPurchased.
If I move the IsProductPurchased test in InAppPurchaseProductsRequestResponse function I get the expected result without introducing the delay.


text:
Q: Convert static node,js request to iterative batch to avoid API limit TL;DR - I'm not a developer and need some help troubleshooting an error I'm getting in code below
Update:
I've got some working code, but I'm getting an intermittent error in visual studio code for an unhandled promise rejection and I'm not sure why. Sometimes the code runs just fine, other times, I get the error in the first code block
Response server [ny-front-api31] session [384923350]:
{"code":"INTERNAL_SERVERL_ERROR","message":"Internal server error
occurred","objectType":"KalturaAPIException","args":[]}
(node:34340) UnhandledPromiseRejectionWarning: #<Object>
(node:34340) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without
a catch block, or by rejecting a promise which was not handled with
.catch(). (rejection id: 1)
(node:34340) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.

Here is the code I am running:
const kaltura = require('kaltura-client');
const sql = require('./UserEngagementSQL');
const moment = require('moment');

const config = new kaltura.Configuration();
config.serviceUrl = 'https://www.kaltura.com';
const client = new kaltura.Client(config);

function process(pageIndex, start, end) {
    return new Promise(function (resolve, reject) {
        kaltura.services.session.start(
            "omitted",
            "omitted",
            kaltura.enums.SessionType.ADMIN,
            omitted)
            .completion((success, ks) => {
                if (!success) throw new Error(ks.message);
                client.setKs(ks);
                let reportType = kaltura.enums.ReportType.USER_ENGAGEMENT;
                let reportInputFilter = new kaltura.objects.EndUserReportInputFilter();
                reportInputFilter.fromDay = start;
                reportInputFilter.toDay = end;
                let pager = new kaltura.objects.FilterPager();
                pager.pageIndex = pageIndex;
                pager.pageSize = 500;
                let order = "";
                let objectIds = "";

                kaltura.services.report.getTable(reportType, reportInputFilter, pager, order, objectIds)
                    .execute(client)
                    .then(async result => {
                        if (result.data){
                            const data = result.data.split(';');
                            for (var i = 0; i < data.length; i++) {
                                const row = data[i].split(',');
                                if (row[0].length > 0) {
                                    await sql.insert(row);
                                }
                            }
                            resolve(data.length);
                        }else{
                            resolve(0);
                        }
                    });

            })
            .execute(client);
    });
}

async function main() {
    const initDate = moment('08/01/2018');
    const startDate = initDate.format('YYYYMMDD');
    const endDate = moment(startDate).add(30, 'day').format('YYYYMMDD');
    let startingIndex = 1;

    //console.log(startDate, endDate);
    let shouldRun = true;
    while(shouldRun){
        let processed =  await process(startingIndex++, startDate, endDate);
        console.log('Number of processed records ' + processed);
        shouldRun = processed > 0;
        console.log('Processing page ' + startingIndex + ' Should Keep running ' + shouldRun);
    }
}

main();

Original Post:
I'm working with the Kaltura API and they've got some pretty good starter console queries that are almost exactly what I need as a non-developer to get the data I am after. I needed the below code to be able to get all records for a date range. I have a 10000 record limit per call, so I needed loop through the request and continually check for records


text:
Q: Facebook - How to request offline access to user_photos? This is my current code to request permission to see email and user_photos
    'req_perms' => 'email,user_photos',

I want to access user photos when the user is offline, I seem to remember this was possible but maybe I am wrong. Anyway if it's possible, how is it done?

A: Hyunmin (in comments) has the right link.
As a very quick summary:

*

*log the user in normally; you'll get an access token. This may be a short lived or long lived (60 day) token - depends on login method being serverside or client-side (PHP or JS) but don't worry which you get.

*Note if you are worried: you can also check expiry if you like as the expiry is provided when you are given the access token. But I again skip this step.

*Once a day you can extend the token back ot the full 60 days. Simply call
https://graph.facebook.com/oauth/access_token?
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN
and you get back an access token (may or may not be the same). Just use/store this new access token in place of the old one.
Actually really simple - except for the bit of tracking the "once per day" upgrade bit. (And for now you can ignore this and call multiple times if needed - just slows things down fractionally.)

In response to comment - "how do you call that URL that gives you the token?"
You don't redirect the user as it's you that needs the response value, so you need to call it and handle it.
In PHP the simplest for testing (but not recommended) is to use
$response = file_get_contents($url);

but on production systems you should usse CURL (as some production systems don't allow file_get_contents for external URLs). Either google for a CURL example, or you could tap into the makeRequest() function in the included facebook SDK libraries.


text:
Q: Strong Chains in $^{\omega_1}\omega_1$ of length $\omega_3$ In a previous question, I asked about the impact of strong chains in $^{\omega_1}\omega_1$ (e.g.,  sequences of functions $\langle f_\alpha:\alpha<\kappa\rangle$ in $^{\omega_1}\omega_1$ that are strictly increasing modulo the ideal of finite sets) on cardinal characteristics of the continuum.
Koszmider [1] proved it is consistent that there is a strong chain in $^{\omega_1}{\omega_1}$ of length $\omega_2$, and Veličković and Venturi showed that Neeman's techniques (finite approximations with side conditions consisting of elementary submodels of two types) can be adapted to  obtain the same result.    Certainly this latter proof does not adapt in a straightforward manner to yield chains of even longer length. I am less familiar with Koszmider's original proof, but that seems to work only for $\omega_2$ as well.
Question:
Is it consistent that there is a sequence $\langle
f_\alpha:\alpha<\omega_3\rangle$ in $^{\omega_1}\omega_1$ that is increasing modulo the ideal of finite sets? What is known about this?
[1] Koszmider, Piotr, On strong chains of uncountable functions, Isr. J. Math. 118, 289-315 (2000). ZBL0961.03039.
[2] Veličković, Boban; Venturi, Giorgio, Proper forcing remastered, Cummings, James (ed.) et al., Appalachian set theory 2006–2012. Based on the Appalachian set theory workshop series during the period 2006–2012. Cambridge: Cambridge University Press (ISBN 978-1-107-60850-4/pbk). London Mathematical Society Lecture Note Series 406, 331-362 (2013). ZBL1367.03094.


text:
Q: Insert SQL Dataset into Tab control in Windows Form I have a simple SQL compact database I added to my project.
I am reading from "Head First C#" and the first program creates a database for contact info.
The book then says to drag the data source onto the form and it will create some data controls in the form automatically.
I tried doing this, but I am using a tab control with multiple tabs and when I drag the dataset onto the form, it erases the tab control.
I want my program to be able to modify the database only from one tab, I have other tabs for other things.
Any ideas on how to insert the dataset into a tab page?

A: In order to do this, go to the Data Source Explorer and right click on the table name you would like to drag and drop into the form.
Choose copy and then click on the tab page you want it inside and then paste it inside using Ctrl+v or right click on it and choose paste.
Sorry, after playing around with it a lot more, I was able to get it inside the tab.


text:
Q: Related to concurrence of lines in triangles In triangle $ABC$, the straight lines $AD, BE, CF$ are drawn through a point $P$ to meet $BC, CA, AB$ at $D, E, F$ respectively. Prove that $PD/AD + PE/BE + PF/CF = 1$ and $AP/AD + BP/BE + CP/CF= 2.$

A: If a parallel to $BC$ is drawn from $P$, we can state that it cuts the perpendicular to $BC$ in ratio of $PD/AD$. This implies
$$\frac{\frac12BC\cdot PD}{\frac12 BC\cdot AD}=\frac{PD}{AD}=\frac{[BPC]}{[ABC]} \tag{1}$$
Similarly,
$$
\frac{PF}{CF} =\frac{[APB]}{[ABC]} \qquad\qquad
\frac{PE}{BE} =\frac{[APC]}{[ABC]}  \tag{2}
$$
Therefore,
$$\frac{PD}{AD}+\frac{PE}{BE}+\frac{PF}{CF} =
\frac{[BPC]+[APC]+[APB]}{[ABC]} =\frac{[ABC]}{[ABC]}= 1 \tag{3}$$
Also,
$$\frac{AP}{AD}=\frac{[ABP]}{[ABD]}=\frac{[APC]}{[APD]}=
\frac{[ABP]+[APC]}{[ABD]+[APD]}=\frac{[ABP]+[APC]}{[ABC]}\tag{4}$$
(because perpendicular from $AD$ and $AP$ to $B$ will be same and that to $C$ will be same)
Similarly,
$$\frac{BP}{BE}=\frac{[BPC]+[BPA]}{[ABC]} \qquad\qquad
\frac{CP}{CF}=\frac{[CPA]+[CPB]}{[ABC]} \tag{5}
$$
Therefore,
$$\begin{align}
\frac{AP}{AD}+\frac{BP}{BE}+\frac{CP}{CF} &=\frac{[APB]+[APC]+[BPC]+[BPA]+[CPA]+[CPB]}{[ABC]} \\[4pt]
&=\frac{2\cdot[ABC]}{[ABC]} \\[4pt]
&=2 \tag{6}
\end{align}$$


text:
Q: How to add an item to a group in a submenu At runtime I would like to add an item inside this group (in my options menu):
<item
        android:id="@+id/action_module_selector"
        android:alphabeticShortcut="m"
        android:orderInCategory="30"
        android:title="@string/module_selector_menu_title"
        app:showAsAction="never">

        <menu>
            <group
                android:id="@+id/group_modules"
                android:checkableBehavior="single">

                <!-- Modules should be added here at runtime -->

            </group>
        </menu>
    </item>

If I call subMenu.add(R.id.group_modules, moduleId, 1, title); they end up at the same level as the group, not inside the group, although I use R.id.group_modules. I would like to know how I can add them inside the group.

A: I "solved" it by removing the group, setting the sumbMenu's items to checkable and manually making sure only one of them is selected.
subMenu.findItem(id).setCheckable(true);

and on changes:
private void updateSelectedModuleOnMenu(Menu menu, int selectedPosition) {

    MenuItem menuItem = menu.findItem(R.id.action_module_selector);
    SubMenu subMenu = menuItem.getSubMenu();

    for (int i = 0; i < subMenu.size(); i++) {
        MenuItem item = subMenu.getItem(i);
        item.setChecked(i == selectedPosition);
    }
}

A solution using a group I could not find.


text:
Q: Cross domain AJAX call and Access-Control-Allow-Origin I understand that you are not allowed to make cross domain Ajax calls, but why is it that I can make a cross domain ajax call to facebook's (or twitter or others) oauth API?
Does this have to do with the following?
"Access-Control-Allow-Origin: *"

Is allowing all access like this bad practice? Is there a better way to allow only people who you authorize?
Thanks!

A: Access-Control-Allow-Origin response header field is part of Cross-Origin Resource Sharing which allows cross-origin requests with XHR under certain conditions that can be controlled by the server the request is sent to.
In this particular case, Access-Control-Allow-Origin: * means that the server allows requests from any origin. This basically means that the resource is publicly available and does not support credentials.
But as you wish to restrict the access to just authorized users, you cannot use *. Instead, you need to return the Origin header field value (see section 6.1). If the client does already have credentials but has not yet requested the resource, you will also need to support preflight requests that negotiate what information the client is allowed to send.


text:
Q: Avoid Cookie Expiration (Web Scraping) So I am using Python to make a web scraper for my school's gradebook website called Schoology. So far, it works great, but I was troubled to see that all of the cookies will expire in a few days. Is there a way to automatically get new cookies so that I dont have to replace them every few days? My school uses an "SSO" login where you have to login with your school google account which makes things sort of complicated. I used CURL to get the header/cookie information. If there is anything else that I can improve on in my code, let me know. Here is my code:
# Schoology Web Scraper

import requests
from bs4 import BeautifulSoup

grades = []

headers = {
    # A bunch of headers / cookies that will expire
}

response = requests.get('https://monongalia.schoology.com/grades/grades', headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

for item in soup.find_all('span', attrs={"class":"course-grade-value"}):
  grades.append(item.get_text())

print('\n'.join(grades))

A: you can have it go through the sign in and use credentials provided by the user you can use:
from bs4 import BeautifulSoup
import requests

##################

username=""
password=""
schoolID=""

##################

# ^ fill in these values ^

payload = {
"mail":username
"pass":password
"school_nid":
}

session = requests.Session()
response = session.post('https://monongalia.schoology.comlogin/ldap', data = payload)
# this will log you in using the credentials provided above

# continue with script below, all cookies will be saved without you needing to do
# anything

send the username and password as a payload to the url, using Session() it will keep the
cookies throughout the script so you dont need to manually collect them


text:
Q: Git fast forward not working in Github Actions/Workflows I have a workflow where i auto merge prod branch into master branch  on push in prod branch using Github Actions
Yml file for github action
name: Merge Prod -> master

on:
  push:
    branches: [ prod ]
jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Merge prod->master ff_only
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git config user.name "test"
          git config user.email "test@test.com"
          git fetch origin master
          git fetch origin prod
          git checkout master
          git pull --rebase
          git merge prod --ff-only --allow-unrelated-histories
          git push origin master

Logs:
Run git config user.name "test"
  git config user.name "test"
  git config user.email "test@test.com"
  git fetch origin master
  git fetch origin prod
  git checkout master
  git pull --rebase
  git merge prod --ff-only --allow-unrelated-histories
  git push origin master
  shell: /usr/bin/bash -e {0}
  env:
    GITHUB_TOKEN: ***
From https://github.com/luvk1412/demo
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master
From https://github.com/luvk1412/demo
 * branch            prod       -> FETCH_HEAD
Switched to a new branch 'master'
Branch 'master' set up to track remote branch 'master' from 'origin'.
From https://github.com/luvk1412/demo
Already up to date.
 * [new branch]      f2          -> origin/f2
 * [new branch]      f3          -> origin/f3
 * [new branch]      test_branch -> origin/test_branch
fatal: Not possible to fast-forward, aborting.
Error: Process completed with exit code 128.

Example commit : https://github.com/luvk1412/demo/commit/790d824111d0c0c5b28157b9108e7b97b6b6cdc8
Commit generated through PR : https://github.com/luvk1412/demo/pull/38
Test branch : https://github.com/luvk1412/demo
After PR merge into prod, my prod branch fully contains master branch and one extra commit(due to PR), hence fast forward condition is met and fast forward should work, I am not sure what i am missing here.
the fast forward works on my local(if i don't automate this and do manually through local)

A: Although I have never used these, I suspect that this is the culprit:

Only a single commit is fetched by default, for the ref/SHA that triggered the workflow. Set fetch-depth: 0 to fetch all history for all branches and tags. Refer here to learn which commit $GITHUB_SHA points to for different events.

(boldface mine).  With the single commit, Git cannot tell whether the merge would be a fast-forward; with the single branch, Git does not have the necessary branch names.  The extra fetches you run will fix some of these problems, but not enough of them.  Setting the fetch depth, as recommended right up front here, would thus fix the problem.

A: Script using checkout@V1 which works
name: Auto Merge prod->master
on:
  push:
    branches: [ prod ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v1

    - name: Merge prod->master
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/<github_user_name>/<repo_name>
        git config user.name "test"
        git config user.email "test@test.com"
        git fetch origin master
        git checkout -b master origin/master
        git merge origin/prod --ff-only
        git push origin master


text:
Q: Django url regexp I am very new to regexp and have some difficulties right now:
I had a regexp
url(r'^users/\w+/$', views.user)

Right now I want to change the alphanumerical 'w+' to alphanumerical plus dot char.
I tried
url(r'^users/([a-zA-Z0-9\.])/$', views.user)

And its not working. I get a 404 page.
 Can anyone help me with this please?

A: Write this:
url(r'^users/([a-zA-Z0-9.]+)/$', views.user)
We dont use\ to escape . inside a character class. So to match a character inside character class, we dont escape it. Ex: [.]

A: url(r'^users/([a-zA-Z0-9\.]+)/$', views.user)

Add +.


text:
Q: use of undeclared identifier 'data' C++
"Write a function, named sums(), that has two input parameters; an array of floats; and an integer,
  n, which is the number of values stored in the array. Compute the sum of the positive values in the array
  and the sum of the negative values. Also count the number of values in each category. Return these four
  answers through output reference parameters.
Write a main program that reads no more than 10 real numbers and stores them in an array. Stop reading numbers when a 0 is entered. Call the sums() function and print the answers it returns. Also compute and print the average values of the positive and negative sets."

#include <iostream>
using namespace std;

void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt);
double input(double UserInput);

int main()
{
    float data[10];
    int count = 10 ;
    double UserInput = 0;
    float posSum=0.0, negSum=0.0; //sum of positives and negatives
    int posCnt =0, negCnt=0; // count of postive and negatives

    input(UserInput);
    sums(data, count, posSum,posCnt, negSum, negCnt);

    cout << "Positive sum: " << posSum << endl;
    cout << "Positive count:" << posCnt << endl;
    cout << "Negative sum: " << negSum << endl;
    cout << "Negative count:" << negCnt << endl;
    return 0;
}

double input(double UserInput) {
    for(int i = 0; i < 10; i++){
        cout << "Enter a real number or '0' to stop: " ;
        cin >> UserInput;
        if(UserInput == 0)break;

        data[i] = UserInput;
    }
    return UserInput;
}

void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt){

    int i;
    for(i = 0; i < count; i++){
        if(data[i] > 0){
            posCnt += 1;
            posSum += data[i];
        }
        else{
            negCnt += 1;
            negSum += data[i];
        }
    }
}

It gives me an error when trying to compile it saying "use of undeclared identifier 'data'" on line 32 in the input function.

A: It is because the data is not declared in the function input, you should use a float pointer.
void input(float *data)
{
   float UserInput;
   for (int i = 0; i < 10; i++)
   {
      cout << "Enter a real number or '0' to stop: ";
      cin >> UserInput;
      if (UserInput == 0)break;

      data[i] = UserInput;
  }
  return;
}

int main()
{
   float *data;

   data = (float*)malloc(10 * sizeof(float));
   input(data);

   cout << data[0];

   free(data);
   system("pause");
  return 0;
}

This should be an accurate example. Good Luck with your following homework.


text:
Q: How to update a node.js app remotely & automatically I need to set up automatic remote updates for my app built on nodeJS (not the nodeJS itself).
In my specific case I can't distribute my app as SaaS, so I have to share a copy of app with each client.
I've checked related topics here, but haven't found helpful ones.
Here are a few related questions: one, two
I don't know how to set it up, but I have a few ideas:

old-school way (?) :

*

*use unix cron + shell (or php) script to make «check-request» to «update-server»,

*stop nodeJS instance,

*replace files with newest ones from tarball,

*run nodeJS instance with my app : from shell(?)

It may work if I use my own server, but how can I do the same on, for example, Heroku ?
Overall, it seems weird a bit.

two nodeJS instances way (?) :

*

*use unix cron + another nodeJS app which checks updates on update-server,

*then stop one node instance from another && update files

*start one nodeJS instance with my app from another : how???

— Is here something else?
— How do folks solve that problem?
— How to realize, for instance, functionality like «Update manager» in Wordpress for nodeJS based app?

A: What you're talking about is CI (continuous integration), there are many tools that can help you in the process but they essentially do the same thing.

*

*Detect a change in the code

*Pull changes

*Build the project

*Run tests if there are any

*Deploy to the server

— How do folks solve that problem?

Folks use Jenkins, bamboo and many other auto deployment systems.
If you're using node with pm2 you can use kinematic that has that build in (one-click deployment feature)


text:
Q: C# type inference : fails where it shouldn't? Notice the following code. The offending line has been commented out.
interface I<R> { }

class C : I<int> { }

class Program
{
    private static void function<T, R>(T t) where T : class, I<R>
    {
    }

    static void Main(string[] args)
    {
        // function(new C()); // wont compile
        function<C, int>(new C());
    }
}

I believe type inference should figure out the type because the argument T provides the first type, while I<R> provides the second type.
Is there a way to redesign the function so that the callers may not have to specify the types?

A: Not if you want to keep all the constraints. However, this should serve equally well, unless you have a specific reason to forbid value types:
private static void function<R>(I<R> t)

A: There are various ways you could add extra rules to type inference - bits of logic that a human can apply but which the compiler (obeying the language spec) doesn't.
Before you suggest that the language really should be updated to make type inference work more flexibly though, I strongly suggest that you read the existing spec. If you can understand that sufficiently easily that you still think it's worth making it even more complicated, post a feature request on Connect - but personally I think it's quite complicated enough already. I would say that it's a lot better than it was in C# 2.0.
To put forward the opposing view, however - several languages (particularly functional ones) have more powerful type inference mechanisms. There are always pros and cons here - I believe one of the benefits of the current inference system in C# is that it always makes progress or stops, for instance - Eric Lippert's blog has more information on this and a number of other type inference issues.

A: class D : I<int>, I<string> { }
//
function<D, int>(new D());
function<D, string>(new D());
//is R int or string?
function(new D());

A: No, C# doesn't support this kind of inference.
Use directly the interface and find the type with get type..
private static void function<R>(I<R> t)
{
   Type typeofT = typeof(T);
}

cannot do better.
If you need to call another generic method with T, you can build a generic call through reflection using typeofT Type.

A: C# does not support this kind of type inference.  Consider this case which adds a bit of ambiguity to the problem.
class Other : I<int>, I<Student>{ ... }
void Example(){
  function(new D());
}

In this case there is an ambiguity as to which I should be chosen.
If you look forward to C# 4.0 the problem only increases with the new variance features they are adding.


text:
Q: SQL : Select row where a column of this row does't match with a certain value I have a table with for exemple, a column id_type and an other column num_area. And I want to search all the id_type where the value of num_area doesn't match with a certain value.
id_type    num_area
----        ----
1           121
2           121
1            95
3            47
4            65

For exemple, if I want id_type that doesn't have the num_area 121, it will returns me, id_type 3 and 4.
Thanks

A: plan

*

*list id_type where num_area is 121

*list distinct id_type not in above

query
select distinct id_type
from example
where id_type not in
(
  select id_type
  from example
  where num_area = 121
)
;

output
+---------+
| id_type |
+---------+
|       3 |
|       4 |
+---------+

sqlfiddle

A: Try this query. I got the result without subquery.
SELECT DISTINCT(e1.id_type)
 FROM example e1
 JOIN example e2 ON(e1.id_type = e2.id_type AND e2.num_area != '121');