text:
Q: Sort divs by value I am trying to sort articles by a child div inside using js.
My article html using Expression Engine looks like this:

{count}

{first_name} {last_name}

        {relationship}
            {if '{relationship:results_grid:total_rows search:session="Race" sort="desc"}' >= 10 && '{relationship:results_grid:total_rows search:session="Race" sort="desc"}' <= 24}

{relationship:results_grid:total_rows search:session="Race" sort="desc"}

            {if:elseif '{relationship:results_grid:total_rows search:session="Race"}' >= 25 && '{relationship:results_grid:total_rows search:session="Race"}' <= 49}

{relationship:results_grid:total_rows search:session="Race" sort="desc"}

            {if:elseif '{relationship:results_grid:total_rows search:session="Race"}' >= 50}

{relationship:results_grid:total_rows search:session="Race" sort="desc"}

            {if:else}

{relationship:results_grid:total_rows search:session="Race" sort="desc"}

            {/if}
        {/relationship}

I basically want to sort the articles by div.totalRows descending. I have so far only managed to return the values, but i'm not sure what to do next.
Heres what I have so far:
var badgeRaces = document.getElementById('races').getElementsByClassName("totalRows");

function badgeRacesCount(i){
   for(var i = 0; i < badgeRaces.length; i++){
     return badgeRaces[i].innerHTML;
  }
}

Any help would be appreciated.


text:
Q: How to handle different speed of team members in scrum? I've been using Scrum for some time, but I still do not have a clear understanding of how to handle the case when all team members have different working speed. For example, given an abstract task an employee A will solve it in 5 days while employee B will need about 10 or even 15 days. My team consists of very different (in expertise) people, so they literally work by different speeds.
These are the main misunderstandings:

*

*How to measure user stories in ideal man-days because they are very different inside the team? (There are often arguments since some people have experience in the area and some don't so they would need to spend some time reading the docs and doing small steps)

*Why to calculate team velocity if I would need to calculate each individual's velocity then to be able to give right amount of work to everybody? (Another reason to calculate each individual's velocity is that there is a big difference when a senior guy goes to vacation and a junior)

A: Velocity is merely here so that the team may take a rough guess at the amount of work it can commit to for the next sprint.
Story points only have a meaning relatively to another story, not as an absolute value, because their sole purpose is to draw a broad stroke parallel between stories the team as a whole has completed until now, and stories it will have to deal with in the future.
If a senior developer goes on vacation, just adjust planned velocity for the next sprint accordingly. Don't take it as a pretext to introduce complex estimates, they will only give you a false sense of security and get you deep in a fractal estimation mire, distracting you from your primary goal which is to deliver value.
You don't need to relate story points to man hours. You don't need to calculate team member-specific estimates. You don't need to pre-assign stories to people.

A: Scrum has no concept of individual performance. It's always about the team. You'll always have individuals that perform to varying degrees and if you try and plan for that, it'll drive you slowly insane.
My strong advice is to ignore the performance of the individuals and concentrate on the velocity of the team.

A: My 2 cents: All my projects have included Scrums. The best way to handle such case is to let the team members choose their stories and assign them points. 3 point is for story that can be done quickly, perhaps 4 hours or less, 8 point is story that would require a person to complete the story within 1 working day(8 hrs), and 13 point(3 days or less) is the story that will require the person to do some research on implementation, implementing and testing it
There should be lead team developer who understands the working velocity of other team members and can assign the stories to other members based on their ability.
If you think the story will require more than 3 days to be completed, then it should be further divided into mini stories that will require less time to do so.

redpajama_set_name: RedPajamaStackExchange


text:
Q: [MS-Access][ODBC] Can't delete an line on a form, ODBC delete on a linked table failed I have a form that is linked to an ODBC (MS SQLServer), that is displaying a result of a VIEW, when I try to delete a record, I'm invoking a function at VBA level
Form_BeforeDelConfirm(Cancel As Integer, Response As Integer){
     If (IsNull(Text104.value) = False) Then
         Dim deleteLabel As DAO.QueryDef
         Set deleteLabel = CurrentDb.CreateQueryDef("")
         deleteLabel.Connect = CurrentDb.TableDefs("KontrollWerte").Connect
         If (InStr(QuerySave, "KontrollWerteVIEW") <> 0) Then
             deleteLabel.sql = "delete from KontrollWerte_Label where Kontrolle_Label_ID = " & Text104.value
         End If
         Close
    End If
}

Error shown:

[Microsoft][SQL Server Native Client 11.0][SQL Server] View or function 'dbo.KontrollwerteVIEW' is not updatable because the modification affects multiple base tables. (#4450)

This error is okay, as the view is a select with multiple tables.
It seems the function is not called at all, and the "default" delete function of the MS Access is being called, there is a way to say to MS Access don't do the default delete and instead execute my sql statement inside of the Form_BeforeDelConfirm function?
Thanks!
I tried to change when the call of function is called, but no luck.

A: You have to ensure that the view allows updates.
When you link a table, and it is a view?
The during the creating of the table link, then you will see this prompt:
First, we select the "view" when linking that "view/table"

and note I also checked the Save password option.
Then next we get/see this:

DO NOT skip the above prompt. If you don't select the PK column for that view, then it will be read only.
FYI:
The above prompt to save password, and the above prompt to select the PK when linking to that view?
It DOES NOT appear on re-link, ONLY when adding a new link!!!!
So, that's why I stated to delete the link to sql server (not just re-link and not just re-fresh table link, but Adding for first time are the key instructions here).
So, yes, views are and can be up-datable, but you MUST answer the above prompt during the linking process in Access, or the result is a read-only table.


text:
Q: How to check which part of page is an article? I would like to create a similar tool to Instapaper or Readability and I wonder what is the best way to find and get text from a web page. Do you have any ideas?

A: The question is too broad to give a concrete answer to, but you can separate this question into three concerns:

*

*A way to grab web resources. libcurl for example, or just about anything able to talk HTTP.

*A DOM parser.  Python has xml.dom.minidom, for example.

*An algorithm for traversing the DOM tree and extracting text.  Be it scanning for elements with class=article, or <div>s with more than 1024 characters etc., is entirely up to you.  You will need experimentation to get this right.
I suggest asking separate questions for each of these concerns.  After doing research on each, of course. :)

A: Here is an idea to get you started in Ruby. Just tested the code below and it is working fine for me. Have a look it might help you.
require 'open-uri'
require 'cgi'
require 'nokogiri'

$url='http://www.stackoverflow.com'

$txt_file = open($url)

$raw_contents = $txt_file.read

$html = Nokogiri::HTML(CGI.unescapeHTML($raw_contents)).content
#strip the web page fetched out of all hmtl tags and encoded chars

$txt_file = File.new('c:\ruby193\bin\web-content\stack.txt', "w")
#stack.txt now contains a stripped, pure txt file which you can manipulate further

$txt_file.write($html)
$txt_file.close

puts 'Here is the stripped text of your webpage\n'+$html


text:
Q: Iterate over the data for multiple series in Highmaps I am using a constructor to plot the Highmaps.
$(function() {
  var options1 = {
    chart: {
      renderTo: 'container',
    },
    series: [{
      name: 'Countries',
      mapData: Highcharts.maps['custom/world'],
      color: '#E0E0E0',
      enableMouseTracking: false,
    }, ]
  };

  var drawMap = function(data) {
    var newSeriesData = {
      type: 'mapbubble',
      mapData: Highcharts.maps['custom/world'],
      name: 'Population 2013',
      joinBy: ['iso-a2', 'code'],
      data: data,
      minSize: 4,
      maxSize: '12%',
    }
    options1.series.push(newSeriesData);
    var chart = new Highcharts.Map(options1);
  };
  $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=world-population.json&callback=?', function(data) {
    var i = 0;
    /*while (i < data.length){
        drawMap([data[i]]);
        i++;
    }*/
    drawMap(data);
  });
});

jsfiddle.
Using a function I am able to plot the whole data in a one go.
I want to iterate through the data and plot it one by one so that the page won't refresh and the new data will not replace the existing ones.
I have tried doing it like:
while (i < data.length){
    drawMap([data[i]]);
    i++;
}

But only the last point is plotted in the map. Rest of the points are not plotted. (I guess the map is plotted with all the points without persistence. So only the last point is there.)
Note: I followed this and tried for Highmaps.


text:
Q: spring security filter issues using Boot 2.1.14.Release / security 5.1.10
I have the following endpoints which need the specified security
/token/exchange - this endpoint should only allow access if the request has an Okta JWT.  It returns a custom JWT I've create manually via JJWT.  Basically, instead of passing in user creds, the users will have already authenticated with Okta and will provide that token as their credential.
I've added the Okta starter and this is working as expected

