Q: trying to run jiunt test cases spring boot application I tried to run junit test cases with spring boot application. But there is bean creating issue due to not finding setProxyTargetClass on PersistenceExceptionTranslationPostProcessor package.
An attempt was made to call the method org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V but it does not exist.
Below is my stack trace.
Description:
An attempt was made to call the method org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V but it does not exist. Its class, org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor, is available from the following locations:

 jar:file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class
    jar:file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-tx/5.1.4.RELEASE/spring-tx-5.1.4.RELEASE.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class

It was loaded from the following location:
file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar

Action:
Correct the classpath of your application so that it contains a single, compatible version of org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor

2020-07-30 12:49:55.741 ERROR 17624 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@73afe2b7] to prepare test instance [com.fanniemae.acquisitions.cdds.datafeed.task.UcdpCompDataFeedTaskHelperTest@5b251fb9]

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418) [surefire-booter-2.22.1.jar:2.22.1]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceExceptionTranslationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:228) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:707) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) ~[spring-boot-test-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.con

Here is my POM file.
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.fanniemae.acquisitions.cdds</groupId>
    <artifactId>ucdp-company-datafeed</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ucdp-company-datafeed</name>
    <properties>
        <java.version>1.8</java.version>
        <ucdp-ram-common.version>0.0.1-SNAPSHOT</ucdp-ram-common.version>
        <common.version>0.0.1-SNAPSHOT</common.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>

            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-ibatis -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-ibatis</artifactId>
            <version>2.0.8</version>
        </dependency>

        <dependency>
            <groupId>com.oracle.ojdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>19.3.0.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <!-- <version>1.6</version> -->
        </dependency>

        <dependency>
            <groupId>org.pojava</groupId>
            <artifactId>pojava</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <!-- <version>42.2.11</version> -->
        </dependency>

        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>addressing</artifactId>
            <version>1.3</version>
            <type>mar</type>
            <exclusions>
                <exclusion>
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>

            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.fanniemae.acquisitions.cdds.internal.dependentjar</groupId>
            <artifactId>rahas</artifactId>
            <version>1.3</version>
            <type>mar</type>
        </dependency>

        <!-- <dependency>
            <groupId>com.oracle.weblogic</groupId>
            <artifactId>wlthint3client</artifactId>
            <version>12.2</version>
            <scope>test</scope>
        </dependency> -->

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
        </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>

            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>

            </plugin>
        </plugins>
    </build>
</project>

Any help will be appreciated.

A: Remove the dependency to spring-ibatis - this is for Spring v 2 and you are using version 5! Look at the release date, this is from 2008.
mybatis-spring is enough for spring integration of mybats (see here)


Q: Finding pairs in a list I'm trying to look for pairs of elements in a list, assuming that they are the only pair in the list, and there are no more than 3 identical consecutive elements.
I have a function that takes in a list, and returns the index of the first element of the pair, if there is any. If not, then it returns -1
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where searchHelp xs n
        | searchHelp xs 0 = -1              -- no pairs found
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs n-1

For some reason, it is returning the error:
Couldn't match expected type `Bool' with actual type `Int'
In the expression: n
In an equation for `searchHelp':
    searchHelp xs n
      | searchHelp xs 0 = - 1
      | (xs !! n) == (xs !! (n - 1)) = n
      | otherwise = searchHelp xs n - 1
In an equation for `searchForPairs':
    searchForPairs xs
      = searchHelp xs ((genericLength xs) - 1)
      where
          searchHelp xs n
            | searchHelp xs 0 = - 1
            | (xs !! n) == (xs !! (n - 1)) = n
            | otherwise = searchHelp xs n - 1

It seems like it should work. Any ideas why it is not?

A: You have two problems. The first is in this line:
        | otherwise = searchHelp xs n-1

The compiler interperets this as (searchHelp xs n) - 1, not searchHelp xs (n-1), as you intended. The second problem is in you use of guards:
        | searchHelp xs 0 = -1              -- no pairs found

Since searchHelp xs 0 is not a boolean expression (you wanted to use it as a pattern), the compiler rejected it. I can see two easy solutions:
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where searchHelp xs n
        | n == 0 = -1              -- no pairs found
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs (n-1)

and
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where
      searchHelp xs 0 = -1         -- no pairs found
      searchHelp xs n
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs (n-1)

Now, unfortunately, although this works, it is terribly inefficient. This is because of your use of !!. In Haskell, lists are linked lists, and so xs !! n will take n steps, instead of 1. This means that the time your function takes is quadratic in the length of the list. To rectify this, you want to loop along the list forward, using pattern matching:
searchForPairs xs = searchHelp xs 0 where
    searchHelp (x1 : x2 : xs) pos
        | x1 == x2 = pos
        | otherwise = searchHelp (x2 : xs) (pos + 1)
    searchHelp _ _ = -1

A: @gereeter already explained your errors, I would just like to point out that you should not return -1 in case the answer is not found. Instead, you should return Nothing if there is no answer and Just pos if the answer is pos. This protects you from many kinds of errors.

A: I couldn't quite grok what you want to do, but from the code, it looks like you're trying to find two consecutive elements in a list that are equal.  Instead of using !! to index the list, you can use pattern matching to extract the first two elements of the list, check if they are equal, and continue searching the remainder (including the second element) if they are not.  If the list doesn't have at least two elements, you return Nothing
searchForPairs xs = go 0 xs where
  go i (x1:xs@(x2:_)) | x1 == x2 = Just i
                      | otherwise = go (i+1) xs
  go _ _ = Nothing

A: For what it's worth, here is a somewhat idiomatic (and point-free) implementation of what you are trying to do:
searchPairs :: Eq a => [a] -> Maybe Int
searchPairs = interpret . span (uncurry (/=)) . (zip <*> tail)
    where
    interpret (flag, res) = if null flag then Nothing else Just $ length res

Explanation: zip <*> tail creates a list of pairs of successive elements (using the reader Applicative type class). uncurry (/=) tests if such a pair is made of identical elements. Finally, interpret translates the result in a value of Maybe Int type.


Q: C# Event causing Session Variable Error ASP.NET 5 MVC 6 So I basically have an event that fired off when my connected cash receiver takes in money, and I'm using a session variable to store the index of the bill inserted, and I get an error that says:
My session variables work everywhere else correctly except here. Any idea why this is happening? Everywhere I look online it tells me to set up my session correctly which it is if my other ones work fine. This event is fired when on a view page with no other methods running. Any help is appreciated. If the information is too vague I apologize, I will provide more information if you need it to help me solve this problem. Thank you.
Edit: Stack

This is the event being fired where the SetString is causing the error.
 void validator_OnCredit(object sender, CreditArgs e)
    {
        Console.WriteLine("Credited bill#: {0}", e.Index);

        switch (e.Index)
        {
            case 1:
                HttpContext.Session.SetString("Test", "1");
                break;
            default:
                HttpContext.Session.SetString("Test", e.Index.ToString());
                break;
        }

        Thread.Sleep(500);
    }

A: 3) Updated Answer
Session Namespace Reference for beta(s) or RC1
Microsoft.AspNet.Session

Session Namespace Reference from CORE 1.0
Microsoft.AspNetCore.Session

2) Updated Answer - If accessing a session outside the controller then you need to inject the session into it as follows
public class TestClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public TestClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void SetString()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public string GetString()
    {
        return _session.GetString("Test");
    }
}

1) Initial Answer - Incorrect for current scenario... but if session isn't working this is a good place to start
From the error message I assume you are using .NET Core?
If so then the middleware is added sequentially so you need to ensure that your code intitialises Session Management first before it uses MVC
public void ConfigureServices(IServiceCollection services)
{
   // ...
   services.AddSession();
   // ...
}

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
    app.UseMvc();
    // ...
}


Q: Order dropdown by existing data SQL I have a list of records from a MySQL database. When a record is clicked it takes you to a page where you can update these records. I'm using a HTML form to display the data dynamically.
For example, if a game was released in 2007 I'd have a dropdown box with all the different years that it could be changed to.
My current SQL for the year dropdown is as follows;
SELECT DISTINCT gameYear FROM games ORDER BY gameYear

This displays the years in order. Is there a way to have them displayed in correct order (IE 2001, 2002, 2003 and so on) but have the existing year selected to begin with?
An example, a game with a year of 2007.
When I click the record and go to edit the game, I want the dropdown box to display the current value (2007) automatically. Then, when I select the dropdown I want the years to still be in order.

A: You can sort it this way:
select DISTINCT gameYear from game order by
  case
     when gameYear = 2007 then 0
     else gameYear
  end;

A: You probably fill the dropdown by looping over your SQL result set and output HTML <option> elements. You need to check inside this loop if the current loop value is equal to the year of your game. If it is add the selected HTML attribute.

A: SelectedYear  is Your  current Selected Year
SELECT '$SelectedYear' as gameYear
UNION
SELECT * FROM
  (SELECT gameYear from game
  WHERE gameYear <> $SelectedYear
  ORDER BY gameYear)


Q: Read txt file line by line into char array C I know this question has been asked a few times, but never in a way that helps me figure out my problem. Essentially, I am reading four text files, all single words separated by a new line, and wanting to store these in a char array. I first count the number of lines in the file and then create a new char array, but for the life of me, I cannot figure out how to get it to read correctly. The last two lines are just to test if it has read the entire file correctly and they always come back a NULL and the question mark symbol.
I want each line to be at the next index in the char array.
Any help would be awesome! Thank you ahead of time.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

void countAnagrams(char* fileName);

void main ()
{
    char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};

    countAnagrams(fileNames[0]);
    countAnagrams(fileNames[1]);
    countAnagrams(fileNames[2]);
    countAnagrams(fileNames[3]);
}

void countAnagrams(char* fileName)
{
    int anagramCount = 0;
    int ch, lines = 0;

    //Count number of lines in file
    FILE *myfile = fopen(fileName, "r");
    do
    {
        ch = fgetc(myfile);
        if(ch == '\n')
            lines++;
    }while(ch != EOF);

    char contents[lines];
    int i = 0;
    for(i=1;i<lines;i++)
    {
        fscanf(myfile,"%s",contents[i]);
    }
    fclose(myfile);

    printf("%.12s\n",fileName);
    printf("number of lines: %d\n", lines);

    printf("first thing: %s\n", contents[0]);
    printf("last thing: %s\n", contents[lines-1]);
}

A: Here's a slight modification of your code that might help you.
The main points:

*

*You can use getline() instead of fscanf(). fscanf() can be used to read line-by-line, but it needs an explicit check for the end of line condition. getline() does this automatically.

*As kaylum pointed out, it's necessary to rewind() the file pointer back to the beginning of the file after counting the number of lines.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

void countAnagrams(char* fileName);

void main ()
{
    char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};

    countAnagrams(fileNames[0]);
    countAnagrams(fileNames[1]);
    countAnagrams(fileNames[2]);
    countAnagrams(fileNames[3]);
}

void countAnagrams(char* fileName)
{
    int anagramCount = 0;
    int ch, lines = 0;

    //Count number of lines in file
    FILE *myfile = fopen(fileName, "r");
    do
    {
        ch = fgetc(myfile);
        if (ch == '\n')
            lines++;
    } while (ch != EOF);

    rewind(myfile);

    char *contents[lines];
    int i = 0;
    size_t len = 0;
    for(i = 0; i < lines; i++)
    {
        contents[i] = NULL;
        len = 0;
        getline(&contents[i], &len, myfile);
    }
    fclose(myfile);

    printf("%.12s\n",fileName);
    printf("number of lines: %d\n", lines);

    printf("first thing: %s\n", contents[0]);
    printf("last thing: %s\n", contents[lines-1]);
}

A: I think that the problem is char contents[lines] and then fscanf(myfile,"%s",contents[i]) and the printf-s after. contents[i] is char type, and you want to read an array of chars into one char. contents needs to be declared as char* contents[lines] to be able to read a char array into contents[i].


Q: radio button in datagrid taking different group name? I have a datagrid whose autogenerated column property is true. Each cell of the grid is bound with a radio button. But radio buttons in different rows are taking different groupname where as all of them are to be in same group. Can anyone resolve this? TIA.
int j = 0;
foreach(DataGridItem dgItem in dgPhoto.Items) {
    for (int i = 4; i < dgItem.Cells.Count; i++) {
        RadioButton rad = new RadioButton();
        rad.ID = "Photo_" + j.ToString() + i.ToString();
        rad.Text = priceTxt;
        rad.Attributes.Add("name", "priceGrp");
        dgItem.Cells[i].Controls.Clear();
        dgItem.Cells[i].Controls.Add(rad);
    }
    j++;
}

A: Try Setting the GroupName Property in your code:
Use:
rad.GroupName = "priceGrp"


Q: Oracle-update multiple row value where the the id column equals specific values I am new in oracle and I want to update multiple row value where the column id = 1 , 2.
I tried this :
update Tester
set employee_phone_number = ( 0789456123,0789456321)
where employee_id in (1,2);

but it gives me "missing right parenthesis"
any help please and thanks in advance.

A: Another approach:
merge into
  tester
using (
  select 1 id,'0123456785' employee_phone_number from dual union all
  select 2 id,'0123456786' employee_phone_number from dual) new_values
on (
  tester.id = new_values.id)
when matched then update
  set employee_phone_number = new_values.employee_phone_number;

More words, but allows the values to be specified in only one place and extends to allow inserts where the id does not already exist.
http://sqlfiddle.com/#!4/8fc86/3

A: Try this instead:
update Tester
set employee_phone_number = CASE WHEN employee_id = 1 THEN 0789456123
                                 WHEN employee_id = 2 THEN 0789456321
                            END
where employee_id in (1,2);


Q: Good implementations of MVC in PHP I've done some development in RoR and I'm now trying to make something in PHP.
I think the MVC architecture is an ideal frame for my current project (users, application data, purchases, etc.)
Is there implementation of MVC on the web that is recommended or does PHP just not work in the same way as Rails and every MVC in PHP must be hand made?
My google fu is weak and I couldn't really find anything conclusive.

A: These four are MVC frameworks:

*

*CakePHP

*Symfony

*CodeIgniter

*Kohana
I prefer CodeIgniter and Kohana, because they're pretty focused and not bloated at all, and because they both, besides being MVC, are also big on the convention over configuration principle, meaning you don't have to go around maintaining XML/YAML/etc config files of your classes, URL routes, etc.
In particular I like Kohana because it has this nifty file system-based configuration hierarchy (they call it "Cascading Filesystem") which basically means you have even less configuration nonsense to maintain, because based on where you put your app's files (classes, config files, etc), the framework will know which parts of the system will be overridden. So I'd recommend you give Kohana a test run. Beware though, it's relatively new and the documentation is kind of weak, so if your google fu is indeed weak as you say, then you might be better off going straight for CodeIgniter, which has been around for longer and thus has more docs. But I'd still keep an eye on the Kohana project.
Symfony is... too bloated for my taste (i.e. having to run scripts in order to "generate views" and whatnot), but I've seen some large successful projects running on it.

A: Rails is an MVC framework, for PHP you could use CodeIgniter or CakePHP both of those use the MVC design pattern. CodeIgniter is the bomb.

A: You can find more discussion about PHP frameworks here: http://www.quora.com/Whats-the-best-MVC-framework-for-PHP
I haven't looked into other frameworks, I have found Codeigniter to satisfy most of my requirements from an MVC framework.

A: Sure, Theres Codeignitor and Frostbite Framework.. Both are good, and easy to find via google. Here is a whole list of php frameworks: http://matrix.include-once.org/framework/simple

A: Everyone else pretty much nailed it. The only reason I'm adding on to this question is because you use Ruby on Rails, and as such, CakePHP is going to be the most similar framework for you.
I use CodeIgniter because it's very well-documented and lightweight (with very little magic), but that's just my personal preference. Cake will be most like what you're used to.

A: I think laravel is best for you. Remember, frameworks are for SSBs Small scale businesses. For large scale businesses you write your own framework with all planning, execution phases etc.


Q: Enable TLS in bitnami Redis Pod - Certificate issue I am trying to enable TLS in my redis cluster.
Followed this article to create self signed certificate.
https://blog.devolutions.net/2020/07/tutorial-how-to-generate-secure-self-signed-server-and-client-certificates-with-openssl/
After generation of certificates followed the steps as given by bitnami documentation as below:-
https://docs.bitnami.com/kubernetes/infrastructure/redis/administration/enable-tls/
deployed using below
tls.enabled="true"
tls.certificatesSecret="certificates-tls-secret"
tls.certFilename="server.crt"
tls.certKeyFilename="server.key"
tls.certCAFilename="ca.crt"

But after this not able to start redis pod, getting below error
Error accepting a client connection: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
I am guessing some issue with certificate chain but cannot figure out what. Can someone point me in right direction?


Q: looping and sentinel values I am trying to find average of inputted numbers by a user. The loop is supposed to repeat itself until the user inputs -9999 (sentinel value) this is what i have so far and it works in idle but the program doesnt end an give me the average when i type -9999. I am new to python and could use a little guidance thank you.
import random

numbers = [int(input("Please, enter number {}(-9999 to end")

if input("-9999"):

# will display prompt like "Please, enter number 1:"
print ("numbers entered:", numbers) # this will print the entered number

positives = [num for num in numbers if num > 0]
negatives = [num for num in numbers if num < 0]

# loop ends here

print ("Average negative number is :", sum(negatives)*1.0/len(negatives))
print ("Average positive number is :", sum(positives)*1.0/len(positives))
print ("Average of all numbers is:",sum(numbers)/len(numbers))

A: ns = []
while not ns or ns[-1] != -9999:
    ns.append(int(input("Please, enter number {}(-9999 to end"))))

A: ns = list(iter(lambda:int(input("Enter Number:")),-9999))

is a cool way to do it
iter can take a sentinal value to wait for as a second argument, if you use a function for the first argument
as an aside with your positive and negatives .... it seems it will ignore zeros (which may be intentional)...

A: This code will loop while you add numbers to your list and stop when you enter -9999. It will then throw the -9999 away so you can get on with your averaging. It's not compact, but it works and it's simple.
numbers = []

while True:
    numbers.append(input("Enter a number: "))   #append user input to 'numbers'
    if numbers[-1] == -9999:     #check to see if the last number entered was -9999
        numbers = numbers[:-1]   #if it was, modify numbers to exclude it
        break                    # and break the loop


Q: ASP dropdown list selected value I have a page with "date" field as drop down list and submit button. When I click on submit the selected value is displayed in grid view in other page.
Now in the grid view I have a field like "edit", when I click on that it is navigated to first page with that date value. The problem is that this time "date which is passed from grid view " is not shown selected value in drop down list.
<asp:TemplateField HeaderText="DOB" SortExpression="dob">
            <ItemTemplate>
                   <asp:Label ID="lbldob" runat="server" Text='<%# Bind("dob") %>'>
                   </asp:Label>
            </ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
                     <asp:LinkButton ID="hypeno" CommandName="cmdBind" runat="server" Text='<%# Eval("id") %>' CommandArgument='<%# Bind("id") %>'>
                     </asp:LinkButton>
           </ItemTemplate>
</asp:TemplateField>

Code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmdBind")
        {
            string id = e.CommandArgument.ToString();
            LinkButton lb = (LinkButton)e.CommandSource;

            Response.Redirect("/practice/registation.aspx?id=" + id +"&type=edit");
        }

    }

      string type = Request.QueryString["type"].ToString();
       if (type == "edit")
       {                 connection con = new connection();
                     DataSet ds;
                     ds = con.select("select dob from registration where id='"+Request.QueryString["id"].ToString()+"'");

      drddate.SelectedItem.Text= ds.Tables[0].Rows[0][0].ToString();
        }

A: Post your code, but sounds to me like you have to set the selected value in your dropdown in the grids onrowdatabound event - but I'm not entirely sure based on the vagueness of your question.


Q: How can I add an external JS file to my laravel controller file I'm new to Laravel and I wrote a piece of code to extract data from a database and display it in a tabular form using the Ajax.
Now I want to add 'onclick' function to the result. I've tried importing the external JS file but can't seem to get it right.
I would also appreciate an alternative approach. Here's my code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class courseController extends Controller
{
 /**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('course_registration');
}
public function search(Request $request)
{
    if($request->ajax())
    {
        $output="";

       $student=DB::table('dataentries')->where('ID_number','LIKE','%'.$request->search.'%')
                                        ->orWhere('name','LIKE','%'.$request->search.'%')->get();

        if($student)
        {
            foreach($student as $key => $student){
                $output.='
'.
                        ''.$student->ID_number.'	'.
                        ''.$student->name.'	'.
                        '
';

            }
            return Response($output);
        }
        else
        {

        }
    }
}

}


Q: Trim bar like the GarageBand and iMovie ones I'm creating a Mac app which needs a trim bar like the GarageBand and iMovie ones. I need a library to get the audio waves to draw them on a NSView. Anyone knows a good library for that?
I think he was referring to the track editor (cut/copy/paste/move).

A: There's a cool blog post on how to draw Waveforms by the author of the Capo audio editing software:
http://supermegaultragroovy.com/2009/10/06/drawing-waveforms/
I wrote Cocoa (Mac) code based on that, and it's not too hard. You can find that code here:
https://github.com/uliwitness/UKSoundWaveformView
Though it's far from a finished, shippable editor, it's under a permissive license (zlib) and could easily be used as a basis for a full editor.

A: Maibe this helps: Drawing waveform with AVAssetReader
and if the issue is to draw, then this may help: Parametric acceleration curves in Core Animation

A: This framework might help you out.  From the examples it looks like its pretty easy to use and works well.  It provides components to open an audio file, play it and draw the waveform.   You might need to implement the cut/copy/paste features on your own.


Q: Thread safety of the plus operator for Strings, optimizations included This post says that a += b is the equivalent of
a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

Let's say I have this code:
public class MultiThreadingClass extends SomeThirdPartyClassThatExtendsObject{
    public void beginmt(String st) throws IOException {
        //st is a thread number
        st = new File("c:\\somepath").getCanonicalPath()+"\\"+st;
        System.out.println(st);
    }
}

Assume that beginmt runs multiple times simultaneously (with thread numbers 1 to 15500) on a single instance of MultiThreading class. Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled?
c:\somepath\2
c:\somepath\1
c:\somepath\1
c:\somepath\4
c:\somepath\5
c:\somepath\6
c:\somepath\7
c:\somepath\8
c:\somepath\8
c:\somepath\10
...

Edit:
Will it be safe to say that the + operator won't get into some unsafe publication issue? I'm thinking the StringBuilder could be optimized into something that resembles an instance variable in which case it could be unsafely published.
Edit 2:
As far as the JLS, the abovementioned post, and a similar class file for the above code are checked, the StringBuilders to be used seem to have to get contained within different stackframes. However, I'd still like to check whether some form of aggressive optimization could cause the StringBuilders to be replaced by a centralized StringBuilder in some way. This sounds possible as it sounds logical for optimizers to optimize when it predicts that an object is just implemented in a non-constant way when in fact such object could be constant.
Found stringopts.cpp but haven't found the time yet to fully check it. I'm hopefully looking for answers involving details of this source file.
Edit 3:
I'm still looking for answers that include code on aggressive inlining for mutable objects.

A: Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled?
st is a method local variable, also st doesn't escape the method's scope so it is thread-safe. So, multithreading will have no effect on st . The messages can be printed out of order depending on which thread runs the method at what time.

A: As you don't share any field between your threads, the order of printing can differ, but any problem concerning thread safety (race conditions) shouldn't appear.

A: No, there is no state that's being shared between different threads so the situation you described can not happen.
If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story.
How it works now is that st will be put on the execution stack, each thread has it's own execution stack and they don't share stuff from there. Therefore each thread has it's own value of st. When it's a member variable of a class it's in memory (single value) and all threads would try to use it (the same one).
@Edit: well I guess it is possible if you call the method several times with the same value :-))

A: The Java Language Specification states

The result of string concatenation is a reference to a String object
  that is the concatenation of the two operand strings. The characters
  of the left-hand operand precede the characters of the right-hand
  operand in the newly created string.

So, although a compiler is free to optimize how the concatenation happens, it must do so while following that rule, "a" + "b" becomes "ab". In an unthread-safe, shared StringBuilder, implementation that would potentially not be the case. That implementation would therefore not be correct and could not be considered Java.

A: Each thread will always have individual StringBuilder instances.
Thread-safety is no issue when threads don't share instances.
So, the following simple method ...
public class MyThreadSafeClass
{
  public String myMethod(String field1, String field2, String field3)
  {
     return field1 + field2 + field3;
  }
}

... will be compiled to use a local StringBuilder.
public class MyThreadSafeClass
{
  public String myMethod(String field1, String field2, String field3)
  {
     return new StringBuilder(field1).append(field2).append(field3).toString();
  }
}

Each time the method is entered, a new StringBuilder instance is created.
This instance is only used withing the scope of this thread.
You are correct however that StringBuilders are not always thread-safe. (see below)
If multiple threads start calling the saveEvent method, they may be using the builder simultaneously.
public class History
{
  // thread-safety issues !!!!
  // In fact, here you should use a StringBuffer or some locking.
  private StringBuilder historyBuilder = new StringBuilder();

  public void saveEvent(String event)
  {
     historyBuilder.append(event).append('\n');
  }

  public String getHistoryString()
  {
     return historyBuilder.toString();
  }
}

But compiler optimizations will not create these kind of constructions. The StringBuilder is always created and used only within one and the same thread.
We could try to make things more complex (static fields, multiple classloaders, ...) but always again, each StringBuilder instance is created and used by only 1 thread.
EDIT:
Perhaps useful to know: This optimization happens during the generation of the byte-code. There are other optimizations later on during JIT compilation, but this optimization is not one of them.  However the JIT compiler does have an important impact in the final performance.

A: I have to partially disagree. This sentence is incomplete / missleading:
"If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story."
What matters in the original example is that the expression on the right is a rvalue. If it were not, the outcome would have been different. I will explain a bit.
So yes, Strings are immutable, and beginmt() receives a final reference to a String and this means a final reference to an immutable heap memory area. JVM will make a copy of this final reference and whatever you do inside the beginmt(), it is done on this copy, and this copy, immediately after the string is modified (st = ...), will point to another memory area. Now the point is that this final heap memory area has no pointer to it, because it is created inside the method and it seems that nothing points to it. Well, almost! The JVM may intern the string and if another thread points to the same value as the interned value it could be possible that they would actually share the same heap address. Now having a race condition exactly here is very hard to detect, so I will make a synthetic example to illustrate what could happen in case the expression on the right is a lvalue (induced by JVM's String intern-al):
public class AnExample {
    private static final int N = 20000;
private static class Foo {
    static HashMap<String, Foo> foos = new
            HashMap<String, Foo>(N);

    static synchronized Foo createInstance(String i) {
        if (foos.containsKey(i))
            return foos.get(i);
        foos.put(i, new Foo(i));
        return foos.get(i);
    }

    String i;

    private Foo(String i) {
        this.i = i;
    }

    Foo inc() {
        synchronized(Foo.class){
            i += "1";
            return createInstance(i);
        }
    }

    @Override public String toString() {
        return i;
    }
}

private static class Bar {
    public void bar(Foo st) {
        st = st.inc();
        System.out.println(st);
    }
}

public static void main(String... args) {
    final Bar cucu = new Bar();
    for (int i = 0; i < N; i++) {
        final Foo st = Foo.createInstance(i + "");
        new Thread(new Runnable(){
            @Override public void run() {
                cucu.bar(st);
            }
        }).start();
    }

    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}
This will produce about 40% duplicates (I have less than 10100 unique values). Note that in the bar() method st = some_expression(st)
In my example I intentionally produce a lvalue just to show what might happen in case the JVM will intern the expression and it happens to have a reference to that (which is sent back in another thread to the same method).
The conclusion is that your code is not correct because "st is not a member variable of that class" and "st becomes a local, copied reference", etc - but because the expression on the right is a rvalue.


Q: Cannot get text of a span attribute using BeautifulSoup I am trying to get from the following
ΚΩΔ. 473768

the value of data-nodeid
I did the following
price_nodes = soup.find('span', attrs={'id': 'SkuNumber'})
datanode = price_nodes.select_one('span[data-nodeid]')

But I get "None"
How can I fix this? thank you

A: If price_nodes is correctly fill
i.e. price_nodes =
ΚΩΔ. 473768

You just have to do this:
datanode = price_nodes.get('data-nodeid')

Full code should be:
from bs4 import BeautifulSoup as soup

html = '
ΚΩΔ. 473768
'
page = soup(html, 'html.parser')
price_nodes = page.find('span', {'id': 'SkuNumber'})
datanode = price_nodes.get('data-nodeid')

A: from bs4 import BeautifulSoup

html = 'ΚΩΔ. 473768
'
soup = BeautifulSoup(html)

price_nodes = soup.find('span', attrs={'id': 'SkuNumber'})
print(price_nodes['data-nodeid'])


Q: using local notification data coming from web service I am new to IOS and wants to used Local Notification feature of iOS.
my problem is i do not know if i can go with local notification. in my case data will come from web service... it is like..no specific date. default time interval is 60 Sec. after 60 sec app has to call webservice which will return notification data..and after some validation i need to push to user.
and if user click on view details it will launch appand get data via webservice.
Is using localnotification will serve my purpose? or i have to go with other approach?
Please help.
Thanks in advanced.

A: I think this 60 second thing is you polling the server every 60 seconds to fetch new data, then if there is new data post a local notification?
This is kinda possible with iOS7 but not exactly every 60 seconds, sometimes not at all, But in general it is strongly frowned upon. Instead the webserver should send push notifications when new data is available, It saves the user battery life.
On iOS7 there are silent push notifications (just don't include the alert) that can ask the client to do the validation you mentioned, and If the user needs a notification you can create a Local Notification to alert the user in a change
You should give this documentation a long look, it isn't trivial work for a new iOS programmer:
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html
And here is a relevant Apple documentation quote "Local and push notifications serve different design needs. A local notification is local to an application on an iPhone, iPad, or iPod touch. Push notifications—also known as remote notifications—arrive from outside a device. They originate on a remote server—the application’s provider—and are pushed to applications on devices (via the Apple Push Notification service) when there are messages to see or data to download."

A: If you are trying to achieve this functionality to happen automatically/polling (i.e without user interaction like, clicking on the view details button)- the answer is a big NO at least not till iOS6.x
Your application cannot run for infinite length in background at-not till ios6.x. You may have to consider using APNS service to achieve this.
Otherwise, your approach on scheduling a local notification for ever 60 sec - The user clicks in the view option - the application comes up - You make a web-service call - Get the data - Validate the received data - Uploading to the server, looks fine to happen.
Will it not be annoying to the user getting notification for ever 60 sec & operating on the app to do whatever you intended to do? - Just curious.


Q: Create SVG components with scoped CSS I am creating React components that will render out various SVGs:
const Close = ({
  fill, width, height, float,
}) => (
  <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
    <title>x</title>
    <g id="Layer_2" data-name="Layer 2">
      <g id="Background">
        <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
        <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
      </g>
    </g>
  </svg>
);

It's very convenient to be able to supply various attributed to this component to control dimensions, colour, etc...
What I don't have a good solution for, however, is handling the styles in a DRY manner. Note the line elements have the same value for style. I presently have them written inline because if I added an embedded stylesheet, then I would get class name collisions with other SVGs I render elsewhere on the page (our SVG software uses the same classes over and over).
<style scoped> has been removed from the spec: https://github.com/whatwg/html/issues/552
Shadow DOM is not yet supported by Edge: https://caniuse.com/#feat=shadowdomv1
Is there any other alternative for scoping styles?

A: To combine the best of both worlds, you could create an external styles file, as you would for CSS, but with exported style objects. You could then import it into any file that needs it.
As example, main file:
import React, { Component } from 'react';
import { render } from 'react-dom';
import * as Styles from './svgstyles';

class App extends Component {
  render() {
    return (
      <div>
        <svg width="100" height="200" viewBox="0 0 100 200">
          <rect x="0" y="0" width="10" height="10" style={Styles.style1} />
          <rect x="15" y="0" width="10" height="10" style={Styles.style2} />
          <rect x="30" y="0" width="10" height="10" style={Styles.style3} />
          <rect x="45" y="0" width="10" height="10" style={Styles.style4} />
          <rect x="0" y="15" width="10" height="10" style={Styles.style4} />
          <rect x="15" y="15" width="10" height="10" style={Styles.style3} />
          <rect x="30" y="15" width="10" height="10" style={Styles.style2} />
          <rect x="45" y="15" width="10" height="10" style={Styles.style1} />
        </svg>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

And an external styles file:
export const style1 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "blue",
}

export const style2 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "green",
}

export const style3 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "yellow",
}

export const style4 = {
  ...style3,
  fill: "pink",
}

Live example here

A: If you just want to DRY up the code, you could create one style-object and reuse it:
const Close = ({
                 fill, width, height, float,
               }) => {
  const style = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 }
  return (
    <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
      <title>x</title>
      <g id="Layer_2" data-name="Layer 2">
        <g id="Background">
          <line style={ style } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
          <line style={ style } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
        </g>
      </g>
    </svg>
  );
}

This would also result in a small performance improvement since fewer objects would be created in each render cycle.

A: Actually, if I was in your place, Surely I use fonts instead of SVGs, but for your exact question, I prefer to use constant variables inside of my arrow function, just like below:
import React from 'react';

const Close = ({ fill, width, height, float }) => {
  const constStyle = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 };

  return (
    <svg
      width={`${width}px`}
      height={`${height}px`}
      viewBox="0 0 14.48 14.48"
      style={{ float: `${float}`, cursor: 'pointer' }}
    >
      <title>x</title>
      <g id="Layer_2" data-name="Layer 2">
        <g id="Background">
          <line style={constStyle} x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
          <line style={constStyle} x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
        </g>
      </g>
    </svg>
  );
};

export default Close;

Even, I make the line dimension variables as props, but I don't know what is your case exactly.
Hope this answer helps you.


Q: TFDMemTable lost/clearing data after filtering I have created a FDMemTable with following structure:
Cds_NaMenu := TFDMemTable.Create(nil);
Cds_NaMenu.FieldDefs.Add('ID', ftInteger);
Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger);
Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500);
Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger);
Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []);
Cds_NaMenu.CreateDataSet;
Cds_NaMenu.LogChanges := False;
Cds_NaMenu.IndexName := 'Ordem';

I put data in TFDMemTable like this:
Cds_NaMenu.Append;
Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1;
Cds_NaMenu.Post;

Well... The problem ocurrs when a set filtered property to True and back to False. The RecordCount property goes to 0; None data has found in, even I use saveToFile procedure. Aparently the data was losted.
_recCount := Cds_NaMenu.RecordCount; // Result = 867;
Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%');
Cds_NaMenu.Filtered := True;
_recCount := Cds_NaMenu.RecordCount; // Result = 0;
Cds_NaMenu.Filtered := False;
Cds_NaMenu.Filter := '';
_recCount := Cds_NaMenu.RecordCount; // Result = 0;

PS: With ClientDataSet, this code works perfectly

A: If you're working with a pure memory table, there should not be any problem to query record count by the RecordCount property. Maybe you expect having NULL and empty value records included in a filtered view when having filter Value LIKE '%%', but it's not so. When having dataset like this:
ID | Value
1  | NULL
2  | ''
3  | 'Some text'

And applying filter like this:
var
  S: string;
begin
  S := '';
  FDMemTable.Filtered := False;
  FDMemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%');
  FDMemTable.Filtered := True;
  { ← FDMemTable.RecordCount should be 1 here for the above dataset }
end;

The empty and NULL value records should not be included in the view. Here is a short proof:
var
  S: string;
  MemTable: TFDMemTable;
begin
  MemTable := TFDMemTable.Create(nil);
  try
    MemTable.FieldDefs.Add('ID', ftInteger);
    MemTable.FieldDefs.Add('Value', ftString, 500);
    MemTable.IndexDefs.Add('PK_ID', 'ID', [ixPrimary]);
    MemTable.CreateDataSet;

    MemTable.AppendRecord([1, NULL]);
    MemTable.AppendRecord([2, '']);
    MemTable.AppendRecord([3, 'Some text']);

    S := '';
    MemTable.Filtered := False;
    MemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%');

    ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 }
    MemTable.Filtered := True;
    ShowMessage(Format('Filtered count: %d', [MemTable.RecordCount])); { ← should be 1 }
    MemTable.Filtered := False;
    ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 }
  finally
    MemTable.Free;
  end;
end;

A: I think this is just a minor FD quirk.  The code below works as expected, with Cds_NaMenu declared as a TFDMemTable (though it would have been nice if you could have dropped the Cds_ to avoid confusion).
The key difference, I think, is the call to .Locate after the filter is cleared.  The reason I put it there is because it causes the dataset to scroll and, I imagine, to recalculate its RecordCount as a result.  Probably any other operation which causes a scroll would have the same effect, even MoveBy(0) - try it.
procedure TForm1.FormCreate(Sender: TObject);
var
  _recCount : Integer;
  ID : Integer;
  sTexto : String;
begin
  sTexto := 'xxx';  // added

  Cds_NaMenu.FieldDefs.Add('ID', ftInteger);
  Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger);
  Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500);
  Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger);
  Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []);
  Cds_NaMenu.CreateDataSet;
  Cds_NaMenu.LogChanges := False;
  Cds_NaMenu.IndexName := 'Ordem';

  Cds_NaMenu.Append;
  Cds_NaMenu.FieldByName('ID').AsInteger := 666;  // added
  Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1;
  Cds_NaMenu.Post;

  _recCount := Cds_NaMenu.RecordCount; // Result = 1

  ID := Cds_NaMenu.FieldByName('ID').AsInteger;  // added

  Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%');
  Cds_NaMenu.Filtered := True;
  _recCount := Cds_NaMenu.RecordCount; // Result = 0;
  Cds_NaMenu.Filtered := False;
  Cds_NaMenu.Filter := '';

  // Now force the dataset to scroll
  if Cds_NaMenu.Locate('ID', ID, []) then;  // added
  _recCount := Cds_NaMenu.RecordCount; // Result = 1;
  Caption := IntToStr(_recCount);  // added
end;


Q: Select every paragraph element that is not the first child of its parent What is the correct CSS selector, if I want to select every
 that is not the first element of its parent?
Like this snippet below, just reverse! (so 'second', 'third', 'fourth' are red, 'first' is normal)

p:first-of-type {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

A: You can use the :not negation pseudo-class. Note that when combining pseudo-classes, you must put the second pseudo-class inside of brackets as :not(:first-of-type):

p:not(:first-of-type) {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

Note that if you're specifically looking to select every element other than the first child of an element, you can use :not(:first-child). Note that the selector goes on the child element in this case though, not the parent:

.parent p:not(:first-child) {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

A: Very simply:

p+p {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

The next-sibling combinator (+) targets an element that is immediately preceded by another element.
So in this case, only p elements following another p are selected. This excludes the first p.
You may also be interested in the subsequent-sibling combinator (~), which is similar to the above, except the first element does not need to immediately precede the second.

A:

.text p:not(:first-child) {
  background: green;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.


Q: Internet Explorer 8 adds line breaks after link_to With the following code, IE 8 adds line breaks after the link_to. Its in a
 tag, so there should not be a line break. Even adding a CSS class to the link_to with display: inline does not help.

After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click <%= link_to "here", user_path(current_user) %>.

Here is the HTML that is generated:

After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click here.


Q: Error fetching data from api and display it I want to make a get request from my restApi and then display the data in a listView but for some reason it is not working.
The error I'm getting:

The getter 'length' was called on null.
Receiver: null
Tried calling: length

Api call (apiBaseHelper.dart)
 Future<List<Post>> getAllPosts() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;

final getPublishedPostUrl = "http://192.168.1.7:5000/post/all";
final response = await http.get(getPublishedPostUrl, headers: {
  'Accept': 'application/json',
  'Authorization': 'Bearer $value'
});
if (response.statusCode == 200) {
  List jsonResponse = json.decode(response.body);
  return jsonResponse.map((posts) => new Post.fromJson(posts)).toList();
} else {
  throw "something ";
}

}
PostListView
class PostListView extends StatelessWidget {
  final List<Post> posts;
  PostListView({Key key, this.posts}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.builder(
      itemCount: posts.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            Container(
              constraints: BoxConstraints.expand(
                height:
                    Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
              ),
              color: Colors.white10,
              alignment: Alignment.center,
              child: Card(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      contentPadding: EdgeInsets.all(10.0),
                      title: new Text(posts[index].title),
                      leading: new Image.network(
                        posts[index].picture,
                        fit: BoxFit.cover,
                        height: 40.0,
                        width: 40.0,
                      ),
                      subtitle: Text(posts[index].category),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    ));
  }
}

homePage.dart
class HomePage extends StatefulWidget {
final ApiBaseHelper apiBaseHelper = ApiBaseHelper();

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  Future<List<Post>> futurePost;
  @override
  void initState() {
    super.initState();
    futurePost = ApiBaseHelper().getAllPosts();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.teal,
      body: new Padding(
        padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
        child: FutureBuilder<List<Post>>(
          future: ApiBaseHelper().getAllPosts(),
          builder: (context, AsyncSnapshot<List<Post>> snapshot) {
            if (snapshot.hasError) {
              print(snapshot.error);
            }
            return snapshot.hasData
                ? PostListView()
                : Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

I have been working on it for like 2 days and I don't know where the problem exactly
I'm sorry if it's too much code. thank you in advance

A: This code section here ,
  return snapshot.hasData
                ? PostListView()
                : Center(child: CircularProgressIndicator());

Add PostListView(posts:snapshot.data)
Tell me if it works.


Q: Why is my shellscript execution of a gradle build behaving differently on jenkins than on cli? When I perform ./gradlew build on command line, gradle downloads and unzips the correct wrapper dist version and continues to download dependencies and build the project.
However when I perform the same within a shellscript on jenkins, it only downloads the gradle wrapper dist zip and tells me there are no dependencies.
How come no dependencies are seen this time ?
------------------------------------------------------------
Root project
------------------------------------------------------------

classpath
No dependencies

BUILD SUCCESSFUL in 9s

I have already (first) tried using the gradle plugin on jenkins, same result.                 ANDROID_HOME is the same and set, I am using the same user on the cli.
Java version 8, Gradle 4.1, Android 25, Android build-tools 26.0.2
When i let jenkins invoke a script holding this build command it does work, but not directly. (current quickfix)
Does anyone have an idea what is going wrong ?

A: It now works, I am not sure what changed to fix this other than the fact i have placed the commands in a function this time, but it is all working as desired.


Q: Select 2 ajax search fires when pressing ctrl keys I have the following select 2 field:
$("select#edit-property-id").select2({
  multiple: false,
  width: 150,
  delay: 250,
  placeholder: "Type",
  minimumInputLength: 1,
  ajax: {// instead of writing the function to execute the request we use Select2's
  // convenient helper
    url: "/tell/product_chosen_search",
    dataType: 'json',
    data: function (params) {
      return {
        term: params.term, // search term
      };
    },
    processResults: function (data, page) {
      return {
        results: data
      };
    },
  },
});

The ajax search fires correctly when I enter characters, however it also fires when I press keys such as ctrl, down button etc... How can I prevent that? Is there a setting?

A: This appears to be a defect in the new 4.0 version of Select2, which is still in beta.
jsfiddle
With v3.5.2, the following line in the updateResults function prevents the unnecessary ajax calls:
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;

jsfiddle
Here's a somewhat related issue. At least, I think both issues could be fixed at the same time. You may want to add a comment to that issue.


Q: Upload File to Wordpress with AJAX All,
I'm using a HTML5 uploader to upload some images. This is part of the file that sends the data to my PHP processing script:
var ajax    = $.ajax({
    url:        ajaxurl,
    //dataType:     options.ajaxDataType || 'json',
    type:       options.ajaxType || 'POST',
    cache:      false,
    data:       { name: $file.data('filename'), filename: $file.data('file'), file: evt.target.result, data: options.data, action: 'test_upload' },
    headers:    options.ajaxHeaders,

From the uploader they process the file upload with this code:
if (!empty($_POST)) {
    $error                  = false;
    $absolutedir            = dirname(__FILE__);
    $dir                    = '/tmp/';
    $serverdir              = $absolutedir.$dir;
    $tmp                    = explode(',',$_POST['file']);
    $file                   = base64_decode($tmp[1]);
    $extension              = strtolower(end(explode('.',$_POST['filename'])));
    $filename               = $_POST['name'].'.'.$extension;
    //$filename             = $file.'.'.substr(sha1(time()),0,6).'.'.$extension;
    $handle                 = fopen($serverdir.$filename,'w');
    fwrite($handle, $file);
    fclose($handle);
    $response = array(
            "result"        => true,
            "url"           => $dir.$filename.'?'.time(), //added the time to force update when editting multiple times
            "filename"      => $filename
    );
    echo json_encode($response);
    //echo json_encode(array('result'=>true));
}

However, I would like Wordpress to handle my file upload so I'm trying to use the following function to handle my file upload:
function test_upload()
{
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $filename = $_POST['filename'];
    $attachment_id = media_handle_upload( $filename, '1' );
    print_r($attachment_id);

}

I'm trying to pass the filename because the media_handle_upload codex for the first argument (in my example $filename) says this:
Index into the $_FILES array of the upload
How can I successfully use WP to upload this file using AJAX to pass me a POST variable instead of a $_FILES variable?
EDIT: When I currently do it this way I get a WP_ERROR saying the file is empty. I created a pastebin with the JS code to handle the file processing form so you can see where the file names are coming from.
http://pastebin.com/Shc4KqX1
Here is the file input:
<input type="file" name="file" />

A: <input id="uploadBtn" type="file" class="upload" name="pimage">

Function media_handle_upload upload your image in wordpress
Use $filename = $_POST['filename']['temp_name'];  not $filename = $_POST['filename'];
if ( !empty( $_FILES["pimage"]["name"] ) ) {
    $attachment_id = media_handle_upload( 'pimage', 0 );
}


Q: Updating global variable via callback I have the following function
   var urls = '';
    handleFiles(f,function(url){
        urls = urls + url + ',';
        console.log("urls is " + urls);
    });

I get the url after uploading and update my urls. But my Urls never gets updated, it shows the url of the last file uploaded.
UPDATE 1
This is my complete code now.
var urls = '';
document.getElementById('question-file-selector').addEventListener('change',handleFileSelect,false);
    function handleFileSelect(evt){
        var files = evt.target.files; //File list object
            // Loop through file list, render image files as thumbnails
        for (var i = 0,f;f = files[i];i++){

        handleFiles(f,function(url){
                urls = urls + url + ',';
                console.log("urls is " + urls);
                });
        // Only process image files
        if (!f.type.match('image.*')){
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();

        //Closure to capture file information
        reader.onload = (function(theFile){
                return function(e){
                    //Render thumbnail
                    $('#list').append('');
                    };
                    })(f);
        reader.readAsDataURL(f);
    }
    }

console.log("Url is",urls);`

And my ajax function
    //Code for Image upload

// Custom jQuery xhr instance to support our progress bar.

var xhr_with_progress = function() {
     var xhr = new XMLHttpRequest();
     xhr.upload.addEventListener("progress",
         function(evt) {
             if (!evt.lengthComputable) return;
             var percentComplete = evt.loaded / evt.total;
             $("#progress-bar div.progress-bar").css('width', String(100*percentComplete) + "%");
         }, false);
     return xhr;
 };

$.support.cors = true;//For cross origin transfer

//Event listners to avoid default drag and drop reaction of browser
window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);