/api/** - any endpoint under /api requires my custom JWT in the Authorization header

I have the following security config:
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class AppWebSecurityConfigurerAdapter {

    @Configuration
    @Order(1)
    public static class OktaWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/token/exchange") <------- this should "pin" this config right?
                    .authorizeRequests()
                    .antMatchers("/token/exchange").authenticated() <--- is this needed?
                    .and()
                    .oauth2ResourceServer().jwt();
            http.cors();
            http.csrf().disable();
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            Okta.configureResourceServer401ResponseBody(http);
        }
    }

    @Configuration
    @Order(2)
    @RequiredArgsConstructor
    public static class ApiWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        private final CustomSecurityConfig customSecurityConfig; <--- JWT secret key in here
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .addFilter(new JwtFilter(authenticationManager(), customSecurityConfig))
                    .csrf().disable()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .cors();
        }
    }
}

and the following JwtFilter
@Slf4j
public class JwtFilter extends BasicAuthenticationFilter {

    private final CustomSecurityConfig customSecurityConfig;

    public JwtFilter(AuthenticationManager authenticationManager, CustomSecurityConfig customSecurityConfig) {
        super(authenticationManager);
        this.customSecurityConfig = customSecurityConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
            if (authentication == null) {
                chain.doFilter(request, response);
                return;
            }
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } catch (Exception exception){
            log.error("API authentication failed", exception);
            SecurityContextHolder.clearContext();
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = new DefaultBearerTokenResolver().resolve(request);
        if (token == null) {
            return null;
        }
        Algorithm algorithm = Algorithm.HMAC256(customSecurityConfig.getSecret());
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(CustomSecurityConfig.ISSUER)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        return new UsernamePasswordAuthenticationToken(
                jwt.getClaim("user_name").asString(),
                null,
                jwt.getClaim("authorities")
                        .asList(String.class)
                        .stream()
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList()));
    }
}

My /api calls all return 401 and its because they are being processed by the BearerTokenAuthenticationFilter (used by my OktaWebSecurityConfigurerAdapter) instead of my JwtFilter.  Naturally, the signatures don't match between the two tokens.  I'm confused why my /api calls are even being processed by that filter, because I'm only applying the .oauth2ResourceServer().jwt(); config for my Okta handler
my logs look like this:
SecurityContextHolder now cleared, as request processing completed
Checking match of request : '/api/entities'; against '/token/exchange'
Checking match of request : '/api/entities'; against '/api/**'
/api/entities at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
/api/entities at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
/api/entities at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
/api/entities at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
/api/entities at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
Trying to match using Ant [pattern='/logout', GET]
Checking match of request : '/api/entities'; against '/logout'
Trying to match using Ant [pattern='/logout', POST]
Request 'GET /api/entities' doesn't match 'POST /logout'
Trying to match using Ant [pattern='/logout', PUT]
Request 'GET /api/entities' doesn't match 'PUT /logout'
Trying to match using Ant [pattern='/logout', DELETE]
Request 'GET /api/entities' doesn't match 'DELETE /logout'
No matches found
/api/entities at position 6 of 13 in additional filter chain; firing Filter: 'BearerTokenAuthenticationFilter'
Authentication attempt using org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider
No event was found for the exception org.springframework.security.oauth2.core.OAuth2AuthenticationException
Authentication request for failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found
Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@13691de5
SecurityContextHolder now cleared, as request processing completed

I've been banging my head all day and night with this....thanks for any help!

A: I'll start with the answer to your question (I think).  You are adding your filter with addFilter(...) which doesn't specify any order information. Use addFilterBefore(...) instead.
I would caution you against using JWT for a sort of session token unless have a way to revoke them. https://developer.okta.com/blog/2017/08/17/why-jwts-suck-as-session-tokens
In your case, it sounds like you might be exchanging one token for a "weaker" one. There are things you can do to mitigate some of this risk, like limiting the duration the token is valid, etc.  I don't have all of the context of your use case or how you are using it, so take this with a grain of salt :)

A: I saw this in the JJWT readme

But you might have noticed something - what if your application doesn't use just a single SecretKey or KeyPair? What if JWSs can be created with different SecretKeys or public/private keys, or a combination of both? How do you know which key to specify if you can't inspect the JWT first?

that led me to rethink the design.
basically, all my routes expect a Bearer token.  One of them (/token/exchange) expects the token came from Okta.  All of my /api/** routes expect the token to be a signed by the API server itself.  To accomplish this, I setup a singular security config like so:
@Configuration
@RequiredArgsConstructor
public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final JwtFilter jwtFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        http
                .cors().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

My JwtFilter
@Slf4j
@Component
public class JwtFilter extends OncePerRequestFilter {

    private static final String HEADER = HttpHeaders.AUTHORIZATION;

    private final OktaTokenUtils oktaTokenUtils;
    private final ApiTokenUtils apiTokenUtils;

    public JwtFilter(OktaTokenUtils oktaTokenUtils, ApiTokenUtils apiTokenUtils) {
        this.oktaTokenUtils = oktaTokenUtils;
        this.apiTokenUtils = apiTokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        final String header = request.getHeader(HEADER);
        if (header != null && !header.isBlank()) {
            final String token = header.substring(7);
            log.debug("{} TOKEN: {}", HEADER, token);
            String uri = request.getRequestURI();
            if (uri.equals("/token/exchange")) {
                SecurityContextHolder.getContext().setAuthentication(oktaTokenUtils.authenticate(token));
            } else {
                SecurityContextHolder.getContext().setAuthentication(apiTokenUtils.authenticate(token));
            }
        }
        filterChain.doFilter(request, response);
    }

}

My OktaUtils and ApiUtils classes are responsible for validating the token and returning the Authentication object so the filter can add it to the security context holder
@Slf4j
@Component
public class ApiTokenUtils {

    private final JwtParser parser;

    public ApiTokenUtils(ApiTokenConfig config){
        parser = Jwts.parserBuilder()
                .requireIssuer(config.getIssuer())
                .setSigningKey(config.getSecret())
                .build();
    }

    public Authentication authenticate(String token) {
        try {
            Jws<Claims> claims = parser.parseClaimsJws(token);
            String username = claims.getBody().get("user_name", String.class);
            log.debug("valid API token for username {}", username);
            List<String> authorities = claims.getBody().get("authorities", List.class);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    username,
                    null,
                    authorities.stream()
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toList())
            );
            authentication.setDetails(MyUserDetails.builder()
                    .token(token)
                    .authorities(authorities)
                    .setUserId(claims.getBody().get("userId", String.class))
                    .email(claims.getBody().get("email", String.class))
                    .username(username)
                    .build());
            return authentication;
        } catch (Exception e) {
            if( log.isDebugEnabled() ) {
                log.error("API token verification failed", e);
            } else {
                log.error("API token verification failed");
            }
            return null;
        }
    }
}

@Slf4j
@Component
public class OktaTokenUtils {

    private final AccessTokenVerifier verifier;

    public OktaTokenUtils(OktaConfig oktaConfig) {
        verifier = JwtVerifiers.accessTokenVerifierBuilder()
                .setIssuer(oktaConfig.getIssuer())
                .setAudience(oktaConfig.getAudience()) // defaults to 'api://default'
                .setConnectionTimeout(Duration.ofSeconds(3)) // defaults to 1s
                .setReadTimeout(Duration.ofSeconds(3)) // defaults to 1s
                .build();
    }

    public Authentication authenticate(String token) {
        try {
            Jwt jwt = verifier.decode(token);
            String subject = jwt.getClaims().get("sub").toString();
            log.debug("valid Okta token for SUB {}", subject);
            return new UsernamePasswordAuthenticationToken(
                    subject,
                    token,
                    Collections.emptyList());
        } catch (Exception e) {
            if( log.isDebugEnabled() ) {
                log.error("Okta token verification failed", e);
            } else {
                log.error("Okta token verification failed");
            }
            return null;
        }
    }

}

some links that helped me along the way:

*

*https://github.com/okta/okta-jwt-verifier-java

*https://github.com/jwtk/jjwt


text:
Q: Send callback paramenter via Ajax jsonp I've been looking for a good 3 hours and haven't found a way that works.
I'm super new to JQuery, Ajax, PHP.
All I'm looking for is how to set a callback parameter from an Ajax request using jsonp.
So basically im looking for this:
    www.mysite.com/service.php?callback=value
How can I change 'value' to whatever I want from an Ajax request...
Here's the last thing I tried
$(document).ready(function(){
var output = $('#results');
$.ajax({
url: 'www.mysite.com/service.php',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback:'select',
timeout: 5000,
success: function(data,status){
    var result = data;
    output.append(result);
});
},
error: function(){
    output.text('Failed.');
}

});
});

My service.php is this
<?php
$callback = $_GET['callback'];
echo $callback;
?>

I'd expect to see a 'select' printed on my html.
And my html is just a basic html with a

 in the body.
Thank you.

A: First of all, in service.php use return $callback;.
Next, create the select element inside the success function:
var select = document.createElement('select');
var option = document.createElement('option');
option.id = result;
option.value = result;


text:
Q: Plot strategy order on chart I would like to plot something (an arrow, a label) that could mark on the chart everytime my strategy sets a buy or sell order (which happens under certain conditions but can disappear)
Is there a way in pine script I could do that ?
Here's the extract of the strategy that creates the order :

strategy.entry("BuyOrder", strategy.long, stop=high+syminfo.mintick, comment="Buy", when = window())

A: You can use ta.change() with strategy.position_size and strategy.opentrades:
//@version=5
strategy("My strategy", overlay=true, margin_long=100, margin_short=100)

longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

changeCond = ta.change(strategy.position_size, 1) or ta.change(strategy.opentrades,1)
bgcolor(changeCond? color.new(color.red, 80) : na)


text:
Q: How to sort read files by using ImageDataGenerator enter image description here
enter image description here
I have a trouble in loading images with DataGenerator. It's not sort like my real path as you can see from images. It should be like img(1), img(2), ... but img(1), img(10), img(100), ...
How can I solve this ? Thank you in advance.

A: The reason the order is NOT what you expect is that the generator processes images in alphanumeric order. For example if your images are labelled 1.jpg, 2.jpg, ...9.jpg, 10.jpg, 11.jpg ...etc
They will be processed in the order
1.jpg, 10,jpg,11.jpg, etc, 2.jpg,20.jpg etc.
One way to preserve the order is to name the files using "zeros'' padding. For example if you have 20 files label them as
01.jpg, 02.jpg, etc 09.jpg, 10.jpg etc. Be aware if you are using flow_from_directory the class directories are also processed in alphanumeric order. Included below is the code for a function that will rename all the files in a directory (source_dir) numerically starting from an integer value (snum) with appropriate 'zeros' padding.
def rename (source_dir, snum, ):
    import os
    import shutil
    flist=os.listdir(source_dir)
    temp_dir=os.path.join(source_dir, 'temp')
    if os.path.isdir(temp_dir):
        shutil.rmtree(temp_dir)
    os.mkdir(temp_dir)
    for f in flist:
        fpath=os.path.join(source_dir,f)
        dpath=os.path.join(temp_dir,f)
        shutil.copy(fpath, dpath)
    tlist=os.listdir(temp_dir)
    for f in tlist:
        fpath=os.path.join(source_dir,f)
        os.remove(fpath)
    tlist=os.listdir(temp_dir)
    fc=len(tlist)  # determine number of d files to process which determines amout of zeros padding needed
    pad=0
    mod = 10
    for i in range(1, fc + 1): # skip i=0 because 0 modulo anything is 0 and we don't want to increment pad
        if i % mod == 0:
            pad=pad+1
            mod =mod * 10
    for i,f in enumerate(tlist):
        fpath=os.path.join(temp_dir,f) #full path to the file
        index=fpath.rfind('.') # find location of last . in file name
        new_path=os.path.join(source_dir, str(i + snum).zfill(pad+1) + fpath[index :] )
        shutil.copy(fpath, new_path)
    shutil.rmtree(temp_dir)


text:
Q: Generate table with predefined parameters I want to create a table with these parameters:
        # Setting parameters for table
        initial_year=2020
        last_year=2030

        # Setting column names

         ## First two columns' names
        The first two columns must have columns with the names 'Wages' and 'Payment'

        ### Columns after the second column
        listName = ['column1','column2','column3','column4']

In the end, I need to have the table as the table below

I tried this line of code, but is not working
df=pd.DataFrame(rows=range(initial_year,last_year)).add_prefix('Year')

Can anybody help me how to solve this problem and generate table as table above ?

A: You can use:
initial_year=2020
last_year=2030

cols = ['Wages', 'Payment']
listName = ['column1','column2','column3','column4']

df = (pd.DataFrame({'Year': range(initial_year, last_year+1)})
        .reindex(columns=['Year']+cols+listName, fill_value=1)
     )

print(df)

Output:
    Year  Wages  Payment  column1  column2  column3  column4
0   2020      1        1        1        1        1        1
1   2021      1        1        1        1        1        1
2   2022      1        1        1        1        1        1
3   2023      1        1        1        1        1        1
4   2024      1        1        1        1        1        1
5   2025      1        1        1        1        1        1
6   2026      1        1        1        1        1        1
7   2027      1        1        1        1        1        1
8   2028      1        1        1        1        1        1
9   2029      1        1        1        1        1        1
10  2030      1        1        1        1        1        1


text:
Q: Run SQL commands inside postgres docker container using docker-compose I can run SQL commands inside a postgres docker container using psql:
psql -U postgres -c "SELECT * FROM USERS;"

Now, I want to run this command using docker-compose. Here's what I have so far but no luck:
docker-compose run db psql -U postgres -c "SELECT * FROM USERS;"
# psql: error: could not connect to server: could not connect to server: No such file or directory
#     Is the server running locally and accepting
#     connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Any idea what I'm doing wrong or is this not possible?

A: I think you can't. See postgresql Dockerfile:

CMD ["postgres"]

The final CMD is postgres which will start the postgresql server.
If you use docker-compose run db psql -U postgres -c "SELECT * FROM USERS;", see this:

the command passed by run overrides the command defined in the service configuration. For example, if the web service configuration is started with bash, then
docker-compose run web python app.py overrides it with python app.py.

So, the original postgres command never have chance to run, which means the postgresql server not start, then you have your error to connect to server.
I don't know if next alternative meet your requirement, just FYI:
First, use docker-compose up -d db to start the service.
Second, use docker-compose exec db psql -U postgres -c "select * from pg_user;" for example to run your command.


text:
Q: Why can I assign from an rvalue twice in C++? I was reading the chapter 13 of C++ Primer when I read :

"It is essential to realize that the call to move promises that we do
not intend to use [an rvalue] again except to assign to it or to
destroy it. After a call to move, we cannot make any assumptions about
the value of the moved-from object."
"We can destroy a moved-from object and can assign a new value to it,
but we cannot use the value of a moved-from object."

So I wrote this code to see if I can't actually use a rvalue twice :
#include <iostream>

int main(int argc, const char * argv[]) {

    int&& rvalue = 42;

    int lvalue1 = std::move(rvalue);

    std::cout << "lvalue1 = " << lvalue1 << std::endl;

    int lvalue2 = std::move(rvalue);

    std::cout << "lvalue2 = " << lvalue2 << std::endl;

    return 0;
}

But according to the output of this code, C++ Primer is wrong and I can use the value of a moved-from object several times (I built with the C++11 standard) :
lvalue1 = 42
lvalue2 = 42

I don't understand...

A: This experiment ...

So I wrote this code to see if I can't actually use a rvalue twice :

... doesn't prove anything.  It might also be the case that your particular compiler doesn't complain when you, say, double-delete a pointer.  That doesn't make this good practice or even language-defined behavior.
After a std::move the moved-from variable is in a valid but unspecified state.  Being valid means you can reassign to it, but unspecified means that until that reassignment happens the variable's value is not guaranteed to be anything in particular.  Maybe the variable appears to maintain its value after a std::move; that's consistent with an unspecified state.  The guidance in your text--"make [no] assumptions about the value of the moved-from object"--is accurate.

A: The wording in the primer is very carefully chosen:

but we cannot use the value of a moved-from object.

"Use" here is ...err, used, in a very general sense. It means, basically: if you have any carefully-laid plans to use it, and expect the object to have anything particilar in it after the move, you are going to be very, very disappointed. "Cannot use" really means here: well, what use could possibly exist for any object whose value is unspecified? What good is an object whose value is unknown? That doesn't sound like a very useful object, doesn't it?
But a moved-from object is not really some kind of an untouchable. It's still a valid object. It still exists. If the moved-from object has a destructor the destructor will still get invoke when the moved-from object goes out of scope and gets destroyed. However, immediately after a move, it's "value" is unspecified.
The C++ standard describes move semantics thusly:

Moved-from state of library types [lib.types.movedfrom]
Objects of types defined in the C++ standard library may be moved from. Move operations may
be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be
placed in a valid but unspecified state.

Emphasis mine. The above technically refers to the objects in the C++ library only, which technically encompasses the native types, too. "Valid but unspecified state" is the key. In your example, the first move operation left the original valid in some "valid but unspecified state". And the key word there is "valid". So, it is not prohibited to move the object again.
In this case, your result happened to produce another 42. But the moved-from value is "unspecified". Someone else might get a different value. Or you may get a random value each time you run the program. Of course, practically, that's not going to happen, but that's what the C++ standard allows to happen.


text:
Q: Solr DataImportHandler: Can I get a dynamic field name from xml attribute with XPathEntityProcessor? I have some XML to ingest into Solr, which sounds like a use case that is intended to be solved by the DataImportHandler.  What I want to do is pull the column name from one XML attribute and the value from another attribute.  Here is an example of what I mean:
<document>
  <data ref="reference.foo">
    <value>bar</value>
  </data>
</document>

From this xml snippet, I want to add a field with name reference.foo and value bar.  The DataImportHandler includes a XPathEntityProcessor for processing XML documents.  I've tried using it and it works perfectly if I give it a known column name (e.g, <field column="ref" xpath="/document/data/@ref">) but have not been able to find any documentation or examples to suggest either how to do what I want, or that it cannot be done.  So:

*

*Can I do this using XPathEntityProcessor? If so, how?

*If not, can I do this some other way with DataImportHandler?

*Or am I left with writing my own import handler?

A: I haven't managed to find a way to do this without bringing in a transformer, but by using a simple ScriptTransformer I worked it out.  It goes something like this:
...
<script>
function makePair(row) {
  var theKey = row.get("theKey");
  var theValue = row.get("theValue");

  row.put(theKey, theValue);
  row.remove("theKey");
  row.remove("theValue");

  return row;
}
</script>

...

<entity name="..."
  processor="XPathEntityProcessor"
  transformer="script:makePair"
  forEach="/document"
  ...>

  <field column="theKey" xpath="/document/data/@ref" />
  <field column="theValue" xpath="/document/data/value" />
</entity>
...

Hope that helps someone!
Note, if your dynamicField is multivalued, you have to iterate over theKey since row.get("theKey") will be a list.

A: What you want to do is select the node keying on an attribute value.
From your example, you'd do this:
<field column="ref" xpath="/document/data[@ref='reference.foo']"/>


text:
Q: npm start not working in the react app, what do i do? So i created a react app when and I did npm start for the first time, the app opened in the browser, no issues. Subsequently I closed the tab & the VSC editor. Now that i try "npm start" again in the VSC terminal, the app doesnt open and I get a strange response.
This is my first proper question on Stackoverflow and first project on React please be kind to me.
After making the app using create-react-app my-app and doing npm start and the project running well. Now when i do npm start this happens:
PS C:\Users\Lenovo\Desktop\Coding\React\Practice> npm start

npm ERR! code ENOENT

npm ERR! syscall open

npm ERR! path

C:\Users\Lenovo\Desktop\Coding\React\Practice/package.json

npm ERR! errno -4058

npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Lenovo\Desktop\Coding\React\Practice\package.json'

npm ERR! enoent This is related to npm not being able to find a file.

npm ERR! enoent

Except npm help, no other command runs. Please help me out.

A: npx create-react-app practice-app
cd practice-app
/practice-app/ npm start
You have to be inside the react application you have created to launch the application with npm or yarn. I think you were still on the parent folder which in this case is the Practice folder.
On vscode terminal type cd then press the tab button u will see all the folders contained inside the Practice folder coming up. keep pressing till your react project folder comes to the screen and press enter.
Then type code . to open the folder on vscode ide. Then use npm start or yarn start on the project to start.


text:
Q: Regex match a string if is not followed by digits in one case I have the regular expression:
 ^[-\s]+|Not Specified$

I get a match on all of the following strings:
--
Not Specified
- - -                    eV
-270 - 1000                    deg C

but I want to get only on the first three.
I don't want to catch word like:
 MTF, Depth, Focus, Blur
sub-micron

A: You need to add parenthesis. The \D matches anything other than a decimal digit:
^(\D+|Not Specified)$

You can even break down to:
^\D*$

A: You could match either Not Specified or match at least a single - without matching digits or a newline:
^(?:Not Specified|[^\r\n\d-]*-[^\r\n\d]*)$

Explanation

*

*^ Start of string

*

*(?: Non capturing group

*Not Specified Match literally

*| Or

*[^\r\n\d-]*- Match 0+ times any char except a digit, - or newline, then match -

*[^\r\n\d]* Match 0+ times any char except a newline or digit

*) Close group

*$ End of string

Regex demo
Note that \s also matches a newline, if that is intended you can omit the \r\n so that the negated character class will match thenewlines.


text:
Q: Are SVG graphics suitable for an in-browser game? Are SVG graphics a viable option for an in-browser game, with a google-maps style interface? This would involve zooming in/out, and scrolling in two dimensions over a very large distance.
For example, the client might request some area to be drawn in from the server -- and rather than the server returning a generated image for that section, it would return a series of gzipped SVG images and their locations in the requested area. Then the user could zoom in and out without grabbing new "tiles" from the server, since SVGs are scalable.
Would this be better than generating pngs or jpegs and sending back tiles? Would it perform well if there were many clients requesting images all over the place? Would it perform well on the client? What are the downsides to this approach?

A: In my experienced. The downside is the achievable level of detail using SVG is lower than lossy image compression like jpeg and png. I had difficulties getting all my vector graphics to play nicely with each other. If your artists are comfortable with working in SVG then this may not be an issue. Another note is that SVG compatibility may very between browsers. For instance I'm not sure which browsers support SVG. Webkit does, and I think Firefox does mostly, but I'm fairly sure IE is out of the picture, so to speak.
Overall SVG will put higher demands on client machines and lower demands on your servers. Calculating hundreds of SVG images is a lot more work than arranging PNGs.
In really depends on your game. If you are writing Chess, it would probably work fine. If you want to do something more complex in real time( E.G. a 2d side scrolling game), I have no clue.
using this SVG clock in Raephael as an Example. I am running Chrome on Windows and periodically different bars "twitch" and "reset for a second"
Edit
I just saw this first person SVG Demo So it can be done.


text:
Q: Matching email legal statement using regex I just need to delete the email disclaimer from the following text. Seems like an easy task but I'm not getting there.
string:

Hello. Please see attached. Thanks. CONFIDENTIAL AND PROPRIETARY *
  The content of this email, including all header and footer information, is the "CONFIDENTIAL AND PROPRIETARY INFORMATION" of The
  Cleaning house, LLC. ("Franchisor") and is protected under the
  applicable  franchise agreement ("applicable Franchise Agreement")
  between Franchisor and each of its franchisees ("Franchisee(s)").
  Accordingly, each Franchisee who receives this email must, both during
  and after the term of the applicable Franchise Agreement, maintain
  the absolute confidentiality of the content of this email and may
  disclose the content of this email only to its employees and agents
  and only to the extent necessary for the operation of its Franchised
  Business (as defined in the applicable Franchise Agreement)  in
  accordance with the applicable Franchise Agreement. None of the
  Franchisees who receive this email may use (or permit any other
  natural or legal person to use) the content of this email in any other
  business or in any way not authorized by Franchisor in  writing. ©
  2009 The Cleaning house, LLC. All rights reserved.{}

Desired output:

Hello. Please see attached. Thanks. .{}

My attempts:
CONFIDENTIAL AND PROPRIETARY[\n|.]*(?=reserved)
CONFIDENTIAL AND PROPRIETARY.*All rights reserved
edit: There may be newlines and all types of weird stuff in the string also. I was hoping the .* would handle this.

A: Probably you aren't usin in the right way the regex parser.
import re

email = "Hello. Please see attached. Thanks. CONFIDENTIAL AND PROPRIETARY * The content of this email, including all header and footer information, is the CONFIDENTIAL AND PROPRIETARY INFORMATION of The Cleaning house, LLC. (Franchisor) and is protected under the applicable franchise agreement (applicable Franchise Agreement) between Franchisor and each of its franchisees (Franchisee(s)). Accordingly, each Franchisee who receives this email must, both during and after the term of the applicable Franchise Agreement, maintain the absolute confidentiality of the content of this email and may disclose the content of this email only to its employees and agents and only to the extent necessary for the operation of its Franchised Business (as defined in the applicable Franchise Agreement) in accordance with the applicable Franchise Agreement. None of the Franchisees who receive this email may use (or permit any other natural or legal person to use) the content of this email in any other business or in any way not authorized by Franchisor in writing. © 2009 The Cleaning house, LLC. All rights reserved.{}"

cleaned_email = re.sub(r'CONFIDENTIAL AND PROPRIETARY[\s\S]*All rights reserved', '', email)

Look te change of .* for [\s\S]*
(dot) . Matches any character except a newline, but \s Matches Unicode whitespace characters, and \S Matches any character which is not a whitespace character


text:
Q: Office Online Server Not Working We've been using office web apps in our SharePoint 2016 farm for over a year.  A few weeks ago it stopped working.  There weren't any updates installed and we're told there weren't any GPO updates.
I found one post on this site around WMI, but that didn't fix our error.

WordDocumentSessionServiceWatchdog reported status for
  WordDocumentSessionService in category 'Ping'. Reported status:
  WordDocumentSessionService ping hit an exception.

A: Were there any DNS changes related to your OWA server? You should ensure that your SPWOPI binding is still valid and if not then update it.
Notes on that:
https://social.technet.microsoft.com/Forums/office/en-US/228588a0-a6ad-4979-a419-d0ffc41bc7e8/sharepoint-2013-wopi-office-webapps-not-opening-full-word-document-but-only-preview?forum=sharepointadmin

A: Make sure all SharePoint Server 2016 web applications use claims-based authentication. Office Online rendering and editing won't work on SharePoint Server 2016 web applications that use classic mode authentication.
If you log on to SharePoint Server 2016 by using the System Account, you won't be able to test the connection between SharePoint Server 2016 and Office Online Server. Log on with a different account to test the connection.
Low memory conditions can cause Office document previews to fail in Office Online.
Besides, release the existing WOPI binding in SharePoint Management Shell and renew it with this script:
Remove-SPWOPIBinding -All:$true

New-SPWOPIBinding -ServerName *YourOfficeOnlineServerNameHere*


text:
Q: Get DC++ hub information with python Is there any way in which i can get a DC++ hub information like the online status of the hub, no. of users online, amount of data shared. I have access to the hubs, so that is not an issue.

A: Write your own client (maybe using some hints, the ADC protocol is not too complex) or reuse parts of pyDC.  Looks like all you want to do is connect to a hub, scrape some information, and drop off, so you don't need to handle searching or sharing.


text:
Q: docker inside nginx html folder can not create mounts I have a project which uses docker and it is hosted inside nginx root folder. When I run docker-compose to create solr container, I get an error when docker tries to create new folders inside the project root folder.

Cannot start service (service): error while creating mount source
  path /path/to/targeted/folder read-only file system

this is piece of docker-compose.yml file
solr-1:
    image: solr:7.4.0
    ports:
    - "8983:8983"
    volumes:
      - ./settings/solr/configsets:/opt/solr/server/solr/configsets
      - ./settings/solr/solr.in.sh:/opt/solr/bin/solr.in.sh
      - ./data/solr-master:/opt/solr/server/solr/sharq/data

How do I solve this problem?

A: restart the docker solved the problem


text:
Q: How to generate a unique (random) output path in Pig? Is it possible to generate a unique output folder (s3 bucket), maybe by contacting a random number of some sort?

A: This is my workaround for this case, is to concatenate the current timestamp:
%declare cts `date +"%s"`
STORE data INTO '/path/$cts' USING PigStorage();

Im not familiar with s3, but the above example show the idea of concatenating random string to get a unique path.


text:
Q: Using Launcher.LaunchUriAsync for UWP app with IL2CPP scripting backend I have a Hololens app built using Unity 2019.3. Within the app, I am trying to use a onClick event on a button to open Microsoft Dynamics Remote assist.
I have tried to follow this tutorial. https://learn.microsoft.com/en-us/archive/blogs/appconsult/call-remote-assist-from-your-hololens-app
This tutorial says to use .net as the scripting backend, however Unity 2019.3 only allows IL2CPP as the scripting backend.
Have tried the code from this thread as well but still not working.
Execute "LaunchUriAsync" from a click of a HoloLens UI Button
Getting the following errors:

I tried a new project in Unity 2018.4 with scripting backend set to .NET and getting similar errors there as well.
I can't find anything online on how to get Launcher.LaunchUriAsync to work.

A:
This tutorial says to use .net as the scripting backend, however Unity 2019.3 only allows IL2CPP as the scripting backend.

That doc is a bit outdated. We recommend using the latest Unity LTS (Long Term Support) as the best version so that we can avoid some known issues, and the current recommendation is to use Unity 2019.4.20f1.
And we don't need to set .NET as Scripting Backend anymore since IL2CPP is the best and only choice for now.
Some key steps are:

*

*Create a new project in the latest LTS version Unity

*Ensure the target platform is Universal Windows Platform. See File->Build Settings

*Build the Unity project (You choose a folder in which Unity generates a Visual Studio solution; Usually, we create a new subfolder of the Unity project named App).

*Open the new generated Visual Studio solution file and set the right configuration, build and run.

If you still need help, please paste the C# script clicker.cs


text:
Q: ImageResizer license for website with one domain per language When purchasing Performance licenses, the ImageResizer website states that it comes with "1 wildcard domain".
I was under the impression that Performance licenses apply to multiple domains, if those domains are simply aliases for the same website?
In this case, the different domains are used to separate different language versions of a website:
tempuri.com -> English website
tempuri.se -> Swedish website
This is instead of using a common domain and URL prefixes, something like:
tempuri.com/en -> English
tempuri.com/se -> Swedish
In the first case, would we need 1 license per domain?
Also, if the domains aren't exactly the same (depending on domain availability) like...
tempuri.com -> English
tempuri-sweden.se -> Swedish
tempuri-denmark.dk -> Danish
...would we then require 3 licenses to support the three languages?
Thanks!

A: Performance licenses include exactly 1 domain; they are tied to the HTTP HOST header that ImageResizer receives. While subdomains are included, unrelated domains are not. All documentation is very clear on this point - it is a domain license, not a site or website or server license. http://imageresizing.net/plugins/editions/performance
ImageResizer Elite licenses are DRM-free and can be used on an unlimited number of domains.


text:
Q: Mocha/Nightmare test failing but still waiting for timeout I'm running this test (simplified), which fails as expected ... but despite the failure, it still waits for the full 20 second timeout. How can I make it fail immediately?
it("should fail before timeout", function (done) {
      var nightmare = new Nightmare({ show: true })
        .goto(url)
        .evaluate(function () {
        })
        .then(function (result) {
          // this point is reached, and then the test just waits
          // 20 seconds before finally failing
          throw "Fail"
        })
    })

A: This is an error using mocha. Instead of throwing, then should call done with an Error object. (also replaced throw "Fail" with throw new Error("Fail"))


text:
Q: Copy a numpy array into a list of empty arrays As I read in files from a set of directories I want to create a new numpy array for a concatenation of all the data I find in each one of the directories... and I want a nice uniquely named array for each:
schaererPath = '../Software-Models/Schaerer/'
schaererDirs = np.array(['pop3_TA/','pop3_TE/','e-70_mar08/','e-50_mar08/'])
Zs           = np.array([0.0, 0.0, 1.0e-7, 1.0e-5])
schaererPopFilePattern  = '*.is2'
pop3TA = pop3TE = Zem7 = Zem5 = np.array([])
arrayNames = [pop3TA, pop3TE, Zem7, Zem5]
for i, (Z, schaererDir,array) in enumerate(zip(Zs,schaererDirs,arrayName)):
    schaererFilePattern = schaererPath + schaererDir + schaererPopFilePattern
    schaererFiles   = glob.glob(schaererFilePattern)  # All the files in the dir...
    schaererAges    = np.array([linecache.getline(file,13) for file in schaererFiles])    # Get the line with the (log) age...
    schaererAges    = np.array([float(sa[30:]) for sa in schaererAges],dtype=float)   # Log age starts at position 30
    schaererData    = np.array([np.loadtxt(file,skiprows=16) for file in schaererFiles])
    ageSortIndxes   = schaererAges.argsort()  # Array of indices to sort things by age...

    # The following builds an array of arrays (one for each age) with each array's entries:
    # log age, Z, waveln, lum/A
    schaererDataSorted = np.array([np.insert(sed[:,[0,2]],[0],[[age, Z] for ii in range(0,len(sed))], axis=1) for age,sed in zip(schaererAges[ageSortIndxes], schaererData[ageSortIndxes])])
    schaererDataSorted = schaererDataSorted.reshape(len(schaererDataSorted)*len(schaererDataSorted[0]),4)
    # We now have:
    # [[log age, Z, waveln, flux], [], ...]

    arrayNames[i] = schaererDataSorted

The last line is my feeble attempt to assign each of the arrays I've just built (from all the files in a single directory) to a single numpy array with the names found in the arrayNames list. This obviously doesn't work ...
I realize there must be an easy way to do this, but it elludes me!


text:
Q: Make automatic scanning for new activity on homepage optional The new feature to automatically scan for new question activity using web sockets is a potentially handy feature, as it reduces the need for refreshes, and makes information available faster. There are some cases where it would be beneficial for users to be able to turn it off though:

*

*Keeping an SO tab open at work: at some workplaces where the internet may be monitored or filtered, having a constant connection open to an SE site might raise flags.

*Mobile devices: for people using a mobile data connection (tablets, smartphones, etc.) with a metered connection, having a constant data connection running may use up data without users intending to do so.

*It's really annoying: some people just don't like having a tab yelling at them (15) new questions!! when they aren't asking for it. It's distracting, and I'm sure there are others who would like to be able to turn it off.
For most users it's a nice addition, but there are definitely situations where it would be nice to turn off the auto-updating.


text:
Q: Is there a way to detour a c++ constructor? Funny thing is, I answered a question not too long ago about getting the address of a C++ constructor saying that it can't be done so use perfect forwarding instead.  However, in terms of detouring using Microsoft's Detour library, this isn't an option.  The address is required in order to detour any call. So now I have to ask the question, if there is no address of a constructor, is it even possible to detour one?  And if so, how?

A: Not sure about MS Detour, but I usually hooking detour manually with inline assembly in C++. If the code (constructor instance) is mapped in memory, and you can write to that memory region, then detouring is possible.

*

*The basic mechanism of hooking detour is find the place to replace the original opcode by a JUMP to your code cave. If the JUMP code doesn't match the size of the original opcode, fill it with NOPs.

*Execute the original opcode in your code cave

*PUSHAD & PUSHFD

*Doing anything you want using global variables (recommended)

*Call any custom function without params

*POPFD & POPAD

*Jump back to the patched opcode (skill some bytes of NOPS)

For the first step, to obtain the address of the constructor instance, you need to search for its dynamic address either by ReadProcessMemory or any method. I did detour a function from a DLL that load dynamically. To obtain the function, I use HANDLE tempHandle = GetModuleHandle((LPCWSTR)"DLLFileName.dll"); and go by the offset of the DLL handle.


text:
Q: iptables, setting DSCP for DHCP? I'm trying to set the DSCP bits on DHCP packets. Although the below works fine for udp, the packet is always sent with DSCP of 16. Any ideas?
 iptables -t mangle -A FORWARD -p udp -j DSCP --set-dscp 1
 iptables -t mangle -A OUTPUT -p udp -j DSCP --set-dscp 1
 iptables -t mangle -A PREROUTING -p udp -j DSCP --set-dscp 1
 iptables -t mangle -A POSTROUTING -p udp -j DSCP --set-dscp 1

I'm using dhclient - I don't see any option there to set it either.
Looks like dhclient hard codes it here, fyi:
void assemble_udp_ip_header (interface, buf, bufix,
                             from, to, port, data, len)
        struct interface_info *interface;
        unsigned char *buf;
        unsigned *bufix;
        u_int32_t from;
        u_int32_t to;
        u_int32_t port;
        unsigned char *data;
        unsigned len;
{
        struct ip ip;
        struct udphdr udp;

        memset (&ip, 0, sizeof ip);

        /* Fill out the IP header */
        IP_V_SET (&ip, 4);
        IP_HL_SET (&ip, 20);
        ip.ip_tos = IPTOS_LOWDELAY;