function handleFiles(file,callback){

            var filename = file.name;
            $.ajax({
                type:'GET',
                data:{"filename":file.name, "FileType":"question_file"},
                url:'/dashboard/generateuploadurl/',
                contentType:"application/json",
                dataType:"json",
                async:false,
                success: function(data){
                    if(data.UploadUrl){
                      console.log("upload url successfully created for " + file.name + " file");
                        console.log(data.UploadUrl);
                        handleUpload(data.UploadUrl, file, data.Filename,callback);

                    }
                },
                error: function(data){
                    console.log("error occured while creating upload url for " + file.name + ' file');
                    console.log(data);
                },
            });
        }
function handleUpload(UploadUrl, file, Filename,callback){
    $.ajax({
        xhr:xhr_with_progress,
        url:UploadUrl,
        type:'PUT',
        data:file,
        cache:false,
        contentType:false,
        processData:false,
        success: function(data){
            console.log('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
            callback('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
        },
        error: function(data){
            alert("error occured while uploading " + file.name );
            console.log(data);
        },
    });
}

A: Coordinating multiple asynchronous operations is a job best solved with tools like promises.  So, in the long run, I'd suggest you read up about promises and how to use them.
Without promises, here's a brute force way you can tell when all your handleFiles() operations are done by using a counter to know when the last async operation is done and then using the urls variable INSIDE that last callback or calling a function from there and passing the urls variable to that function:
document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    var urls = "";
    // Loop through file list, render image files as thumbnails
    var doneCnt = 0;
    for (var i = 0, f; f = files[i]; i++) {
        handleFiles(f, function (url) {
            urls = urls + url + ',';
            console.log("urls is " + urls);
            ++doneCnt;
            if (doneCnt === files.length) {
                // The last handleFiles async operation is now done
                // final value is in urls variable here
                // you can use it here and ONLY here

                // Note: this code here will get executed LONG after the
                // handleFileSelect() function has already finished executing
            }
        });
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('');
            };
        })(f);
        reader.readAsDataURL(f);
    }
}

// You can't use the urls variable here.  It won't be set yet.

Ohhh.  Please remove the async: false from your ajax call.  That's a horrible thing to code with for a variety of reasons.

Here's a version using the promises built into jQuery:
document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    // Loop through file list, render image files as thumbnails
    var promises = [];
    for (var i = 0, f; f = files[i]; i++) {
        promises.push(handleFiles(f));
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('');
            };
        })(f);
        reader.readAsDataURL(f);
    }
    $.when.apply($, promises).then(function() {
        var results = Array.prototype.slice.call(arguments);
        // all handleFiles() operations are complete here
        // results array contains list of URLs (some could be empty if there were errors)
    });
}

function handleFiles(file) {
    var filename = file.name;
    return $.ajax({
        type: 'GET',
        data: {
            "filename": file.name,
            "FileType": "question_file"
        },
        url: '/dashboard/generateuploadurl/',
        contentType: "application/json",
        dataType: "json"
    }).then(function(data) {
        if (data.UploadUrl) {
            console.log("upload url successfully created for " + file.name + " file");
            console.log(data.UploadUrl);
            return handleUpload(data.UploadUrl, file, data.Filename);
        }
    }, function(err) {
        console.log("error occured while creating upload url for " + file.name + ' file');
        console.log(err);
        // allow operation to continue upon error
    });
}