A: I think DHCP cannot be caught with iptables as it uses RAW sockets that bypass the entire netfilter mechanism. There are some sources that report this here:
http://louwrentius.com/why-filtering-dhcp-traffic-is-not-always-possible-with-iptables.html
https://serverfault.com/questions/297383/unable-to-block-dhcp-and-other-traffic-on-input-chain


text:
Q: Overlap items in recyclerView I have a RecyclerView with list of items displayed top to bottom.
I would like to have view of last item overlapping with the previous one.
I used RecyclerView.ItemDecoration with negative top margin and it almost does the trick. Item views indeed overlap, but when I'm at the bottom of the list and I start scrolling up then overlapping view disappears too early.
It looks like RecyclerView does not take into account the negative margin at all when deciding if item is visible or not.
Is there a way to fix that?
Thanks,


text:
Q: Searching with Jquery - Work for multiple terms I found this great snippet online for a searchable FAQ. However, I was wondering if anyone knew how it could be modified to work with multiple terms.
http://jsfiddle.net/pT6dB/
On the example above, I would like to be enter "paper Earth" to have both example results returned. If I enter that now, it doesn't return anything. I guess I want to make it equivalent to searching "paper" OR "Earth".
Any help would be much appreciated.
James

A: What you can do is matching the search string against a regular expression to get all words. Then, for each li you check whether its text contains any of the words and show or hide appropriately. I've used array.some which is only available on newer browsers, though.
I've tidied it up a bit as well - not all code was necessary: http://jsfiddle.net/pT6dB/29/.
// no need for preventDefault here - clicking a <strong> doesn't do anything
$('li strong').click(function(e) {
    $(this).parent().find('em').slideToggle();
});

// the "input" event is available on newer browsers, and is also fired when e.g.
// pasting or dragging text
$('#search').on("input", function(e) {
    // make it case-insensitive, and match against a regexp that matches
    // non-space characters
    var words = $(this).val().toLowerCase().match(/\S+/g);
    if (!words) {  // no match, i.e. no words found
        $('#result li').show();
    } else {
        $('#result li').each(function() {
            var text = $(this).text().toLowerCase();
            var show = words.some(function(word) {
                return ~text.indexOf(word);  // ~ with indexOf means "contains"
            });
            $(this).toggle(show);  // will show or hide depending on "show"
        });
    }
});

A: You need to split the value by the " " character using the javascript string.split function.  Then loop through each element to see if there is a match.
For example:
 $('#search').keyup(function(e) {
        var s = $(this).val().trim();
        if (s === '') {
            $('#result LI').show();
            return true;
        }

        $('#result LI').hide();

        splits = s.split(" ");

        for(x in splits){
            $('#result LI:contains(' + splits[x]+ ')').show();
        }

        return true;
    });


text:
Q: BSOD: driver_power_state_failure; can't find cause Windows 8.1 x64 I have a notebook, ASUS ROG G750JM, with Windows 8.1 64 bit, that I've been using for a few months.  Three or four times, absolutely random, I get a BSOD with the message: driver_power_state_failure...  I check the dump file in Windows folder, but it's empty.
My question: is there a way to track all activity, so if a BSOD occurs I can see why it crashed and what needs to be repaired?