function handleUpload(UploadUrl, file, Filename) {
    return $.ajax({
        xhr: xhr_with_progress,
        url: UploadUrl,
        type: 'PUT',
        data: file,
        cache: false,
        contentType: false,
        processData: false
    }).then(function(data) {
        console.log('https://7c.ssl.cf6.rackcdn.com/' + Filename);
        return 'https://7c.ssl.cf6.rackcdn.com/' + Filename;
    }, function(err) {
        console.log("error occured while uploading " + file.name);
        console.log(err);
        // allow operation to continue upon error
    });
}

Since I can't run this code to test it, there could be a mistake or two in here, but you should be able to debug those mistakes or tell us where the errors occur and we can help you debug it.  These are conceptually how you solve these types of problems of coordinating multiple async operations.


Q: how to install android app remotely by sending image? Is it possible to install any android app directly via sending any image or directly on clicking on web link?
when anyone click on link or download image application directly starts downloading and install without manual interaction of user without rooting of android phone.

A: Auto execution/installation of a downloaded file are disabled in every main stream Operating systems, be it windows, android, etc.


Q: LINQ to Entities does not recognize the method NotSupportedException LINQ to EF:
 db.ReadonlyQuery<Transaction>()
     .Select(t => new ACurrentDayInfo
         {
              OrderId = t.TransactionIdentifier,
              OrderTime = t.TransactionTime,
              UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? ""
         })
     .ToListAsync();