text:
Q: Transformer secondary winding resistance I am struggling to understand how to model a resistance loss of a transformer secondary winding. In a typical flyback converter, if the primary and secondary transformer have a resistance loss, how do we model the the secondary transformer resistor during the second interval (when the mosfet is off and diode conducts). If the turns ratio is 1:n, the current during the second interval would be i/n. So the voltage drop across the secondary winding resistor would be i/n*Rsecondary. As per my understanding, the voltage reflected on the primary winding during the second interval should be -Vload/n - i/n * Rsecondary/n. But this does not seem to be correct. The schematic of a flyback converter is:

Any help/pointer will be appreciated. Thanks

A:
Any help/pointer will be appreciated

And

how do we model the the secondary transformer resistor during the
  second interval (when the mosfet is off and diode conducts).

You can model the secondary resistance as a simple resistor in series with the diode.

If the turns ratio is 1:n, the current during the second interval
  would be i/n

Here's where it falls apart. At the instant the MOSFET disconnects the primary, the primary current can be called \$I_{P(PK)}\$ and this transfers to a secondary current peak of \$I_{P(PK)}/n\$. Thereafter, the current is falling from that peak towards zero like this for example: -

Picture from here showing the \$\color{green}{\text{secondary current}}\$ of a 2:1 step-down flyback transformer operating (in this example) in DCM at a duty of 0.34.
As can be seen, the secondary current ramps down from \$I_{P(PK)}/n\$ towards zero amps.

So the voltage drop across the secondary winding resistor would be
  i/nRsecondary.*

Correct if assuming an ideal diode and we are talking about \$I_{P(PK)}/n\$ at the instant the 2nd phase of the switching cycle begins. Clearly, as \$I_{S}/n\$ falls, the volt drop gets smaller because the current gets smaller.

*As per my understanding, the voltage reflected on the primary winding
  during the second interval should be -Vload/n - i/n * Rsecondary/n.*

Given the dot notation in the transformer, the reflected voltage on the primary (at the MOSFET drain) becomes more positive than the supply rail i.e. the minus sign is an error. The flyback on the primary raises the drain above the power (source) voltage by: -
$$\dfrac{V_{LOAD}}{n} + \dfrac{I_{LOAD}\cdot R_{SECONDARY}}{n} + \dfrac{V_{DIODE}}{n}$$
$$ = L_{SECONDARY}\cdot \dfrac{d(I_{LOAD})}{n\cdot dt} + \dfrac{I_{LOAD}\cdot R_{SECONDARY}}{n} + \dfrac{V_{DIODE}}{n}$$
This does not take into account spurious overshoots caused by leakage inductance in the windings.


text:
Q: Android add row to ListView with custom adapter Having a bit of problems with android.
Si heres whats going on, I have a ListView with a custom adapter, what iam tring to do is add rows dynamicly, heres the code:
Adapter:
public class ProductAdapter extends ArrayAdapter<Product>{

    Context context;
    int layoutResourceId;
    String data[] = null;

    public ProductAdapter(Context context, int layoutResourceId,String[] data) {
        super(context, layoutResourceId);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data=data;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ProductHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ProductHolder();
            holder.nameText = (TextView)row.findViewById(R.id.product_name);
            holder.quantityText = (EditText)row.findViewById(R.id.quan_text);

            row.setTag(holder);
        }
        else
        {
            holder = (ProductHolder)row.getTag();
        }

        Product product = DBAdaptor.getProductByName(data[position]);
        holder.img=(ImageView)row.findViewById(R.id.imgIcon);
        holder.nameText.setText(product.getName());
        holder.quantityText.setText(" ");