The t.UserInfo is a json string like {"RealName ":"XY"} in each record of in table's field.
How can I translate this to a server query?

A: Extend you ACurrentDayInfo class with a getter like this
class  ACurrentDayInfo
{
    public string UserName
    {
        get
        {
            return JsonConvert.DeserializeObject<UserInfo>(UserInfo).RealName ?? "";
        }
    }
}

and modify your query like this:
db.ReadonlyQuery<Transaction>()
                    .Select(t => new ACurrentDayInfo
                    {
                        OrderId = t.TransactionIdentifier,
                        OrderTime = t.TransactionTime,
                        UserInfo = t.UserInfo
                    }).ToListAsync();

A: In EF Dbcontext don't support cast json in query, You need fix same that:
var listData = db.ReadonlyQuery<Transaction>()
                        .Select(t => new ACurrentDayInfo
                        {
                            OrderId = t.TransactionIdentifier,
                            OrderTime = t.TransactionTime,

                            UserInfo = t.UserInfo
                        }).ToListAsync();

foreach (var item in listData)
{
    item.UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? ""
}


Q: creating List within a list in recurrsion from string python I am trying to create a list from a string
input string
st = "zzabcxzghfxx"
the list is enclosed in 'z' and 'x'
this is my attempt to create a recursive function
st = "zzabcxzghfxx"

def createlist(strin):
    l1=[]
    for i in st:
        if(i=='x'):
            createlist(strin)
        elif(i=='z'):
            l1.append(i)
    return(l1)

following is the desired output:"[[abc][ghf]]"
string = "zzabcxzghzfxx"=> [[abc][ghzf]]"

A: You could strip the trailing x and z and split on xz:
st.strip('xz').split('xz')
# ['abc', 'ghf']

A: Using regex.
Ex:
import re

st = "zzabcxzghfxx"
print(re.findall(r"z+(.*?)(?=x)", st))
#or print([[i] for i in re.findall(r"z+(.*?)(?=x)", st)])

Output:
['abc', 'ghf']

A: Does it have to be recursive? Here's a solution using itertools.groupby.
from itertools import groupby

string = "zzabcxzghfxx"

def is_good_char(char):
    return char not in "zx"

lists = [["".join(char for char in list(group))] for key, group in groupby(string, key=is_good_char) if key]
print(lists)

Output:
[['abc'], ['ghf']]

EDIT - Just realized that this might not actually produce the desired behavior. You said:

[a] list is enclosed in 'z' and 'x'

Which means a sublist starts with 'z' and must end with 'x', yes? In that case the itertools.groupby solution I posted will not work exactly. The way it's written now it will generate a new sublist that starts and ends with either 'z' or 'x'. Let me know if this really matters or not.