        return row;
    }

    static class ProductHolder
    {
        ImageView img;
        TextView nameText;
        EditText quantityText;
    }
}

Here's My Main Activity:
public class Main extends Activity
{
    public ListView lstView;
    ProductAdapter productListAdapter;
    DBAdaptor mDb;
    @Override
    protected void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
        openDB();
        productListAdapter = new ProductAdapter(this,        R.layout.shoping_list_row,getAllProducts());
        Bundle b = this.getIntent().getExtras();
        if(b!=null)
        {
            Product p =(Product) b.getSerializable("Product");
            productListAdapter.add(p);
            productListAdapter.notifyDataSetChanged();
        }

    }

}

Theres no error coming up but nothing is been add'd to the listView
Kind Reggards,

A: The ArrayAdapter relies heavily on its own private Array. You should pass data in the appropriate super constructor:
super(context, layoutResourceId, data);

Then you need to change this line:
Product product = DBAdaptor.getProductByName(data[position]);

To:
Product product = DBAdaptor.getProductByName(getItem(position));

(You also don't need to call notifyDataSetChanged() when using methods like ArrayAdapter#add(). It calls notifyDataSetChanged() for you.)

If you want your adapter to use your local copy of data you will need to override getCount(), getItem(), add(), etc. to use data... but by the time you have corrected everything you won't be using much of ArrayAdapter any more, you may as well extend BaseAdapter.
Though it looks like you want to work with a database (openDB()). You should use Cursors and CursorAdapters since they are much more efficient than converting a table to an Array.


text:
Q: Typescript Vue project breaking when updating to ^2.5 from 2.4.2 I have an old Vue project that I want to update from 2.4.2 to a newer supported version. I found that the underlying problem comes with 2.5 but I can't find anything in release notes that might affect the problems I am having.
My project uses webpack and all components are written in Typescript and end with .ts
It also utilises a dependancy called 'av-ts', that allows to build class style components with @Prop and @Component decorators.
They look like this:
import { Component, p, Prop } from 'av-ts';
import * as Vue from 'vue';

@Component({
  template: require('./animated-icon.component.html')
})
export default class AnimatedIconComponent extends Vue {
  @Prop public icon: any = p({
    type: String,
    required: false,
    default: ''
  });

  @Prop public width: any = p({
    type: Number,
    required: false,
    default: 24
  });

  @Prop public height: any = p({
    type: Number,
    required: false,
    default: 24
  });

  @Prop public classes: any = p({
    type: String,
    required: false,
    default: ''
  });

with main.ts and home.ts having the following structure:
import * as Vue from 'vue';
import AnimatedIconComponent from './components/animated-icon/animated-icon.component';

Vue.use(Vuex);
Vue.use(VueScrollTo);
Vue.use(Toasted, notificationConfig);
Vue.use(VeeValidate, validationConfig);
Vue.use(VueTippy);
Vue.use(VueCookie);
Vue.use(VueResource);
Vue.use(VueTouch, { name: 'v-touch' });

Vue.component('animated-icon', AnimatedIconComponent);

Vue.directive('animated-icon-trigger', AnimatedIconTriggerDirective);

declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    store?: Store<any> | undefined;
  }
}

export const app = new Vue({
  el: '#vue-app',
  store: new Vuex.Store(AppStore)
});

This setup works perfectly fine with the current version but once I update vue to 2.5 the whole project falls apart starting with the following error on the @Component decorator in the example component.
Decorator function return type 'VClass<Vue>' is not assignable to type 'void | typeof AnimatedIconComponent'.
  Type 'VClass<Vue>' is not assignable to type 'typeof AnimatedIconComponent'.
    Type 'Vue' is missing the following properties from type 'AnimatedIconComponent': icon, width, height, classes -ts(1270)

These are the packages installed:
 "dependencies": {
    "animejs": "2.2.0",
    "awesomplete": "1.1.2",
    "core-js": "3.6.4",
    "custom-event-polyfill": "0.3.0",
    "file-saver": "1.3.3",
    "inputmask": "3.3.10",
    "moment": "2.22.2",
    "numeral": "2.0.6",
    "smoothscroll-polyfill": "0.4.0",
    "url-search-params-polyfill": "2.0.3",
    "vee-validate": "2.0.0-rc.19",
    "vue": "^2.5.0",
    "vue-cookie": "1.1.4",
    "vue-multiselect": "2.0.6",
    "vue-resource": "1.3.4",
    "vue-scrollto": "2.7.10",
    "vue-tippy": "0.3.3",
    "vue-toasted": "1.1.22",
    "vue-touch": "2.0.0-beta.4",
    "vuex": "2.3.1"
  },
  "devDependencies": {
    "@types/file-saver": "1.3.0",
    "@types/node": "8.0.51",
    "av-ts": "0.11.0",
    "copy-webpack-plugin": "4.2.0",
    "css-loader": "0.28.7",
    "cssnano": "3.10.0",
    "extract-text-webpack-plugin": "3.0.2",
    "file-loader": "1.1.5",
    "filemanager-webpack-plugin": "2.0.1",
    "html-loader": "0.5.1",
    "html-webpack-plugin": "2.30.1",
    "postcss-cssnext": "3.0.2",
    "postcss-loader": "2.0.8",
    "postcss-smart-import": "0.7.5",
    "postcss-url": "7.1.2",
    "prettier": "1.19.1",
    "rimraf": "2.6.2",
    "style-ext-html-webpack-plugin": "3.4.5",
    "style-loader": "0.19.0",
    "ts-loader": "3.2.0",
    "tslint": "5.15.0",
    "typescript": "2.4.2",
    "uglify-es": "3.1.9",
    "uglifyjs-webpack-plugin": "1.0.1",
    "vue-hot-reload-api": "2.1.0",
    "vue-loader": "16.0.0",
    "vue-template-compiler": "2.4.2",
    "vue-ts-loader": "0.0.3",
    "webpack": "3.8.1",
    "webpack-dev-server": "2.9.4",
    "webpack-merge": "4.1.1"
  },
  "peerDependencies": {
    "vue": "^2.5.0"
  },
  "optionalDependencies": {
    "fsevents": "1.1.2"
  },

I think the issue might be with 'vue-ts-loader' but I am not quite sure what it does.
Help is appreciated!


text:
Q: Dynamically adding types to a jaxb context I have multiple plug-ins in my RCP-based project. I want to be able to define @XMLElements in one plug-in that can then be marshaled / un-marshaled from the core plugin. To do so, I report the classes that are serializable as soon as the plug-in is loaded. However, dynamically adding classes seems to be not supported by the JAXBContext. I implemented a work-around by holding all classes in a list and creating a new JAXBContext every time some new classes are reported based on that list, but this solution is not really nice.
Is there a better way to do that?

A: You definitely can not add classes dynamically to a JAXBContext.  This has to do with maintaining the thread safety of JAXBContext.
I have recently posted an example on my blog explaining how to leverage the @XmlAnyElement annotation to generate a generic message that could have different payloads:

*

*http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html
Root Object
The root element for the body property will be controlled by that objects @XmlRootElement.
package message;

import javax.xml.bind.annotation.*;

@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
    @XmlAttribute
    private String to;

    @XmlAttribute
    private String from;

    @XmlAnyElement
    private Object body;
}

Creating the JAXBContext
Instead of creating the JAXBContext on an array of classes, the JAXBContext could be created on a context path:
JAXBContext.newInstance("message:customer:product");

This context path includes 3 package names seperated by the colon ':' character.  In each of these packages we need to include a file named jaxb.index with a list of files.  Below is an example of the jaxb.index file in the customer package:
Address
Customer

When we want to add a model to represent orders to our framework we would extend our JAXBContext creation to like (this String could be passed in as a variable):
JAXBContext.newInstance("message:customer:product:order");


text:
Q: There exists $i, j \in \mathbb{N}$ such that $n=3i+5j$ for $n\ge 8$
Prove that there exists $i, j \in \mathbb{N}$ such that $n=3i+5j$ for $n\ge 8$

I'm having a hard time with this exercise, I'm trying to prove it by induction:
Basis step:

*

*$n=8 \implies 8=3\cdot1+5\cdot 1$

*$n=9 \implies 9=3\cdot3+5\cdot0$

*$n=10 \implies 10=3\cdot0+5\cdot2$
Induction step:
If it's true for $n=h$ then it must be true for $n=h+1$.
So now, I don't know how to begin proving that $k+1=3i+5j$.

A: Hint: Go from $n$ to $n+3$, that is easyer since you have base for $8$, $9$ and $10$:
If $$n=3a+5b$$ then $$n+3 = 3(a+1)+5b$$

A: Hint $:$ $3$ and $5$ are relatively prime to each other.

A: Take any $n>7$. Set $j = floor(n/5)$. if $3|n-5j$ then we are done.
Note than exactly one of $x,x+5,x+10$ is divisible by 3 if $x\in \mathbb N$
Now, if $n = 8,9,10$, we know the solution. if $n>10$ then current $j\ge2$ so consider $n-5j+5$ and $n-5j+10$.
say $3|n-5j+10$. then set $j = floor(n/5)-2$ and you're done
say $3|n-5j+5$ . then set $j= floor(n/5)-1$ and you're done

A: Assuming you mean $i,j\in\mathbb{Z}$ we can easily show that we can write $1=3i+5j$ for some $i,j\in\mathbb{Z}$.
Indeed, choose $i=-3$ and $j=2$. Suppose we get an integer $n$ then we know $n=1\cdot n=(-3\cdot 3+2\cdot 5) n= 3(-3n)+5(2n)$.
So we can simply choose $i=-3n$ and $j=2n$.

A: Trick is induction step doesn't need to be base case $n = 8$ and the induction step from $k\to k+1$.
You can have base cases $n=8,9,10$ and induction step from $k \to k+3$.  So the base case $n=8$ will give you $k=8,11,14,17.....$ and the base case $n=9$ will give you $k=9,12,15,18,....$  and base case $n=10$ will give you $k =10,13,16,19,.....$ and between the three base cases and the ability to induct from one case to the case three steps up... that's enough to conclude it's true for all.
Now to figure out the induction step:  if $k = 3i + 5j$ then we can find  $k+3 = ......$  Well, that's just too easy, isn't it?
.... alternative....
$1 = 2*3 - 1*5$ and $1 = 2*5 - 3*3$.
So if $k = 3*i + 5*j$ then $k+ 1 = 3(i+2) + 5(j-1)$ or $k+1 = 3(i-3) + 5(j+2)$.
If $j \ge 1$ we can do $k+1 = 3(i+2) + 5(j-1)$.  If $i\ge 3$ we can do $k+1 =3(i-3) + 5(j+2)$.
So we can always go from $k\to k+1$ so long as either $j \ge 1$ or $i \ge 3$.
But what if $j \le 0$ and $i\le 2$?  Well, then $n\le 3*2 + 5*0 = 6$.  Which is not an issue if our base cases are $n = 8,9,10$.