A: st.replace("z", "[").replace("x", "]")


Q: Image Rotates 90 degrees left when resized I have a resize script and it makes every image uploaded 300x300. It works fine when something from computer or mobile is uploaded. The problem is when user decides to take a picture from camera: After the resize script image rotates 90 degrees to the left and it is a problem because it should be displayed correctly without rotating. I don't know the reason here is the script:
    function resize_image($path, $width, $height, $update = false) {
    $size  = getimagesize($path);// [width, height, type index]
    $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
    if ( array_key_exists($size['2'], $types) ) {
       $load        = 'imagecreatefrom' . $types[$size['2']];
       $save        = 'image'           . $types[$size['2']];
       $image       = $load($path);
       $resized     = imagecreatetruecolor($width, $height);
       $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
       imagesavealpha($resized, true);
       imagefill($resized, 0, 0, $transparent);
       imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
       imagedestroy($image);
       return $save($resized, $update ? $path : null);
    }
 }
  if(!resize_image($_FILES["fileToUpload"]["tmp_name"], 300, 300, true))
  {
    exit();
  }


Q: Using capacity and time window constraints with pick up and delivery problem I am new to the OR-Tools libraries. I am trying to solve pick up and delivery problem with capacity and time window constraints. The code is working fine with 5 location nodes (2 pick up and 2 delivery locations and 1 depot location). But, when I change the number of nodes to 17(with 1 depot location), the code does not work and the kernel dies in Spyder editor for Python 3.5 without giving any error. And, if I run it in the terminal it produces following output.
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