text:
Q: Store Private Keys Wallet I'm working at a crypto wallet extension for a startup and currently we are facing the issue of storing private keys after we generate them from a mnemonic phrase. I was thinking about storing those password in the local localStorage as an encrypted format using AES but this doesn't seems to be good enough.
I was also thinking about using the chrome.storage but this one seems to have the same issue of not being secured.
As for the chrome.filesystem this one is deprecated.
If anyone has an idea of how we could store private keys safely on the user's machine please let me know.


text:
Q: Erasing multiline #define macros with php regexp (preg_replace) I am trying to erase multiline macros in C file with PHP regexp
This one of the examples
this one should stay
#define HI    something is here ()d5gf           \
dgkdflgj \
it ends here
this one should stay
        #define HII something is here 2
this one should stay

Output should look like this:
this one should stay
this one should stay
this one should stay

I am using this regexp, but it doesn't work properly:
preg_replace("/#define[^\n\\]+(\\\n[^\n\\])*/u", "", $input_lines);

Note: the file is in UTF-8, thats why the u in preg_replace.

A: You can use this pattern:
$pattern = '~#define(?=\s)(?>.*\\\\\R)*.*\R?~u';
$result = preg_replace($pattern, '', $code);


text:
Q: Dynamic jquerymobile colum toggle not getting refreshed I am using jquerymobile 1.3 -> column toggle Table widget.
http://view.jquerymobile.com/1.3.0/docs/widgets/table-column-toggle/
I am creating the rows and columns dynamically. When I do this, the column toggle mode doesn't work. If I hardcode the data, it works. What could be wrong?
I am also refreshing as suggested in their documentation.
$( "#myTable" ).table-columntoggle( "refresh" );

My Javascript code is straight forward.
var tBody = document.getElementById('idTBody');
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.innerHTML = "Some string";
tr.appendChild(td);
tBody.appendChild(tr);

idTBody is an id assigned to Tbody tag.

A: It seems that it is a known bug in jquerymobile in 1.3.0 and will be fixed in 1.3.1.
Here's the link --> https://github.com/jquery/jquery-mobile/issues/5640 and here is the tracker link -->https://github.com/jquery/jquery-mobile/issues/5570


text:
Q: HTML OnClick image source changes in web, but not mobile I'm working in Wordpress with the Elementor block builder and I'm trying to have a .gif image switch sources to another .gif image. The OnClick event I have works perfectly fine via web, but not mobile. I've searched endlessly and have made sure another element is not blocking the touch event, added OnTouch, etc but to no avail.

A: Change onClick to onclick:

HTML attributes are case sensitive.


text:
Q: Is there way to export overleaf document in to a .doc or .docx file? I'm trying to convert an overleaf project to a .doc or .docx file. Does anybody know if this even possible?

A: I have actually had a lot of issues with pandoc when trying to convert a scientific paper, especially concerning resized/split images and missing references.
However I had very acceptable results that only needed minor polishing when using a free web conversion service (https://smallpdf.com/pdf-to-word) to convert the .pdf that I generated from Overleaf to a .docx file.

A: You can try using pandoc: https://pandoc.org/
Use the following command:
pandoc -o output.docx -t docx  input.tex

A: You can use Microsoft word to open the pdf downloaded from overleaf.
The pdf will be automatically converted to a normal word document (enable you to comment and everything).


text:
Q: NextAuth - Doesn't redirect to callback url but stays on the singin page I am working on nextjs & nextauth project, with custom signin page. Below are the configurations
Package.json
"next": "^12.0.8"
"next-auth": "^4.2.1"

[..nextauth].js
pages:{
  signIn:'/auth/signin'
},
callbacks: {
    async redirect({ url, baseUrl }) {
      console.log('redirect : '+url+' : '+baseUrl);
      if (url.startsWith(baseUrl)) return url
      // Allows relative callback URLs
      else if (url.startsWith("/")) return new URL(url, baseUrl).toString()
      return baseUrl;
    }
  }

I have a middleware in my profile folder, this is done to secure the files inside this folder. Which should be visible only when user signin.
Folder Structure :

_middleware.js
export { default } from "next-auth/middleware"

Issue : When i try to open the files inside profile folder, it shows the signin screen(working as expected) after successfully signing in the page doesn't redirect to callback url, it still stays on the signin page.


text:
Q: What event fire when you attach a file/attachment on the record page? I've created a lightning component that shows a table of all contentversions related to the record detail page you are on.
However, if upload/add a new file using the "Files" related list, it doesn't update the component I created..
Is there any lightning event I could use to refresh this automatically?

A: Your problem is very similar (not exactly same) to one asked in this question. The answer to this is though same.
You cannot utilize any standard component to interact with any of your custom component. In your scenario, you are using the standard "Files" related list, so there's no way capture any event from that to be able to utilize it in your custom component.
The only way I find you may be able to refresh your component with the uploaded file is to keep on "polling" or "refreshing" your component at regular intervals, but this can be an overhead at times.
The other option was, if you had implemented the file upload feature in a custom way using lighting:fileUpload, you could have used the onuploadfinished. With that you could have raised an event with every upload, so that your other component handles that and refreshes the data every time you upload a file.

A: Once you upload the file, you need to refresh the tab by using event="force:refreshView" in cmponent.
<aura:handler event="force:refreshView" action="{!c.RefreshTab}"/>

In JSController you need to fire this event in order to refresh the tab after your file gets uploaded.
 action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result=response.getReturnValue();
                $A.get('e.force:refreshView').fire();

            }

For more information refer this link:
https://developer.salesforce.com/docs/component-library/bundle/force:refreshView/documentation


text:
Q: jquery: How to know element hover on another element I have problem with my case, this is my code:
HTML code:

CSS code:
.wrapper {
    position: relative;
    width: 800px; height: 400px;
    margin-left: 100px;
}
.elem {
    position: absolute;
    top: 10px;
    width: 100px; height: 100px;
}
.green {
    left: 10px; background: green;
}
.red {
    left: 110px; background: red;
}
.blue {
    left: 210px; background: blue;
}
.Line {
    position: absolute;
    width: 10px; height: 500px;
    background: yellow;
    left: 60px;
}

JavaSript code:
$(document).ready(function() {
    var img = $('.Line');
    var offset = img.offset();

    function mouse(evt){
        var center_x = (offset.left) + (img.width()/2);
        var center_y = (offset.top) + (img.height()/2);
        var mouse_x = evt.pageX; var mouse_y = evt.pageY;
        var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
        var degree = (radians * (180 / Math.PI) * -1) + 90;
        img.css('-moz-transform', 'rotate('+degree+'deg)');
        img.css('-webkit-transform', 'rotate('+degree+'deg)');
        img.css('-o-transform', 'rotate('+degree+'deg)');
        img.css('-ms-transform', 'rotate('+degree+'deg)');
    }
    $(document).mousemove(mouse);
});

I want to when yellow element move on green element, green element add new class name, Apply for red element or blue element. How to do it.
Thanks,

A: I believe you want to do something like this:
function customAddClass(d)
{
    if(d>160 && d<190)
    {
        $(".elem").removeClass('test');
        $(".green").addClass('test');
    }
    else if(d>=190 && d<215)
    {
        $(".elem").removeClass('test');
        $(".red").addClass('test');
    }
    else if(d>=215 && d<235)
    {
        $(".elem").removeClass('test');
        $(".blue").addClass('test');
    }
}

DEMO


text:
Q: Visual Studio ComboBox won't cycle through items with up/down arrows once users types I have a userform with a dropdown combobox that is filled with items when the form is opened. If the box has focus, the up/down arrow keys will cycle through the items (as it should), or the user can select from the drop down list and still be able to use the up/down arrows from there. If the user starts typing, the box is set to append from the list items, but that disables the up/down arrow keys from cycling through ALL the items. At that point, it only cycles through the items that start with whatever the user typed. I would like it to erase the typed data and cycle through all the combobox items (starting at the index was whatever was appended) just like it does in the VBA version.
Even if the user types something, then selects a completely different item from the dropdown, the next time up/down keys are pressed, it only goes back to whatever was typed.
I attempted to handle this in the arrow up/down keydown (or keyup) event as follows:
Private Sub SeriesBox_KeyDown(sender As Object, e As KeyEventArgs) Handles SeriesBox.KeyDown

    Dim CurIndex As Integer = SeriesBox.FindStringExact(SeriesBox.Text)
    Select Case e.KeyCode

        Case Keys.Down

            SeriesBox.Text = String.Empty
            SeriesBox.SelectedIndex = CurIndex + 1

        Case Keys.Up

            SeriesBox.Text = String.Empty
            SeriesBox.SelectedIndex = CurIndex - 1

    End Select

End Sub

The arrow keys don't actually enter this sub, so I tried adding:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keydata As Keys) As Boolean

  If keydata = Keys.Right Or keydata = Keys.Left Or keydata = Keys.Up Or keydata = Keys.Down Then
    OnKeyDown(New KeyEventArgs(keydata))
    ProcessCmdKey = True
  Else
    ProcessCmdKey = MyBase.ProcessCmdKey(msg, keydata)
  End If

End Function

But this didn't seem to make a difference. Is there something I am missing?

A: This may work:
First set you combobox's AutoCompleteMode and AutoCompleteSouce to None
Then paste this to your code:
 Private Sub SeriesBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SeriesBox.TextChanged
    For Each it As String In SeriesBox.Items
        If Not SeriesBox.Text = it Then
            If it.Contains(SeriesBox.Text) Then
                Dim length As Integer = SeriesBox.Text.Length
                SeriesBox.Text = ""
                SeriesBox.Text = it
                SeriesBox.Select(length, SeriesBox.Text.Length - length)
                SeriesBox.SelectedItem = SeriesBox.Text
            End If
        End If
    Next
End Sub


text:
Q: R - create list from dataframe and print in markdown here is my dataframe
dt <-
  data.frame(
    year = c(2018, 2019, 2020),
    sales = c(123, 987, 852)
  )

In my markdown document I print data this way
datatable(
  dt,
  escape = F,
  rownames = F,
  filter = 'top',
  options = list(
    pageLength = 999,
    dom = "t",
    columnDefs = list(list(className = "dt-center", targets = "_all")),
    ordering = T)
) %>%
  formatCurrency(c("sales"), digits = 1)

My actual dataframe is much bigger, I'd like to split it by year and print each year in a separate datatable. Also I'd like to print h4 header for each section.
I experimented with lapply this way, but I can't make it to print in markdown and I don't know how to add that header.
t_list <-
  lapply(split(dt, dt$year), function(df) {

    datatable(
      df,
      escape = F,
      rownames = F,
      filter = 'top',
      options = list(
        pageLength = 999,
        dom = "t",
        columnDefs = list(list(className = "dt-center", targets = "_all")),
        ordering = T)
    ) %>%
      formatCurrency(c("sales"), digits = 1)
})

A: You could use htmltools::tagList:
```{r}
library(DT)
t_list <-
  lapply(split(dt, dt$year), function(df) {
    year <- unique(df$year)
    htmltools::tagList(htmltools::h4(year),datatable(
      df,
      escape = F,
      rownames = F,
      filter = 'top',
      options = list(
        pageLength = 999,
        dom = "t",
        columnDefs = list(list(className = "dt-center", targets = "_all")),
        ordering = T)
    ) %>%
      formatCurrency(c("sales"), digits = 1))
})
htmltools::tagList(t_list)

```


text:
Q: Comparing simulated to exact distributions I am looking to simulate a stochastic process using Monte Carlo methods. The stochastic RV is known to have a non-central $\chi^2$ distribution, so I draw pseudo-random numbers using R's rchisq function.
When I compare the probability density of the exact distribution to empirically measured probabilities from the simulated distribution, the two distributions correspond to each other very well for "benign" parameters. However, for extreme parameters, I find there is a major discrepancy between the two distributions, especially near 0 and on the right tail. This issue remains even when pushing the Monte Carlo parameters (time steps, number of scenarios) to very high levels.
It is unclear to me whether the issue lies with the random number generator or with the iterative procedure used for the simulation. Has someone come across such issues before, for any stochastic process whose distribution is known? Is there a way to use importance/rejection sampling or any other techniques to help get a better match for all parameters? Any references which deal with this issue would be much appreciated.

A: After running the simulation myself, I find no indication that R rchisq function is not an accurate random generator. Here is an illustration for 3 degrees of freedom and a range of non-centrality parameters:

Produced by the following R code:
 ncp=c(1,5,10,50,100,500)
    for (i in 1:6){
    x=rchisq(1e6,df=3,ncp=ncp[i])
   hist(x,prob=TRUE,nclass=1234)
    curve(dchisq(x,df=3,ncp=ncp[i]),add=TRUE)}

The warning in the R documentation:

The code for non-zero 'ncp' is principally intended to be used for
       moderate values of 'ncp': it will not be highly accurate,
       especially in the tails, for large values.

must correspond to much higher values of 'ncp' as I did not spot any discrepancy even for ncp=1e12.
As a side remark, an reasonable alternative to using rchisq with non-zero ncp is to represent the $\chi^2_d(\lambda)$ variable as the sum of a $\chi^2_d$ variable and of a $\mathcal{N}(\sqrt{\lambda},1)$ variable.


text:
Q: Difference between queue implementations in Python One of the exercises (namely, #6) asks us to compare performance of queue implementations (with head in the beinning / at the end of a list). That sounds like there could be some difference, so I tried to figure it out. Here's my code
import timeit

class QueueStart(object):
    '''Queue implementation with head in the beginning of a list'''
    def __init__(self):
        self.items = []

    def enqueue(self, i):
        self.items.append(i)

    def dequeue(self):
        return self.items.pop(0)

    def isEmpty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

class QueueEnd(object):
    '''Queue implementation with head at the end of a list'''
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.insert(0, item)

    def dequeue(self):
        return self.items.pop()

    def isEmpty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

# store results for further plotting
start_add_list = [] # QueueStart.enqueue(item) runtimes for inputs of different sizes
start_pop_list = [] # the same for QueueStart.dequeue(item)
end_add_list = [] # the same for QueueEnd.enqueue(item)
end_pop_list = [] # the same for QueueEnd.dequeue(item)

for i in range(100000, 500000, 10000):
    qs = QueueStart()
    qs.items = list(range(i))
    qe = QueueEnd()
    qe.items = list(range(i))
    start_add = timeit.Timer('qs.enqueue(1)', 'from __main__ import qs')
    start_pop = timeit.Timer('qs.dequeue()', 'from __main__ import qs')
    end_add = timeit.Timer('qe.enqueue(1)', 'from __main__ import qe')
    end_pop = timeit.Timer('qe.dequeue()', 'from __main__ import qe')

    start_add_list.append(start_add.timeit(number=1000))
    start_pop_list.append(start_pop.timeit(number=1000))
    end_add_list.append(end_add.timeit(number=1000))
    end_pop_list.append(end_pop.timeit(number=1000))

And here are plots that reflect results of my experiment

It's known that insert and pop(index) are O(n). The interesting thing, though, is that from the graphs we see that insert(0, item) takes twice as long as pop(0). That observation made me wonder, why this is the case. On the surface, two methods look very similar, but, apparently, under the hood there's something interesting going on. So, the question is: could you help me figure it out?

A: Some reading on CPython's list implementation: http://www.laurentluce.com/posts/python-list-implementation/
Basically, lists are designed to have about twice as much memory as they need at any given time, so they can change length slightly without needing to reallocate memory.  When lists need more memory, they sometimes need to move the whole list to another location in memory that has enough space.  When they shrink, they can just free memory at the end of the list.


text:
Q: How does adding a primitive root of unity to a number field affect the ring of integers? We know that if $\xi$ is a primitive $n^\text{th}$-root of unity, then the ring of integers $\mathcal{O}_{\mathbb{Q}(\xi)}$ of $\mathbb{Q}(\xi)$ is $\mathbb{Z}[\xi]$.
Can we generalise this result to say much about the ring of integers $\mathcal{O}_{K(\xi)}$ of $K(\xi)$, where $K / \mathbb{Q}$ is some finite algebraic extension?
Is it the case that $\mathcal{O}_{K(\xi)} = \mathcal{O}_{K}[\xi]$?
If this is not generally true, do we have a characterisation of circumstances where this may hold?
Failing that, do we have an alternate description of $\mathcal{O}_{K(\xi)}$ in terms of $\mathcal{O}_{K}$?
I would appreciate any comments, or even just a reference for these kinds of results.

A: By a result in Hilbert's report, the ring of integers in a compositum KL of normal extensions is the obvious one generated by the rings of integers in $K$ and $L$ if the discriminants of $K$ and $L$ are coprime.
If the discriminants are not coprime, the result is fals in general. In particular, the ring of integers in ${\mathbb Q}(\sqrt{3},\sqrt{-1})$ is not ${\mathbb Z}[\sqrt{3}][\sqrt{-1}]$.


text:
Q: Download all dependencies of a jar from artifactory using gradle I have two jars A and B. I want to add a dependency between these two. So, I read a few examples available for this and came to a conclusion that we need to edit the pom.xml of B to add a dependency of A (adding info like group ID, artifactID and version of A). Then if we include B in our project, A will automatically be included. For adding the dependency information in pom.xml, I do this:
pom.withXml {
                    def node = asNode().appendNode('dependencies').appendNode('dependency')
                    node.appendNode('groupId', 'A')
                    node.appendNode('artifactID', 'a')
                    node.appendNode('version', '1.0.0')
                }

To use this in project, in my main build.gradle I write :
classpath 'B:b:1.0.0'
But I do not get A:a:1.0.0 included in project. So I am little confused about the approach that I am following.

A: The only mistake I was doing was writing 'artifactId' not 'artifactID'. this worked.


text:
Q: A question on the definition of $0$-tensor I'm working on the following question in Munkres.

Let $\omega$ be a $k$-form defined in an open set $A \subset \mathbb{R}^n$. We say that $\omega$ vanishes
  at $x$ if $\omega(x)$ is the $0$-tensor. Show that if $\omega$ vanishes at each $x$ in a neighborhood of $x_0$, then $d\omega$ vanishes at $x_0$.

I have a question on the meaning of $0$-tensor. Consider a generic $k$-form: $$\omega = \sum_{[I]} f_I \,dx_I$$
This means all $f_I$ are zero right?
In particular, can I choose $f_I\, dx_I$ in the sum so that they all non-zero, but their sum evaluates to zero?

A: Q1: yes.
Q2: no.
When evaluating at a point, $\omega(x)$ belongs a to vector space of dimension $\binom{n}{k}$ and the $dx_I$ are a linear basis of this space. In more advanced language, you start from a vector space $V$ of dimension $n$, then you build the $k$-th exterior power $\wedge^kV$. If $e_1,\ldots,e_n$ is a basis of $V$, then $e_{i_1}\wedge\cdots \wedge e_{i_k}$ where $I=\{i_1<\cdots<i_k\}$ where $I$ ranges over the size $k$ subsets of $\{1,\ldots,n\}$, forms a basis of $\wedge^k V$. In your situation the elements of this basis are denoted $dx_I$.

A: I guess it depends on what do you mean by the $dx_I$'s or from which set exactly you consider your multiindices $I$.
We have that $dx_1\wedge dx_2+dx_2\wedge dx_1=0$. So, in this sense, the answer is yes, the sum can be zero.
But if you consider just $dx_I=dx_{i_1}\wedge\cdots\wedge dx_{i_n}$, where $i_1<\dots<i_n$, then those are linearly independent. So, the answer is no.


text:
Q: Refer to values in JSS theme in the theme it self I'm using jss through react-jss.
Let's say that I have a theme where I have defined a base color. Then I want to define a default border in this theme, referring to the base color.
const theme = {
  baseColor: '#aaaaaa',
  defaultBorder: [[1, 'solid', this.baseColor]]
}

I haven't found a syntax for this. Isn't it possible? Do I have to define the color outside and use it both places?
const baseColor = '#aaaaaa';
const theme = {
  baseColor: baseColor,
  defaultBorder: [[1, 'solid', baseColor]]
}

A: This is how I'd do it. There maybe a better solution though.
mytheme.js :
export const baseColor = '#aaa'

const theme = {
  baseColor,
  defaultBorder: [[1, 'solid', baseColor]]
}

export default theme

The advantages I see in this are the following:

*

*Your theme will be "auto documented" as the project grows and easily
updatable.

*Exporting each constant like export const baseColor =
'#aaa' also makes your theme constants useable in the components if
needed.

*You could implement multiple themes based on just the
constants having a object structure "convention" with a little
modifications on the structure of the theme files.

A: It is basically a JavaScript question, not a JSS one. You can put it in a separate variable like you suggested. In order to use "this" you need to create a class.
So I would also recommend putting reusable stuff in separate variables or even into a separate object and if it grows even export it from a separate module.