System specifications are: OS-Ubuntu 16.04 LTS, Python version - 3.5.2, OR-Tools version - 7.7, RAM - 8GB, Graphics - 2GB AMD Radeon.
I have written the code by combining the relevant parts of the sample codes given on the OR-Tools website.
Following is the code with 16 nodes which is not working:
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['time_matrix'] = [
        [0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7],
        [6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14],
        [9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9],
        [8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16],
        [7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14],
        [3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8],
        [6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5],
        [2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10],
        [3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6],
        [2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5],
        [6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4],
        [6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10],
        [4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8],
        [4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6],
        [5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2],
        [9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9],
        [7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0],
    ]
    data['time_windows'] = [
        (0, 1800),  # depot
        (0, 1800),  # 1
        (0, 1800),  # 2
        (0, 1800),  # 3
        (0, 1800),  # 4
        (0, 1800),  # 5
        (0, 1800),  # 6
        (0, 1800),  # 7
        (0, 1800),  # 8
        (0, 1800),  # 9
        (0, 1800),  # 10
        (0, 1800),  # 11
        (0, 1800),  # 12
        (0, 1800),  # 13
        (0, 1800),  # 14
        (0, 1800),  # 15
        (0, 1800),  # 16
    ]
    data['pickups_deliveries'] = [
        [1, 6],     #2
        [2, 10],    #4
        [4, 3],     #1
        [5, 9],     #2
        [7, 8],     #5
        [15, 11],   #3
        [13, 12],   #1
        [16, 14],   #3
        [6, 15],    #5
        [7, 14],    #6
        [12, 9],    #3
    ]
    data['demands'] = [0, 2, 4, -1, 1, 2, 3, 11, -5, -5, -4, -3, 2, 1, -9, -2, 3]
    data['vehicle_capacities'] = [20, 20, 20, 20]
    data['num_vehicles'] = 4
    data['depot'] = 0
    return data

def print_solution(data, manager, routing, solution):
    """Prints solution on console."""
    time_dimension = routing.GetDimensionOrDie('Time')
    total_time = 0
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        while not routing.IsEnd(index):
            time_var = time_dimension.CumulVar(index)
            plan_output += '{0} Time({1},{2}) -> '.format(
                manager.IndexToNode(index), solution.Min(time_var),
                solution.Max(time_var))
            index = solution.Value(routing.NextVar(index))
        time_var = time_dimension.CumulVar(index)
        plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index),
                                                    solution.Min(time_var),
                                                    solution.Max(time_var))
        plan_output += 'Time of the route: {}min\n'.format(
            solution.Min(time_var))
        print(plan_output)
        total_time += solution.Min(time_var)
    print('Total time of all routes: {}min'.format(total_time))

def main():
    """Solve the VRP with time windows."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def time_callback(from_index, to_index):
        """Returns the travel time between the two nodes."""
        # Convert from routing variable Index to time matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['time_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(time_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Time Windows constraint.
    time = 'Time'
    routing.AddDimension(
        transit_callback_index,
        30000,  # allow waiting time
        3000,  # maximum time per vehicle
        False,  # Don't force start cumul to zero.
        time)
    time_dimension = routing.GetDimensionOrDie(time)
    # Add time window constraints for each location except depot.
    for location_idx, time_window in enumerate(data['time_windows']):
        if location_idx == 0:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
    # Add time window constraints for each vehicle start node.
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],
                                                data['time_windows'][0][1])

    # Instantiate route start and end times to produce feasible times.
    for i in range(data['num_vehicles']):
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.Start(i)))
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.End(i)))
    # Define Transportation Requests.
    for request in data['pickups_deliveries']:
        pickup_index = manager.NodeToIndex(request[0])
        delivery_index = manager.NodeToIndex(request[1])
        routing.AddPickupAndDelivery(pickup_index, delivery_index)
        routing.solver().Add(
            routing.VehicleVar(pickup_index) == routing.VehicleVar(
                delivery_index))
        routing.solver().Add(
            time_dimension.CumulVar(pickup_index) <=
            time_dimension.CumulVar(delivery_index))

    def demand_callback(from_index):
        """Returns the demand of the node."""
        # Convert from routing variable Index to demands NodeIndex.
        from_node = manager.IndexToNode(from_index)
        return data['demands'][from_node]

    demand_callback_index = routing.RegisterUnaryTransitCallback(
        demand_callback)
    routing.AddDimensionWithVehicleCapacity(
        demand_callback_index,
        0,  # null capacity slack
        data['vehicle_capacities'],  # vehicle maximum capacities
        True,  # start cumul to zero
        'Capacity')

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution)

    print("Status", routing.status())
if __name__ == '__main__':
    main()

And I am replacing the create_data_model() function with following for 5 nodes case which is working:
def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['time_matrix'] = [
        [0, 6, 9, 8, 7],
        [6, 0, 8, 3, 2],
        [9, 8, 0, 11, 10],
        [8, 3, 11, 0, 1],
        [7, 2, 10, 1, 0],
    ]

    data['time_windows'] = [
        (0, 180),  # depot
        (0, 180),  # 1
        (0, 180),  # 2
        (0, 180),  # 3
        (0, 180),  # 4

    ]
    data['pickups_deliveries'] = [
        [1, 3],     #2
        [2, 4],    #4 ripler
            #3
    ]
    data['demands'] = [0, 2, 4, -2, -4]
    data['vehicle_capacities'] = [2, 7]
    data['num_vehicles'] = 2
    data['depot'] = 0
    return data

A: My 2 cents,
If you have 16 nodes, they should be in range [0;15] but in your PickupAndDelivery array we can see a 16...
EDIT: seems you have 17 nodes (with the depot)


Q: Running "pub install" for dart-html5-samples leads to weird errors I encountered some weird errors when running "pub install" for dart-html5-samples. The first one was:
Illegal argument(s): join(): part 0 was null, but part 1 was not.

The second one was:
Running pub install ...
Pub install failed, [1] Resolving dependencies...
Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org.

What's going on, and how do I fix it?

A: The first error is:
Illegal argument(s): join(): part 0 was null, but part 1 was not.

That's because pubspec.yaml contained:
dependencies:
  htmlescape:
    sdk: htmlescape

htmlescape no longer comes with the SDK. Removing the dependency fixed the problem. I simply made a copy of htmlescape.dart in my lib directory. Eventually, I won't need my own copy once the following bug is fixed:
http://code.google.com/p/dart/issues/detail?id=1657
The second error is:
Running pub install ...
Pub install failed, [1] Resolving dependencies...
Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org.

dart-html5-samples depends on vector_math which depends on unittest. I think they must have changed how unittest is loaded by pub. Running pub update fixed the problem.